Spring Boot 2.7.5如何读取不同目录下的激活配置文件?
核心问题
你把环境配置文件放在src/main/resources/properties目录下,但Spring Boot默认只会扫描classpath:/、classpath:/config/、file:./、file:./config/这些路径下的配置文件,所以直接设置spring.profiles.active=dev无法自动加载properties目录下的application-dev.properties。你写的两个配置类要么不符合Spring Boot的配置逻辑,要么存在路径/时机问题,所以无效。
最优解决方案(无需自定义配置类)
直接在主配置文件src/main/resources/application.properties中添加spring.config.import配置,指定额外的配置文件路径:
spring.profiles.active=dev # 导入对应环境的配置文件,${spring.profiles.active}会自动替换为激活的环境标识 spring.config.import=classpath:/properties/application-${spring.profiles.active}.properties
如果需要允许激活的环境配置文件不存在(比如本地开发可能没有prod配置),可以加上optional:标记:
spring.config.import=optional:classpath:/properties/application-${spring.profiles.active}.properties
这个方法是Spring Boot 2.4+官方推荐的导入额外配置的方式,能完美适配profile的动态切换,不需要写任何自定义配置类。
现有配置类的问题分析
ActiveProfileConfiguration:继承
AbstractSecurityWebApplicationInitializer完全没必要,这个类是用来初始化Spring Security过滤器链的,不是设置Spring profile的正确入口。而且手动通过ServletContext设置spring.profiles.active的时机晚于Spring Boot加载配置文件的时机,所以无法让主配置文件识别这个profile。DevPropertyReader:
- 硬编码了
EnvironmentProfiles/application-local.properties路径,但你的实际目录是properties,路径不匹配; - 仅针对
localprofile生效,无法适配dev/prod等其他环境; PropertySourcesPlaceholderConfigurer的静态Bean加载时机早于Spring解析spring.profiles.active的时机,导致${spring.profiles.active}无法被正确替换,同时手动配置这个Bean会干扰Spring Boot的自动配置逻辑,可能导致配置加载顺序混乱。
- 硬编码了
验证方法
启动项目后,查看日志中是否有类似如下的记录:
Loaded config file 'classpath:/properties/application-dev.properties'
或者在任意Bean中通过@Value("${your.property.key}")注入一个application-dev.properties中的属性,验证是否能正常获取到值。
内容的提问来源于stack exchange,提问作者Shubham

