自动装配

通过id名字进行自动装配

新建测试用的两个bean类:ClassRoom、Teacher

代码如下:

 Teacher类:

public class Teacher {
	private Integer teacherNo;
	private String name;
	/**
	 * 
	 * @return the teacherNo
	 */
	public Integer getTeacherNo() {
		return teacherNo;
	}
	/**
	 * @param teacherNo the teacherNo to set
	 */
	public void setTeacherNo(Integer teacherNo) {
		this.teacherNo = teacherNo;
	}
	/**
	 * 
	 * @return the name
	 */
	public String getName() {
		return name;
	}
	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}
	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "Teacher [teacherNo=" + teacherNo + ", name=" + name + "]";
	}

 

 ClassRoom类:

public class ClassRoom {
	private String className;
	private String classNo;
	private Teacher teacher;
	/**
	 * 
	 * @return the className
	 */
	public String getClassName() {
		return className;
	}
	/**
	 * @param className the className to set
	 */
	public void setClassName(String className) {
		this.className = className;
	}
	/**
	 * 
	 * @return the classNo
	 */
	public String getClassNo() {
		return classNo;
	}
	/**
	 * @param classNo the classNo to set
	 */
	public void setClassNo(String classNo) {
		this.classNo = classNo;
	}
	/**
	 * 
	 * @return the teacher
	 */
	public Teacher getTeacher() {
		return teacher;
	}
	/**
	 * @param teacher the teacher to set
	 */
	public void setTeacher(Teacher teacher) {
		this.teacher = teacher;
	}
	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "Class [className=" + className + ", classNo=" + classNo
				+ ", teacher=" + teacher + "]";
	}
	
	
}

 配置文件如下:

<?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.xsd">

	<bean id="teacher" class="com.pfSoft.autowire.beans.Teacher" p:teacherNo="89757" p:name="L林俊杰"></bean>
	<bean id="classRoomBean" class="com.pfSoft.autowire.beans.ClassRoom" p:classNo="302" p:className="三年二班" autowire="byName"></bean>
</beans>

 关键点在于,autowire选择的是byName。同时id为“teacher”的bean,与ClassRoom类中seeter风格的属性名具有相同的名字。因此实现了通过名字进行自动装配。

同样的autowire="byType"是表示可以通过类型来进行自动匹配,不过需要注意的是如果同类型有多个bean的话就会报不只一个的异常了。

 

posted on 2016-04-21 22:56  falcon_fei  阅读(286)  评论(0编辑  收藏  举报