一、新建类
School.java
public class School {
private String sname;
public void setSname(String sname) {
this.sname = sname;
}
@Override
public String toString() {
return "School{" +
"sname='" + sname + '\'' +
'}';
}
}
School.java
public class Student {
private String name;
private String gender;
private School school;
public void setName(String name) {
this.name = name;
}
public void setGender(String gender) {
this.gender = gender;
}
public void setSchool(School school) {
this.school = school;
}
public void add(){
System.out.println("姓名:"+name+" 性别:"+gender+" 学校"+school);
}
}
二、编写配置文件
在配置文件中配置对象创建并进行注入
bean7.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">
<bean id="stu" class="com.health.IOC.G_注入内部bean.beans.Student">
<property name="name" value="health"/>
<property name="gender" value="男"/>
<property name="school">
<bean id="school" class="com.health.IOC.G_注入内部bean.beans.School">
<property name="sname" value="哈佛大学"/>
</bean>
</property>
</bean>
</beans>
三、测试
test7.java
public class test7 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("com/health/IOC/G_注入内部bean/bean7.xml");
Student stu = context.getBean("stu", Student.class);
stu.add();
}
}
输出结果: