Open In App

Spring Conditional Annotations

Last Updated : 28 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The Spring Framework provides a powerful way to control bean creation and configuration based on specific conditions through its conditional annotations. These features can be particularly useful in building flexible and environment-specific configurations without cluttering the application with boilerplate code. Conditional annotations let developers specify the conditions under which beans are included or excluded from the application context, allowing for a more dynamic and adaptable application startup.

Spring's conditional annotations are part of the org.springframework.context.annotation package and primarily revolve around the @Conditional annotation. This annotation allows developers to specify custom conditions as Java classes that implement the Condition interface. The bean will only be loaded into the Spring application context if the specified condition is met.

Conditional Annotations

1. @Conditional

The @Conditional annotation allows for the registration of beans based on custom conditions. We can create a class that implements the Condition interface and defines the logic that determines whether the bean should be created. It can be used at the class or method level and provides a way to integrate custom logic into the bean creation process.

Example code:

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

@Configuration
public class MyConfiguration {

@Bean
@Conditional(MyCondition.class)
public MyBean myBean() {
return new MyBean();
}
}

In this example, the MyCondition class implements the Condition interface, defining the logic that determines whether the bean should be created in the application.

2. @ConditionalProperty

The @ConditionalOnProperty annotation creates the bean only if the specified property is present in the environment and optionally has a specific value. It is commonly used to enable or disable beans based on application configuration properties. We can specify the property name and the optional value that the property must match for the bean to be created.

Example

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyConfiguration {

@Bean
@ConditionalOnProperty(name = "my.property.enabled", havingValue = "true")
public MyBean myBean() {
return new MyBean();
}
}

In this example, the myBean bean will only be created if the property my.property.enabled is set to true in the application properties.

3. @ConditionalOnClass

The @ConditionalOnClass annotation creates the bean only if the specified class is present on the classpath. It is useful for creating beans that depend on the presence of a particular library or class. It helps in writing modular code that can be adapted based on the available classpath.

Example

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyConfiguration {

@Bean
@ConditionalOnClass(name = "com.example.MyClass")
public MyBean myBean() {
return new MyBean();
}
}

In this example, the myBean can only be created if the com.example.MyClass is present on the classpath.

4. @ConditionalOnMissingBean

The @ConditionalOnMissingBean annotation creates the bean only if the specified bean type or name is not already defined in the application context. It can be useful for providing default bean definitions that can be overridden by custom beans in the application context. It ensures that the bean is created only if another bean of the same type is not present.

Example

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyConfiguration {

@Bean
@ConditionalOnMissingBean(MyBean.class)
public MyBean myBean() {
return new MyBean();
}
}

In this example, the myBean bean will only be created if no other beans of type MyBean are already defined in the context.

5. @ConditionalOnBean

The @ConditionalOnBean annotation creates the bean only if the specified bean type or name is already defined in the application context. This annotation is useful for defining beans that depend on the presence of other beans. It allows for conditional bean creation based on the existence of dependencies in the application context.

Example

import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyConfiguration {

@Bean
@ConditionalOnBean(MyDependencyBean.class)
public MyBean myBean() {
return new MyBean();
}
}

In this example, the myBean can be created if the MyDependencyBean bean is already defined in the context.

6. @ConditionalOnExpression

The @ConditionalOnExpression annotation creates the bean based on the evaluation of the Spring Expression Language (SpEL) expression. It provides a flexible way to create beans based on complex conditions. The SpEL expression can evaluate various aspects of the environment, system properties, or even bean properties to determine whether the bean should be created.

Example

import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyConfiguration {

@Bean
@ConditionalOnExpression("#{systemProperties['os.name'].toLowerCase().contains('windows')}")
public MyBean myBean() {
return new MyBean();
}
}

In this example, the myBean bean can be created if the operating system name contains "windows".

7. @ConditionalOnJava

The @ConditionalOnJava annotation can create the bean based on the Java version that the application is running on. It allows for the creation of beans that are specific to certain Java versions, ensuring compatibility and leveraging version-specific features. It provides a straightforward way to conditionally create beans based on the runtime Java version.

Example

import org.springframework.boot.autoconfigure.condition.ConditionalOnJava;
import org.springframework.boot.system.JavaVersion;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyConfiguration {

@Bean
@ConditionalOnJava(JavaVersion.EIGHT)
public MyBean myBean() {
return new MyBean();
}
}

In this example, myBean can only be created if the application is running on the Java 8 version.

@ConditionalOnWebApplication and @ConditionalOnNotWebApplication

The @ConditionalOnWebApplication annotation creates the bean only if the application is a web application, while the @ConditionalOnNotWebApplication annotation creates the bean if the application is not a web application. These annotations help distinguish between web and non-web contexts, allowing for the creation of beans that are appropriate for the specific type of application.

Example

package com.example.demo;

import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class WebConfiguration {

@Bean
@ConditionalOnWebApplication
public WebService webService() {
return new WebService();
}
}

class WebService {
public WebService() {
System.out.println("WebService bean created because this is a web application");
}

public void doSomething() {
// Some logic for web service
}
}

This example demonstrates creating a bean that is only loaded when the application is a web application.

Conclusion

Spring conditional annotations are powerful tools for managing bean creation and configuration based on various conditions. They enable developers to write flexible, modular, and adaptable applications that can dynamically adjust their behaviours based on the runtime environment and configuration. By leveraging these annotations, we can create more maintainable and scalable Spring applications.


Article Tags :

Similar Reads