Autowired和Resource的关系

相同点

对于下面的代码来说,如果是Spring容器的话,两个注解的功能基本是等价的,他们都可以将bean注入到对应的field中

java 复制代码
@Autowired1
private Bean beanA;
@Resource
private Bean beanB;

不同点

byName和byType匹配顺序不同

1、Autowired在获取bean的时候,先是byType的方式,再是byName的方式。意思就是先在Spring容器中找以Bean为类型的Bean实例,如果找不到或者找到多个bean,则会通过fieldName来找。举个例子

java 复制代码
@componentbeanone"
class BeanOne implements Bean
@component("beanTwo")
class BeanTwo implements Bean}
@Service5
class Test {
//此时会报错,先byType找到两个bean:bean0ne和beanTwo
//然后通过byName(bean)仍然没办法匹配
@Autowired
private Bean bean;
//先byType找到两个bean,然后通过byName确认最后要注入的bean
@Autowired 
private Bean beanOne;
//先byType找到两个bean,然后通过byName确认最后要注入的bean
@Autowired
@Qualifier("beanone")
private Bean bean:

2、Resource在获取bean的时候,和Autowired恰好相反,先是byName方式,然后再是byType方式。当然我们也可以通过注解中的参数显示指定通过哪种方式。同样举个例子:

java 复制代码
@Component("beanone")
class BeanOne implements Bean{}
@Component("beanTwo")
class BeanTwo implements Bean{}
@Service
class Test{
//此时会报错,先byName,发现没有找到bean
//然后通过byType找到了两个Bean:beanone和beanTwo,仍然没办法匹配
    @Resource
    private Bean bean;
    //先byame直接找到了beanone,然后注入
    @Resource
    private Bean beanone;
    //显示通过byType注入,能注入成功
    @Resource(type = BeanOne.class)
    private Bean bean;

作用域不同

1.Autowired可以作用在构造器,字段,setter方法上

2.Resource 只可以使用在field,setter方法上

支持方不同

1.Autowired是Spring提供的自动注入注解,只有Spring容器会支持,如果做容器迁移,是需要修改代码的

2.Resource是JDK官方提供的自动注入注解(JSR-250)。它等于说是一个标准或者约定,所有的I0C容器都会支持这个注解。假如系统容器从Spring迁移到其他IOC容器中,是不需要修改代码的。

相关推荐
QQ_AHAO2 个月前
SpringBoot原理解析(三)- Bean的属性注入方式
java·spring boot·后端·autowired·属性注入·aware
SuperHeroWu74 个月前
【HarmonyOS】鸿蒙应用子模块module资源如何获取
华为·harmonyos·openharmony·resource·rawfile·获取资源
菠菠萝宝5 个月前
【吃透Java手写】- Spring(上)-启动-扫描-依赖注入-初始化-后置处理器
java·开发语言·spring·autowired·component·componentscan·beannameaware
Yongqiang Cheng6 个月前
Ubuntu Desktop Server - Resource temporarily unavailable
resource·ubuntu desktop·ubuntu server·temporarily·unavailable
爱看书的小沐7 个月前
【小沐学QT】QT学习之资源文件qrc的使用
c++·qt·widget·resource·qrc·qt资源·qresource
丁总学Java10 个月前
Spring-IOC-Spring6和JUnit5集成
spring·bean·autowired·configuration·junitconfig
WalkingWithTheWind~1 年前
Spring Boot 下载文件(word/excel等)文件名中文乱码问题|构建打包不存在模版文件(templates等)
utf-8·spring boot·乱码·template·resource
bug菌¹1 年前
Spring Boot进阶(57):Spring中什么时候不要用@Autowired注入 | 超级详细,建议收藏
spring boot·springboot零基础入门·autowired·autowired注入