返回介绍

1.1 XML 配置文件

发布于 2025-04-22 20:09:57 字数 1303 浏览 0 评论 0 收藏

从 1.0 版本开始,Spring 就支持基于 XML 的配置;从 2.5 版本开始,增加了通过注解的配置支持。下面介绍如何配置 XML 文件。配置文件的根元素通常为 beans:

< ?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 配置能力,可以在 schema location 属性中添加相应的 schema,也可以指定 schema 版本:

http://www.springframework.org/schema/beans/spring-beans-4.2.xsd

不过,笔者推荐使用默认 schema,以便升级 spring 库时无需修改配置文件。

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

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

< ?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 元素的配置后面将会详细介绍。

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。