Conditional Java Configurations in Spring Framework


Dec 14, 2014 1 minutes read

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

See Also

JAX-WS with Custom SSLSocketFactory

It’s very easy to configure custom SSLSocketFactory for JAX-WS web-service: just specify custom property referring to SSLSocketFactory bean. But there is a nuance…

Webapp Inter-Communication in Tomcat

Sometimes you need to access services deployed in one web application from another web application within same application server. For Tomcat there is not so many options to do it. In this article we’ll discuss you how to use JMX for communication between web applications.

logo   Never miss a story, subscribe to our newsletter