@Autowired / @Resource / @Inject用法总结

这篇博客详细总结了Spring中常用的自动注入注解@Autowired、JSR 330规范的@Inject以及JSR 250规范的@Resource的用法。@Autowired主要根据类型进行装配,可以与@Qualifier结合按名称装配。@Inject与@Autowired类似,但其required属性默认为false,允许没有匹配的bean。@Resource则按名称进行装配,属于JSR 250规范。

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

@Autowired / @Resource / @Inject用法总结

一直以来,写的项目中用到的自动注入注解都是@autowired,突然有次面试问到三者区别,却不知如何回答,这里趁着手上的项目完结,集中总结一下。

首先创建一个类,交给spring管理

import org.springframework.stereotype.Component;

@Component("test")
public class TestComonent {

    public static final String TEST="测试成功啦~~~~";

}

一、@Autowired

spring自带的注解,根据类型进行自动装配,可以使用在成员变量、setter方法、构造方法上,如果和@Qualifier一起使用,则按照名称装配,同时,@Qualifier使用在成员变量、setter方法入参、构造方法入参上

代码块

1.@Autowired用在成员变量上,例如:

    @Autowired
    private TestComonent component;

    @Autowired
    @Qualifier("test")
    private TestComonent component;

2.@Autowired使用在setter方法上

    private TestComonent component;

    @Autowired
    public void setComponent(TestComonent component) {
        this.component = component;
    }
    private TestComonent component;

    @Autowired
    public void setComponent(@Qualifier("test")TestComonent component) {
        this.component = component;
    }

3.@Autowired使用在构造方法上

    private TestComonent component;

    @Autowired
    public TestController(TestComonent component){
        this.componente =component;
    }
   private TestComonent component;

    @Autowired
    public TestController(@Qualifier("test")TestComonent component){
        this.component=component;
    }

二、@Inject

SR330中的规范,需要导入java x.inject.Inject;实现注入。
@Inje行自动装配,与@Named(“XXX”)配合使名称进行装配。
@Inject使用在成员变量、setter方法、构造方法上,@Named使用在成员变量、setter方法入参、构造方法入参上
注:使用方法和@Autowired一致。
不同点:@Autowired有个属性为required,默认为true,如果配置为false之后,当没有找到相应bean的时候,系统不会抛错;

三、 @Resource

SR250中的规范,按照名称进行装配,需要导入javax.annotation实现注入
@Resource可以作用在变量、setter方法上。

   @Resource(name="test")
   private TestComonent component;
    private TestComonent component;

    @Resource(name="test")
    public TestController(TestComonent component){
        this.component=component;
    }   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值