SpringBoot整合Swagger
1.首先創建一個springboot項目
2.引入依賴
<!--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>
3.編寫Swagger配置類
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.niuben.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("測試Swagger") .description("這是一個Restful風格的API文檔") .version("1.0") //.contact(new Contact("負責人", "http://xxx.xxx.com/負責人訪問鏈接", "負責人郵箱")) .build(); } }
4.啟動項目
對Swagger配置類的詳解
配置掃描接口
通過 .select()
方法,去配置掃描接口, RequestHandlerSelectors.xx
配置如何掃描接口
any():掃描所有,項目中的所有接口都會被掃描到 none():不掃描接口 basePackage(final String basePackage):根據包路徑掃描接口 withMethodAnnotation(final Class<? extends Annotation> annotation):通過方法上的注解掃描,如withMethodAnnotation(GetMapping.class)只掃描get請求 withClassAnnotation(final Class<? extends Annotation> annotation):通過類上的注解掃描,如.withClassAnnotation(Controller.class)只掃描有controller注解的類中的接口
配置接口掃描過濾
any() :任何請求都掃描 none() :任何請求都不掃描 regex(final String pathRegex) :通過正則表達式控制 ant(final String antPattern) :通過ant()控制
動態配置根據環境時顯示swagger
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi(Environment environment) { // 設置要test、dev環境時顯示swagger,處於prod時不顯示 Profiles of = Profiles.of("dev", "test"); // 判斷當前是否處於該環境 boolean b = environment.acceptsProfiles(of); return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()) .enable(b) // 通過 enable() 接收此參數判斷是否要顯示 .select() .apis(RequestHandlerSelectors.basePackage("com.niuben.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("測試Swagger") .description("這是一個Restful風格的API文檔") .version("1.0") //.contact(new Contact("負責人", "http://xxx.xxx.com/負責人訪問鏈接", "負責人郵箱")) .build(); } }