使 @PropertySource 注解同时支持 yml yaml 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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值