Spring Boot - 4

AOP

@Aspect

编写切面处理类,加上@Aspect注解,还需要添加**@Component**加入IOC容器中

@Pointcut

为了去除重复的切入点配置,通常设置一个@Pointcut注解的方法来管理切入点 而其他相同切入点的方法调用该方法即可

@AfterReturning

可以获取从服务端发回的数据,并打印到日志里

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.medemede.springbootdemo1.controller.GrilController.girlList(..))")
    public void log(){
        logger.info("-->切入");
    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        logger.info("-->事务执行前");
        ServletRequestAttributes attributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attributes.getRequest();

        //url
        logger.info("url={}",request.getRequestURL());

        //method
        logger.info("method={}",request.getMethod());

        //ip
        logger.info("ip={}",request.getRemoteAddr());

        //类方法
        logger.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName()+"()");

        //参数
        logger.info("args={}",joinPoint.getArgs());

    }

    @After("log()")
    public void doAfter(){
        logger.info("-->事务执行后");
    }


    //获取服务端的响应数据
    @AfterReturning(returning = "o",pointcut = "log()")
    public void doAfterReturnint(Object o){
        logger.info("response={}",o.toString());
    }

}
# 开发 

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×