@Resource和@Autowired的区别

本文深入解析了@Resource与@Autowired的区别,包括它们的默认匹配方式、所属包及在实际项目中的应用。通过具体示例展示了在Spring框架下,如何解决因多个相同类型Bean导致的注入问题,提供了使用@Primary和@Qualifier的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在项目中开发用到注入有时用@Resource,有时用@Autowired,但到底两者有什么区别呢?
1、匹配方式
@Resource默认是按照名称方式进行bean匹配
@Autowired默认按照类型方式进行bean匹配
2、所属包
@Resource(javax.annotation.Resource)
@Autowired(org.springframework.beans.factory.annotation.Autowired)
3、测试场景
一个接口HumanService、两个实现类WomanServiceImpl、ManServiceImpl,在service层的一个bean中引用接口Human

HumanService接口
human接口

实现类1:WomanServiceImpl
woman实现

实现类2:ManServiceImpl
man实现

调用类方式一:使用@Autowired
@autowired

报错:需要一个唯一的注入bean,但是发现了两个
Field humanService in com.ice.springboot.diveinspringboot.controller.People required a single bean, but 2 were found:

  • manServiceImpl: defined in file [/Users/allin/InteliJ3/dive-in-spring-boot/target/classes/com/ice/springboot/diveinspringboot/serviceimpl/ManServiceImpl.class]
    • womanServiceImpl: defined in file [/Users/allin/InteliJ3/dive-in-spring-boot/target/classes/com/ice/springboot/diveinspringboot/serviceimpl/WomanServiceImpl.class]
      Action:
      Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

@Autowired报错

解决办法:
1、在其中一个bean上添加@Primary
2、在注入的时候,添加@Qualifier声明那个是要注入的bean

调用类方式一:使用@Resource 会有类似的报错
解决办法:@Resource(name = “manServiceImpl”)指定实现类即可,注意用小写的首字母,因为容器创建bean时默认首字母小写

参考:https://blog.youkuaiyun.com/wangzuojia001/article/details/54312074/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值