Saturday, July 2, 2022

@Conditional Annotation in Spring

In some cases you do want to conditionally enable or disable a complete @Configuration class, or even individual @Bean methods. One common example of this is to use the @Profile annotation to activate beans only when a specific profile has been enabled in the Spring Environment. Another way is using @Conditional annotation in Spring which is the topic of this post.

@Conditional annotation in Spring

In Spring 4 @Conditional annotation has been added which can be used for providing your own logic for conditional checking and then decide whether specific bean should be registered or not.

The @Conditional annotation indicates specific org.springframework.context.annotation.Condition implementations that specifies the condition which should be consulted before a @Bean is registered.

Condition interface in Spring framework

A single condition that must be matched in order for a component to be registered. The class given as value in @Conditional annotation has to implement the Condition interface. Condition interface requires that you provide an implementation of the matches() method.

  • boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata)- Determine if the condition matches.

    Parameters:

    • context- the condition context
    • metadata- metadata of the class or method being checked
    • Returns: true if the condition matches and the component can be registered or false to veto registration.

Spring Conditional annotation example

Suppose you want to create a bean only if a specific condition is present in the property file otherwise you don’t want to create the bean. That conditional creation of bean can be done using @Conditional annotation.

TestBean class

public class TestBean {
 private String name;
 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 } 
}

TestBeanCondition class

This is the class which implements the Condition interface and provides the condition for creating the TestBean. As you can see in the matches method it checks if environment contains the property “test”.

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 TestBeanCondition implements Condition {
 @Override
 public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
  Environment env = context.getEnvironment();
  return env.containsProperty("test");
 }
}

test.properties class

test=true
country=India

TestBeanConfig class

This is the class where TestBean is created, you can see the @Conditional annotation used here with the class that provides the condition.
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource(value="classpath:config/test.properties", ignoreResourceNotFound=true)
public class TestBeanConfig {
 @Bean
 @Conditional(TestBeanCondition.class)
 public TestBean testBean() {
  System.out.println("test bean creation");
  return new TestBean();
 }
}

You can test this code using the following piece of code-

 
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class AppProfile {
 public static void main( String[] args ){
   AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext
   (TestBeanConfig.class);
  
   TestBean tb = (TestBean)context.getBean("testBean");  
   tb.setName("Ram");
   System.out.println("" + tb.getName());
   context.close();
 }
}

Output

test bean creation
Ram

That's all for this topic @Conditional Annotation in Spring. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring Profiles With Examples
  2. Spring JdbcTemplate Insert, Update And Delete Example
  3. Wiring Collections in Spring
  4. How to Inject Null And Empty String Values in Spring
  5. Data access in Spring framework

You may also like-

  1. Dependency Injection in Spring Framework
  2. BeanPostProcessor in Spring Framework
  3. @Required Annotation in Spring Framework
  4. Find All Permutations of a Given String Java Program
  5. How to Remove Duplicate Elements From an ArrayList in Java
  6. Java BlockingQueue With Examples
  7. Is String Thread Safe in Java
  8. Encapsulation in Java