gradle文件增加
// swagger implementation "io.springfox:springfox-swagger2:2.9.2" implementation "io.springfox:springfox-swagger-ui:2.9.2"
添加配置類SwaggerConfig
package com.zuo.model.config; 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.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 //添加swagger啟用注解 //@Profile({"dev", "test"}) //方式一 //@ConditionalOnProperty(name = "swagger2.enable", havingValue = "true") //方式二 public class SwaggerConfig { //讀取yml文件配置 @Value("${swagger2.enable}") private boolean swagger2Enable; /** * .enable() 控制是否進行初始化 * .select() 初始化並返回一個API選擇構造器 * .paths(PathSelectors.any()) 設置路徑篩選器 * .apis(RequestHandlerSelectors.basePackage("com.xxx.xxx.xxx")) 添加路徑選擇條件 * .build(); 構建 * * PathSelectors 類的方法: * - Predicate<String> any():滿足條件的路徑,該斷言總為true * - Predicate<String> none():不滿足條件的路徑,該斷言總為false * - Predicate<String> regex(final String pathRegex):符合正則的路徑 * * RequestHandlerSelectors 類的方法: * - Predicate<RequestHandler> any():返回包含所有滿足條件的請求處理器的斷言,該斷言總為true * - Predicate<RequestHandler> none():返回不滿足條件的請求處理器的斷言,該斷言總為false * - Predicate<RequestHandler> basePackage(final String basePackage):返回一個斷言(Predicate),該斷言包含所有匹配basePackage下所有類的請求路徑的請求處理器 */ @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .enable(swagger2Enable) //方式三 .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.zuo.model.controller")) // 注意修改此處的包名 .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("項目模板集成系統") .description("API接口文檔") .version("1.0.0") .build(); } }
生產環境建議不要啟用swagger
配置如下
訪問swagger
http://localhost/swagger-ui.html
配置成功