这是我的问题:我有一个基本接口和两个实现类。
而一个Service类对基接口有依赖,代码是这样的:
@Component
public interface BaseInterface {}
@Component
public class ClazzImplA implements BaseInterface{}
@Component
public class ClazzImplB implements BaseInterface{}
配置是这样的:
@Configuration
public class SpringConfig {
@Bean
public BaseInterface clazzImplA(){
return new ClazzImplA();
}
@Bean
public BaseInterface clazzImplB(){
return new ClazzImplB();
}
}
服务类对基接口有依赖,将由一些业务逻辑决定自动装配哪个实现。代码是这样的:
@Service
@SpringApplicationConfiguration(SpringConfig.class)
public class AutowiredClazz {
@Autowired
private BaseInterface baseInterface;
private AutowiredClazz(BaseInterface baseInterface){
this.baseInterface = baseInterface;
}
}
IDEA 抛出异常:Could not autowire.There is more than one bean of BaseInterface
type。
虽然可以使用@Qualifier 来解决,但是在这种情况下我无法选择依赖类。
@Autowired
@Qualifier("clazzImplA")
private BaseInterface baseInterface;
我试图阅读 spring 文档,它提供了一个 Constructor-based dependency injection
但我仍然对这个问题感到困惑。
谁能帮我 ?
原文由 0x822a5b87 发布,翻译遵循 CC BY-SA 4.0 许可协议
Spring 混淆了您在配置类中声明的 2 个 bean,因此您可以使用
@Qualifier
注释以及@Autowired
通过指定将连接哪个 bean 来消除混淆,应用这些修改你的配置类然后在
@autowired
注释