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