博客详情

springboot中引入自定义的yml文件注入bean (原创)

作者: 朝如青丝暮成雪
发布时间:2018-08-27 23:53:57  文章分类:springboot   阅读(2878)  评论(0)

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



关键字:  springboot  yml
评论信息
暂无评论
发表评论

亲,您还没有登陆,暂不能评论哦! 去 登陆 | 注册

博主信息
   
数据加载中,请稍候...
文章分类
   
数据加载中,请稍候...
阅读排行
 
数据加载中,请稍候...
评论排行
 
数据加载中,请稍候...

Copyright © 叮叮声的奶酪 版权所有
备案号:鄂ICP备17018671号-1

鄂公网安备 42011102000739号