Why @Value Is Discouraged in Spring Boot and How @ConfigurationProperties Offers a Better Alternative
This article explains the drawbacks of using Spring Boot's @Value annotation for configuration injection, demonstrates how @ConfigurationProperties can centralize and simplify config management, and shows how to add validation support for robust application settings.
The @Value annotation is widely known among Spring Boot developers for quickly loading configuration values into beans. For example, using @Value("${com.didispace.title}") can inject the com.didispace.title property into a TestService class:
@Service
public class TestService {
@Value("${com.didispace.title}")
private String title;
}Although convenient, @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, the article recommends using @ConfigurationProperties to group related settings. By defining a properties class such as:
@Configuration
@ConfigurationProperties(prefix = "com.didispace")
public class DidispaceProperties {
private String title;
}all properties with the com.didispace prefix are loaded into a single bean, which can then be injected wherever needed, simplifying maintenance and reducing duplication.
To further enhance configuration safety, the article suggests adding validation support. Include the spring-boot-starter-validation dependency, annotate the properties class with @Validated, and apply constraint annotations like @NotNull to fields:
@Validated
@Configuration
@ConfigurationProperties(prefix = "com.didispace")
public class DidispaceProperties {
@NotNull
private String title;
}This approach enables automatic validation of configuration values, ensuring that required properties are present and correctly formatted.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
