概述
@ConditionalOnSingleCandidate 是Spring Framework中的一个条件注解,它用于根据特定类型的 bean 是否有且仅有一个候选者来决定是否创建一个 bean 或者配置一个类。
应用场景
-
依赖特定类型的唯一bean: 当需要依赖一个特定类型的 bean,并且这种类型的 bean 在容器中应该是唯一的时,可以使用
@ConditionalOnSingleCandidate来控制另一个 bean 或者配置的加载或生效。 -
可插拔的实现: 在实现某个接口的多个类中,如果需要选择唯一的实现类来配置某些功能或行为时,可以利用
@ConditionalOnSingleCandidate来确保只有一个实现类被选择。
使用示例代码
假设有一个接口 MyService 和两个实现类 MyServiceImpl1 和 MyServiceImpl2,我们希望根据 MyService 接口的实现类是否唯一来配置另一个 bean。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;public interface MyService {void doSomething();
}@Service
public class MyServiceImpl1 implements MyService {public void doSomething() {// Implementation}
}@Service
public class MyServiceImpl2 implements MyService {public void doSomething() {// Implementation}
}@Configuration
public class AnotherConfiguration {@Bean@ConditionalOnSingleCandidate(MyService.class)public AnotherBean anotherBean(MyService myService) {// Only configure AnotherBean if there is a single candidate for MyServicereturn new AnotherBean(myService);}}
在上面的示例中:
MyService是一个接口,有两个实现类MyServiceImpl1和MyServiceImpl2。AnotherConfiguration类中的anotherBean方法使用了@ConditionalOnSingleCandidate(MyService.class)注解,这意味着只有当容器中存在且仅存在一个MyService类型的 bean 时,才会创建AnotherBean实例,并注入该唯一的MyService实例。
注意事项
- 如果容器中不存在
MyService类型的 bean,或者存在多个MyService类型的 bean,则anotherBean方法不会被调用。 @ConditionalOnSingleCandidate默认要求依赖的 bean 类型是单一候选者,如果存在多个符合条件的 bean,则会抛出异常或者不会生效,可以通过value属性指定需要依赖的 bean 类型。