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

本文详细介绍了如何使用tx/aop命名空间进行XML配置,实现spring的声明式事务管理。首先,文章提到了需要引入的相关jar包,接着展示了配置application.xml文件的步骤,以此实现对DAO层的事务自动管理。最后预告了下篇将讨论基于@Transactional注解的事务管理方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们知道,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声明式事务管理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值