ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Spring自动装配Bean

2019-10-28 15:00:08  阅读:263  来源: 互联网

标签:装配 autowire Spring Bean 自动 Property 属性


要使用自动装配,就需要配置 <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 元素定义。

下面通过修改《Spring基于Annotation装配Bean》中的案例演示如何实现自动装配。首先将 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() 方法,控制台的显示结果如图 1 所示。

运行结果
图 1  运行结果


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

标签:装配,autowire,Spring,Bean,自动,Property,属性
来源: https://www.cnblogs.com/lowerma/p/11752310.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有