相信大家用spring的自动装配的时候就首先想到 @Autowired,但是今天我要谈谈@Resource的自动装备,
@Resource装配顺序
1. 如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常
2. 如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常
3. 如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常
4. 如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,
则回退为一个原始类型进行匹配,如果匹配则自动装配;
因为@Resource注解在字段上,这样就不用写setter方法了,并且这个注解是属于J2EE的,减少了与spring的耦合。
这样代码看起就比较优雅。
现在我们来看一下使用@Resource的准备
在spring配置文件中声明打开注解和配置相应的bean
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<context:annotation-config />
<bean
class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
在要注入相应的bean的字段上使用该注解
@Resource
private IUserDao userDao;
这样就全搞定了