Issue
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.
Solution
@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
Answered By - Molay
Answer Checked By - David Marino (JavaFixing Volunteer)