在 Spring 中,除了使用基于 XML 的方式可以实现声明式事务管理以外,还可以通过 Annotation 注解的方式实现声明式事务管理。
使用 Annotation 的方式非常简单,只需要在项目中做两件事,具体如下。
1 在 Spring 容器中注册驱动,代码如下所示:
<tx:annotation-driven transaction-manager="txManager"/>
2 在需要使用事务的业务类或者方法中添加注解 @Transactional,并配置 @Transactional 的参数。关于 @Transactional 的参数如下图所示。
下面通过修改Spring声明式事务管理(点击跳转至Spring声明式事务管理)中银行转账的案例讲解如何使用 Annotation 注解的方式实现 Spring 声明式事务管理。
1. 注册驱动
修改 Spring 配置文件 applicationContext.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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema