Why @Value Is Discouraged in Spring Boot and How @ConfigurationProperties Solves It
This article explains the drawbacks of using Spring Boot's @Value for configuration injection, demonstrates how @ConfigurationProperties provides a cleaner, maintainable alternative, and shows how to add validation with @Validated and standard bean validation annotations.
The @Value annotation is widely known among Spring Boot developers for quickly loading configuration values into beans.
For example, you can inject the configuration key com.didispace.title directly into a service:
@Service
public class TestService {
@Value("${com.didispace.title}")
private String title;
}Although convenient, using @Value is discouraged because it fragments configuration loading; the same property may be scattered across multiple services or controllers, making updates error‑prone and hard to maintain.
Instead, it is recommended to use @ConfigurationProperties to group related settings. For the prefix com.didispace, you can define a dedicated properties class:
@Configuration
@ConfigurationProperties(prefix = "com.didispace")
public class DidispaceProperties {
private String title;
}The DidispaceProperties class will load all configurations that start with com.didispace. Other services or controllers can simply inject this bean, avoiding scattered @Value annotations and centralizing configuration changes.
Configuration validation can also be added by including the spring-boot-starter-validation dependency and annotating the properties class with @Validated and standard bean‑validation constraints:
@Validated
@Configuration
@ConfigurationProperties(prefix = "com.didispace")
public class DidispaceProperties {
@NotNull
private String title;
}This approach enables automatic validation of configuration values, ensuring they meet required criteria before the application starts.
Overall, replacing @Value with @ConfigurationProperties and optional validation leads to cleaner, more maintainable Spring Boot configuration management.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
