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