在测试Spring Boot功能代码的时候,出现了这个错误
Unsatisfied dependency expressed through field 'consumerService';
nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException:
Bean named 'consumerServiceImpl' is expected to be of type 'com.example.testspringboot2.demo20190808.service.impl.ConsumerServiceImpl' but was actually of type 'com.sun.proxy.$Proxy148'
原因是我的接口ConsumerService有两个实现类ConsumerServiceImpl和ConsumerServiceImpl2
而我是这样注入的
@Autowired
private ConsumerServiceImpl consumerService;
@Autowired
private ConsumerServiceImpl2 consumerService2;
这就有问题了,注解方式注入bean使用的是JDK的动态代理机制,而JDK的动态代理是不支持类注入的,只支持接口注入
所以,有两个实现类,想用@Autowired注入而不是@Resource,可以这么写
@Autowired
@Qualifier(value = "consumerServiceImpl")
private ConsumerService consumerService1;
@Autowired
@Qualifier(value = "consumerServiceImpl2")
private ConsumerService consumerService2;