Spring Boot Recipe: Turn beans on and off by setting a property

In Spring Boot, you can use the @ConditionalOnProperty annotation to enable or disable a particular bean based on the presence of a property. This is very useful if you want to provide optional features to your microservice.

To do so, add the annotation either at the class or bean level, as follows

@ConditionalOnProperty(value='mybean.enabled')
@Bean 
MyOptionalClass optionalBean(){
}

Any place where you want this bean used, you should specify that is it optionally required:

@Autowired(required=false)
MyOptionalClass optionalClass

And that’s it. Your optionalClass bean should resolve to null when you specify mybean.enabled=false in your application.properties or system property file, or if it does not exist.

This mechanism is used extensively in Spring Boot itself, for example to turn on autoconfiguration in Spring social.

Warning, this blog post applies to Spring Boot 1.1.x and below, the annotation is slightly different in Spring Boot 1.2.

2 thoughts on “Spring Boot Recipe: Turn beans on and off by setting a property

Leave a comment