如果我们在spring框架中配置了多个xml文件,我们可以在读取配置文件的时候把这些xml文件一下全都读取,也可以只读一个总的xml文件,在这个总的xml文件中把其他的xml全都都导入进来。
比如:
POJO类我就不写了,想要的可以去我前几篇找~
有配置文件student.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<bean name="student" class="com.x.spring.bean.Student">
<property name="id" value="1"></property>
<property name="name" value="tom"></property>
<property name="age" value="20"></property>
</bean>
</beans>
还有teacher.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<bean name="teacher" class="com.x.spring.bean.Teacher">
<property name="student" ref="student"></property>
</bean>
</beans>
需求:
比如我想一起读取这俩个配置文件,可以在创建个配置文件,代码如下:
import.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<import resource="student.xml"/>
<import resource="teacher.xml"/>
</beans>
测试类ImportTest:
public class ImportTest {
public static void main(String[] args) {
//一个xml配置文件中 导入另外一个xml配置文件
//String[] path = {"com/x/spring/test3/imp/teacher.xml","com/x/spring/test3/imp/student.xml"};
String[] path = {"com/x/spring/test3/imp/import.xml"};
ApplicationContext container =
new ClassPathXmlApplicationContext(path);
Teacher t = (Teacher)container.getBean("teacher");
System.out.println(t);
System.out.println(t.getStudent());
System.out.println(t.getStudent().getName());
}
}
效果图: