代码结构 路径下的所有controller里面的方法,访问都需要经过aop
package com.example.demo.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class DemoAop {
@Around("execution(* com.example.demo.controller.*.*(..))")
public Object tenantAop(ProceedingJoinPoint point) {
long start = System.currentTimeMillis();
Object proceed = null;
//执行方法前
try {
//执行方法
proceed = point.proceed();
//执行方法
} catch (Throwable throwable) {
//抛出异常
throwable.printStackTrace();
}finally {
//最终通知
}
long end = System.currentTimeMillis();
System.out.println("aop打印执行时间:"+(end - start));
return proceed;
}
}
controller层代码
@RestController
public class TestController {
@GetMapping("test")
public void test(){
System.out.println("执行方法内容");
}
}
执行结果
扩展知识
前置通知 Before:执行方法前执行
后置通知 @AfterReturning:在方法不抛出异常的情况下执行
异常通知 @AfterThrowing:在连接点抛出异常后执行
最终通知 @After:执行方法后,不管有没有发生异常都会执行
环绕通知 @Around:方法执行前和执行后或者是异常,都会执行环绕通知内容