第一步:添加依赖
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-aop</artifactId>
- </dependency>
第二步:定义一个切面类
- package com.example.demo.aop;
- import java.lang.reflect.Method;
- import java.util.Arrays;
- import javax.servlet.http.HttpServletRequest;
- import org.aspectj.lang.JoinPoint;
- import org.aspectj.lang.ProceedingJoinPoint;
- import org.aspectj.lang.annotation.*;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.core.annotation.Order;
- import org.springframework.stereotype.Component;
- import org.springframework.web.context.request.RequestContextHolder;
- import org.springframework.web.context.request.ServletRequestAttributes;
- import static com.sun.xml.internal.ws.dump.LoggingDumpTube.Position.Before;
- @Component
- @Aspect // 将一个java类定义为切面类
- @Order(-1)//如果有多个aop,这里可以定义优先级,越小级别越高
- public class LogDemo {
- private static final Logger LOG = LoggerFactory.getLogger(LogDemo.class);
- @Pointcut("execution(* com.example.demo.test.TestController.test(..))")//两个..代表所有子目录,最后括号里的两个..代表所有参数
- public void logPointCut() {
- }
- @Before("logPointCut()")
- public void doBefore(JoinPoint joinPoint) throws Throwable {
- // 接收到请求,记录请求内容
- ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
- HttpServletRequest request = attributes.getRequest();
- System.out.println("before");
- }
- @After(value = "logPointCut()")
- public void after(JoinPoint joinPoint) {
- System.out.println("after");
- }
- @AfterReturning(returning = "ret", pointcut = "logPointCut()")// returning的值和doAfterReturning的参数名一致
- public void doAfterReturning(Object ret) throws Throwable {
- System.out.println("AfterReturning");
- }
- @Around("logPointCut()")
- public void doAround(ProceedingJoinPoint pjp) throws Throwable {
- System.out.println("around1");
- Object ob = pjp.proceed();//环绕通知的进程方法不能省略,否则可能导致无法执行
- System.out.println("around2");
- }
- }
注意:
如果同一个 切面类,定义了定义了两个 @Before,那么这两个 @Before的执行顺序是无法确定的
对于@Around,不管它有没有返回值,但是必须要方法内部,调用一下 pjp.proceed();否则,Controller 中的接口将没有机会被执行,从而也导致了 @Before不会被触发
测试的controller如下:
-
- package com.example.demo.test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class TestController {
@RequestMapping(value = "test",method = RequestMethod.GET)
@ResponseBody
public String test(String name){
System.out.println("============method");
return name;
}
}
-
配置完成,看看效果,输出如下:
- around1
- before
- ============method
- around2
- after
- AfterReturning
可以看到,切面方法的执行如下:
around-->before-->method-->around-->after-->AfterReturning
如果配置了@AfterThrowing,当有异常时,执行如下:
around-->before-->method-->around-->after-->AfterThrowing