问题
@Autowired默认按照类型进行注入。当一个接口有多个实现类时,使用@Autowired注解时会报org.springframework.beans.factory.NoUniqueBeanDefinitionException。
代码示例
接口
public interface AbcService {
public ABC getAbcById(int id);
}
实现类1
@Service("abcService1")
public class AbcImpl1 implements AbcService {
@Override
public EmployeeDto getAbcById(Long id) {
return new ABC();
}
}
实现类2
@Service("abcService2")
public class AbcImpl2 implements AbcService {
@Override
public EmployeeDto getAbcById(Long id) {
return new ABC();
}
}
解决
@Qualifier
@Autowired
//注入 abcService1
@Qualifier("abcService1")
AbcService abcService;
@Primary
//优先被注入
@Primary
@Service("abcService2")
public class AbcImpl2 implements AbcService {
@Override
public EmployeeDto getAbcById(Long id) {
return new ABC();
}
}
版权声明:本文为xue_xiaofei原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。