【注解】添加spring的aop事务管理的通知类型

4 篇文章 0 订阅
1 篇文章 0 订阅

事务的通知类型有:
1.前置通知,后置通知,异常通知,最终通知
2.环绕通知可以自定义通知的顺序灵活调用上面的通知方法()
配置方式是:
不管是xml配置的还是注解配置的都要引入空间和约束声明:
在这里插入图片描述
导入依赖坐标:

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.2.RELEASE</version>
 </dependency>
 <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.7</version>
</dependency>
    基于xml配置的
<!--配置事务通知类型对象-->
    <aop:config>
        <!--配置切入点-->
        <aop:pointcut id="pc" expression="execution(* com.test.service.impl..*.*(..))"></aop:pointcut>
        <!--配置通知类型-->
        <aop:aspect id="logAdvice" ref="transactionManager">
            <!--前置通知-->
            <aop:before method="beginTransaction" pointcut-ref="pc"></aop:before>
            <!--后置通知-->
            <aop:after-returning method="commit" pointcut-ref="pc" ></aop:after-returning>
            <!--异常通知-->
            <aop:after-throwing method="rollback" pointcut-ref="pc"></aop:after-throwing>
            <!--最终通知-->
            <aop:after method="close" pointcut-ref="pc"></aop:after>
            <!--环绕型通知-->
            <!--<aop:around method="aroundPringLog" pointcut="execution(* com.test.service.impl..*.*(..))"></aop:around>-->
        </aop:aspect>
    </aop:config>


基于注解的方式:
第一步要在配置文件开启组件扫描:

<!--配置包组件扫描-->
<context:component-scan 
base-package="com.test"></context:component-scan>

第二步:开启aop注解支持

<!--配置spring开启注解AOP支持-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

配置切面类:

@Component("logger")
@Aspect  //声明切面类
public class Logger {

开启事务通知:

@Component("logger")
@Aspect  //声明切面类
public class Logger {
    @Pointcut("execution(* com.test.service..*.*(..))")
    public void myexcute(){

    }
    /**
     * 前置通知
     */
    @Before("myexcute()")
    public void beforePrintLog() {
       //这里开启事务 代码略
    }

    /**
     * 后置通知
     */
    @AfterReturning("myexcute()")
    public void afterReturningPrintLog() {
       这里提交事务 代码略
    }

    /**
     * 异常通知
     */
    @AfterThrowing("myexcute()")
    public void afterThrowingPrintLog() {
       这里回滚事务 代码略
    }

    /**
     * 最终通知
     */
    @After("myexcute()")
    public void afterPrintLog() {
       这里关闭事务 代码略
    }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值