··近期因为公司有个需求做配置文件加解密,参数加解密可以直接用jasyp来做,但是键的加密需要自己完成,最一开始是新建一个固定配置文件来存储新旧键值比如(abc=username);这样其他配置文件的usename都要改成abc,使用的方法是实现Springapplicationrunlistener,在contexloaded阶段获取全局环境变量Environment读取所有配置文件列表,循环读取文件中的键值对去比较固定配置文件中的键值对去修改键,然后再放回去做更改;
··后来领导说度固定配置文件太死了,需要放到所有spring可加载的配置文件中去读取,这时候因为不再固定文件所以需要自定义一个前缀去读取,但是因为可配置所以是一个集合类似于
properties中的配置
test.test.model[0].key
test.test.model[0].value
test.test.model[1].key
test.test.model[1].value
yml中的话是:
test:
test:
model:
- key: abc
value: username
- key: dfg
value: password
//这时候通过env读取properties 获取到的属性都会是
//test.test.model[0].key
//test.test.model[0].value
//test.test.model[1].key
//test.test.model[1].value
//这种形式 需要自己转换成model对象集合的话比较费劲
//model对象
public class Model{
private String key;
private string value;
}
我有尝试过使用:
@ConfigurationProperties(prefix="test.test")
public class test{
public List<model> models;
}
注解来用spring自动注入属性但是没生效,获取到的models在进入到我这个阶段断点的时候是null,但是在容器启动起来之后就会有值,因为对底层没太深研究所以猜测是因为在contextLoaded阶段spring还无法进行属性配置,所以我只能手动匹配到model对象上去;
所以我去寻找解决办法,找了好久找到了这个Binder的类;
他可以绑定配置文件属性到对象、集合、map上去;
废话不多说上代码:
获取env
private final ConfigurableEnviroment environment;
//获取binder对象
Binder binder=Binder.get(environment);
//把配置文件中的某个属性绑定到对应对象上例如:
//spring.datasource.url
//spring.datasource.username
//spring.datasource.password
//就会把这三个属性绑定到datasource对象的三个属性上
Datasource datasoure=binder.bind("spring.datasource",Datasource.class).get();
//test.test.model[0].id
//test.test.model[0].name
//test.test.model[1].id
//test.test.model[1].name
//model的数组对象转换为list集合对象
List<model> models=binder.bind( "test.test.model",Bindable.listOf(Model.class) ).get();
//把配置文件中的某个对象转为map键值对类似于对象
//spring.datasource.url
//spring.datasource.username
//spring.datasource.password
//就会把这三个属性换为map的键值对
Map<String,Object> propMap=binder.bind("spring.datasource",Bindable.mapOf(String.class, Object.class).get();
很方便,不需要自己苦哈哈的处理test.test.model[0].id这种数据。
希望对你们有帮助,我自己也做个记录。