I want to register a Boss when there is a Car in Spring container.
My code is below
@Configuration
@ComponentScan(value ={"org.example.springframework.condition","org.example.springframework.bean"})
public class ConditionConfig {
}
@Component
public class Car {
}
@Conditional(value = BossCondition.class)
@Component
public class Boss {
}
public class BossCondition implements Condition {
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getRegistry().containsBeanDefinition("car");
}
}
But it doesn't work, I can't discover the car in Condition.
Then, I change my code below, it can work well.
@Configuration
public class ConditionConfig {
@Bean
public Car car() {
return new Car();
}
@Bean
@Conditional(value = BossCondition.class)
public Boss boss() {
return new Boss();
}
}
public class Car {
}
public class Boss {
}
public class BossCondition implements Condition {
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getRegistry().containsBeanDefinition("car");
}
}
So, what is the difference between @Bean and @Component?