swagger一般是在开发时调试用的,在生产环境要关闭swagger,下面是我找到的几种关闭swagger的方法,记录一下,噶供大家参考。
1、启动判断写在相应的环境配置文件中,根据条件判断是否启动 swagger :
添加配置项:swagger.is.enable
@Value("${swagger.is.enable}") private boolean swagger_is_enable;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(swagger_is_enable)
.apiInfo(apiInfo()).select()
// 扫描指定包中的swagger注解
.apis(RequestHandlerSelectors.basePackage("springboot_druid_demo.controller"))
.paths(PathSelectors.any())
.build()
.pathMapping("/");
}
具体实现,参考链接:https://blog.csdn.net/u012946310/article/details/82379429
2、通过不同的profile给swagger的依赖设置不同的scope
使用注解@Profile({"dev","test"}) 表示在开发或测试环境开启,而在生产关闭。(推荐使用)
<!-- Swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${springfox-swagger.version}</version>
<scope>${swagger.scope}</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<scope>${swagger.scope}</scope>
<version>${springfox-swagger-ui.version}</version>
</dependency>
<profiles>
<profile>
<id>dev</id>
<properties>
<profiles.active>dev</profiles.active>
<swagger.scope>compile</swagger.scope>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<profiles.active>test</profiles.active>
<swagger.scope>compile</swagger.scope>
</properties>
</profile>
<profile>
<id>online</id>
<properties>
<profiles.active>online</profiles.active>
<swagger.scope>provided</swagger.scope>
</properties>
</profile>
</profiles>
具体实现,参考链接:https://blog.csdn.net/goldenfish1919/article/details/78280051
3、使用注解@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
然后在测试配置或者开发配置中 添加 swagger.enable = true 即可开启,生产环境不填则默认关闭Swagger.