[英]Spring boot. The profit of using @ConfigurationProperties annotation
你能解釋一下使用@ConfigurationProperties 注釋的好處嗎?
我必須選擇我的代碼。
首先使用 @ConfigurationProperties 注釋:
@Service
@ConfigurationProperties(prefix="myApp")
public class myService() {
private int myProperty;
public vois setMyProperty(int myProperty) {
this.myProperty = myProperty;
}
// And this I can use myProperty which was injected from application.properties (myApp.myProperty = 10)
}
第二個沒有@ConfigurationProperties 注釋。
它看起來像這樣:
@Service
public class myService() {
private final Environment environment;
public myService(Environment environment) {
this.environment = environment;
}
// And this I can use myProperty which was injected from application.properties (myApp.myProperty = 10)
environment.getProperty("myApp.myProperty")
}
使用一個屬性,代碼量看起來是一樣的,但如果我有大約 10 個屬性,第一個選項將有更多的代碼樣板(為此屬性定義 10 個屬性和 10 個設置器)。
第二個選項將注入一次 Environment 並且不添加樣板代碼。
@ConfigurationProperties
用於 map 屬性文件中的一組屬性 Class 屬性。 使用@ConfigurationProperties
使您的代碼更具可讀性、分類/模塊化和更清晰。 如何?
您將應用程序屬性映射到 POJO bean 並確保可重用性。
您正在使用帶有抽象的 spring bean(屬性會自動注入)。
現在,如果您使用Environment
bean,您將始終必須調用getProperty
然后指定屬性的字符串名稱,因此需要大量樣板代碼。 此外,如果您必須重構某些屬性並重命名它,則必須在所有使用它的地方進行。
因此,我的建議是當您必須對屬性進行分組並在多個地方重用@ConfigurationProperties
時,@ConfigurationProperties。 如果您必須在整個應用程序中使用一個或兩個屬性並且僅在一個位置使用,則可以使用 Environment。
@ConfigurationProperties是外部化配置的注解。 要將屬性文件中的屬性值注入 class,我們可以在 class 級別添加@ConfigurationProperties
使用ConfigurationProperties
時,您無需記住屬性名稱即可檢索它。 Spring 負責映射。 例如:
屬性中app.properties.username-max-length
將映射到
POJO 中的String usernameMaxLength
您只需要一次正確獲取usernameMaxLength
字段名稱。
使用ConfigurationProperties
使您的代碼易於測試。 您可以為不同的測試場景擁有多個屬性文件,並可以在測試中使用它們TestPropertySource("path")
。
現在,如果樣板getters
/ setters
困擾你。 你總是可以使用@Getter
的@Getter / @Setter
。 這只是一個建議,取決於個人的選擇。
此外,從Spring Boot 2.2.0開始,您的@ConfigurationProperties
類可以是不可變的
@ConfigurationProperties(prefix = "app.properties")
public class AppProperties {
private final Integer usernameMaxLength;
@ConstructorBinding
public AppProperties(Integer usernameMaxLength) {
this.usernameMaxLength = usernameMaxLength;
}
// Getters
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.