javaresource注解,关于@Resource注解使⽤的注意事项@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 ‘BallGameSettingService’ but was actually of type
‘SettingService…4ce4a19’
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;
......
resource和autowired注解的区别
}
public class BallGameSettingController extends BaseController {
@Resource
private BallGameSettingService ballGameSettingService;
......
}
使⽤@Autowired的本质是通过BallGameSettingService类型去获取

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。