场景
swagger 用来在开发阶段方便前后端分离的项目实战中,提高前后端人员的工作效率,降低交流成本。但是版本上线之后,要是把 swagger 带上去会存在很大的风险
禁用方法
基于 2.9.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>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-spring-webmvc</artifactId>
<version>2.9.2</version>
</dependency>
方法一(推荐)
在自定义的 Swagger2 配置类中,通过 @ConditionalOnProperty(prefix = “base”,name=“swagger-open”,havingValue = “true”)注解实现
@Configuration
@EnableSwagger2
@ConditionalOnProperty(prefix = "base",name="swagger-open",havingValue = "true")
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs")
.description("")
.termsOfServiceUrl("")
.contact(new Contact("亦安✘","http:www.xxx.com","xxx@xxx.com"))
.version("1.0")
.build();
}
}
PS
-
在自定义的 Swagger2配置类中,通过 @ConditionalOnProperty(prefix = “base”,name=“swagger-open”,havingValue = “true”) 注解实现
-
读取配置文件中前缀为 base的配置,属性名为 swagger-open,只为 true
-
当条件成立,此配置类被激活
-
配置文件如下
################### 项目启动端口 ###################
server:
port: 8080
servlet:
context-path: /${base.project}-api
base:
project: yian
filePath: /data/${base.project} #静态文件路径
swagger-open: true #是否启用swagger
方法二
- 在配置中编写配置文件
base:
swagger-open: true #是否启用swagger
- 在自定义的 Swagger2 配置类中获取配置文件中的配置信息
@Configuration
@EnableSwagger2
public class Swagger2 {
@Value("${base.swagger-open}")
private boolean swaggerSwitch;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(swaggerSwitch)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs")
.description("")
.termsOfServiceUrl("")
.contact(new Contact("亦安✘","http:www.xxx.com","xxx@xxx.com"))
.version("1.0")
.build();
}
}