4 上下文对象的创建
ClassPathXmlApplicationContext context1=
new ClassPathXmlApplicationContext("com/zhiyou100/test01/spring_config.xml");
Student s11=(Student)context1.getBean("stu1");
System.out.println(s11);
context1.close();
FileSystemXmlApplicationContext context2=
new FileSystemXmlApplicationContext("src/com/zhiyou100/test01/spring_config.xml");
Student s12=(Student)context2.getBean("stu1");
System.out.println(s12);
context2.close();
5 多核心配置文件
5.1 方式1:ClassPathXmlApplicationContext构造方法是不定参数
ClassPathXmlApplicationContext context1=
new ClassPathXmlApplicationContext("com/zhiyou100/test01/spring_config01.xml","com/zhiyou100/test01/spring_config02.xml");
Student s11=(Student)context1.getBean("stu1");
System.out.println(s11);
Student s12=(Student)context1.getBean("stu2");
System.out.println(s12);
context1.close();
5.2 方式2:定义一个总的配置文件:通过import引入其他配置文件
<import resource="spring_config01.xml"/>
<import resource="spring_config02.xml"/>
- 创建ClassPathXmlApplicationContext只需要加载总的核心配置文件即可
ClassPathXmlApplicationContext context2=
new ClassPathXmlApplicationContext("com/zhiyou100/test01/spring_config03.xml");
Student s111=(Student)context2.getBean("stu1");
System.out.println(s111);
Student s122=(Student)context2.getBean("stu2");
System.out.println(s122);
context1.close();
6 对象关联
6.1 创建teacher类
public class Teacher implements Serializable{
private Integer tid;
private String tname;
private String tsex;
...
}
6.2 在student类中定义引用指向其关联的teacher对象
public class Student implements Serializable{
...
private Teacher teacher;
...
}
6.3 在核心配置文件中为teacher定义bean 并在student的bean中通过ref来关联此对象
<bean id="stu1" class="com.zhiyou100.test01.Student">
<property name="sid" value="1001"/>
<property name="sname" value="韩梅梅"/>
<property name="sage" value="19"/>
<property name="sdy" value="true"/>
<property name="score" value="11.6"/>
<property name="teacher" ref="tea1"/>
</bean>
<bean id="tea1" class="com.zhiyou100.test01.Teacher">
<property name="tid" value="1"/>
<property name="tname" value="高老师"/>
<property name="tsex" value="女"/>
</bean>
<bean id="stu2" class="com.zhiyou100.test01.Student">
<constructor-arg index="0" value="1003"/>
<constructor-arg index="1" value="韩非子"/>
<constructor-arg index="2" value="29"/>
<constructor-arg index="3" value="false"/>
<constructor-arg index="4" value="35.5"/>
<constructor-arg index="5" ref="tea1"/>
</bean>
6.4 测试
ClassPathXmlApplicationContext context2=
new ClassPathXmlApplicationContext("com/zhiyou100/test01/spring_config04.xml");
Student s111=(Student)context2.getBean("stu1");
System.out.println(s111);
Student s1112=(Student)context2.getBean("stu2");
System.out.println(s1112);
context2.close();
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/80ecc1532b0905acdc950f3fdc460d93.png)