[英]@ConfigurationProperties vs @PropertySource vs @Value
我是 Spring/Spring Boot 的新手。 我想application.yml
Java文件中application.properties
的鍵值對數據。 我知道我們可以在任何 POJO class 中使用@Value
來設置application.properties
或application.yml
文件中字段的默認值。
Q1)但是為什么我們需要另外兩個呢? @ConfigurationProperties
和@PropertySource
。
Q2) @ConfigurationProperties
和@PropertySource
都可以用來加載application.properties
或application.yml
文件中提到的外部數據嗎? 或者有什么限制?
PS:我嘗試在互聯網上搜索,但沒有得到明確的答案。
@ConfigurationProperties
用於帶有 POJO bean 的 map 屬性。 然后您可以使用 bean 訪問應用程序中的屬性值。
@PropertySource
是引用一個屬性文件並加載它。
@Value
是通過它的鍵注入特定的屬性值。
@Value("${spring.application.name}")
如果 application.properties/yml 文件中沒有匹配的鍵,@Value 將拋出異常。 它嚴格注入財產價值。
例如: @Value("${spring.application.namee}")
拋出以下異常,因為屬性文件中不存在namee
字段。
application.properties file
----------------------
spring:
application:
name: myapplicationname
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testValue': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.application.namee' in value "${spring.application.namee}"
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.application.namea' in value "${spring.application.namee}"
@ConfigurationProperties(prefix = "myserver.allvalues")
注入 POJO 屬性,它並不嚴格,如果屬性文件中沒有鍵,它會忽略該屬性。
例如:
@ConfigurationProperties(prefix = "myserver.allvalues")
public class TestConfigurationProperties {
private String value;
private String valuenotexists; // This field doesn't exists in properties file
// it doesn't throw error. It gets default value as null
}
application.properties file
----------------------
myserver:
allvalues:
value: sampleValue
根據我的研究和理解::
@ConfigurationProperties
從application.properties
加載屬性
您指定字段名稱以對應於application.properties
中的屬性名稱
-- @ConfigurationProperties
不適用於@Value
@PropertySource
從您指定的文件加載屬性
可以與@Value
或@Autowired Environment env;
@Value
它與application.properties
一起使用
application.properties
默認加載(您不需要在@PropertySource
中指定)
參考
https://mkyong.com/spring-boot/spring-boot-configurationproperties-example/
https://mkyong.com/spring/spring-propertysources-example/
-
SpringApplication 將從以下位置的 application.properties 文件中加載屬性並將它們添加到 Spring 環境中:
-
@ConfigurationProperties 注釋。 當放置在任何 Spring bean 上時,它指定可以從 Spring 環境中的屬性注入該 bean 的屬性。
< Spring 在行動 >
-
您可以將配置文件捆綁在您的應用程序 jar 中或將文件放入運行時環境的文件系統中,並在 Spring 啟動時加載。
Spring Boot 會自動從項目類路徑加載 application.properties 文件。
http://dolszewski.com/spring/spring-boot-application-properties-file/
-
4.1。 application.properties:默認屬性文件
Boot 將其典型的約定優於配置方法應用於屬性文件。 這意味着我們可以簡單地將 application.properties 文件放在我們的 src/main/resources 目錄中,它將被自動檢測到。 然后我們可以像往常一樣從中注入任何加載的屬性。
因此,通過使用此默認文件,我們不必顯式注冊 PropertySource,甚至不必提供屬性文件的路徑。
https://www.baeldung.com/properties-with-spring
-
@ConfigurationProperties 向 spring 指示它應該根據名稱將 java 字段綁定到某些匹配屬性。
spring 要求具有此注解的 class 必須是 spring bean
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.