springboot aop使用介紹
阿新 • • 發佈:2018-10-14
參數 sys boot aspect arrays servle 切面 tar div
第一步:添加依賴
<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 classLogDemo { 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
springboot aop使用介紹