SpringBoot属性绑定Environment和Binder

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);
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值