1.引入starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.切面代码
package com.util;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
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.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.alibaba.fastjson.JSON;
@Aspect
@Component
public class RequestAspect {
private Logger logger = Logger.getLogger(RequestAspect.class);
@Pointcut("execution(public * com.web.controller.*.*(..))")
public void log(){}
@Before("log()")
public void exBefore(JoinPoint joinPoint){
ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = sra.getRequest();
logger.info("url:"+request.getRequestURL());
logger.info("method:"+request.getMethod());
logger.info("class method:"+joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
logger.info("args:"+JSON.toJSONString(joinPoint.getArgs()));
}
@After("log()")
public void exAfter(JoinPoint joinPoint){
logger.info("class method:"+joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName()
+"方法执行完毕!");
}
@AfterReturning(returning="result",pointcut="log()")
public void exAfterReturning(Object result){
logger.info("执行返回值:"+JSON.toJSONString(result));
}
}