通过@PropertySource和@ConfigurationProperties来加载(读取)自定义配置文件

在项目中,习惯用YAML来写配置文件,但读取自定义配置文件时,遇到了问题:

编写两个配置文件:

1. temp.yml

prefix:
  what: x
  list:
    - name: tech
      item: 123
    - name: skill
      item: 987

2. temp.properties

prefix.what = x
prefix.list[0].name = a
prefix.list[0].item = 11
prefix.list[1].name = b
prefix.list[1].item = 12

编写配置类:

@PropertySource(value = "file:src/main/resources/config/temp.yml")
@ConfigurationProperties(prefix = "prefix", ignoreUnknownFields = false)
@Configuration
public class TempConfiguration {

	private String what;
	private List<Map<String, String>> list = new ArrayList<>();

	public String getWhat() {
		return what;
	}

	public void setWhat(String what) {
		this.what = what;
	}

	public List<Map<String, String>> getList() {
		return list;
	}

	public void setList(List<Map<String, String>> list) {
		this.list = list;
	}

}

这时是有问题的,what和list其实都并没有加载进去。验证:

@RequestMapping(path = "test")
@RestController
public class TempRestController {
    @Autowired
	TempConfiguration tempConfiguration;
	
	@PostMapping(path = "binder")
	public MyResponse binder() {
		MyResponse response = new MyResponse();
		System.out.println(tempConfiguration.getWhat());
		for (Map<String, String> map : tempConfiguration.getList()) {
			for (String key : map.keySet()) {
				System.out.println(key + " " + map.get(key));
			}
		}
		return response;
	}
}

将TempConfiguration.java中的temp.yml改成temp.properties,就可以,属性都能加载进去。

参考:

24.7.4 YAML Shortcomings

YAML files cannot be loaded by using the @PropertySource annotation. So, in the case that you need to load values that way, you need to use a properties file.

@PropertySource不支持YAML文件。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值