使 @PropertySource 注解同时支持 yml yaml properties, 以及配置文件加载范例

本文介绍了如何在Spring Boot应用中自定义PropertySource工厂,以支持YAML格式的配置文件,并展示了如何使用@PropertySource和@ConfigurationProperties注解加载user.yaml和user.properties。

此文关于 yml 部分参考了此文:@PropertySource加载yml

1.首先写一个 ConfigurationFactory 类,作为 配置属性源工厂

public class ConfigurationFactory extends DefaultPropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource)
            throws IOException {

        // 指定配置路径中的文件名
        String filename = resource.getResource().getFilename() == null ?
                "" : resource.getResource().getFilename();

        // 资源为空,则会抛出异常
        resource.getInputStream();

        // 配置文件为 properties 文件,调用原逻辑
        if ( resource == null
                || filename.endsWith(".properties"))
            return super.createPropertySource( name, resource);

        // yml文件 或 yaml文件,则使用yaml属性源加载器加载并返回标准属性源
        else if ( filename.endsWith(".yml")
                || filename.endsWith(".yaml"))
            return new YamlPropertySourceLoader()
                    .load( resource.getResource().getFilename(), resource.getResource()).get(0);

        // 非以上情况,则直接抛出异常,提示格式错误
        else
            throw new IOException("file format error! only support: properties, yml, yaml!");
    }
}

2.在 接收配置的bean 上加注解(此处业务需要,用的Hashtable,接收类型只要是实现了Map接口即可):

/**
 * 配置结构类
 */
// factory 指定刚才写的 ConfigurationFactory.class
@PropertySource(value = {"classpath:user.yml", "classpath:user.yaml", "classpath:user.properties"}, encoding = "utf-8", factory = ConfigurationFactory.class)
@ConfigurationProperties(prefix = "user")
@Component
class UserConfig implements Cloneable {

	private Hashtable<String,String> person;

	public Hashtable<String, String> getPerson() {
		return person;
	}

	public void setPerson(Hashtable<String, String> person) {
		this.person = person;
	}
}

3.最后在 resources 中,加入配置文件,文件名为 user.yaml

user:
  person:
    AAA: 1
    BBB: 2

resources 中,加入配置文件,文件名为 user.properties

user.person.AAA=1
user.person.BBB=2

测试程序就不写了,大家请自行测试。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值