@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属性没有值,则:
- 先判断该属性名字在Spring容器中是否存在Bean对象。
- 如果存在,则成功找到Bean对象进行注入。
- 如果不存在,则根据属性类型去Spring容器找Bean对象,找到一个则进行注入。
@Resource也可以使用在构造方法上。