[英]@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.