@Component vs @Bean Annotations in Spring
Introduction
In this article we'll explore two annotations @Bean and @Component. Both these annotations are used to define Spring Beans - objects that'll be managed by Spring IoC container. However, they're used in different contexts as per project's...
juhilee.hashnode.dev5 min read
What is @Conditional? The @Conditional annotation is used to conditionally register a bean based on the result of one or more Condition implementations. It's part of Spring's org.springframework.context.annotation package.
Basic Usage Custom Condition: You can create your own condition by implementing the Condition interface. For example:
java Copy code import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata;
public class MyCustomCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { // Add your condition logic here return true; // or false based on your condition } } Applying the Condition: You use @Conditional to apply this condition to a configuration class or bean definition.
java Copy code import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration;
@Configuration @Conditional(MyCustomCondition.class) public class MyConfiguration { // Bean definitions } Predefined Conditions Spring Boot also provides several predefined conditions through annotations like:
@ConditionalOnClass @ConditionalOnMissingBean @ConditionalOnProperty @ConditionalOnResource @ConditionalOnWebApplication These annotations make it easier to conditionally register beans based on classpath availability, bean presence, configuration properties, and other conditions.
Example with @ConditionalOnProperty Here’s a simple example using @ConditionalOnProperty:
java Copy code import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
@Configuration public class MyConfig {
@Bean @ConditionalOnProperty(name = "feature.enabled", havingValue = "true") public MyBean myBean() { return new MyBean(); } } In this example, MyBean will only be created if the feature.enabled property is set to true.
Summary @Conditional allows you to register beans based on custom conditions. Predefined conditions make it easier to control bean registration based on common scenarios. These conditional annotations can help create more flexible and modular configurations in your Spring Boot applications.