Junior — Middle
Can you tell me about the different types of @Conditional annotation in Spring?
sobes.tech AI
Answer from AI
The @Conditional annotation in Spring is used for conditionally creating beans within the application context. It allows for including or excluding certain components based on specified conditions. The main types and usage options are:
-
@Conditional— a basic annotation that takes a class implementing theConditioninterface. This class describes the logic under which the bean will be created. -
Specialized annotations based on
@Conditional:@ConditionalOnProperty— creates a bean if a specific property is set in the configuration.@ConditionalOnClass— creates a bean if the specified class is present in the classpath.@ConditionalOnMissingBean— creates a bean if a bean of a certain type is absent in the context.@ConditionalOnBean— creates a bean if a bean of a certain type already exists in the context.@ConditionalOnExpression— creates a bean if the SpEL expression evaluates to true.
Example of using @ConditionalOnProperty:
@Configuration
public class MyConfig {
@Bean
@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")
public MyService myService() {
return new MyService();
}
}
Thus, @Conditional and its derivatives allow flexible management of application configuration depending on the environment, presence of classes, properties, and other conditions.