@Resource VS @Autowired @上源码

1.@Resource VS @Autowired

@Resource与@Autowired都可以用来完成Spring Bean的注入。

@Resource并不是spring提供的(javax.annotation.Resource)。

@Autowired为Spring提供的注解(org.springframework.beans.factory.annotation.Autowired)。

@Resource = (@Autowired +@Qualifier)。

2.@Autowired

package org.springframework.beans.factory.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

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

@Autowired 注解单独使用只能按照类型(by type)注入依赖对象,同时要求注入对象必须存在,可通过设置required=false允许注入对象为null。可以使用@Autowired组合@Qualifier方式来实现按照名称(by name)注入依赖对象。

public class OrderServiceImpl {
    @Autowired
    @Qualifier("orderDao")
    private OrderDao orderDao; 
}

3.@Resource

package javax.annotation;

import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;

@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
public @interface Resource {

    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 默认按照名称(by name)注入依赖对象,@Resource有两个核心属性name,type;Spring将name属性解析为bean的名称,将type属性解析为bean的类型。

@Resource装配顺序:

1.同时指定了name和type属性,则从Spring上下文中找到唯一匹配的bean进行注入,找不到则抛出异常。

2.仅指定了name属性,则从Spring上下文中查找名称(id)匹配的bean进行注入,找不到则抛出异常。

3.仅指定了type属性,则从Spring上下文中找到类型匹配的唯一bean进行注入,找不到或找到多个,都会抛出异常。

4.name和type都未指定,则默认按照名称方式进行注入;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动注入。

@浅见 @如有疏漏请帮忙补充完善 @开发一家人  0000002

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值