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

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


import java.io.IOException;

import org.springframework.boot.env.PropertySourcesLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.util.StringUtils;

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 。。

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值