原文地址:https://www.toutiao.com/a6713376817320837643/?tt_from=mobile_qq&utm_campaign=client_share×tamp=1563152683&app=news_article_lite&utm_source=mobile_qq&utm_medium=toutiao_ios&req_id=201907150904430100270571455767307&group_id=6713376817320837643
其他相關地址:https://blog.csdn.net/a657281084/article/details/78485500(一個很不錯的AspectJ的Execution表達式說明)
https://blog.csdn.net/a657281084/article/details/78485500(Spring 事物 expression="execution(*service..*.*(..))")
https://blog.csdn.net/qq_15037231/article/details/80624064(JoinPoint的用法)
https://blog.csdn.net/a9529lty/article/details/7031070(org.aspectj.lang.JoinPoint-中文簡要API)
https://www.cnblogs.com/lvbinbin2yujie/p/10186862.html(Spring Aop AfterReturning接收返回值)
第五章springboot2.0添加aop日誌實現記錄請求地址
liveorverday 2019-07-14 12:50:45
1. 添加spring-boot-starter-aop包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
2. 新建WebLogAspect類
3. 添加@Aspect @Component註解
4. 實現方法
package com.dyp.config;
import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
@Aspect
@Component
public class WebLogAspect {
private Logger logger = LoggerFactory.getLogger(getClass());
//定義execution表達式使用
@Pointcut("execution(public * com.dyp.controller..*.*(..))")
public void webLog(){}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 接收到請求,記錄請求內容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 記錄下請求內容
logger.info("URL : " + request.getRequestURL().toString());
logger.info("HTTP_METHOD : " + request.getMethod());
logger.info("IP : " + request.getRemoteAddr());
logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
}
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
// 處理完請求,返回內容
logger.info("RESPONSE : " + ret);
}
}
5. 測試