在spring中, 可以定义多个配置文件。
例子:
①首先定义一个班级类和一个学生类
1 package com.fuwh.spring;
2
3 public class Clazz {
4
5 private String name;
6 private int grade;
7
8 public int getGrade() {
9 return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public Clazz() {
System.out.println("Clazz类被初始化");
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student [name=" + name + ", grade=" + grade + "]";
}
}
1 package com.fuwh.spring;
2
3 public class Student {
4
5 private String name;
6 private int age;
7 private Clazz clazz;
8
9 public Clazz getClazz() {
return clazz;
}
public void setClazz(Clazz clazz) {
this.clazz = clazz;
}
public Student() {
System.out.println("Student类被初始化");
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ",grade=" + clazz.getGrade()+clazz.getName() +"]";
}
}
② 定义两个配置文件,分别配置clazz(beanClazz)和student(studentClazz)
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://www.springframework.org/schema/beans
5 http://www.springframework.org/schema/beans/spring-beans.xsd">
6
7 <!-- services -->
8
9 <bean id="clazz" class="com.fuwh.spring.Clazz" lazy-init="default">
<property name="name" value="信息与计算科学"></property>
<property name="grade" value="08"></property>
</bean>
</beans>
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://www.springframework.org/schema/beans
5 http://www.springframework.org/schema/beans/spring-beans.xsd">
6
7 <!-- services -->
8
9 <bean id="student" class="com.fuwh.spring.Student" lazy-init="default">
<property name="name" value="fengzi"></property>
<property name="age" value="23"></property>
<property name="clazz" ref="clazz"></property>
</bean>
</beans>
③接下来测试一下,由于使用了多个配置文件的方式,所以在实例化applicationContext的时候,需要给ClassPathXmlApplicationContext传递一个配置文件的数组
1 package com.fuwh.spring;
2
3 import org.springframework.context.ApplicationContext;
4 import org.springframework.context.support.ClassPathXmlApplicationContext;
5
6 public class Spring01 {
7
8 public static void main(String[] args) {
9
// ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
ApplicationContext ac=new ClassPathXmlApplicationContext(new String[]{"beanStudent.xml","beanClazz.xml"});
System.out.println(ac.getBean("student"));
}
14 }
★也可以在beanStudent.xml文件中,使用如下命令,将beanClazz.xml文件引入进来。这样在实例化ApplicationContext的时候,就只需要传入beanStudent.xml文件即可。
【<import resource="beanClazz.xml"/>】