Spring如何处理多属性文件?自定义库@PropertyResource加载YAML属性为null问题
问题根因
你遇到的属性为null是配置未被正常加载导致,而非被覆盖,核心原因有3个:
- 代码注解笔误:Spring 中不存在
@PropertyResource注解,正确的配置文件加载注解是@PropertySource,错误注解不会被Spring识别,自然不会加载对应配置文件。 - 即使修正注解为
@PropertySource,Spring 原生的@PropertySource默认仅支持.properties格式的配置文件解析,不支持YAML格式,直接指定yaml文件不会被解析。 - 如果你没有开启
@EnableConfigurationProperties配置绑定开关,哪怕配置文件加载成功,@ConfigurationProperties的属性绑定逻辑也不会触发,属性依然为null。
修复方案
方案1:调整为properties格式(最稳妥)
将LIB内的配置文件改为library.properties,按properties语法编写配置,修正配置类注解即可:
@Configuration @PropertySource("classpath:library.properties") @ConfigurationProperties(prefix = "com.lib") public class RemotePropertiesConfig { private String someProperty; // getters and setters }
同时在LIB的自动配置类上添加@EnableConfigurationProperties(RemotePropertiesConfig.class),确保绑定逻辑自动触发,不需要引入LIB的应用做额外配置。
方案2:自定义YAML解析工厂适配@PropertySource
如果一定要使用YAML格式配置,需要先实现YAML解析的属性源工厂:
import org.springframework.boot.env.YamlPropertySourceLoader; import org.springframework.core.env.PropertySource; import org.springframework.core.io.support.EncodedResource; import org.springframework.core.io.support.PropertySourceFactory; import java.io.IOException; import java.util.List; public class YamlPropertySourceFactory implements PropertySourceFactory { @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { List<PropertySource<?>> propertySources = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource()); return propertySources.get(0); } }
再修改配置类的@PropertySource注解指定工厂类:
@Configuration @PropertySource(value = "classpath:library.yaml", factory = YamlPropertySourceFactory.class) @ConfigurationProperties(prefix = "com.lib") public class RemotePropertiesConfig { private String someProperty; // getters and setters }
同样需要添加@EnableConfigurationProperties(RemotePropertiesConfig.class)开启绑定。
注意事项
不要依赖配置文件后缀不同避免覆盖的方案,Spring Boot不同版本对application.yml和application.yaml的加载优先级逻辑可能调整,该方案无兼容性保障,生产环境不要使用。
你当前的自定义命名配置文件的思路是正确的,LIB的默认配置和应用的主配置隔离,同时应用可以在自身的application配置中通过相同前缀的属性覆盖LIB的默认值,符合Spring Boot Starter的设计规范。
内容的提问来源于stack exchange,提问作者Robert van der Spek
相关产品推荐
相关产品推荐

