1. 程式人生 > >Springboot|第五篇@Value和@ConfigurationProperties獲取值比較

Springboot|第五篇@Value和@ConfigurationProperties獲取值比較

Springboot 是簡化Spring應用開發的建立、執行、除錯、部署等一系列問題的框架是J2EE開發的一站式解決方案,自動裝配的特性可以讓我們更好的關注業務本身而不是外部的XML配置,我們只需遵循規範,引入相關的依賴就可以輕鬆的搭建出一個WEB工程 [如果你覺得對你有幫助,歡迎轉發分享給更多的人學習]

上篇學習了學習Spring Boot的配置檔案的一些基本語法,接下來還是繼續深入學習分析@Value獲取值和@ConfigurationProperties獲取值比較

上篇使用@Component和@ConfigurationProperties(prefix = “person”)就可以將配置檔案中的每個屬性,對映到這個Person類元件中,還有一個屬性@Value可以將配置檔案中的資訊對映注入到Person的屬性中,@Value還可以直接給屬性配置表示式值 @Value("#{10*2}"),而@ConfigurationProperties卻不支援

@Component //@ConfigurationProperties(prefix = “person”) public class Person {

@Value("${person.last-name}")
private String lastName;
@Value("#{10*2}")
private Integer age;
@Value("#{true}")

} 測試結果輸出:

Person{lastName='張三', age=20, boss=true, birth=null, maps=null, lists=null, dog=null}

@ConfigurationProperties支援複雜型別封裝,而@Value不支援,什麼是複雜型別的封裝?之前我們寫的private Mapmaps就是複雜型別封裝,不可以直接使用@Value("#{person.maps}")注入配置檔案的屬性值

@Value不支援JSR303資料校驗,@ConfigurationProperties支援JSR303資料校驗 註解在lastName的@Email的意思是lastName必須是一個合法的電子郵件地址,否則就是不合法值

@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {
    @Email
    private String lastName;
    private Integer age;
    private Boolean boss;
}

報錯情況:

Property: person.lastName
Value: 張三
Origin: class path resource [application.properties]:2:18
Reason: 不是一個合法的電子郵件地址

而使用@Value配置注入卻不會報錯

@Component
@Validated
public class Person {
   @Value("${person.last-name}")
    private String lastName;
    private Integer age;
    private Boolean boss;

程式的輸出結果:

Person{lastName='張三', age=null, boss=null, birth=null, maps=null, lists=null, dog=null}

配置檔案yml還是properties他們都能獲取到值,什麼時候使用@Value什麼時候使用@ConfigurationProperties; 如果說,我們專門編寫了一個javaBean來和配置檔案進行對映,我們就直接使用@ConfigurationProperties; 如果說,我們只是在某個業務邏輯中需要獲取一下配置檔案中的某項值,使用@Value;

從配置檔案中獲取一個name來sayhello

@RestController
public class HelloController {
    @Value("${person.last-name}")
    private String name;
    @RequestMapping(value = "/sayhello")
    public String sayhello(){
        return "Hello,"+name+"";
    }
}

瀏覽器訪問: 在這裡插入圖片描述

說點什麼

QQ學習交流群:277300227 微信公眾號(歡迎關注):SeptemberNotes 在這裡插入圖片描述