一、场景介绍
Swagger
用来在开发阶段方便前后端分离的项目实战中,提高前后端人员的工作效率,降低交流成本。但是版本上线之后,要是把 Swagger
带上去会存在很大的风险。
二、禁用方式
-
基于
2.10.5
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.10.5</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.10.5</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-spring-webmvc</artifactId> <version>2.10.5</version> </dependency>
-
方式一(推荐)
在自定义的
SwaggerConfig
配置类中,通过@ConditionalOnProperty(prefix = "swagger2", value = {"enable"}, havingValue = "true")
注解实现@Configuration @EnableSwagger2WebMvc @ConditionalOnProperty(prefix = "swagger2", value = {"enable"}, havingValue = "true") public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .pathMapping("/") .select() .apis(RequestHandlerSelectors.basePackage("com.---.---.controller")) .paths(PathSelectors.any()) .build().apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("****接口文档") .description("自动接口文档详细描述信息") .version("version1.0") .contact(new Contact("开发者:***项目组", "http://www.***.com", "***@***.com")) .license("The Apache License") .licenseUrl("http://apache.org/") .build(); } }
P.S
-
在自定义的
SwaggerConfig
配置类中,通过@ConditionalOnProperty(prefix = "swagger2", value = {"enable"}, havingValue = "true")
注解实现 -
读取配置文件中前缀为
swagger2
的配置,属性名为enable
,只为true
-
当条件成立,此配置类被激活
-
配置文件如下
spring: profiles: dev swagger2: enable: true --- spring: profiles: prod swagger2: enable: false(或者在prod环境下不写此配置)
-
-
方式二
-
同样在配置文件中编写配置文件
swagger: enable: true
-
在自定义的
SwaggerConfig
配置类中获取配置文件中的配置信息@Configuration @EnableSwagger2 public class SwaggerConfig { @Value("${swagger.enable}") private boolean enableSwagger; @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .enable(enableSwagger) // <--- Flag to enable or disable possibly loaded using a property file .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.--.---.---.---.rest")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("···接口文档") .description("") .version("1.0") .build(); } }
-
-
测试
通过 http://localhost/swagger-ui.html 查看项目中所有的接口信息
通过 http://localhost/v2/api-docs 查看 json 数据