Spring自动装配Bean实现过程详解

网友投稿 251 2022-12-13


Spring自动装配Bean实现过程详解

这篇文章主要介绍了Spring自动装配Bean实现过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

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

表 1 autowire 的属性和作用

名称

说明

byName

根据 Property 的 name 自动装配,如果一个 Bean 的 name 和另一个 Bean 中的 Property 的 name 相同,则自动装配这个 Bean 到 Property 中。

byType

根据 Property 的数据类型(Type)自动装配,如果一个 Bean 的数据类型兼容另一个 Bean 中 Property 的数据类型,则自动装配。

constructor

根据构造方法的参数的数据类型,进行 byType 模式的自动装配。

autodetect

如果发现默认的构造方法,则用 constructor 模式,否则用 byType 模式。

no

默认情况下,不使用自动装配,Bean 依赖必须通过 ref 元素定义。

下面通过案例演示如何实现自动装配。首先将 applicationContext.xml 配置文件修改成自动装配形式,如下所示。

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:aop="http://springframework.org/schema/aop"

xmlns:p="http://springframework.org/schema/p"

xmlns:tx="http://springframework.org/schema/tx"

xmlns:context="http://springframework.org/schema/context"

xsi:schemaLocation="

http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-2.5.xsd

http://springframework.org/schema/aop

http://springframework.org/schema/aop/spring-aop-2.5.xsd

http://springframework.org/schema/tx

http://springframework.org/schema/tx/spring-tx-2.5.xsd

http://springframework.org/schema/csHFGUontext

http://springframework.org/schema/context/spring-context.xsd">

autowire="byName" />

autowire="byName" />

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:aop="http://springframework.org/schema/aop"

xmlns:p="http://springframework.org/schema/p"

xmlns:tx="http://springframework.org/schema/tx"

xmlns:context="http://springframework.org/schema/context"

xsi:schemaLocation="

http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-2.5.xsd

http://springframework.org/schema/aop

http://springframework.org/schema/aop/spring-aop-2.5.xsd

http://springframework.org/schema/tx

http://springframework.org/schema/tx/spring-tx-2.5.xsd

http://springframework.org/schema/csHFGUontext

http://springframework.org/schema/context/spring-context.xsd">

autowire="byName" />

autowire="byName" />

autowire="byName" />

autowire="byName" />

autowire="byName" />

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

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

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


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:基于java web获取网页访问次数代码实例
下一篇:Spring JDK动态代理实现过程详解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~