基于tx/aop命名空间的spring声明式事务管理

来源:互联网 发布:淘宝开店货源哪里找 编辑:程序博客网 时间:2024/05/18 00:26

我们知道,spring声明式事务管理有两种方式:1、使用tx/aop命名空间XML配置文件式的方式 ;2、使用@Transactional注解的方式。
在本文中,我将会介绍第一种方式配置spring声明式事务管理。
首先,在我们使用spring声明式管理前,我们需要导入几个相关的jar包:
Spring-Aop相关jar包
下面我们先编写我们的application.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:p="http://www.springframework.org/schema/p"    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"    xsi:schemaLocation="                http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd              http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.2.xsd              http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd"><bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">    <!-- transactionManager 顾名思义为 事务管理者 -->    <tx:advice id="txAdvice" transaction-manager="transactionManager">        <tx:attributes>            <tx:method name="add*" propagation="REQUIRED" />            <tx:method name="del*" propagation="REQUIRED" />            <tx:method name="mod*" propagation="REQUIRED" />            <tx:method name="*" propagation="REQUIRED" read-only="true" />        </tx:attributes>    </tx:advice>    <!-- aop配置信息 -->    <aop:config>        <!-- 这里pointcut为定义aop的切面 -->        <aop:pointcut id="interceptorPointCuts"            expression="execution(*           news.dao.*.*(..))" />        <aop:advisor advice-ref="txAdvice" pointcut-ref="interceptorPointCuts" />    </aop:config>

注:

1.以上 <tx:attributes> 中<method name=”add*”>里为定义我们在代码中使用 add为开头的方法会启用spring进行事务管理。
2.expression=”execution(* news.dao.* .* (..))” 代码当中第一个 * 为定义通配 返回值类型;第二个 * 为定义通配 news.dao包中所有类;第三个* 为定义通配 类中的任意方法。第四(..) 为定义方法中可以有任意参数。

这样,我们在dao层中spring便会实施管理,自动为我们dao层中代码使用事务了。

下一篇,我将为大家介绍基于@Transactional注解方式的spring声明式事务管理。

0 0