题解代码:
1.Student.java
package step3;
public class Student {
private String name;
private int age;
private double score;
/****** Begin ******/
Student(String name,int age,double score){
this.name=name;
this.age=age;
this.score=score;
}
/****** End ******/
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", score=" + score
+ "]";
}
}
2.Teacher.java
package step3;
public class Teacher {
private String name;
private String grade;//学生年级
private Student student;
/****** Begin ******/
Teacher(String name,String grade,Student student){
this.name=name;
this.grade=grade;
this.student=student;
}
/****** End ******/
@Override
public String toString() {
return "Teacher [name=" + name + ", grade=" + grade + ", student="
+ student + "]";
}
}
3.applicationContext.java
<?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 -->
<bean id="teacher" class="step3.Teacher">
<constructor-arg value="张老师"></constructor-arg>
<constructor-arg value="C366"></constructor-arg>
<constructor-arg ref="student"></constructor-arg>
</bean>
<bean id="student" class="step3.Student">
<constructor-arg value="小花"></constructor-arg>
<constructor-arg value="18"></constructor-arg>
<constructor-arg value="89.0"></constructor-arg>
</bean>
<!--结束配置 -->
</beans>
4.Test.java
package step3;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
//使用ApplicationContext容器获取对象
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext3.xml");
Teacher t = app.getBean("teacher",Teacher.class);
//打印对象
System.out.println(t.toString());
}
}