SpringBoot使用@PropertySource加载自定义YAML配置读取属性报错求解
问题根因
Spring 原生@PropertySource注解默认仅支持.properties、.xml格式的配置文件解析,不内置YAML格式的解析能力。你将配置内容改为properties键值对格式后可以正常运行,也完全印证了这个结论:YAML格式的文件被加载后无法被默认解析器识别为可注入的属性键值对,因此抛出Could not resolve placeholder 'app.message'的异常。
解决方案
你可以根据项目场景选择以下任意一种方案解决:
方案一(Spring Boot项目优先选择)
将你的YAML配置文件重命名为application.yml,放到项目src/main/resources目录或者${user.dir}/config/目录下,Spring Boot会自动加载该配置文件,不需要额外添加@PropertySource注解即可直接读取app.message属性。方案二(保留自定义YAML文件名+
@PropertySource加载)
自定义YAML配置解析工厂类,手动指定@PropertySource使用该工厂解析YAML文件:- 新增YAML解析工厂类:
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; import org.springframework.core.env.PropertiesPropertySource; import org.springframework.core.env.PropertySource; import org.springframework.core.io.support.DefaultPropertySourceFactory; import org.springframework.core.io.support.EncodedResource; import java.io.IOException; import java.util.Properties; public class YamlPropertySourceFactory extends DefaultPropertySourceFactory { @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); } }- 修改控制器类的
@PropertySource注解,指定解析工厂:
@PropertySource(value = "file:${user.dir}/config/webappdemo.yml", factory = YamlPropertySourceFactory.class)
注意事项
YAML配置对缩进要求严格,禁止使用Tab缩进,统一使用2/4个空格缩进即可,你当前的YAML配置缩进格式符合要求,不需要调整。
内容的提问来源于stack exchange,提问作者SRI HARSHA S V
相关产品推荐
相关产品推荐

