springboot生产环境中关闭swagger

时间:2025-03-21 09:30:58

      swagger一般是在开发时调试用的,在生产环境要关闭swagger,下面是我找到的几种关闭swagger的方法,记录一下,噶供大家参考。

1、启动判断写在相应的环境配置文件中,根据条件判断是否启动 swagger :
    添加配置项:
    @Value("${}") private boolean swagger_is_enable;

@Bean
public Docket createRestApi() {

return new Docket(DocumentationType.SWAGGER_2)
    .enable(swagger_is_enable)
    .apiInfo(apiInfo()).select()
    // 扫描指定包中的swagger注解
    .apis(("springboot_druid_demo.controller"))
    .paths(())
    .build()
    .pathMapping("/");
}

具体实现,参考链接:/u012946310/article/details/82379429

2、通过不同的profile给swagger的依赖设置不同的scope
     使用注解@Profile({"dev","test"}) 表示在开发或测试环境开启,而在生产关闭。(推荐使用)

        <!-- Swagger -->
		<dependency>
			<groupId></groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>${}</version>
			<scope>${}</scope>
		</dependency>
		<dependency>
			<groupId></groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<scope>${}</scope>
			<version>${}</version>
		</dependency>
    <profiles>
		<profile>
			<id>dev</id>
			<properties>
				<>dev</>
				<>compile</>
			</properties>
			<activation>
				<activeByDefault>true</activeByDefault>
			</activation>
		</profile>
		<profile>
			<id>test</id>
			<properties>
				<>test</>
				<>compile</>
			</properties>
		</profile>
		<profile>
			<id>online</id>
			<properties>
				<>online</>
				<>provided</>
			</properties>
		</profile>
	</profiles>

具体实现,参考链接:/goldenfish1919/article/details/78280051
3、使用注解@ConditionalOnProperty(name = "", havingValue = "true")  
    然后在测试配置或者开发配置中 添加 = true 即可开启,生产环境不填则默认关闭Swagger.