以前一直都在用@Resource习惯了,看源码感觉用@Autowired比较多,感觉区别不大,习惯也就一直没改。写代码的时候启动发现报错:
Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'userService' is expected to be of type 'com.example.user.UserInfoServiceImpl' but was actually of type 'com.example.app.UserServiceImpl.'
我写了一个UserInfoServiceImpl,偷懒引用的时候把变量名写成UserService,这时候旧报错了
这是由于@Resource首先根据名称查找,再根据类型,刚好项目中别人使用@Service的时候,把userService这个名字抢了,所以spring注入的时候找到了UserServiceImpl,而不是想要的UserInfoServiceImpl,所以报错。
解决:
1.使用@Autowired,别偷懒,使用@Service的时候,把名字也加上去@Service("userInfoService")
2.变量名改回userInfoService。