Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@ConfigurationProperties vs @PropertySource vs @Value

I am new to Spring/Spring Boot. I want to use the key-value pair data of application.properties / application.yml in Java file. I know that we can use @Value in any POJO class to set a default value of a field from application.properties or application.yml file.

Q1) But then why do we need the other two? @ConfigurationProperties and @PropertySource.

Q2) @ConfigurationProperties and @PropertySource, both can be used to load external data mentioned in application.properties or application.yml file? Or any restrictions?

PS: I have tried to search on internet but didn't get a clear answer.

like image 911
SuryaN Avatar asked Nov 04 '19 10:11

SuryaN


2 Answers

@ConfigurationProperties is used to map properties with POJO beans. Then you could use bean to access the properties values in your application.

@PropertySource is to reference a properties file and load it.

@Value is to inject a particular property value by it's key.

like image 100
Vinay Prajapati Avatar answered Sep 27 '22 19:09

Vinay Prajapati


@Value("${spring.application.name}") @Value will throw exception if there no matching key in application.properties/yml file. It strictly injects property value.

For example: @Value("${spring.application.namee}") throws below exception, as namee field doesn't exists in properties file.

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") injects POJO properties, it's not strict, it ignores the property if there is no key in properties file.

For example:

@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
like image 32
Molay Avatar answered Sep 27 '22 19:09

Molay