最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring Boot2.0 @ConfigurationProperties使用詳解

 更新時(shí)間:2018年11月08日 11:20:09   作者:paderlol  
這篇文章主要介紹了Spring Boot2.0 @ConfigurationProperties使用詳解,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

引言

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

配置項(xiàng)目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,因?yàn)槲覀冃枰褂玫絁SR-303規(guī)范的Validator,如果不想使用web依賴,也可以直接依賴hibernate-validator
  2. 添加spring-boot-configuration-processor,可以在編譯時(shí)生成屬性元數(shù)據(jù)(spring-configuration-metadata.json).
  3. 添加lombok,可以方便使用注釋處理器的功能省去Pojo定義中g(shù)et 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>

例子編寫

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

@Getter
@Setter
public 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并沒有把當(dāng)前類注冊(cè)成為一個(gè)Spring的Bean,下面介紹@ConfigurationProperties配置注入的三種方式.

配合@Component注解直接進(jìn)行注入

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

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

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

@EnableConfigurationProperties
@Configuration
public class SomeConfiguration {
  private DocumentServerProperties documentServerProperties
    
  public SomeConfiguration(DocumentServerProperties documentServerProperties) {
    this.documentServerProperties = documentServerProperties;
  }

}

使用@Bean方式在標(biāo)有@Configuration的類進(jìn)行注入,這種方式通??梢杂迷趯?duì)第三方類進(jìn)行配置屬性注冊(cè)

@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兩種格式,針對(duì)上面的配置對(duì)象分別寫了兩種格式的配置文件例子.

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

在上面的兩個(gè)配置文件中,其實(shí)已經(jīng)把我們平常大部分能使用到的屬性配置場(chǎng)景都覆蓋了,可能還有一些特殊的未介紹到,比如Duration、InetAddress等。

增加屬性驗(yàn)證

下面我們利用JSR303規(guī)范的實(shí)現(xiàn)對(duì)DocumentServerProperties屬性配置類,添加一些常規(guī)驗(yàn)證,比如Null檢查、數(shù)字校驗(yàn)等操作,

需要注意在Spring-Boot 2.0版本以后,如果使用JSR303對(duì)屬性配置進(jìn)行驗(yàn)證必須添加@Validated注解,使用方式如下片段:

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

在有些數(shù)情況下,我們希望自定義驗(yàn)證器,有兩種方式可以進(jìn)行實(shí)現(xiàn)

實(shí)現(xiàn)org.springframework.validation.Validator接口,并且在配置一個(gè)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 );
    }
  }
}

和上面一樣也是實(shí)現(xiàn)org.springframework.validation.Validator接口,不過是需要驗(yàn)證的屬性配置類本身去實(shí)現(xiàn)這個(gè)接口

@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) {
    //判斷邏輯其實(shí)可以參照上面的代碼片段
  }
}

特別注意:

  • 只有在需要使用JSR303規(guī)范實(shí)現(xiàn)的驗(yàn)證器時(shí),才需要對(duì)對(duì)象配置@Validated,剛剛上面兩種方式并不需要。
  • 第一種實(shí)現(xiàn)和第二種實(shí)現(xiàn)都是實(shí)現(xiàn)org.springframework.validation.Validator接口,但是前者是針對(duì)全局的,后者只針對(duì)實(shí)現(xiàn)這個(gè)接口的配置對(duì)象

關(guān)于上述兩點(diǎn),我為啥確定? 來自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;
}

總結(jié)

通過上面的例子,我們了解了@ConfigurationProperties的使用以及如何進(jìn)行驗(yàn)證,包括屬性驗(yàn)證器的幾種實(shí)現(xiàn)方式.下個(gè)章節(jié)我會(huì)從源碼的角度分析屬性的加載,以及如何解析到Bean里面去的。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Spring常見的事務(wù)失效場(chǎng)景及解決方案

    Spring常見的事務(wù)失效場(chǎng)景及解決方案

    Spring 事務(wù)管理是企業(yè)級(jí)應(yīng)用開發(fā)中不可或缺的一部分,它可以幫助我們確保數(shù)據(jù)的一致性和完整性,然而,在實(shí)際開發(fā)中,由于各種原因,事務(wù)可能會(huì)失效,本文將詳細(xì)介紹 Spring 事務(wù)失效的常見情況,并提供相應(yīng)的解決方案和示例代碼,需要的朋友可以參考下
    2024-11-11
  • Java求解二叉樹的最近公共祖先實(shí)例代碼

    Java求解二叉樹的最近公共祖先實(shí)例代碼

    樹是一種非線性的數(shù)據(jù)結(jié)構(gòu),它是由n(n>=0)個(gè)有限結(jié)點(diǎn)組成一個(gè)具有層次關(guān)系的集合,這篇文章主要給大家介紹了關(guān)于Java求解二叉樹的最近公共祖先的相關(guān)資料,需要的朋友可以參考下
    2021-06-06
  • Mybatis Properties 配置優(yōu)先級(jí)詳解

    Mybatis Properties 配置優(yōu)先級(jí)詳解

    這篇文章主要介紹了Mybatis Properties 配置優(yōu)先級(jí),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • SpringCloud中的灰度路由使用詳解

    SpringCloud中的灰度路由使用詳解

    這篇文章主要介紹了SpringCloud中的灰度路由使用詳解,在微服務(wù)中,?通常為了高可用,?同一個(gè)服務(wù)往往采用集群方式部署,?即同時(shí)存在幾個(gè)相同的服務(wù),而灰度的核心就?是路由,?通過我們特定的策略去調(diào)用目標(biāo)服務(wù)線路,需要的朋友可以參考下
    2023-08-08
  • Java List集合去重的多種實(shí)現(xiàn)方法

    Java List集合去重的多種實(shí)現(xiàn)方法

    Java中List集合去重的多種方法,包括使用循環(huán)、HashSet、保持順序去重、contain方法去重等,注意在刪除元素時(shí),直接操作會(huì)導(dǎo)致ConcurrentModificationException,應(yīng)使用傳統(tǒng)for循環(huán)或倒序刪除
    2025-02-02
  • Java編碼算法與哈希算法深入分析使用方法

    Java編碼算法與哈希算法深入分析使用方法

    首先,我們一起來學(xué)習(xí)一下編碼算法,舉例說明,ASCII碼就是我們常見的一種編碼,字母a的編碼是十六進(jìn)制的0x61,字母b是0x62,以此類推。哈希算法,可被稱為摘要算法。因此,哈希算法的加密是單向的,不可用密文解密得到明文
    2022-11-11
  • MyBatis中動(dòng)態(tài)sql的實(shí)現(xiàn)方法示例

    MyBatis中動(dòng)態(tài)sql的實(shí)現(xiàn)方法示例

    這篇文章主要給大家介紹了關(guān)于MyBatis中動(dòng)態(tài)sql的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-11-11
  • 用Java實(shí)現(xiàn)一個(gè)簡(jiǎn)單的布隆過濾器

    用Java實(shí)現(xiàn)一個(gè)簡(jiǎn)單的布隆過濾器

    這篇文章主要介紹了用Java實(shí)現(xiàn)一個(gè)簡(jiǎn)單的布隆過濾器,布隆過濾器是1970年由布隆提出的,它實(shí)際上是一個(gè)很長(zhǎng)的二進(jìn)制向量和一系列隨機(jī)映射函數(shù),布隆過濾器可以用于檢索一個(gè)元素是否在一個(gè)集合中,需要的朋友可以參考下
    2023-12-12
  • 淺談在頁(yè)面中獲取到ModelAndView綁定的值方法

    淺談在頁(yè)面中獲取到ModelAndView綁定的值方法

    下面小編就為大家分享一篇淺談在頁(yè)面中獲取到ModelAndView綁定的值方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-03-03
  • springboot整合flowable框架入門步驟

    springboot整合flowable框架入門步驟

    最近工作中有用到工作流的開發(fā),引入了flowable工作流框架,在此記錄一下springboot整合flowable工作流框架的過程,感興趣的朋友一起看看吧
    2022-04-04

最新評(píng)論

平定县| 和平区| 安多县| 阿拉尔市| 麟游县| 灵寿县| 万宁市| 盐源县| 武强县| 乐昌市| 宜宾县| 车险| 定襄县| 清流县| 丰都县| 三明市| 拉孜县| 西林县| 上虞市| 定陶县| 永昌县| 湖南省| 柳州市| 汉阴县| 青铜峡市| 五家渠市| 出国| 青铜峡市| 镇雄县| 米脂县| 江津市| 浦城县| 句容市| 尉犁县| 富平县| 封丘县| 临颍县| 板桥市| 海阳市| 江达县| 交口县|