How to access a value defined in the file in Spring Boot

In Spring Boot, you can access values defined in the file using the @Value annotation or the Environment object. Spring Boot is a popular Java framework that makes it easy to create stand-alone, production-grade Spring-based applications. One of the key features of Spring Boot is its ability to automatically configure properties using the or application.yml file. In this post, we’ll explore different ways to access these properties in your Spring Boot application.

Using the @Value annotation

The @Value annotation is the simplest way to access properties defined in the file. To use this annotation, simply add it to a field in your class and specify the property you want to access as the value. For example:

private String propertyValue;

This will automatically set the value of the propertyValue field to the value of the propertyName property defined in the file.

Using the Environment object

Another way to access properties defined in the file is to use the Environment object. This object provides access to all of the properties defined in the file, as well as any other properties defined in the system. To use the Environment object, you need to first autowire it in your class:

private Environment env;
String propertyValue = env.getProperty("propertyName");

Then you can access properties using the getProperty method:

Using @ConfigurationProperties

The @ConfigurationProperties annotation is used to map a group of related properties to a bean. To use this annotation, you need to create a bean, annotate it with @ConfigurationProperties and specify the prefix of the properties that you want to map to this bean.

@ConfigurationProperties(prefix = "propertyName")
public class PropertyBean {
  private String value;
  // getters and setters

You can then autowire the bean to access the properties.


Spring Boot makes it easy to access properties defined in the file using the @Value annotation, the Environment object, or the @ConfigurationProperties annotation. Each approach has its own advantages and disadvantages, and the best choice will depend on the specific requirements of your application.