国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > Java > 正文

Spring Boot2.0 @ConfigurationProperties使用詳解

2024-07-14 08:42:47
字體:
來源:轉載
供稿:網友

引言

Spring Boot的一個便捷功能是外部化配置,可以輕松訪問屬性文件中定義的屬性。本文將詳細介紹@ConfigurationProperties的使用。

配置項目POM

在pom.xml中定義Spring-Boot 為parent

<parent>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-parent</artifactId>  <version>2.0.4.RELEASE</version>  <relativePath/> <!-- lookup parent from repository --> </parent>

添加依賴

  1. 添加web,因為我們需要使用到JSR-303規范的Validator,如果不想使用web依賴,也可以直接依賴hibernate-validator
  2. 添加spring-boot-configuration-processor,可以在編譯時生成屬性元數據(spring-configuration-metadata.json).
  3. 添加lombok,可以方便使用注釋處理器的功能省去Pojo定義中get set這些麻煩工作.
  <dependency>   <groupId>org.springframework.boot</groupId>   <artifactId>spring-boot-starter-web</artifactId>  </dependency>  <!--<dependency>-->   <!--<groupId>org.hibernate.validator</groupId>-->   <!--<artifactId>hibernate-validator</artifactId>-->   <!--<version>6.0.11.Final</version>-->   <!--<scope>compile</scope>-->  <!--</dependency>-->  <dependency>   <groupId>org.projectlombok</groupId>   <artifactId>lombok</artifactId>  </dependency>  <dependency>   <groupId>org.springframework.boot</groupId>   <artifactId>spring-boot-configuration-processor</artifactId>   <optional>true</optional>  </dependency>

例子編寫

首先定義一個DocumentServerProperties對象,下面這個文檔服務器配置是我假設的,主要是為了演示屬性配置的大部分情況

@Getter@Setterpublic class DocumentServerProperties {  private String remoteAddress;  private boolean preferIpAddress;  private int maxConnections=0;  private int port;  private AuthInfo authInfo;  private List<String> whitelist;  private Map<String,String> converter;  private List<Person> defaultShareUsers;  @Getter  @Setter  public static class AuthInfo {    private String username;    private String password;  }}

綁定屬性配置

注意@ConfigurationProperties并沒有把當前類注冊成為一個Spring的Bean,下面介紹@ConfigurationProperties配置注入的三種方式.

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

@ConfigurationProperties(prefix = "doc")@Componentpublic class DocumentServerProperties {  //代碼...}

使用@EnableConfigurationProperties,通常配置在標有@Configuration的類上,當然其他@Component注解的派生類也可以,不過不推薦.

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

使用@Bean方式在標有@Configuration的類進行注入,這種方式通常可以用在對第三方類進行配置屬性注冊

@Configurationpublic 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.1doc.port=8080doc.max-connections=30doc.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.1doc.whitelist[1]=192.168.0.2doc.default-share-users[0].name=jackdoc.default-share-users[0].age=18doc.converter.a=xxConverterdoc.converter.b=xxConverterdoc.auth-info.username=userdoc.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")@Validatedpublic 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<Validator> getValidators(Bindable<?> target) {  List<Validator> 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里面去的。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到JAVA教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 乐陵市| 伽师县| 临颍县| 广安市| 莆田市| 积石山| 海丰县| 曲松县| 上栗县| 肥东县| 罗城| 固镇县| 蓬溪县| 郎溪县| 曲水县| 通化县| 琼海市| 嘉定区| 禹州市| 新化县| 合川市| 定边县| 阿瓦提县| 红桥区| 买车| 富民县| 白山市| 双峰县| 滦平县| 望谟县| 安仁县| 洮南市| 理塘县| 三都| 南昌县| 深圳市| 许昌县| 黑河市| 江永县| 镇江市| 福海县|