@Resource和@Autowired的区别

前言

@Resource和@Autowired都是做bean的注入时使用,@Resource的作用相当于@Autowired,只不过@Autowired按照byType自动注入。

其中@Resource并不是Spring的注解,它的包是javax.annotation.Resource,但是Spring支持该注解的注入。

1、共同点

1) @Resource和@Autowired都是用于bean的注入;

2)@Resource和@Autowired都可以标注在字段和setter方法上,两者如果都写在字段上,那么就不需要再写setter方法。

2、不同点

1)@Autowired 源码

@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
    boolean required() default true;
}

@Autowired为Spring提供的注解,需要导入包org.springframework.beans.factory.annotation.Autowired;只按照byType注入。

@Autowired注解是按照类型(byType)注入对象,默认情况下它要求依赖对象必须存在,如果允许null值,可以设置它的required属性为false。如果我们想使用按照名称(byName)来注入,可以结合@Qualifier注解一起使用。

public class TestServiceImpl {
    @Autowired
    @Qualifier("testDao")
    private TestDao testDao;
}

2)@Resource 源码

@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
@Repeatable(Resources.class)
public @interface Resource {
    /**
     * The JNDI name of the resource.  For field annotations,
     * the default is the field name.  For method annotations,
     * the default is the JavaBeans property name corresponding
     * to the method.  For class annotations, there is no default
     * and this must be specified.
     */
    String name() default "";

    String lookup() default "";

    Class<?> type() default java.lang.Object.class;

    enum AuthenticationType {
	    CONTAINER,
	    APPLICATION
    }

    AuthenticationType authenticationType() default AuthenticationType.CONTAINER;

    boolean shareable() default true;

    String mappedName() default "";

    String description() default "";
}

@Resource默认按照 byName 自动注入,由J2EE提供,需要导入包javax.annotation.Resource。

@Resource有两个重要的属性:name和type。

Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以,如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不制定name也不制定type属性,便会通过反射机制使用 byName 自动注入策略。

@Resource 最好放在setter方法上,因为这样更符合面向对象的思想,通过set、get去操作属性,而不是直接去操作属性。

@Resource装配顺序也有不同:

①如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常。

②如果指定了name,则从上下文中查找名称匹配的bean进行装配,找不到则抛出异常。

③如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或是找到多个,都会抛出异常。

④如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配。

 

补充

1)Spring 自动注入 autowire 中 byName 和 byType 的区别

Autowire modes

no

默认不开启

byName

根据被注入属性的名称作为 Bean 名称作为依赖查找,并将对象设置到该属性

byType

根据被注入属性的类型作为依赖类型进行依赖查找,并将该对象设置到该属性

constructor

特殊 byType 类型,用于构造器参数

  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

几行代码

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

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

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

打赏作者

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

抵扣说明:

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

余额充值