springboot中引入自定义的yml文件注入bean

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jasnet_u/article/details/82121018

如题,我们知道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 @Valueannotation 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")

扫描二维码关注公众号,回复: 3277790 查看本文章

ok 。。

猜你喜欢

转载自blog.csdn.net/jasnet_u/article/details/82121018