Spring AOP:實現Request資訊獲取
阿新 • • 發佈:2018-11-14
關鍵程式碼
ServletRequestAttributes attributes = (ServletRequestAttributes)
RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
RequestLogAop
@Aspect @Order(5) @Component public class RequestLogAop { private staticfinal Logger LOGGER = LoggerFactory.getLogger(RequestLogAop.class); private ThreadLocal<RequestInfo> localInfo = new ThreadLocal<>(); @Pointcut("execution(public love.ning.yangxuyue.common.base.ResultBean *(..))") public void requestLogAop() { } @Before("requestLogAop()")public void outInfo(JoinPoint joinPoint) { // 接收到請求,記錄請求內容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 記錄下請求內容 RequestInfo info = new RequestInfo(); info.setUrl(request.getRequestURI()); info.setIp(request.getRemoteAddr()); info.setClientPort(request.getRemotePort()); info.setServerPort(request.getServerPort()); info.setHttpMethod(request.getMethod()); info.setClassMethod(joinPoint.getSignature().getDeclaringTypeName()+ "." + joinPoint.getSignature().getName()); info.setArgs(Arrays.toString(joinPoint.getArgs())); localInfo.set(info); System.out.println(info); } @AfterReturning(returning = "body", pointcut = "requestLogAop()") public void doAfterReturning(Object body) throws Throwable { RequestInfo info = localInfo.get(); info.setReturnMsg(body); // 處理RequestInfo System.out.println(info); // 刪除ThreadLocal中的資料,以防記憶體洩露問題 localInfo.remove(); } //@AfterThrowing(pointcut = "webPointcut()", throwing = "e") //public void handleThrowing(Exception e) { // e.printStackTrace(); // logger.error("發現異常!" + e.getMessage()); //logger.error(JSON.toJSONString(e.getStackTrace())); // //這裡輸入友好性資訊 // writeContent("出現異常"); // }
切面的處理順序問題。
@Order(i)註解來標識切面的優先順序。i的值越小,優先順序越高。
例如:一個切面為@Order(10),而上文中另一個切面為@Order(5)
在@Before中優先執行@Order(5)的內容,再執行@Order(10)的內容
在@After和@AfterReturning中優先執行@Order(10)的內容,再執行@Order(5)的內容
總結:
在切入點前的操作,按order的值由小到大執行
在切入點後的操作,按order的值由大到小執行