CREATING Conditional Bean in Spring

At times we might come across situations where we want a bean to be created only when a particular condition is met, say for example when a particular environment property is set. Spring offers the @Conditional annotation to serve this purpose.

Spring's @Conditional annotation can be applied to @Bean annotated methods. The bean for the method will be created only when the prescribed condition is met.

Example Code

To understand Spring conditional beans better lets consider a situation where we have the choice of two web service implementations to choose from, say Rest and Soap. We need to make the decision depending on the value of an environment property called ‘webservice’. If the value is set to ‘rest’ we create the ‘RestWebServiceBean’  and fire the rest web service else the soap web webservice is fired.

package cubearticle.spring.conditional.bean.examples;

public class RestWebServiceBean {
    public void fireWebService(){
        System.out.println("Firing REST WebService");
package cubearticle.spring.conditional.bean.examples;

public class SOAPWebServiceBean {
    public void fireWebService(){
        System.out.println("Firing SOAP WebService");

Shown above are our RestWebServiceBean and SOAPWebServiceBean. The SOAPWebServiceBean is our default choice; this bean will always be created but fired only when rest is not enabled.

Note: We can always choose to create the SOAPWebServiceBean conditionally as well, but we are ignoring this step to keep our example precise.

Shown below is the Config class, which we will use to configure the Spring beans:

package cubearticle.spring.conditional.bean.examples;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

public class Config { 
    public RestWebServiceBean restWebService(){
        return new RestWebServiceBean();
    public SOAPWebServiceBean soapWebService(){
        return new SOAPWebServiceBean();

Notice the @PropertySource annotation in the above Config class; it informs Spring about the location of our property file from where it can load the environment properties. Also notice the @Conditional annotation in the restWebService() method, it is used to create our Spring bean depending on the condition mentioned in the WebServiceCondition class.

The WebServiceCondition class is shown below; it should implements the Condition interface. This interface defines a single method called matches() ,which should be overridden in our class. The creation of our RestWebServiceBean depends on the value returned by this method. Here we obtain the Environment object from the context and use it to check the value of our 'webservice' property. We will return true if the property is found and its value is set to 'rest', else we will return false.

package cubearticle.spring.conditional.bean.examples;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;

public class WebServiceCondition implements Condition{

    public boolean matches(ConditionContext context, AnnotatedTypeMetadata annoMetaData) {
        Environment env =  context.getEnvironment();
        String webservice = env.getProperty("webservice");
        if(webservice!=null &&  webservice.equals("rest"))
            return true;
        return false;

Below is our file which is used to set the value of the 'webservice' property.


The Main class used to run our example code is shown below. It uses the AnnotationConfigApplicationContext to initialize the Spring Application Context. It then tries to get the 'restWebService' bean and fires REST web service if the bean is found. If rest bean is not found it fire the SOAP web service.

package cubearticle.spring.conditional.bean.examples;

import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String args[]){
        ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
            RestWebServiceBean rest = (RestWebServiceBean)context.getBean("restWebService");
        catch(NoSuchBeanDefinitionException ne){
            SOAPWebService soap = (SOAPWebService)context.getBean("soapWebService");

Below is the output generated in console on executing the Main class:

Firing REST WebService

We can also remove the 'webservice' property or set it some other value in the, to validate that the rest bean is not created. Below is the output we get on the console in this case:

Firing SOAP WebService

Creating Conditional Beans in Spring

The concept of condition beans enables Spring to restrict the creation of any bean depending on the evaluation of a condition. These beans get created only when a preset condition is evaluated as true

View Article

Accepting Request Param and Path Variable in Spring Controller

Spring MVC provides various ways through which a client browser can pass data to the Controller. In this article we will discuss about accepting Request Parameters and Path Variables in Spring Contr..

View Article

Generate Namespace & Schema Information using JAXB

Most xml documents used in enterprise applications makes use of namespace to avoid element name conflicts. This article talks about generating these namespace and schema information when marshaling...

View Article

Switching Database Profile using Spring Profiles

We are most likely to have separate db configuration for different environment like development and production environment. Spring profiles provide a convenient way to switch db profiles at runtime.

View Article

SQL and its Sub-Languages

SQL (Structured Query Language) is a language understood by most modern databases. It is an ANSI (American National Standard Institute) standard language which is used to manipulate databases.

View Article

Introducing JUnit Rule

Junit Rules allows developers to add additional functionalities that can applied to all test methods in a test class. It is similar to the concept of custom test runners but with reduced restrictions.

View Article

Addressing Ambiguity in Spring Autowiring

Spring autowiring is powerful concept, but we should be very cautious while using it. We may end up in creating ambiguity while autowiring beans, which will cause autowiring to fail.

View Article

Creating and Using Synonym in Oracle Database

Synonyms are database objects used to provide duplicate names to existing objects in the database. It is just an alternate name used to hide the original name of the object.

View Article

Creating and Using Sequence in Oracle Database

A sequence is used to auto-generate numbers in ascending or descending order which can serve as a primary key or a part of it (in case of composite key).

View Article

Creating and Manipulating Constraints in Oracle Database

Constraints are used to impose certain rules on columns to avoid invalid data entry into the table. If any of the constraint is violated the operation fails.

View Article

Integrating Log4J with Perf4J for Performance Logging

Perf4j is an open source logging framework used primarily for monitoring performance statistics in java applications. Log4j has the ability to integrate with perf4j to capture performance data.

View Article

Tagging in GIT

Tagging allows us to mark a specific point in the commit history or snapshot. A tag is typically used to mark a project release. This article shows how to create tags in Git.

View Article