Spring Boot集成swagger

一、Swagger是什么?

Swagger可以看做是一个API文档构建工具,根据Swagger的规范去定义接口及接口相关的信息,可以动态地生成API文档,方便调试接口。在项目开发中,仅仅需要掌握几个常用的swagger注解就好。

二、Spring Boot如何集成Swagger?

1、添加依赖

首页要引入swagger的依赖。

<!-- swagger2 -->
<properties>
    <springfox.version>2.7.0</springfox.version>
</properties>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${springfox.version}</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${springfox.version}</version>
</dependency>

2、添加Swagger配置

Swagger可以根据需要灵活的生成API文档

  • 生成指定包下面的类的API文档 -> apis(RequestHandlerSelectors.basePackage("com.xx.xx.controller"))
  • 生成有指定注解(@Api注解)的类的API文档 -> apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
  • 生成有指定注解(@ApiOperation注解)的方法的API文档 -> apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
@Configuration
@EnableSwagger2
@ConditionalOnProperty(name = "enable", prefix = "swagger", havingValue = "true")
public class Swagger2Config {
    @Bean
    public Docket swaggerSpringMvcPlugin() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("demo")
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo())
                .useDefaultResponseMessages(false);
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .version("1.0")
                .title("Swagger2 文档 API")
                .description("API v1.0")
                .build();
    }
}

 

三、Swagger常用注解

1、模型相关的注解

两个注解:

  • @ApiModel:用在模型类上,对模型类做注释;
  • @ApiModelProperty:用在属性上,对属性做注释

2、与接口相关的注解

六个注解:

  • @Api:用在controller上,对controller进行注释;-> 例如:@Api(tags "OrderController", description "订单模块",hidden=false)
  • @ApiOperation:用在API方法上,对该API做注释,说明API的作用;-> 例如:@ApiOperation("创建订单")
  • @ApiImplicitParams:用来包含API的一组参数注解,可以简单的理解为参数注解的集合声明;
  • @ApiImplicitParam:用在@ApiImplicitParams注解中,也可以单独使用,说明一个请求参数的各个方面,该注解包含的常用选项有:
    • paramType:参数所放置的地方,包含query、header、path、body以及form,最常用的是前四个。
    • name:参数名;
    • dataType:参数类型,可以是基础数据类型,也可以是一个class;
    • required:参数是否必须传;
    • value:参数的注释,说明参数的意义;
    • defaultValue:参数的默认值;
  • @ApiResponses:通常用来包含接口的一组响应注解,可以简单的理解为响应注解的集合声明;
  • @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
    • code:即httpCode,例如400 
    • message:信息,例如"请求参数没填好"

注意点:

  1. 为了在swagger-ui上看到输出,至少需要两个注解:@Api和@ApiOperation
  2. 即使只有一个@ApiResponse,也需要使用@ApiResponses包住
  3. 对于@ApiImplicitParam的paramType:query、form域中的值需要使用@RequestParam获取, header域中的值需要使用@RequestHeader来获取,path域中的值需要使用@PathVariable来获取,body域中的值使用@RequestBody来获取,否则可能出错;而且如果paramType是body,name就不能是body,否则有问题,与官方文档中的“If paramType is "body", the name should be "body"不符。

四、生产环境如何禁用swagger?

开发过程中,一般本地、dev、test环境需要用到swagger-ui,进行接口调试。

而生产环境,需要禁用swagger,定义的接口不能暴露出去,会有安全问题。

 

方法一:使用@ConditionalOnProperty

dev、test环境配置文件中配置swagger.enable =true表示开启swagger文档,生产环境配置swagger.enable=false表示关闭swagger文档。

@Configuration
@EnableSwagger2
@ConditionalOnProperty(name = "enable", prefix = "swagger", havingValue = "true")
public class Swagger2Config {

方法二:使用@Profile区分

根据配置文件中配置的spring.profiles.active=dev,test表示在dev和test环境开启,生产环境不开启。

@Configuration
@EnableSwagger2
@Profile({"dev","test"})
public class Swagger2Config {

方法三:可以根据某个系统参数自己定义

@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket swaggerSpringMvcPlugin() {
        if(System.getProperty("disable_swagger").equals("on") {
            return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.none()).build();
        }
        return new Docket(DocumentationType.SWAGGER_2).groupName("demo").select()
                                                      .apis(RequestHandlerSelectors.any())
                                                      .paths(regex("/(" + servername + "/).*"))
                                                      .build().apiInfo(serviceInfo.getApiInfo()).useDefaultResponseMessages(false);
    }
}

五、用nginx做反向代理,如何访问swagger-ui?

location /swagger-ui.html {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080/swagger-ui.html;
}
location /swagger-resources {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080/swagger-resources;
}
location /v2/api-docs {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080/v2/api-docs;
}
location /webjars {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080/webjars;
}

 

posted @ 2020-04-11 21:48  Eason.Wang  阅读(445)  评论(0)    收藏  举报