How to access a value defined in the application.properties file in Spring Boot
You can use the @Value
annotation and access the property in whichever Spring bean you're using
@Value("${userBucket.path}")
private String userBucketPath;
The Externalized Configuration section of the Spring Boot docs, explains all the details that you might need.
Another way is injecting org.springframework.core.env.Environment
to your bean.
@Autowired
private Environment env;
....
public void method() {
.....
String path = env.getProperty("userBucket.path");
.....
}
Currently, I know about the following three ways:
1. The @Value
annotation
@Value("${<property.name>}")
private static final <datatype> PROPERTY_NAME;
- In my experience there are some situations when you are not
able to get the value or it is set to
null
. For instance, when you try to set it in apreConstruct()
method or aninit()
method. This happens because the value injection happens after the class is fully constructed. This is why it is better to use the 3'rd option.
2. The @PropertySource
annotation
@PropertySource("classpath:application.properties")
//env is an Environment variable
env.getProperty(configKey);
PropertySouce
sets values from the property source file in anEnvironment
variable (in your class) when the class is loaded. So you able to fetch easily afterword.- Accessible through System Environment variable.
3. The @ConfigurationProperties
annotation.
This is mostly used in Spring projects to load configuration properties.
It initializes an entity based on property data.
@ConfigurationProperties
identifies the property file to load.@Configuration
creates a bean based on configuration file variables.@ConfigurationProperties(prefix = "user") @Configuration("UserData") class user { //Property & their getter / setter } @Autowired private UserData userData; userData.getPropertyName();
@ConfigurationProperties
can be used to map values from .properties
( .yml
also supported) to a POJO.
Consider the following Example file.
.properties
cust.data.employee.name=Sachin
cust.data.employee.dept=Cricket
Employee.java
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@ConfigurationProperties(prefix = "cust.data.employee")
@Configuration("employeeProperties")
public class Employee {
private String name;
private String dept;
//Getters and Setters go here
}
Now the properties value can be accessed by autowiring employeeProperties
as follows.
@Autowired
private Employee employeeProperties;
public void method() {
String employeeName = employeeProperties.getName();
String employeeDept = employeeProperties.getDept();
}