spring AOP基于XML声明式事务管理的简单应用

实际使用场景:为了避免java中间件或者前台程序出错而数据库数据依旧成功修改这种情况出现,要使用spring的事务管理组件防止数据出错

第零步:引入jar包(cglib包必须引入,否则aop会失效,织入不成功)

在这里插入图片描述

第一步:配置数据源连接池(这里采用的c3p0连接池)

<!-- 加载数据库文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 获取信息 -->
<bean id="comboPooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
 <property name="user" value="${jdbc.username}"></property>
 <property name="password" value="${jdbc.password}"></property>
 <property name="jdbcUrl" value="${jdbc.url}"></property>
 <property name="driverClass" value="${jdbc.driver}"></property>
</bean>

第二步:定义transactionManager这个bean(事务管理器常用的有四种,hibernate的、jta的、jdo的、jdbc的,这里我直接选用Jdbc的)

<!-- 配置事务管理器 -->
 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
     <property name="dataSource" ref="comboPooledDataSource" />
 </bean>

第三步:设置自动代理(不设置自动代理,aop会失效)

<aop:aspectj-autoproxy proxy-target-class="true"/>

第四步:使用tx标签配置拦截器(aspectj表达式必须准确,否则aop织入会失效)

<tx:advice id="txAdvice" transaction-manager="transactionManager">
 <tx:attributes>
  <tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/>
 </tx:attributes>
</tx:advice>
<aop:config>
  <!-- 原来是写com.web.service,实际上项目的package是com.web.Service -->
 <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.web.Service.*.*(..))" /> 
</aop:config>

补充说明:如果同时使用事务管理切面和日志输出切面的话,可以这么配置,同时写两个aop:config

<bean id = "logAspect" class = "com.web.aspect.LogAspect"></bean>
<aop:config>
 <aop:aspect id="LogAspect" ref="logAspect">
  <aop:pointcut expression="execution(* com.web.Service.*.*(..))" id="logPointCut"/>
  <!-- 原来是写com.web.service,实际上项目的package是com.web.Service -->
  <aop:before method="doBefore" pointcut-ref="logPointCut"/>
  <aop:after method="after" pointcut-ref="logPointCut"/>
  <aop:around method="Around" pointcut-ref="logPointCut"/>
  <aop:after-returning method="AfterReturning" pointcut-ref="logPointCut"/>
  <aop:after-throwing method="AfterThrowing" pointcut-ref="logPointCut" throwing="error"/>
 </aop:aspect>   
</aop:config>

<aop:config>
 <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.web.Service.*.*(..))" /> 
</aop:config>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值