• 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")






  • 相关阅读:
    DRF版本控制
    Django Rest Framework 视图和路由
    ModelSerializer
    linux下jdk安装与配置
    linux下各种安装包下载地址
    Creating mailbox file: 文件已存在
    vim常用设置
    zookeeper集群搭建与升级
    linux下shell 脚本 中windows换行符换成linux换行符
    spring注解
  • 原文地址:https://www.cnblogs.com/meet/p/4758211.html
Copyright © 2020-2023  润新知