AOP

头像
LLL_
    阅读 2 分钟

    依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>

    AOP详情

    常用的动态代理技术
    JDK代理:基于接口的动态代理技术
    CGLIB代理:基于父类的动态代理技术(默认)
    
    1、before通知                  在执行目标方法之前执行
    2、afterRhrowing通知           在目标方法执行之后执行
    3、afterReturning通知          在目标方法执行之后报错时执行
    4、after通知                   无论什么时候程序执行完成都要执行的通知
    5、around通知(功能最为强大)      在目标方法执行前后执行
    因为环绕通知可以控制目标方法是否执行,控制程序的执行的轨迹
    
    切入点表达式
    1、bean("bean的ID") 粒度:粗粒度 按bean匹配 当前bean中的方法都会执行通知
    2、within("包名.类名") 粒度:粗粒度 可以匹配多个类
    3、execution("返回值类型 包名.类名.方法名(参数列表)") 粒度:细粒度 方法参数级别
    4、@annotation("包名.类名") 粒度:粗粒度 按照注解匹配

    例子

    @Aspect                         //把当前类标识为一个切面供容器读取
    @Component                      //交给spring boot去管理
    public class CommonAop {
    
        //Pointcut是植入Advice的触发条件
        //within("包名.类名") 粒度:粗粒度 可以匹配多个类
        @Pointcut("within(com.hj.controller.LogController)")
        public void oneAop(){}
    
        //within("包名.类名") 粒度:粗粒度 匹配多个类
        @Pointcut("within(com.hj.controller.LogController)||within(com.hj.controller.StudentController)")
        public void twoAop(){}
    
        //execution("返回值类型 包名.类名.方法名(参数列表)") 粒度:细粒度 方法参数级别 参数列表可以使用*代替多个参数
        @Pointcut("execution(* com.hj.controller.StudentController.selectAll())")
        public void threeAop(){}
    
        //@annotation("注解") 调用到该注解匹配
        @Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping)")
        public void fourAop(){}
    
        @Around("oneAop()")
        public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
            System.out.println("Around开始执行");
            Object proceed = joinPoint.proceed();
            System.out.println("Around执行完毕");
            return proceed;
        }
    
        @AfterReturning("threeAop()")
        public Object afterReturning(ProceedingJoinPoint joinPoint) throws Throwable {
            System.out.println("AfterReturning开始执行");
            Object proceed = joinPoint.proceed();
            System.out.println("AfterReturning执行完毕");
            return proceed;
        }
    
    
    }

    LLL_
    15 声望3 粉丝