zoukankan      html  css  js  c++  java
  • SpringAnnotation注解之@Resource

    @Resource:同样也是注入,默认是按byName,byName找不到的话按byType


    1
    2
    3
    4
    @Resource
    public 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")






  • 相关阅读:
    【BestCoder #48】
    【一场模拟赛?】
    【普通の随笔】6.30
    【BestCoder #45】
    【BestCoder #44】
    【普通の惨败】GDOI2015卖萌记
    我的新博客
    【BZOJ 2964】Boss单挑战
    【NOI 2015】软件包管理器
    【NOI 2015】程序自动分析
  • 原文地址:https://www.cnblogs.com/meet/p/4758211.html
Copyright © 2011-2022 走看看