如题,我们知道springboot中@PropertySource注解只能引入properties配置文件,而不能引入yml配置文件。
The YamlPropertySourceLoader
class can be used to expose YAML as a PropertySource
in the Spring Environment
. This allows you to use the familiar @Value
annotation with placeholders syntax to access YAML properties.
(出自官网文档 https://docs.spring.io/spring-boot/docs/1.5.6.RELEASE/reference/htmlsingle/#boot-features-external-config-exposing-yaml-to-spring)
那么问题来了,如果我们想在springboot项目中采用yml格式配置一个自定义的配置文件,然后将配置信息注入一个自定义的bean中,该怎么办呢?
github上有人提出了这样的疑问,并有人作出了解答:
https://github.com/spring-projects/spring-boot/issues/6726
具体解决的办法如下:
1 创建自定义的YamlPropertySourceFactory继承PropertySourceFactory,重写createPropertySource方法。
2 在@PropertySource注解中设置factory属性,值为自定义的YamlPropertySourceFactory类
这样就可以使用PropertySource注解注入yml配置文件了。
YamlPropertySourceFactory .java
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
return name != null ? new PropertySourcesLoader().load(resource.getResource(), name, null) : new PropertySourcesLoader().load(
resource.getResource(), getNameForResource(resource.getResource()), null);
}
private static String getNameForResource(Resource resource) {
String name = resource.getDescription();
if (!StringUtils.hasText(name)) {
name = resource.getClass().getSimpleName() + "@" + System.identityHashCode(resource);
}
return name;
}
}
你的配置类:
@Component
@PropertySource(value = "classpath:someyml.yml", factory = YamlPropertySourceFactory.class)
@ConfigurationProperties("prefix")
ok 。。