@Resource是Java自带的@interface类型,类似于Spring的@Autowired。但是两者的注入方式有很大的区别。@Resource是通过name注入,@Autowired是通过type注入,这也是这次刨坑的主要原因。
场景还原
背景介绍
- 一个类SettingService加了@Service,name为settingService(spring扫描自动命名机制-将类的首字母小写当做name)
- 另一个类BallGameSettingService也加了@Service,name为ballGameSettingService
代码如下:
@Service
public class SettingService {
......
}
@Service
public class BallGameSettingService{
.......
}
导火线
以下注入将会出现异常:Error creating bean with name ‘ballGameSettingController’: Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named ‘settingService’ is expected to be of type ‘com.xxx.BallGameSettingService’ but was actually of type ‘com.xxx.SettingService…EnhancerBySpringCGLIB..e4ce4a19’
public class BallGameSettingController extends BaseController {
@Resource
private BallGameSettingService settingService;
......
}
将上面的代码换成以下三种写法都可以:
public class BallGameSettingController extends BaseController {
@Resource(name = "ballGameSettingService")
private BallGameSettingService settingService;
......
}
或者
public class BallGameSettingController extends BaseController {
@Resource
private BallGameSettingService ballGameSettingService;
......
}
或者
public class BallGameSettingController extends BaseController {
@Autowired
private BallGameSettingService settingService;
......
}
根本原因:@Resource是通过name注入,@Autowired是通过type注入
在使用@Resource时,如果没有设置name,也就是 @Resource(name = “ballGameSettingService”) 时,会默认取变量名称当做name。所以造成这次异常的原因:
- 我们环境中存在两个@Service的bean,名字分别为:settingService和ballGameSettingService,我们在通过以下代码注入的时候,获取到的是settingService(类型:SettingService),导致了类型出错。
@Resource
private BallGameSettingService settingService;
- 以下两种正确写法的本质是一样,就是获取ballGameSettingService(类型:BallGameSettingService)
public class BallGameSettingController extends BaseController {
@Resource(name = "ballGameSettingService")
private BallGameSettingService settingService;
......
}
和
public class BallGameSettingController extends BaseController {
@Resource
private BallGameSettingService ballGameSettingService;
......
}
- 使用@Autowired的本质是通过BallGameSettingService类型去获取