spring基于XML的事务配置

这篇博客详细介绍了如何在Spring中配置AOP和事务管理。首先,引入了AOP所需的AspectJ和CGLIB依赖。接着,注册了DataSourceTransactionManager作为事务管理器,并配置了切入点来指定哪些方法参与事务。然后,通过aop:config和tx:advice设置了事务属性,如只读事务和异常回滚策略。最后,针对不同的业务方法,定义了不同的事务传播行为和回滚规则,以确保数据的一致性。

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

具体操作:

1. 加入 AOP 依赖包

 <!-- AOP 所需依赖 -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
        </dependency>
        <!-- AOP 所需依赖 -->
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
        </dependency>

2. 注册配置事务管理器

<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
</bean>

3. 配置AOP,定位哪些方法参与事务

 <aop:config>
        <!--配置切入点:该配置的作用是确定哪些方法参与事务   execution(public void com.crowd.service.AdminService.saveAdmin(Admin admin))-->
        <aop:pointcut id="txPointCut" expression="execution(* *..*Service.*(..))"></aop:pointcut>
        <!--将事务通知和切入点关联起来-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"></aop:advisor>
    </aop:config>

4.配置事务属性

	<!--配置通知-->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <!--配置事务的属性-->
        <tx:attributes>
            <!--配置查询方法为只读 :可以提高性能-->
            <tx:method name="get*" read-only="true"/>
            <tx:method name="query*" read-only="true"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="count*" read-only="true"/>
            <!--配置增删改方法 ,propagation属性为REQUIRES_NEW时,如果方法在另一个事务中启动,会重新创建一个新的事务-->
            <!--rollback-for: 针对什么样的异常事务会进行回滚 默认情况下是运行时回滚,建议编译和运行异常时都回滚-->
            <tx:method name="save*" propagation="REQUIRES_NEW" rollback-for="java.lang.Exception"/>
            <tx:method name="update*" propagation="REQUIRES_NEW" rollback-for="java.lang.Exception"/>
            <tx:method name="remove*" propagation="REQUIRES_NEW" rollback-for="java.lang.Exception"/>
            <tx:method name="batch*" propagation="REQUIRES_NEW" rollback-for="java.lang.Exception"/>
        </tx:attributes>
    </tx:advice>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值