关于java:AOP

6次阅读

共计 1559 个字符,预计需要花费 4 分钟才能阅读完成。

依赖

<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;
    }


}
正文完
 0