SpringBoot加载配置-springboot加载配置

1. 作用

  • SpringBoot在底层给我们自动做了一些配置,所以springboot项目不编写配置文件也可以正常运行,但是根据我们的具体开发我们需要修改SpringBoot自动配置的默认值;

2. 配置文件加载

  • SpringBoot启动时会按如下优先级加载配置文件
    bootstrap.properties > bootstrap.yml > application.properties > application.yml
  • 如果配置了 spring.profiles 同时会加载对应的 application-{profile}.properties或 application-{profile}.yml
  • profile为对应的环境变量,比如 dev,如果没有配置,则会加载 profile=default 配置文件。

3. 准备

  • 使用@ConfigurationProperties如要引入如下坐标
  • maven
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
        </dependency>
  • gradle
implementation "org.springframework.boot:spring-boot-starter-processor"
  • 以下面的配置项为例介绍配置
    top.shellfish.ip=192.168.0.1
    top.shellfish.domain=shellfish

4. @Value注解获取配置信息

  • 这种方式最快捷,当你仅需要配置文件中的一个字段,可采用。
@Value("${top.shellfish.domain}")
private String domain;

5. @ConfigurationProperties获取配置信息

  • 定义一个类接受配置信息,@ConfigurationProperties用来绑定类的成员变量和配置文件中的配置项,prefix为配置项前缀,加载配置格式为 ${prefix}.field,下面将 top.shellfish.ip 配置项注入到 ip 成员变量。
  • @EnableConfigurationProperties使使用 @ConfigurationProperties 注解的类生效。作用是将ShellFishProperties注入ioc,所以这里的@EnableConfigurationProperties也可以换成@Component注解。
  • @EnableConfigurationProperties(ShellFishProperties.class)属性可以在别的类上将ShellFishProperties注入ioc(一般会采取这种方法)
@Data
@ConfigurationProperties(prefix = "top.shellfish")
@EnableConfigurationProperties
public class ShellFishProperties {
    /**
     * ip地址
     */
    private String ip;
    /**
     * 域名
     */
    private String domain;
}
  • 如果你有多个配置文件,也可以通过在类上声明 @PropertySource 注解,表明你要从哪个配置文件中注入配置项。
@PropertySource(value = "classpath:xxx.properties",encoding="utf-8")

6. 通过Environment配置信息

  • springboot 1.x版本的属性绑定方法。
  • Environment默认会被注入到ioc容器
  • Environment适合简单属性的获取,不适合复杂对象的绑定
environment.getProperty("top.shellfish.domain")

7. 通过Binder获取配置信息

  • Springboot 2.x新引入的类,负责处理对象与多个配置项之间的绑定。
  • 比Environment类更加强大,可以非常方便地进行类型转换,以及提供回调方法介入绑定的各个阶段进行深度定制。
  • 定义一个对象接受配置信息
@Data
public class ShellFishProperties {
    /**
     * ip地址
     */
    private String ip;
    /**
     * 域名
     */
    private String domain;
}
  • 通过Binder将配置注入到ShellFishProperties
    void test(Environment environment){
        ShellFishProperties shellFishProperties = Binder.get(environment).bind("top.shellfish", Bindable.of(ShellFishProperties.class)).get();
        System.out.println(shellFishProperties);
    }
  • Binder还能绑定各种复杂的类型,类型转换,回调函数等。
  //绑定对象
  MailPropertiesC propertiesC = Binder.get(environment) //首先要绑定配置器
      //再将属性绑定到对象上
      .bind("top.shellfish", Bindable.of(ShellFishProperties.class)).get(); //再获取实例
      
  //绑定Map
  Map<String,Object> propMap = Binder.get(environment)
      .bind( "top.shellfish",Bindable.mapOf(String.class, Object.class)).get();
      
  //绑定List
  List<String> list = Binder.get(environment)
      .bind( "top.shellfish",Bindable.listOf(String.class) ).get();
      
  //转换以及默认值
  String datestr = (String) Binder.get(environment)
      .bind( "top.shellfish",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("top.shellfish", 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();
posted @ 2023-06-20 20:11  Shellfish  阅读(867)  评论(0)    收藏  举报