java / intermediate
Snippet
Conditional Bean Loading with @ConditionalOnProperty
This snippet demonstrates how to conditionally load a Spring Bean based on a configuration property. If 'app.feature.modern-mode' is set to 'true' in application.properties, the bean is created; otherwise, it is ignored.
snippet.java
1
2
3
4
5
6
7
8
@Configurationpublic class FeatureConfig {@Bean@ConditionalOnProperty(name = "app.feature.modern-mode", havingValue = "true")public ModernService modernService() {return new ModernService();}}
spring
Breakdown
1
@ConditionalOnProperty(name = "app.feature.modern-mode", havingValue = "true")
Checks if the property exists and matches the specified value before registering the bean.
2
public ModernService modernService()
The factory method that Spring calls to instantiate the service if the condition is met.