共同点:
@Resource和@Autowired都是用于bean的注入
@Resource和@Autowired都可以标注在字段和方法上
不同点:
@Autowired为Spring提供的注解,导入的依赖为org.springframework.beans.factory.annotation.Autowired
@Resource由J2EE提供,导入的依赖为javax.annotation.Resource
@Autowired注解默认是按照类型(byType)装配依赖对象,如果spring容器中存在一个与指定属性类型相同的bean,那么将与该属性自动装配。如果存在多个该类型的bean,那么会抛出异常。默认@Autowired是要求依赖对象必须存在的,否则会抛出异常,当然我们也可以设置@Autowired注解的required属性(这也是Autowired注解唯一的属性),将required设为false即可。
@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;
}
@Resource默认是按照名称来自动装配(byName),它会查找spring容器中bean名称与@Resource属性名相同的bean,并将其自动装配到@Resource标注的属性。@Resource除了byName配置,它也支持byType配置,只需要配置@Resource注解的type属性即可。
下面介绍下@Resource的装配顺序:
①如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常。
②如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常。
③如果指定了type,则从上下文中找到类似匹配的唯一bean进行装配,找不到或是找到多个,都会抛出异常。
④如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配。
@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 "";
/**
* 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;
....省略其他属性字段
}