一. @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我们通过指定名字注入就能避免部分问题,所以使用根据情况选择。