@Resource注解的解释

@Resource注解是什么?

@Resource(基于类的名称)注解与@Autowired注解类似,也是用来进行依赖注入的,@Resource时Java层面所提供的注解,@Autowired(基于类型type)是Spring所提供的注解,它们依赖注入的底层实现逻辑也不同。

@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
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 "";

    /**
     * The name of the resource that the reference points to. It can
     * link to any compatible resource using the global JNDI names.
     *
     * @since Common Annotations 1.1
     */

    String lookup() default "";

    /**
     * The Java type of the resource.  For field annotations,
     * the default is the type of the field.  For method annotations,
     * the default is the type of the JavaBeans property.
     * For class annotations, there is no default and this must be
     * specified.
     */
    Class<?> type() default java.lang.Object.class;
 }

@Resource注解中有一个name属性,针对name属性是否有值,@Resource的依赖注入底层流程是不同的。

@Resource(name="student")    //这里的student是指bean的ID
private Student student;

@Resource如果name属性有值,那么Spring会直接根据所指定的name值去Spring容器找Bean对象,如果找到了则成功,如果没有找到则报错。

 @Resource()         
 //未指定name,默认取将要注入属性的字段名,
 //如下Student是类类型,student是属性名也就是字段名 
private Student student;

如果@Resource中的name属性没有值,则:

  1. 先判断该属性名字在Spring容器中是否存在Bean对象。
  2. 如果存在,则成功找到Bean对象进行注入。
  3. 如果不存在,则根据属性类型去Spring容器找Bean对象,找到一个则进行注入。

@Resource也可以使用在构造方法上。

  • 5
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值