School类
package com.bjpowernode.pojo2;
public class School {
private String name;
private String address;
public School(){
System.out.println("学习无参被调用");
}
public void setName(String name) {
this.name = name;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString(){
return "Student{"+
"name="+name+'\''+
",age+"+address+
'}';
}
}
Student类
package com.bjpowernode.pojo2;
public class Student {
private String name;
private int age;
//引用类型学生变量,所在学校
private School school;
//学生无参构造方法
public Student() {
System.out.println("学生的无参构造方法");
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setSchool(School school) {
this.school = school;
}
@Override
public String toString(){
return "Student{"+
"name="+name+'\''+
",age="+age+
"school="+school+
'}';
}
}
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--创建学校对象
等同于Student stu=new Student();
id:就是创建的对象的名称
class:就是创建的对象的类型,底层通过反射构建对象-->
<bean id="school" class="com.bjpowernode.pojo2.School">
<property name="name" value="中国海洋大学"></property>
<property name="address" value="市南区"></property>
</bean>
<!--创建学生对象-->
<bean id="stu" class="com.bjpowernode.pojo2.Student">
<property name="name" value="张三"></property>
<property name="age" value="18"></property>
<property name="school" ref="school"></property>
</bean>
</beans>
test
package com.bjpowernode.test;
import com.bjpowernode.pojo2.School;
import com.bjpowernode.pojo2.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest2 {
@Test
public void testStudent(){
//创建容器对象
ApplicationContext ac=new ClassPathXmlApplicationContext("s02/applicationContext.xml");
//取出学校的对象
School school=(School) ac.getBean("school");
System.out.println(school);
}
@Test
public void testStudent2(){
//创建容器对象
ApplicationContext ac=new ClassPathXmlApplicationContext("s02/applicationContext.xml");
//取出学生的对象
Student stu2=(Student) ac.getBean("stu");
System.out.println(stu2);
}
}
运行结果如下图所示