Skip to content

附录 (Appendix)

本附录列出了与数据访问相关的 XML Schema(架构定义),包括 txjdbc 命名空间。

XML Schemas

1. tx Schema

tx 标签用于配置 Spring 综合事务支持中的所有 Bean。这些标签在 事务管理 章节中进行了详细介绍。

建议

我们强烈建议你查看 Spring 分发包中自带的 spring-tx.xsd 文件。该文件包含了 Spring 事务配置的 XML Schema,涵盖了 tx 命名空间中的所有元素,包括属性默认值等信息。该文件内部带有完整的文档注释,因此为了遵循 DRY(Don't Repeat Yourself)原则,这里不再重复这些详细信息。

要使用 tx 架构中的元素,你需要在 Spring XML 配置文件的顶部添加以下声明。以下代码片段引用了正确的 Schema,以便你可以使用 tx 命名空间中的标签:

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:tx="http://www.springframework.org/schema/tx" <!-- (1) -->
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans
		https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/tx
		https://www.springframework.org/schema/tx/spring-tx.xsd <!-- (2) -->
		http://www.springframework.org/schema/aop
		https://www.springframework.org/schema/aop/spring-aop.xsd">

	<!-- Bean 定义 -->

</beans>
  1. 声明使用 tx 命名空间
  2. 指定 Schema 位置(与其他 Schema 位置一起)。

注意

通常,在使用 tx 命名空间中的元素时,你也会使用 aop 命名空间中的元素(因为 Spring 的声明式事务支持是使用 AOP 实现的)。上述 XML 片段包含了引用 aop Schema 所需的相关行。

2. jdbc Schema

jdbc 元素允许你快速配置内嵌数据库或初始化现有的数据源。这些元素分别在 内嵌数据库支持初始化 DataSource 中有详细文档。

要使用 jdbc 架构中的元素,你需要在 XML 配置文件的顶部添加以下声明:

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:jdbc="http://www.springframework.org/schema/jdbc" <!-- (1) -->
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans
		https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/jdbc
		https://www.springframework.org/schema/jdbc/spring-jdbc.xsd"> <!-- (2) -->

	<!-- Bean 定义 -->

</beans>
  1. 声明使用 jdbc 命名空间
  2. 指定 Schema 位置

补充教学

1. XML Schema (XSD) 的作用是什么?

在 Spring 的 XML 配置文件中,XSD 就像是一个“语法说明书”。

  • 校验:它告诉 IDE(如 IntelliJ IDEA 或 Eclipse)哪些标签是合法的,哪些属性是必填的。
  • 提示:正是因为有了 XSD,你在写代码时才能享受到标签补全功能。
  • 版本控制:URL 中的 spring-tx.xsd 通常会指向最新版本。如果你想锁定特定版本,可以使用类似 spring-tx-4.3.xsd 的路径。

2. 为什么现在的 Spring 很少看到 XML 了?

随着 Spring 3.0 引入 Java Config(@Configuration)和 Spring Boot 的流行,大多数配置已迁移到 Java 类和注解。

  • XML 的现状:在维护遗留系统(Legacy Systems)或某些特定的企业级中间件配置时,XML 仍然存在。
  • 对应关系
    • <tx:annotation-driven/> 对应 Java 中的 @EnableTransactionManagement
    • <jdbc:embedded-database/> 对应 Java 中的 EmbeddedDatabaseBuilder

3. 理解 Namespace 处理过程

Spring 在启动时,会通过 META-INF/spring.handlers 文件找到处理特定命名空间的 NamespaceHandler。 例如,当 Spring 看到 tx 命名空间时,它会调用 TxNamespaceHandler 来解析这些标签,并动态地创建相应的事务切面和后置处理器。这就是为什么简简单单一行 XML 就能开启强大事务功能的原因。 No browser pages are currently open. Running terminal commands:

  • pnpm run docs:dev (in f:\project\doc, running for 44m55s)

Based on Spring Framework.