Spring多Profile场景下,如何为Swagger UI新增YAML配置文件而非替换?
解决方案:Spring Profile区分Swagger服务器配置
你的需求完全可以实现,下面提供两种简洁的方案,避免维护重复的Swagger配置类:
方案一:Profile专属YAML配置文件(配置与代码分离)
这种方式通过不同Profile加载对应YAML文件,仅定义差异化的servers配置,公共配置保留在@OpenApiDefinition中:
创建Profile专属OpenAPI YAML文件
在src/main/resources下创建两个YAML文件,仅包含服务器配置:openapi-dev.yaml(开发环境):openapi: 3.0.1 servers: - url: http://dev.example.com/api description: 开发环境服务器openapi-prod.yaml(生产环境):openapi: 3.0.1 servers: - url: http://prod.example.com/api description: 生产环境服务器
在Profile配置文件中指定加载对应YAML
修改各自的application-${profile}.properties,配置SpringDoc加载对应YAML:application-dev.properties:# 保留原有Swagger基础配置 springdoc.api-docs.path=/v3/api-docs springdoc.swagger-ui.url=/v3/api-docs # 指定加载开发环境的服务器配置YAML springdoc.openapi.location=classpath:openapi-dev.yamlapplication-prod.properties:springdoc.api-docs.path=/v3/api-docs springdoc.swagger-ui.url=/v3/api-docs springdoc.openapi.location=classpath:openapi-prod.yaml
SpringDoc会自动将@OpenApiDefinition的公共配置与YAML中的服务器配置合并,无需重复编写公共Swagger配置。
方案二:代码动态生成服务器配置(无需额外文件)
通过配置类结合Spring环境变量,动态根据当前激活的Profile生成服务器配置,更灵活:
@Configuration public class SwaggerServerConfig { @Bean public OpenApiCustomizer serverCustomizer(Environment environment) { List<String> activeProfiles = Arrays.asList(environment.getActiveProfiles()); Server server; if (activeProfiles.contains("dev")) { server = new Server().url("http://dev.example.com/api").description("开发环境"); } else if (activeProfiles.contains("prod")) { server = new Server().url("http://prod.example.com/api").description("生产环境"); } else { // 默认本地环境配置 server = new Server().url("http://localhost:8080/api").description("本地开发环境"); } return openApi -> openApi.servers(Collections.singletonList(server)); } }
这个配置类会自动覆盖或补充@OpenApiDefinition中的服务器配置,无需修改原有注解,逻辑集中在一处。
方案对比
- YAML方案:配置与代码解耦,非开发人员可直接修改服务器地址,适合配置频繁调整的场景。
- 代码动态注入:逻辑集中,无需维护多个配置文件,适合配置相对固定的场景。
两种方案均能完美兼容你现有的@OpenApiDefinition配置,无需重复编写冗余代码。
内容的提问来源于stack exchange,提问作者IceMajor
相关产品推荐
相关产品推荐

