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.
@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.
@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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With