@ConfigurationProperties与@PropertySource与@Value

我是Spring / Spring Boot的新手。我想在Java文件中使用application.properties / application.yml的键值对数据。我知道我们可以在任何POJO类中使用@Value来设置application.properties或application.yml文件中字段的默认值。

Q1)但是为什么我们需要另外两个呢? @ConfigurationProperties和@PropertySource。

Q2)@ConfigurationProperties和@PropertySourceBoth都可以用来加载application.properties或application.yml文件中提到的外部数据吗?还是有任何限制?

PS:我曾尝试在互联网上进行搜索,但没有明确的答案。

landaming 回答:@ConfigurationProperties与@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用于通过POJO bean映射属性。然后,您可以使用bean访问应用程序中的属性值。

@PropertySource是引用属性文件并加载它。

@Value是通过其键注入特定的属性值。

本文链接:https://www.f2er.com/3167591.html

大家都在问