@Autowired和@Resource的使用

一. @Autowired注解

 源码:

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

	/**
	 * Declares whether the annotated dependency is required.
	 * <p>Defaults to {@code true}.
	 */
	boolean required() default true;

}

可以看到其中只有一个属性可以选择 required,这个属性代表,我们容器启动时候是否必须进行值加载给对应的属性,对于这个注解是通过byType注入的,意思就是我们容器如果存在类型和当前属性一样,将会将容器中的该bean赋值给被@Autowired修饰的属性,如果存在多个类型匹配,请在需要被注入的bean上加@Primary进行标识,具体可以参考:AutowiredAnnotationBeanPostProcessor 源码

二. @Resource注解

源码:

@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 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.
     */
    Class<?> type() default java.lang.Object.class;

}

这个注解主要是默认通过byName进行bean查找,意思就是如果查找到我们指定的别名和这个容器中的名字存在相同,而且能够被正常赋值,那么可以就查找成功,如果没有查到,我们将通过byType进行查找,具体源码,可以参考CommonAnnotationBeanPostProcessor 源码

总结:一般我们使用@Autowired和@Resource基本没有咋分,有时候可能会遇到我们@Autowired出错情况,要不就是找不到bean,或者bean超过一个,这个时候@Resource我们通过指定名字注入就能避免部分问题,所以使用根据情况选择。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值