Spring自动安装(二)autowire=“byName”
Spring自动装配(二)autowire=“byName”
在Spring配置文件中bean标签中的autowire属性的值为byName
指:根据属性名自动装配。此选项将检查容器并根据名字查找与属性完全一致的bean,并将其与属性自动装配。例如,在bean定义中将autowire设置为by name,而该bean包含master属性(同时提供setMaster(..)方法),Spring就会查找名为master的bean定义,并用它来装配给master属性。
案例:autowire=“byName”
1、创建TeacherServiceImpl类
2、创建StudentServiceImpl类
以上两步骤的代码见《Spring自动装配(一)autowire=“no”》
3、配置文件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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="studentServiceImpl" class="cn.zd.service.StudentServiceImpl">
<property name="studentName">
<value>张迪</value>
</property>
</bean>
<!-- TeacherServiceImpl这个类中因为使用了autowire="byName"参数,
所以当引用StudentServiceImpl这个类时会自动在配置文件中寻找与studentServiceImpl对象名相同的id名进行加载就不需要使用ref来指明对象了。
注意:只适用于类的对象的引用
-->
<bean id="teacherServiceImpl" class="cn.zd.service.TeacherServiceImpl" autowire="byName">
<property name="teacherName">
<value>陈</value>
</property>
</bean>
</beans>
解析:TeacherServiceImpl这个类中因为使用了autowire="byName"参数,所以当引用StudentServiceImpl这个类时会自动在配置文件中寻找与studentServiceImpl对象名相同的id名进行加载就不需要使用ref来指明对象了。
注意:只适用于类的对象的引用。
4、测试类TestNO,代码见《Spring自动装配(一)autowire=“no”》
5、运行结果:
老师的名字是:陈 陈老师的学生是:张迪
------------------------------------------
以上为个人理解总结,若有不足,请高手指点....