一个项目通常需要经历开发、测试和正式上线三个阶段。通常我们在不同的阶段将采用不同的数据库、redis、缓存等配置信息。在 Spring Boot 中,我们可以通过 profile 来实现。例如在项目的 resources 目录分别创建如下配置文件:
application.yml:主配置文件,在不同阶段配置不会改变
application-dev.yml:开发环境配置文件
application-test.yml:测试环境配置文件
application-prod.yml:正式环境配置文件
可以使用 spring.profiles.active 配置来指定当前环境类型,例如:spring.profiles.active=prod 指定使用正式环境配置。
然而,Swagger 对于开发和测试阶段很有帮助,但是在正式环境下可能会出现安全问题(可以通过防火墙解决安全问题)。我们还可以使用 @Profile 注解根据当前的 profile 动态决定是否启动 Swagger。
你需要将 @EnableSwagger2 注解从 Spring Boot 启动类上面删除,添加到 WebMvcConfigurer 类上面。然后在该配置类上面使用 @Profile 注解根据 profile 动态决定是否激活这个配置文件。代码如下:
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* 配置 Swagger
* @author Administrator 2021/4/23 22:23
* @version 1.0
*/
@EnableSwagger2
@Configuration
@Profile({"dev", "test"})
public class WebMvcConfig implements WebMvcConfigurer {
/**
* 发现如果继承了WebMvcConfigurationSupport,则在yml中配置的相关内容会失效。
* 需要重新指定静态资源
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
System.out.println("addResourceHandlers()");
// 映射 webjars 资源
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}将 spring.profiles.active 配置项指定为 dev 或 test。然后启动项目,访问 http://localhost:8080/swagger-ui.html 地址,效果如下图:

将 spring.profiles.active 配置项指定为 pro。然后启动项目,访问 http://localhost:8080/swagger-ui.html 地址,效果如下图:

从上图得知,Swagger 已经不能正常访问了。