0 day streak
java / intermediate
Snippet

Conditional Bean Registration

Using @ConditionalOnProperty allows you to control whether a bean is registered in the Spring context based on application properties, perfect for toggling features or mocks.

snippet.java
java
1
2
3
4
5
6
7
8
@Configuration
public class ExternalApiConfig {
@Bean
@ConditionalOnProperty(name = "api.mock.enabled", havingValue = "false")
public ApiService realApiService() {
return new RealApiServiceImpl();
}
}
spring
Breakdown
1
@ConditionalOnProperty(...)
Checks if 'api.mock.enabled' is 'false' in the environment configuration before creating this bean.
2
public ApiService realApiService()
The bean that will only exist if the condition above is met.