@ConfigurationProperties 与 @PropertySource 与 @Value

Sur*_*yaN 8 java spring spring-boot

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

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

Q2)@ConfigurationProperties@PropertySource,两者都可以用来加载application.propertiesapplication.yml文件中提到的外部数据?或者有什么限制?

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

Vin*_*ati 11

@ConfigurationProperties用于使用 POJO bean 映射属性。然后您可以使用 bean 访问应用程序中的属性值。

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

@Value 是通过它的键注入一个特定的属性值。


Kum*_*mar 10

@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}"
Run Code Online (Sandbox Code Playgroud)

@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
Run Code Online (Sandbox Code Playgroud)

  • @PropertySource 怎么样 (4认同)