• Spring自动装配Bean


    除了使用 XML 和 Annotation 的方式装配 Bean 以外,还有一种常用的装配方式——自动装配。自动装配就是指 Spring 容器可以自动装配(autowire)相互协作的 Bean 之间的关联关系,将一个 Bean 注入其他 Bean 的 Property 中。

    要使用自动装配,就需要配置 元素的 autowire 属性。autowire 属性有五个值,具体说明如表 1 所示。

    名称说明
    byName根据 Property 的 name 自动装配,如果一个 Bean 的 name 和另一个 Bean 中的 Property 的 name 相同,则自动装配这个 Bean 到 Property 中。
    byType根据 Property 的数据类型(Type)自动装配,如果一个 Bean 的数据类型兼容另一个 Bean 中 Property 的数据类型,则自动装配。
    constructor根据构造方法的参数的数据类型,进行 byType 模式的自动装配。
    autodetect如果发现默认的构造方法,则用 constructor 模式,否则用 byType 模式。
    no默认情况下,不使用自动装配,Bean 依赖必须通过 ref 元素定义。

    下面通过修改《Spring基于Annotation装配Bean》中的案例演示如何实现自动装配。首先将 applicationContext.xml 配置文件修改成自动装配形式,如下所示。

    1. <beans xmlns="http://www.springframework.org/schema/beans"
    2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xmlns:aop="http://www.springframework.org/schema/aop"
    4. xmlns:p="http://www.springframework.org/schema/p"
    5. xmlns:tx="http://www.springframework.org/schema/tx"
    6. xmlns:context="http://www.springframework.org/schema/context"
    7. xsi:schemaLocation="
    8. http://www.springframework.org/schema/beans
    9. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    10. http://www.springframework.org/schema/aop
    11. http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
    12. http://www.springframework.org/schema/tx
    13. http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
    14. http://www.springframework.org/schema/context
    15. http://www.springframework.org/schema/context/spring-context.xsd">
    16. <bean id="personDao" class="com.mengma.annotation.PersonDaoImpl" />
    17. <bean id="personService" class="com.mengma.annotation.PersonServiceImpl"
    18. autowire="byName" />
    19. <bean id="personAction" class="com.mengma.annotation.PersonAction"
    20. autowire="byName" />
    21. beans>

    在上述配置文件中,用于配置 personService 和 personAction 的 元素中除了 id 和 class 属性以外,还增加了 autowire 属性,并将其属性值设置为 byName(按属性名称自动装配)。

    默认情况下,配置文件中需要通过 ref 装配 Bean,但设置了 autowire=”byName”,Spring 会在配置文件中自动寻找与属性名字 personDao 相同的 ,找到后,通过调用 setPersonDao(PersonDao personDao)方法将 id 为 personDao 的 Bean 注入 id 为 personService 的 Bean 中,这时就不需要通过 ref 装配了。

    使用 JUnit 再次运行测试类中的 test() 方法,控制台的显示结果如图 1 所示。


    图 1 运行结果

    从图 1 的输出结果中可以看出,使用自动装配的方式同样完成了依赖注入。

     

  • 相关阅读:
    Qt实现多人聊天室(单聊、群聊、文件传输)
    Java LinkedList类详解
    (翻译)JavaFX高级教程:JavaFX2.0的FXML语言
    NodeJs - for循环的几种遍历方式
    3.webpack4初体验(webpack可以处理的文件)
    23种设计模型
    【2022-05-31】JS逆向之易企秀
    数字先锋 | 随时随地云端阅片,“云胶片”时代来啦!
    【前端】“局部页面跳转”的作用与缺陷
    工控机通过Profinet转Modbus RTU网关连接变频器与电机通讯案例
  • 原文地址:https://blog.csdn.net/unbelievevc/article/details/126278174