1. 程式人生 > >SpringBoot 使用AOP處理請求

SpringBoot 使用AOP處理請求

面向切面程式設計AOP是一種程式設計正規化,與語言無關,是一種程式設計思想

使用AOP統一處理請求日誌

1、增加maven配置

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

2、新增類

package cn.edu.shu.ces_chenjie.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
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;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class HttpAspect {
    private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    //新增一個切點
    @Pointcut("execution(public * cn.edu.shu.ces_chenjie.controller.PersonController.*(..))")
    public void log(){
    }

    //在切點執行以前
    @Before("log()")
    public void before(JoinPoint joinPoint){
        logger.info("-------------------------所有請求結束之前進行攔截-------------------------------------");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        logger.info("url={}",request.getRequestURL());
        logger.info("method={}",request.getMethod());
        logger.info("ip={}",request.getRemoteAddr());
        logger.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName() + "." +
                joinPoint.getSignature().getName()
        );
        logger.info("args={}",joinPoint.getArgs());
    }

    //在切點執行以後
    @After("log()")
    public void after(){
        logger.info("-------------------------所有請求結束之後進行攔截-------------------------------------");
    }

    //在切點返回以後
    @AfterReturning(pointcut = "log()",returning = "object")
    public void afterReturning(Object object){
        logger.info("response={}",object);
    }
}

3、執行