SpringBoot自定义配置的正确使用姿势

Springboot中把配置文件的键值读取到程序中的方法有很多,以前常用@Value或者@Envrionment形式去获取,如果参数简便也可以满足需求,但是并不推荐这样的做法,属性装配的时候采用@ConfigurationProperties 配置形式可以实现松散绑定,同时还能在配置注入容器时进行数据校验,功能更为强大灵活。步骤主要三步:

1.引入MAVEN依赖

  • 添加spring-boot-configuration-processor,可以在编译时生成属性元数据(spring-configuration-metadata.json)。
  • 添加lombok,可以方便使用注释处理器的功能省去Pojo定义中get set这些麻烦工作。
    
      org.projectlombok
      lombok
    
    
      org.springframework.boot
      spring-boot-configuration-processor
      true
    

2.属性绑定

定义好Bean类对象与配置的映射关系,比如我这里有一个容器线程池参数配置属性类,可以设定默认值

@Data
@ConfigurationProperties(prefix="excutor")
public class ExcutorProperties {
    private int corePoolSize = 5;
    private int maxPoolSize = 10;
    private int queueCapacity = 64;
}

同时在yml或者properties配置文件中配置相应的键值,松散绑定即可,容器会优先读取配置文件中配置值,覆盖属性上的默认值:

excutor:
  core-pool-size: 6
  max-pool-size: 20
  queueCapacity: 100

3.容器注入

主要有三种方式:

  • 配合@Component注解直接进行注入,这种方式简单直观
@Data
@Component
@ConfigurationProperties(prefix="excutor")
public class ExcutorProperties {
  • 使用@EnableConfigurationProperties,通常配置在标有@Configuration的类上,当然其他@Component注解的派生类也可以,不过不推荐。
  • 使用@Bean方式在标有@Configuration的类进行注入,这种方式通常可以用在对第三方类进行配置属性注册
@Configuration
public class ExcutorConfiguration {
    @Bean
    public ExcutorProperties excutorProperties() {
        return new ExcutorProperties();
    }
}

完成注入以后,即可在Spring容器中使用该配置对象的值。

source: Spring Boot 2.0 @ConfigurationProperties 使用

你可能感兴趣的:(SpringBoot自定义配置的正确使用姿势)