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.
@Autowiredprivate Environment env;....public void method() { ..... String path = env.getProperty("userBucket.path"); .....}
@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=Sachincust.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.
@Autowiredprivate Employee employeeProperties;public void method() { String employeeName = employeeProperties.getName(); String employeeDept = employeeProperties.getDept();}