Environment
-
springboot 1.x版本的属性绑定方法。
-
适合简单属性的获取,不适合复杂对象的绑定。
-
方法:
-
# 判断是否包含键值 boolean containsProperty(String key); # 获取属性值,如果获取不到返回null String getProperty(String key); # 获取属性值,如果获取不到返回缺省值 String getProperty(String key, String defaultValue); # 获取属性对象;其转换和Converter有关,会根据sourceType和targetType查找转换器 <T> T getProperty(String key, Class<T> targetType);
Binder
-
Springboot 2.x新引入的类,负责处理对象与多个ConfigurationPropertySource(属性)之间的绑定。
-
比Environment类好用很多,可以非常方便地进行类型转换,以及提供回调方法介入绑定的各个阶段进行深度定制。
-
# 绑定对象 MailPropertiesC propertiesC = Binder.get(environment) //首先要绑定配置器 //再将属性绑定到对象上 .bind( "kaka.cream.mail-c", Bindable.of(MailPropertiesC.class) ).get(); //再获取实例 # 绑定Map Map<String,Object> propMap = Binder.get(environment) .bind( "fish.jdbc.datasource",Bindable.mapOf(String.class, Object.class) ).get(); # 绑定List List<String> list = Binder.get(environment) .bind( "kaka.cream.list",Bindable.listOf(String.class) ).get(); # 转换以及默认值 String datestr = (String) Binder.get(environment) .bind( "kaka.cream.date",Bindable.of(String.class) ) //映射为大写 .map(String::toUpperCase) /** .map(new Function(){ @Override public Object apply(Object o) { String str = (String)o; return str.toUpperCase(); } }) **/ //默认值 .orElse("bad date string"); # 绑定过程回调函数,高度定制 LocalDate str = Binder.get(environment) .bind("kaka.cream.date", Bindable.of(LocalDate.class), new BindHandler() { @Override public <T> Bindable<T> onStart(ConfigurationPropertyName name, Bindable<T> target, BindContext context) { log.info("绑定开始{}",name); return target; } @Override public Object onSuccess(ConfigurationPropertyName name, Bindable<?> target, BindContext context, Object result) { log.info("绑定成功{}",target.getValue()); return result; } @Override public Object onFailure(ConfigurationPropertyName name, Bindable<?> target, BindContext context, Exception error) throws Exception { log.info("绑定失败{}",name); return "没有找到匹配的属性"; } @Override public void onFinish(ConfigurationPropertyName name, Bindable<?> target, BindContext context, Object result) throws Exception { log.info("绑定结束{}",name); } }).get();
使用实例:
# properties自定义配置
custom.datasource.ds1.type=com.zaxxer.hikari.HikariDataSource
custom.datasource.ds1.driverClassName=com.mysql.cj.jdbc.Driver
custom.datasource.ds1.url=jdbc:mysql://192.168.2.14:3306/financial?useUnicode=true&characterEncoding=utf8&useSSL=true
custom.datasource.ds1.username=root
custom.datasource.ds1.password=123456
/**
* 动态数据源注册
* 实现 ImportBeanDefinitionRegistrar 实现数据源注册
* 实现 EnvironmentAware 用于读取application.yml配置
*/
@Component
public class DataSourceConfig implements ImportBeanDefinitionRegistrar, EnvironmentAware {
private void defaultDataSource(Environment environment) {
//Binder Springboot 2.x新引入的类,负责处理对象与多个ConfigurationPropertySource(属性)之间的绑定。
Binder binder = Binder.get(environment);
Map<String, Object> configMap = binder.bind("custom.datasource.ds1", Map.class).get();
System.out.println(configMap);
}
}