这是我的问题:我有一个基本接口和两个实现类.
Service类对基接口有依赖关系,代码如下:
@Component
public interface BaseInterface {}
Run Code Online (Sandbox Code Playgroud)
@Component
public class ClazzImplA implements BaseInterface{}
Run Code Online (Sandbox Code Playgroud)
@Component
public class ClazzImplB implements BaseInterface{}
Run Code Online (Sandbox Code Playgroud)
配置是这样的:
@Configuration
public class SpringConfig {
@Bean
public BaseInterface clazzImplA(){
return new ClazzImplA();
}
@Bean
public BaseInterface clazzImplB(){
return new ClazzImplB();
}
}
Run Code Online (Sandbox Code Playgroud)
服务类依赖于基接口将决定通过某些业务逻辑自动装配哪个实现.代码如下:
@Service
@SpringApplicationConfiguration(SpringConfig.class)
public class AutowiredClazz {
@Autowired
private BaseInterface baseInterface;
private AutowiredClazz(BaseInterface baseInterface){
this.baseInterface = baseInterface;
}
}
Run Code Online (Sandbox Code Playgroud)
并且IDEA抛出异常:无法自动装配.有多个BaseInterface类型的bean .
虽然可以通过@ Qualifier来解决,但在这种情况下我无法选择依赖类.
@Autowired
@Qualifier("clazzImplA")
private BaseInterface baseInterface;
Run Code Online (Sandbox Code Playgroud)
我试着阅读弹簧文档并提供了一个,Constructor-based dependency injection但我仍然对这个问题感到困惑.
谁能帮我 ?