15.3 XML配置文件

15.3 XML配置文件

从1.0版本开始,Spring就支持基于XML的配置,从2.5版本开始,增加了通过注解的配置支持。

使用XML文件配置beans

下面介绍如何使用XML文件配置beansbeansxml配置文件的根元素通常为:

1
2
3
4
5
6
7
<?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">
...
</beans>

如果需要更强的Spring配置能力,可以在schemalocation属性中添加相应的schema

配置文件可以是一份,也可以分解为多份,以支持模块化配置。ApplicationContext的实现类支持读取多份配置文件。另一种选择是,通过一份主配置文件,将该文件导入到其他配置文件。

beans的xml文件导入其他被子beans的xml文件

下面是一个beans的配置文件导入其他beans的配置文件的示例:

1
2
3
4
5
6
7
8
9
10
<?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">
<import resource="config1.xml"/>
<import resource="module2/config2.xml"/>
<import resource="/resources/config3.xml"/>
...
</beans>

bean元素的配置后面将会详细介绍。