@Resource:同样也是注入,默认是按byName,byName找不到的话按byType
1
2
3
4
@Resourcepublic void setUserDao(UserDao userDao) {
this.userDao = userDao;
}xml文件里,没有一个名字为userDao的bean
1
2
3
4
5
6
<bean id="userDaoImpl" class="com.fz.annotation.dao.impl.UserDaoImpl">
</bean>
<bean id="userDaoImpl1" class="com.fz.annotation.dao.impl.UserDaoImpl">
</bean>
<bean id="userService" class="com.fz.annotation.service.UserService">
</bean>
此时测试的时候会报错,因为默认按byName,此时是没有名字为userDao的bean的,所以再次按byType,但是byType会出现两个相同类型的bean
所以会报错。
此时,删掉一个bean的定义
1
2
3
4
<bean id="userDaoImpl1" class="com.fz.annotation.dao.impl.UserDaoImpl">
</bean>
<bean id="userService" class="com.fz.annotation.service.UserService">
</bean>
再次测试的时候就正常,不会报错。
然后,再测试byName
1
2
3
4
<bean id="userDao" class="com.fz.annotation.dao.impl.UserDaoImpl">
</bean>
<bean id="userService" class="com.fz.annotation.service.UserService">
</bean>
此时测试就没问题,因为这里的bean名称为userDao,和参数的名字setUserDao(UserDao userDao)是一样的。
总结:
1、@Resource可以写在属性上,方法上
2、@Resource:默认按byNmae注入,byName找不到则按byType
3、如果按byType找的话,如果找到多个相同类型的bean,则可以指定name来决定使用哪个bean
@Resource(name="userDaoImpl1")