1. Introduction
In this tutorial, we’ll learn how to access values defined in a properties file in a Spring Boot application.
First, we’ll define how properties are configured in a Spring Boot application. Then, we’ll check out how these properties can be read at runtime in the application.
Having a properties file is the most common way to externalize the configuration for a Spring Boot application. Therefore, it’s a good way for us to customize the application behavior without changing the code.
Let’s begin.
2. Defining Properties in Spring Boot
First, we need to define some properties. Spring uses a convention of creating a file named application.properties
inside the resources folder where we write all the configurations. If we are using the YAML format the file is named application.yml
.
Now, suppose we want to define a rate limit for users’ requests. Inside our properties file, we can define a property named userRequest.rate_limit
:
userRequest.rate_limit=20
Here, we defined a rate limit of 20 requests per minute for the user’s request. Let’s see how we can read this property in our application.
3. Accessing Properties Inside Spring Service
Now, we have a value for a custom property we can read. For this purpose, we can use @Value
annotation inside a Spring boot service:
@Service
public class UserRequestService {
@Value("${userRequest.rate_limit}")
private String userRequestRateLimit;
// ...
}
In short, the @Value
annotation is used to inject the value of a property into a field in a Spring.
Additionally, we can also use the @Value
annotation to inject properties on constructor parameters or method parameters:
@Service
public class UserRequestService {
private final String userRequestRateLimit;
@Autowired
public UserRequestService(@Value("${userRequest.rate_limit}") String userRequestRateLimit) {
this.userRequestRateLimit = userRequestRateLimit;
}
// ...
}
4. Setting Default Values
Sometimes, we may not want to enforce the property to be defined by the user. In such cases, we want the property to have a default value. For this purpose, we can use the ${property:defaultValue}
format to define the default value:
@Value("${userRequest.rate_limit:10}")
private String userRequestRateLimit;
In this case, we won’t have to set a value inside the properties file. If the property is not defined, the default value of 10 will be used.
5. Conclusion
In this short tutorial, we learned how to access values defined in a properties file in a Spring Boot application. First, we defined a custom property and then we used the @Value
annotation to inject the property’s values into our Spring service. Finally, we saw how to set default values for properties.