官網:https://swagger.io/
使用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>
編寫接口
@RestController public class HelloController { @RequestMapping("/hello") public String hello(){ return "hello , swagger"; } }
集成Swagger2
@Configuration @EnableSwagger2 //開啟Swagger2 public class SwaggerConfig {
訪問:http://localhost:8083/swagger-ui.html
配置Swagger的apiInfo信息
@Configuration @EnableSwagger2 //開啟Swagger2 public class SwaggerConfig { //配置Swagger2的Docket實例,並交給Spring容器管理 @Bean public Docket getDocket(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()); } //配置Swagger信息 private ApiInfo apiInfo(){ //作者信息 Contact contact = new Contact("", "", ""); return new ApiInfo( "Api Documentation", "Api Documentation", "1.0", "urn:tos", contact, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList()); } }
Swagger配置掃描接口
格式:Docket.select().apis().paths.build()
return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo())
.select() //RequestHandlerSelectors 配置掃描接口方式 //basePackage 掃描指定包 //any 掃描全部 //none 不掃描 //withClassAnnotation 掃描指定注解的類 //withMethodAnnotation 掃描指定注解的方法 .apis(RequestHandlerSelectors.basePackage("com.marw.controller")) //根據配置過濾請求路徑 .paths(PathSelectors.ant("/")) .build();
配置啟動Swagger
Docket.enable(false):關閉Swagger
Docket.enable(true):開啟Swagger
根據發布環境設置Swagger開啟或關閉
spring.profiles.active="dev"多環境配置
public Docket getDocket(Environment environment){ //設置開啟Swagger的環境 Profiles profiles=Profiles.of("dev","uat"); //判斷當前環境是否符合設置的開啟Swagger的條件 boolean b = environment.acceptsProfiles(profiles); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() //RequestHandlerSelectors 配置掃描接口方式 //basePackage 掃描指定包 //any 掃描全部 //none 不掃描 //withClassAnnotation 掃描指定注解的類 //withMethodAnnotation 掃描指定注解的方法 .apis(RequestHandlerSelectors.basePackage("com.marw.controller")) //根據配置過濾請求路徑 //.paths(PathSelectors.ant("/")) .build().enable(b); }
配置API分組
Docket().groupName("分組名")
多個分組
本質多個Docket對象
//配置Swagger2的Docket實例,並交給Spring容器管理 @Bean public Docket a(){ return new Docket(DocumentationType.SWAGGER_2).groupName("A"); } //配置Swagger2的Docket實例,並交給Spring容器管理 @Bean public Docket b(){ return new Docket(DocumentationType.SWAGGER_2).groupName("B"); }
Models
Swagger掃描Models只要接口中返回值存在就會被掃描到Swagger中
@GetMapping("/index") public User index(){ return new User(); }