10.AOP统一处理Web请求日志

POM文件新增依赖

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

WebLogAspect类

@Aspect
@Component
public class WebLogAspect {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Pointcut("execution(public * com.shujuwajue.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());
        Enumeration<String> enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String name = (String) enu.nextElement();
            logger.info("name:{},value:{}", name, request.getParameter(name));
        }
    }
    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求,返回内容
        logger.info("RESPONSE : " + ret);
    }
}

额外示例,

对注解GetMapping拦截,并通过方法拿到GetMapping内的参数值.

package com.boot.study.aop;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;

@Component
@Aspect
public class AopTest {

  // 定义切片
	@Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping)")
	public void aspect() {

	}

	@Before("aspect()")
	public void before(JoinPoint joinPoint) {
		System.out.println(joinPoint);
	}

	@Around("aspect()")
	public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
		System.out.println(joinPoint);
		MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
		GetMapping getMapping = methodSignature.getMethod().getAnnotation(GetMapping.class);
		String[] strings = getMapping.value();
		System.out.println(Arrays.toString(strings));

		Object[] objects = joinPoint.getArgs();
		System.out.println(Arrays.toString(objects));

		return joinPoint.proceed();
	}

}

资料

springboot引入AOP

spring-boot使用AOP统一处理日志

  • @Pointcut 定义一个方法为切点里面的内容为一个表达式,下面详细介绍

  • @Before 在切点前执行方法,内容为指定的切点

  • @After 在切点后,return前执行,

  • @AfterReturning 在切入点,return后执行,如果想对某些方法的返回参数进行处理,可以在这操作

  • @Around 环绕切点,在进入切点前,跟切点后执行

  • @AfterThrowing 在切点后抛出异常进行处理

  • @order(i) 标记切点的优先级,i越小,优先级越高

Last updated