1 注意事项
a.使用<contructor-arg标签进行属性赋值;
b.使用构造注入的类,只需要有参构造方法即可,可以不用无参构造方法,且不用set方法;
2 实验
2.1 Student类(用于构造注入)
package study.domain;
public class Student {
private int id ;
private String user;
private String password;
private School school;
public Student(int id, String user, String password, School school) {
this.id = id;
this.user = user;
this.password = password;
this.school = school;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", user='" + user + '\'' +
", password='" + password + '\'' +
", school=" + school +
'}';
}
}
2.2 School类(作为引用数据类型使用)
package study.domain;
public class School {
private String name;
private String location;
public void setName(String name) {
this.name = name;
}
public void setLocation(String location) {
this.location = location;
}
@Override
public String toString() {
return "School{" +
"name='" + name + '\'' +
", location='" + location + '\'' +
'}';
}
}
2.3 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="mySchool" class="study.domain.School">
<property name="name" value="qhdx"/>
<property name="location" value="北京"/>
</bean>
<bean id="myStudent" class="study.domain.Student">
<constructor-arg name="id" value="007"/>
<constructor-arg name="password" value="123"/>
<constructor-arg name="school" ref="mySchool"/>
<constructor-arg name="user" value="liming"/>
</bean>
</beans>
2.4 实验结果
package study.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import study.domain.Student;
public class Mytest {
@Test
public void test1(){
String config = "bean.xml";
ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
Student myStudent = (Student) ctx.getBean("myStudent");
System.out.println(myStudent);
}
}