Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a value defined in the application.properties file in Spring Boot

I want to access values provided in application.properties, e.g.:

logging.level.org.springframework.web: DEBUG logging.level.org.hibernate: ERROR logging.file=${HOME}/application.log  userBucket.path=${HOME}/bucket 

I want to access userBucket.path in my main program in a Spring Boot application.

like image 561
Qasim Avatar asked May 29 '15 11:05

Qasim


People also ask

How do I read application properties in spring boot?

Another very simple way to read application properties is to use @Value annotation. Simply annotation the class field with @Value annotation providing the name of the property you want to read from application. properties file and class field variable will be assigned that value.

How do you read a key value pair from properties file in spring boot?

Using the @Value Annotation The @Value annotation in spring boot reads the value from the application properties file and assigns it to a java variable. To read the property, the property key name must be provided in the @Value annotation.


2 Answers

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.

like image 114
Master Slave Avatar answered Sep 18 '22 08:09

Master Slave


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");     ..... } 
like image 26
Rodrigo Villalba Zayas Avatar answered Sep 19 '22 08:09

Rodrigo Villalba Zayas