一个接口有多个实现类
// A code block
var foo = 'bar';
// An highlighted block
/**
* 接口
*/
public interface InterfaceA{
void doSomething();
}
/**
* a实现
*/
public class AImpl implements InterfaceA{
@Override
void doSomething(){
//
}
}
/**
* b实现
*/
public class BImpl extends aImpl {
@Override
public void doSomething() {
//
}
}
/**
* c实现
*/
public class CImpl extends aImpl {
@Override
public void doSomething() {
//
}
}
想要注入bImpl,直接通过@Resource或者@Autowired注解会报错
报错提示:
// An highlighted block
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'interfaceA' available: expected single matching bean but found 3: aImpl,bImpl,cImpl
解决方法
1.用注解 @Qualifier,@Autowired
(1)如果实现类里,注解 @Service 没有指定实现类的 bean 名称,则注入的时候默认用该实现类首字母小写的bean的名字
(2)如果用注解 @Service("aImpl") 指定了实现类的 bean 名称,则用注解 @Qualifier("aImpl") 注入的时候,注意名称保持一致,@Autowired 注释,它可以对类成员变量、方法及构造函数进行标注,让 spring 完成 bean 自动装配的工作。 默认是按照类型去匹配注入,配合 @Qualifier 按照指定的 name 名称去装配 bean。
/**
* a实现
*/
@Service("aImpl")
public class AImpl implements InterfaceA{
@Override
void doSomething(){
//
}
}
/**
* b实现
*/
@Service("bImpl")
public class BImpl extends aImpl {
@Override
public void doSomething() {
//
}
}
/**
* c实现
*/
@Service("cImpl")
public class CImpl extends aImpl {
@Override
public void doSomething() {
//
}
}
@Qualifier("cImpl")
@Autowired
private InterfaceA cService;
2.用注解@Resource实现
用注解 @Resource(name = "aImpl") 或 @Resource(type = CImpl.class) 替换 @Autowired 、 @Qualifier 这两个组合注解
//因为是继承BImpl、CImpl的type跟AImpl的type是一样的, @Resource(type = AImpl.class)会报错,只能用name指定
@Resource(name = "AImpl")
private InterfaceA aService;
@Resource(name = "BImpl")
private InterfaceA bService;
@Resource(name = "CImpl")
private InterfaceA cService;
3.可以用@Configuration注解解决
通过@Configuration注解定义spring注入指定的service
@Configuration
public class MyBeanConfig {
@Bean
public InterfaceA aService() {
return new AImpl();
}
@Bean
public InterfaceA bService() {
return new BImpl();
}
@Bean
public InterfaceA cService() {
return new CImpl();
}
}
//......
//使用
@Resource
private InterfaceA aService;
@Resource
private InterfaceA bService;
@Resource
private InterfaceA bService;
以上就是三种方法实现