<!--Swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
SwaggerConfig
package com.zhoupiyao.config;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@EnableSwagger2 //开启swagger
@Configuration
public class SwaggerConfig {
}
http://localhost:8080/swagger-ui.html
@Bean
public Docket docket(Environment environment){
boolean flag = environment.getActiveProfiles().equals("dev");
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
//是否启用swagger,默认true
.enable(false)
.select()
// .apis(RequestHandlerSelectors.withMethodAnnotation(ResponseBody.class))
//basePackage():配置接口扫描包路径
//any():扫描所有路径下接口
//none(): 不扫描任何路径下的接口
//withMethodAnnotation():扫描方法上带有指定注解的接口
//withClassAnnotation():扫描类上带有指定注解的接口
.build();
}
通过控制配置文件中的开发环境来控制swagger是否开启
//获取并判断当前开发环境是否为dev
boolean flag = environment.getActiveProfiles()[0].equals("dev");
//如果是则返回true,表示开启swagger
return new Docket(DocumentationType.SWAGGER_2)
//是否启用swagger,默认true
.enable(flag)
或者通过以下方法指定多个开发环境是否开启swagger
//获取并判断当前开发环境是否为dev或prod
boolean flag = environment.acceptsProfiles(Profiles.of("dev", "prod"));
//如果是则返回true,表示开启swagger
return new Docket(DocumentationType.SWAGGER_2)
//是否启用swagger,默认true
.enable(flag)
当指定的开发环境没有开启swagger时:
创建多个Docket并添加@Bean注解
.groupName("周飘")
@Bean
public Docket docket1(){
return new Docket(DocumentationType.SWAGGER_2).groupName("A");
}
@Bean
public Docket docket1(){
return new Docket(DocumentationType.SWAGGER_2).groupName("B");
}
再通过扫描指定包或注解来绑定不同组下面的接口。
@Api给Controller类添加Swagger文档标注
@ApiModel给实体类添加Swagger文档标注
//给Controller类添加Swagger文档标注
@Api(tags = "Hello控制类")
//给实体类添加Swagger文档标注
@ApiModel("用户实体类")
给实体类添加Swagger文档标注
@ApiModelProperty("用户名")
给Controller类的方法添加Swagger文档标注
@ApiOperation("通过username获取用户")
原文:https://www.cnblogs.com/yzxzpy-1012/p/14666453.html