SpringBoot多模块Maven项目无法读取application.yml配置报错如何解决
问题原因分析
@PropertySource注解原生仅支持properties格式配置文件的加载,默认不支持yml/yaml格式,即使文件存在也无法正确解析配置项- 多模块项目中配置文件路径不匹配:SpringBoot默认仅加载启动模块
src/main/resources路径下的application.yml,若配置文件放在普通业务子模块且未配置资源打包,编译后不会被打入classes目录,会触发文件不存在报错 - 未验证yml配置格式正确性:yml严格要求层级缩进,若keycloak相关配置缩进错误,也会导致配置项无法被识别
解决方案
步骤1:移除冗余注解
首先删除KeyCloakServiceImpl类上的@PropertySource(value = "classpath:application.yml")注解,SpringBoot默认会自动加载classpath根路径下的application.yml,无需手动指定。
步骤2:修正配置文件存放与打包规则
- 优先将application.yml放在启动模块的
src/main/resources路径下 - 若需要将公共配置放在公共子模块,需在公共子模块的
pom.xml中添加资源打包配置,确保配置文件编译后被输出到classes目录:
<build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.yml</include> <include>**/*.yaml</include> <include>**/*.properties</include> </includes> <filtering>true</filtering> </resource> </resources> </build>
- 确认启动类的扫描范围覆盖服务类所在包:若启动类与服务类不在同一个父包下,需在启动类上添加
@ComponentScan(basePackages = "服务类所在包前缀")配置。
步骤3:校验yml配置格式
确认application.yml中keycloak配置层级缩进正确,禁止使用tab缩进,必须使用空格,示例正确格式:
keycloak: realm: 实际的realm名称 # 其余keycloak相关配置保持同层级缩进
步骤4:(可选)自定义yml加载逻辑
若确实需要使用@PropertySource加载指定yml配置文件,需自行实现yml解析工厂类,修改注解配置如下:
@PropertySource(value = "classpath:application.yml", factory = YamlPropertySourceFactory.class)
对应工厂类实现代码:
import org.springframework.core.env.PropertiesPropertySource; import org.springframework.core.env.PropertySource; import org.springframework.core.io.support.EncodedResource; import org.springframework.core.io.support.PropertySourceFactory; import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; import java.io.IOException; import java.util.Properties; public class YamlPropertySourceFactory implements PropertySourceFactory { @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(resource.getResource()); Properties properties = factory.getObject(); return new PropertiesPropertySource(resource.getResource().getFilename(), properties); } }
步骤5:验证编译结果
执行mvn compile命令后,检查对应模块的target/classes目录下是否存在application.yml文件,若不存在则重新检查maven资源打包配置。
内容的提问来源于stack exchange,提问作者user9347049
相关产品推荐
相关产品推荐

