Swagger实用示例全集

Swagger是一套基于OpenAPI规范构建的开源工具,可以快速帮助我们编写最新的API接口文档。

常用注解

@Api:修饰整个类,描述Controller的作用
@ApiOperation:描述方法,或者说接口
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@ApiModelProperty:用对象接收参数时,描述对象的一个字段
@ApiImplicitParam:一个请求参数
@ApiImplicitParams:多个请求参数

Swagger2使用

在2.10.0版本之前,是swagger2阻塞式编程,配置swagger都是用的注解@EnableSwagger2 从2.10.0—2.10.5,由于20年初响应式编程的出现,从2.10.0开始,配置swagger已经把注解@EnableSwagger2弃用,为区分阻塞式和响应式,开始使用的注解开始分为:@EnableSwagger2WebMvc、@EnableSwagger2WebFlux。此时会出现不利于维护的问题。因此不常用。

Swagger3:基于之前2.10版本,swagger3正式推出,非阻断式升级兼容阻塞式编程和响应式编程。Swagger3将@EnableSwagger2WebMvc、 @EnableSwagger2WebFlux注解弃用,兼容的注解为@EnableOpenAPI或@EnableSwagger2,使用这俩个注解都可以。

访问:

        swagger2:/swagger-ui.html

        swagger3:/swagger-ui/index.html

各项注释在代码中体现,属性取值只贴一遍,因为下面三个都一样.

Swagger2 

版本2.10.0之前的依赖包,常用的是2.9.2版本



    io.springfox
    springfox-swagger2
    2.9.2



    io.springfox
    springfox-swagger-ui
    2.9.2

YML配置

swagger:
  enabled: true;
  contact-name: Ltter
  contact-url: https://www.baidu.com/
  contact-email: [email protected]
  title: 测试Swagger服务
  version: v1.0
  description: Swagger描述
  license: 1.1.1
  license-url: https://blog.csdn.net/u013812135?type=blog
  terms-of-service-url: https://blog.csdn.net/u013812135/article/details/121357346?spm=1001.2014.3001.5502
package com.learn.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @Title SwaggerProperties
 * @Description 属性
 * @Author Ltter
 * @Date 2022/8/17 14:01
 * @Version 1.0
 */
@Data
@Component
@ConfigurationProperties(prefix = "swagger")
public class SwaggerProperties {

    /**
     * 作者名称
     */
    private String contactName;
    /**
     * 作者—url
     */
    private String contactUrl;
    /**
     * 作者邮箱
     */
    private String contactEmail;
    /**
     * 标题
     */
    private String title;
    /**
     * 版本
     */
    private String version;
    /**
     * 描述
     */
    private String description;
    /**
     *
     */
    private String termsOfServiceUrl;
    /**
     * 网站连接显示文字
     */
    private String license;
    /**
     * 网站连接地址
     */
    private String licenseUrl;
}

配置文件

package com.learn.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.List;

/**
 * @Title SwaggerConfig
 * @Description Swagger配置文件
 * @Author Ltter
 * @Date 2022/8/17 9:26
 * @Version 1.0
 */
@Configuration
@EnableSwagger2
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerConfig {

    @Autowired
    private SwaggerProperties swaggerProperties;

    /**
     * 配置Docket的Bean
     * @return
     */
    @Bean
    public Docket customDocket(){
        return new Docket(DocumentationType.SWAGGER_2)
                //接口文档的基础信息
                .apiInfo(customApiInfo())
                //对Api进行安全认证
                //.securitySchemes(customSecurity())
                //设置需要使用参数的接口
                //.securityContexts(customSecurityContext())
                .select()
                //1、扫描所有
                //.apis(RequestHandlerSelectors.any())
                //2、扫描所有使用注解的API,这种方法更灵活
                //.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                //3、扫描指定包中的注解
                .apis(RequestHandlerSelectors.basePackage("com.learn"))
                //路径风格
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 接口文档的基础信息
     * @return
     */
    private ApiInfo customApiInfo() {
        return new ApiInfoBuilder()
                .title(swaggerProperties.getTitle())
                .version(swaggerProperties.getVersion())
                .description(swaggerProperties.getDescription())
                .contact(new Contact(swaggerProperties.getContactName(), swaggerProperties.getContactUrl(), swaggerProperties.getContactEmail()))
                .license(swaggerProperties.getLicense())
                .licenseUrl(swaggerProperties.getLicenseUrl())
                .build();
    }

    /**
     * 对Api进行安全认证
     * @return
     */
    private List customSecurity() {
        return null;
    }

    /**
     * 设置需要使用参数的接口
     * @return
     */
    private List customSecurityContext() {
        return null;
    }
}
@RestController
@RequestMapping("/knsw")
@Api(tags = "KNIFE4J-SWAGGER服务测试")
public class Knife4jController {

    @ApiOperation(value = "查询")
    @GetMapping("/find")
    public String find(){
        return "查询-结果-";
    }

    @ApiOperation(value = "保存")
    @PostMapping("/save")
    public String save(){
        return "保存-结果-";
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "编码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "params", value = "参数", dataType = "String", paramType = "query")
    })
    @ApiOperation(value = "查询测试")
    @GetMapping("findALl")
    public String findALl(@RequestParam("code") String code,@RequestParam("params") String params){
        return "返回结果:编码:"+ code +" 参数信息:"+ params;
    }
}

Swagger实用示例全集_第1张图片

Swagger3

Swagger3的依赖包



    io.springfox
    springfox-boot-starter
    3.0.0
swagger:
  enabled: true;
  contact-name: Ltter
  contact-url: https://www.baidu.com/
  contact-email: [email protected]
  title: 测试Swagger服务
  version: v1.0
  description: Swagger描述
  license: 1.1.1
  license-url: https://blog.csdn.net/u013812135?type=blog
  terms-of-service-url: https://blog.csdn.net/u013812135/article/details/121357346?spm=1001.2014.3001.5502
package com.learn.config;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.List;

/**
 * @Title Swagger3Config
 * @Description Swagger3配置文件
 * @Author Ltter
 * @Date 2022/8/17 14:59
 * @Version 1.0
 */

@Configuration
@EnableSwagger2
@EnableConfigurationProperties(Swagger3Properties.class)
public class Swagger3Config {

    @Autowired
    private Swagger3Properties swagger3Properties;

    @Bean
    public Docket customSwagger3Docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(customApiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.learn"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo customApiInfo() {
        return new ApiInfoBuilder()
                .title(swagger3Properties.getTitle())
                .version(swagger3Properties.getVersion())
                .description(swagger3Properties.getDescription())
                .contact(new Contact(swagger3Properties.getContactName()
                        , swagger3Properties.getContactUrl()
                        , swagger3Properties.getContactEmail()))
                .license(swagger3Properties.getLicense())
                .licenseUrl(swagger3Properties.getLicenseUrl())
                .build();
    }

}

Swagger实用示例全集_第2张图片

Knife4j-Swagger2

        knife4j是Swagger的升级版本;引用所有的knife4j提供的资源,包括前端Ui的jar包。在项目中一般将knife4j和knife4j-micro俩个依赖放入根pom中;若是微服务项目并使用了gateway的情况下,将knife4j依赖放入gateway中;knife4j-micro在其它微服务中,一般放common中,以避免依赖臃肿。



    com.github.xiaoymin
    knife4j-spring-boot-starter
    2.0.2




    com.google.guava
    guava
    20.0


    io.projectreactor
    reactor-core
    3.4.17
knife4j:
  enabled: true;
  contact-name: Ltter
  contact-url: https://www.baidu.com/
  contact-email: [email protected]
  title: 测试knife4j-Swagger2服务
  version: v1.0.0
  description: knife4j-Swagger2描述
  license: 哇呀呀呀```呔、何方妖孽
  license-url: https://blog.csdn.net/u013812135?type=blog
package com.learn.config;

import com.google.common.base.Predicates;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @Title Knife4jSwaggerConfig
 * @Description 配置文件
 * @Author Ltter
 * @Date 2022/8/17 15:48
 * @Version 1.0
 */
@Configuration
@EnableSwagger2
@EnableConfigurationProperties(Knife4jSwaggerProperties.class)
public class Knife4jSwaggerConfig {

    @Autowired
    private Knife4jSwaggerProperties knife4jSwaggerProperties;

    @Bean
    public Docket customKnife4jSwaggerDocket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(customApiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.learn"))
                .paths(PathSelectors.any())
                //不显示错误的接口地址 basic-error-controller
                .paths(Predicates.not(PathSelectors.regex("/error.*")))
                .build();
    }

    private ApiInfo customApiInfo() {
        return new ApiInfoBuilder()
                .title(knife4jSwaggerProperties.getTitle())
                .version(knife4jSwaggerProperties.getVersion())
                .description(knife4jSwaggerProperties.getDescription())
                .contact(new Contact(knife4jSwaggerProperties.getContactName()
                        , knife4jSwaggerProperties.getContactUrl()
                        , knife4jSwaggerProperties.getContactEmail()))
                .license(knife4jSwaggerProperties.getLicense())
                .licenseUrl(knife4jSwaggerProperties.getLicenseUrl())
                .build();
    }
}

Swagger实用示例全集_第3张图片

GtiHub代码地址https://github.com/mrzltao/spring-boot-learns

你可能感兴趣的:(Swagger2,SpringBoot,java,spring,boot)