• AOP在Spring Boot中如何使用


    AOP在开发中的用处还是很广的,它的设计模式是代理模式,里面的原则就是在不改变源码的基础上增加一些新的功能。比如说项目上线了,但是发现项目中的某个模块运行的很慢,这个时候就需要打印日志去查看,那么可以使用AOP把代码动态的嵌入到项目中,如果检测完成,移除它就可以了。

    下面来看一下,它在Spring Boot中是如何使用的。

    package com.zl.aop.component;
    
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.*;
    import org.springframework.stereotype.Component;
    //声明这是一个组件
    @Component
    //定义他是一个切面
    @Aspect
    public class LogComponent {
        //定义拦截规则第一个*表示方法返回值任意
        //com.zl.aop.Service.*.*的意思是:这个包里面任意类里面的任意方法,
       //(..)表示参数任意,
        @Pointcut("execution(* com.zl.aop.Service.*.*(..))")
        public void pc(){
        }
        //前置通知
        @Before(value ="pc()")
        public void before(JoinPoint jp){
            //name就是拿到的Service中的方法名
            String name = jp.getSignature().getName();
            System.out.println("before:"+name);
        }
        //后置通知
        @After(value ="pc()")
        public void after(JoinPoint jp){
            //name就是拿到的Service中的方法名
            String name = jp.getSignature().getName();
            System.out.println("after:"+name);
        }
        //返回通知(有返回值就会触发这个方法)
        @AfterReturning(value ="pc()",returning = "result")
        public void afterReturning(JoinPoint jp,Object result){
            //name就是拿到的Service中的方法名
            String name = jp.getSignature().getName();
            System.out.println("afterReturning:"+name+"---"+result);
        }
        //异常通知
        @AfterThrowing(value ="pc()",throwing = "e")
        public void afterThrowing(JoinPoint jp,Exception e){
            //name就是拿到的Service中的方法名
            String name = jp.getSignature().getName();
            System.out.println("afterThrowing:"+name+"---"+e);
        }
        //环绕通知(相当于前四个通知的综合)
        @Around(value ="pc()")
        public Object arount(ProceedingJoinPoint pjp) throws Throwable {
            //proceed就是Service中方法的返回值
            Object proceed = pjp.proceed();
            //这个return会篡改方法的返回值并输出他
            return proceed+"java";
        }
    }

    就是定义一个组件,去获取Service中方法,并对他处理。

    看一下运行结果:

  • 相关阅读:
    LeetCode——面试题57
    翻译——5_Summary, Conclusion and Discussion
    LeetCode——114. 二叉树展开为链表
    LeetCode——1103. 分糖果 II
    LeetCode——337. 打家劫舍 III
    LeetCode——994. 腐烂的橘子
    Python——潜在会员用户预测
    Vue中div高度自适应
    webpack中使用vue-resource
    Mint UI组件库 和 Mui
  • 原文地址:https://www.cnblogs.com/javazl/p/12642714.html
Copyright © 2020-2023  润新知