栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring 中Aop的使用注解完成通知的使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring 中Aop的使用注解完成通知的使用

1.引入aop依赖


    
      org.aspectj
      aspectjweaver
      1.9.7
    

2.开启包扫描

3.使用aop开启注解

 

 4.创建切面类使用注解

package cn.kgc.spring.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;


@Component
@Aspect  //标记当前类时通知类
public class AllAdvice {
    //实现切点表达式的复用
    @Pointcut("execution(* *(..))")
    public void all(){

    }
    //前置通知
    @Before("all()")
    public void before() {
        System.out.println("---前置通知---");
    }

    //后置通知
    @AfterReturning("execution(* *(..))")
    public void afterReturning() {

        System.out.println("-------------后置通知---------------");

    }

    //最终通知 不管核心业务是否有异常 均要执行
    @After(("execution(* *(..))"))
    public void after() {

        System.out.println("-------------最终通知---------------");

    }

    //异常通知 核心业务出现异常时添加的通知 没有异常不添加
    @AfterThrowing(("execution(* *(..))"))
    public void afterThrowing() {
        System.out.println("---异常通知---");
    }

    //环绕通知
    @Around(("execution(* *(..))"))
    public Object around(ProceedingJoinPoint proceedingJoinPoint) {
        try {
            System.out.println("---环绕前置通知---");
            Object proceed = proceedingJoinPoint.proceed();
            System.out.println("---环绕后置通知---");
            return proceed;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.println("---环绕异常通知---");
        } finally {
            System.out.println("---环绕最终通知---");
        }
        return null;
    }

}

5.运行结果

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1006761.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号