关于@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 ‘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类型去获取
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

瑾析编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值