如何使用Spring实现自动装配Bean

发布时间:2021-05-24 11:52:13 作者:小新
来源:亿速云 阅读:115

这篇文章将为大家详细讲解有关如何使用Spring实现自动装配Bean,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

要使用自动装配,就需要配置 <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 配置文件修改成自动装配形式,如下所示。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p" 
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation=" 
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="personDao" class="com.mengma.annotation.PersonDaoImpl" />
<bean id="personService" class="com.mengma.annotation.PersonServiceImpl"
autowire="byName" />
<bean id="personAction" class="com.mengma.annotation.PersonAction"
autowire="byName" />
</beans>

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

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

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

如何使用Spring实现自动装配Bean

关于“如何使用Spring实现自动装配Bean”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

推荐阅读:
  1. 怎么在Spring中使用Struts实现自动装配
  2. 怎么在Spring中自动装配Bean属性

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring bean

上一篇:如何实现iOS语言本地化/国际化

下一篇:微信小程序vant弹窗组件怎么实现

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》