Conditional Java Configurations in Spring Framework
Table of Contents
Spring Framework offers very flexible means for binding application components. Externalizable properties, composite configuration, nested application contexts and profiles.
Sometimes, it is necessary to control whether particular beans or @Configuration
will be loaded or not. Spring Framework v.4.1.x does not provide that feature out of the box. But, hopefully, Spring allows conditional bean initialization (see @Profile
implementation and @Configurable
).
So, I created the annotation @Enabled
which allows me to control bean instantiation via properties.
@Enabled
indicates that a component is eligible for registration when evaluated expression is true. This annotation should be used in conjunction with Configuration and Bean annotations.
Usage Example #
Given property file application.properties
with property values my.service.enabled
and my.config.enabled
.
Following code will only instantiate and configure MyService
and MyConfig
if values of appropriate properties are evaluated as true
.
@Configuration
@PropertySource}("classpath:/application.properties")
@Import(MyConfig.class)
class AppConfig {
@Bean
@Enabled("${my.service.enabled}")
MyService myService {
return new MyService()
}
}
@Configuration
@Enabled("${my.config.enabled}")
class MyConfig {
...
}
Link: project on GitHub
Update: spring-boot-conditionals