资讯专栏INFORMATION COLUMN

Spring Boot 2.0 @ConfigurationProperties 使用

mating / 1595人阅读

摘要:引言的一个便捷功能是外部化配置,可以轻松访问属性文件中定义的属性。本文将详细介绍的使用。

引言

Spring Boot的一个便捷功能是外部化配置,可以轻松访问属性文件中定义的属性。本文将详细介绍@ConfigurationProperties的使用。

配置项目POM

在pom.xml中定义Spring-Boot 为parent


    org.springframework.boot
    spring-boot-starter-parent
    2.0.4.RELEASE
     
  

添加依赖

添加web,因为我们需要使用到JSR-303规范的Validator,如果不想使用web依赖,也可以直接依赖hibernate-validator

添加spring-boot-configuration-processor,可以在编译时生成属性元数据(spring-configuration-metadata.json).

添加lombok,可以方便使用注释处理器的功能省去Pojo定义中get set这些麻烦工作.

   
      org.springframework.boot
      spring-boot-starter-web
    
    
      
      
      
      
    
    
      org.projectlombok
      lombok
    
    
      org.springframework.boot
      spring-boot-configuration-processor
      true
    
例子编写

首先定义一个DocumentServerProperties对象,下面这个文档服务器配置是我假设的,主要是为了演示属性配置的大部分情况

@Getter
@Setter
public class DocumentServerProperties {

    private String remoteAddress;
    private boolean preferIpAddress;
    private int maxConnections=0;
    private int port;
    private AuthInfo authInfo;
    private List whitelist;
    private Map converter;
    private List defaultShareUsers;

    @Getter
    @Setter
    public static class AuthInfo {

        private String username;
        private String password;
    }
}
绑定属性配置

注意@ConfigurationProperties并没有把当前类注册成为一个Spring的Bean,下面介绍@ConfigurationProperties配置注入的三种方式.

配合@Component注解直接进行注入

@ConfigurationProperties(prefix = "doc")
@Component
public class DocumentServerProperties {
    //代码...
}

使用@EnableConfigurationProperties,通常配置在标有@Configuration的类上,当然其他@Component注解的派生类也可以,不过不推荐.

@ConfigurationProperties(prefix = "doc")
public class DocumentServerProperties {
    //代码...
}
@EnableConfigurationProperties
@Configuration
public class SomeConfiguration {
    private DocumentServerProperties documentServerProperties
       
    public SomeConfiguration(DocumentServerProperties documentServerProperties) {
        this.documentServerProperties = documentServerProperties;
    }

}

使用@Bean方式在标有@Configuration的类进行注入,这种方式通常可以用在对第三方类进行配置属性注册

@Configuration
public class SomeConfiguration {
    
    @Bean
    public DocumentServerProperties documentServerProperties(){
        return new DocumentServerProperties();
    }
    
    @ConfigurationProperties("demo.third")
    @Bean
    public ThirdComponent thirdComponent(){
        return new ThirdComponent();
    }

}
编写配置文件

Spring-Boot中配置文件的格式有properties和yaml两种格式,针对上面的配置对象分别写了两种格式的配置文件例子.

Properties

doc.remote-address=127.0.0.1
doc.port=8080
doc.max-connections=30
doc.prefer-ip-address=true
#doc.whitelist=192.168.0.1,192.168.0.2
# 这种等同于下面的doc.whitelist[0] doc.whitelist[1]
doc.whitelist[0]=192.168.0.1
doc.whitelist[1]=192.168.0.2
doc.default-share-users[0].name=jack
doc.default-share-users[0].age=18
doc.converter.a=xxConverter
doc.converter.b=xxConverter
doc.auth-info.username=user
doc.auth-info.password=password

Yaml

doc:
  remote-address: 127.0.0.1
  port: 8080
  max-connections: 30
  prefer-ip-address: true
  whitelist: 
    - 192.168.0.1
    - 192.168.0.2
  default-share-users: 
    - name: jack
      age: 18
  converter: 
    a: aConverter
    b: bConverter
  auth-info:
    username: user
    password: password

在上面的两个配置文件中,其实已经把我们平常大部分能使用到的属性配置场景都覆盖了,可能还有一些特殊的未介绍到,比如Duration、InetAddress等。

增加属性验证

下面我们利用JSR303规范的实现对DocumentServerProperties属性配置类,添加一些常规验证,比如Null检查、数字校验等操作,

需要注意在Spring-Boot 2.0版本以后,如果使用JSR303对属性配置进行验证必须添加@Validated注解,使用方式如下片段:

@ConfigurationProperties(prefix = "doc")
@Validated
public class DocumentServerProperties {
    @NotNull // 判断不为空的情况
    private String remoteAddress;
    
    //限制端口只能是80-65536之间
    @Min(80)
    @Max(65536)
    private int port;
    //其他代码
}

在有些数情况下,我们希望自定义验证器,有两种方式可以进行实现

实现org.springframework.validation.Validator接口,并且在配置一个Bean名称必须叫configurationPropertiesValidator,代码如下:

public class UserLoginValidator implements Validator {

    private static final int MINIMUM_PASSWORD_LENGTH = 6;

    public boolean supports(Class clazz) {
       return UserLogin.class.isAssignableFrom(clazz);
    }

    public void validate(Object target, Errors errors) {
       ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName", "field.required");
       ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "field.required");
       UserLogin login = (UserLogin) target;
       if (login.getPassword() != null
             && login.getPassword().trim().length() < MINIMUM_PASSWORD_LENGTH) {
          errors.rejectValue("password", "field.min.length",
                new Object[]{Integer.valueOf(MINIMUM_PASSWORD_LENGTH)},
                "The password must be at least [" + MINIMUM_PASSWORD_LENGTH + "] characters in );
       }
    }
}

和上面一样也是实现org.springframework.validation.Validator接口,不过是需要验证的属性配置类本身去实现这个接口

@ConfigurationProperties(prefix = "doc")
public class DocumentServerProperties implements Validator{
    @NotNull
    private String remoteAddress;
    private boolean preferIpAddress;
       //其他属性 
   
    @Override
    public boolean supports(Class clazz) {
        return true;
    }

    @Override
    public void validate(Object target, Errors errors) {
        //判断逻辑其实可以参照上面的代码片段
    }
}

特别注意:

只有在需要使用JSR303规范实现的验证器时,才需要对对象配置@Validated,刚刚上面两种方式并不需要。

第一种实现和第二种实现都是实现org.springframework.validation.Validator接口,但是前者是针对全局的,后者只针对实现这个接口的配置对象

关于上述两点,我为啥确定? 来自ConfigurationPropertiesBinder的源码片段

private List getValidators(Bindable target) {
    List validators = new ArrayList<>(3);
    if (this.configurationPropertiesValidator != null) {
        validators.add(this.configurationPropertiesValidator);
    }
    if (this.jsr303Present && target.getAnnotation(Validated.class) != null) {
            validators.add(getJsr303Validator());
    }
    if (target.getValue() != null && target.getValue().get() instanceof Validator) {
        validators.add((Validator) target.getValue().get());
    }
    return validators;
}
总结

通过上面的例子,我们了解了@ConfigurationProperties的使用以及如何进行验证,包括属性验证器的几种实现方式.下个章节我会从源码的角度分析属性的加载,以及如何解析到Bean里面去的。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72077.html

相关文章

  • 【译】Spring Boot 2.0的属性绑定

    摘要:比如,在中,不能将属性绑定到对象。引入了新的接口,能够指出属性取值的准确位置。比如,属性绑定的验证异常现在会显示类允许你使用多个。我们计划在中继续加强的功能,而第一个想要支持的功能是不可变属性绑定。 Spring Boot2.0的属性绑定 原文从Spring boot第一个版本以来,我们可以使用@ConfigurationProperties注解将属性绑定到对象。也可以指定属性的各种不...

    1treeS 评论0 收藏0
  • Spring Boot 2.0 外部化配置介绍

    摘要:可以使用外部化配置来方便在不同环境的运行同样的程序文件文件环境变量命令行参数内置顺序实现了很多按以下顺序进行合理的相同属性的覆盖目录下的全局设置属性,如果激活测试用例上的注解测试用例上的注解。 简介 在应用中管理配置并不是一个容易的任务,尤其是在应用需要部署到多个环境中时。通常会需要为每个环境提供一个对应的属性文件,用来配置各自的数据库连接信息、服务器信息和第三方服务账号等。通常的应用...

    lmxdawn 评论0 收藏0
  • 记录spring-boot 1.5.9升级至2.0.1的那些坑

    摘要:前两天组里的大佬心血来潮,让我这周把项目里的版本升级到最新版本,目前项目用到的是版本为的版本为现在按照要求统一升级到。三数据库连接池同样也是版本不兼容,需要升级到,亲测有效。差不多这些,后续遇到其他问题还会继续补充。 前两天组里的大佬心血来潮,让我这周把项目里的spring-boot、spring-cloud版本升级到最新版本,目前项目用到的是spring-boot版本为1.5.9.R...

    gitmilk 评论0 收藏0
  • Spring Boot 2.0 配置属性自定义转换

    引言 当我们通过@ConfigurationProperties注解实现配置 bean的时候,如果默认的配置属性转换无法满足我们的需求的时候,我们可以根据自己的需求通过以下扩展方式对配置属性进行转换 PropertyEditorSupport实现 下面的例子是把属性中定义的字符串转换成Movie,并且把name的值大写 继承PropertyEditorSupport并且实现PropertyEdi...

    lingdududu 评论0 收藏0
  • @ConfigurationProperties 注解使用姿势,这一篇就够了

    摘要:在项目中,为满足以上要求,我们将大量的参数配置在或文件中,通过注解,我们可以方便的获取这些参数值使用配置模块假设我们正在搭建一个发送邮件的模块。这使得在不影响其他模块的情况下重构一个模块中的属性变得容易。 在编写项目代码时,我们要求更灵活的配置,更好的模块化整合。在 Spring Boot 项目中,为满足以上要求,我们将大量的参数配置在 application.properties 或...

    SolomonXie 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<