Spring Boot 2升级后无法加载子文件夹内的配置文件问题排查
Spring Boot 2多模块配置文件读取问题解决指南
关键问题定位
Spring Boot 2对配置文件加载规则做了调整,默认仅扫描类路径根目录、config/子目录,且profile名称大小写敏感。你的情况大概率是两个问题叠加:配置文件放在非默认扫描的子文件夹,且profile文件名大小写与激活的dev不匹配(你用的是application-DEV.yml大写)。
分步解决方案
1. 修正Profile文件名大小写
日志显示激活的是dev,将application-DEV.yml重命名为application-dev.yml——Spring Boot会严格匹配profile名称的大小写,大写的DEV无法被devprofile激活,这是最可能解决问题的第一步。
2. 指定额外配置文件扫描路径
如果需要保留子文件夹存放配置,可通过以下方式让Spring Boot识别:
- 启动参数方式(推荐):在IDE启动参数或命令行中添加:
比如你的配置在--spring.config.additional-location=classpath:/你的子文件夹名称/properties/下,就加--spring.config.additional-location=classpath:/properties/。 - 代码注解方式:在启动类添加
@PropertySource支持YAML文件(需自定义工厂类):
配套的YAML解析工厂类:@EnableAsync @EnableFeignClients @SpringBootApplication @PropertySource(value = "classpath:/properties/application-${spring.profiles.active}.yml", factory = YamlPropertySourceFactory.class) public class IgipDealingApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(IgipDealingApplication.class, args); } }import org.springframework.core.env.PropertySource; import org.springframework.core.io.support.EncodedResource; import org.springframework.core.io.support.PropertySourceFactory; import org.springframework.boot.env.YamlPropertiesFactoryBean; import java.util.Properties; public class YamlPropertySourceFactory implements PropertySourceFactory { @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) { YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(resource.getResource()); Properties props = factory.getObject(); return new PropertiesPropertySource(name != null ? name : resource.getResource().getFilename(), props); } }
3. 调整目录结构到默认扫描路径
将配置文件移至Spring Boot默认扫描的路径:
- 类路径根目录(
src/main/resources/) - 类路径下的
config/子目录(src/main/resources/config/)
4. 验证模块依赖与资源打包
确认war模块已正确依赖resource模块,且resource模块的子文件夹在打包时被包含到classpath中。可解压war包检查WEB-INF/classes/下是否存在配置文件所在的子文件夹。
内容的提问来源于stack exchange,提问作者Nanor
相关产品推荐
相关产品推荐

