欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Boot 菜鸟笔记(三) 使用AOP处理请求

程序员文章站 2022-06-02 19:36:24
...

Spring Boot 菜鸟笔记(三) 使用AOP处理请求

1、添加依赖

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

2、建立aspect包,在其下建立HttpAspect类

@Aspect
@Component
public class HttpAspect {
    @Before("execution(public * com.egghu.girl.controller.GirlController.*(..))")
    public void log(){
        System.out.println(11111);
    }
    @After("execution(public * com.egghu.girl.controller.GirlController.*(..))")
    public void doAfter(){
        System.out.println(22222);
    }
}

或是

@Aspect
@Component
public class HttpAspect {


    @Pointcut("execution(public * com.egghu.girl.controller.GirlController.*(..))")
    public void log(){
    }
    @Before("log()")
    public void doBefore(){
        System.out.println(11111);
    }
    @After("log()")
    public void doAfter(){
        System.out.println(22222);
    }
}

或是

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


    @Pointcut("execution(public * com.egghu.girl.controller.GirlController.*(..))")
    public void log(){
    }
    @Before("log()")
    public void doBefore(){
        logger.info("11111");
    }
    @After("log()")
    public void doAfter(){
        logger.info("22222");
    }
}

最终形式(HttpAspect):

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


    @Pointcut("execution(public * com.egghu.girl.controller.GirlController.*(..))")
    public void log(){
    }
    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes=(ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request= attributes.getRequest();
        //url
        logger.info("url={}",request.getRequestURI());
        //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("22222");
    }
    //获取输出的内容
    @AfterReturning(returning = "object",pointcut = "log()")
    public void doAfterReturning(Object object){
        logger.info("response={}",object);
    }
}

为了获取输出的内容,在Girl中要添加toString方法

@Override
    public String toString() {
        return "Girl{" +
                "id=" + id +
                ", cupSize='" + cupSize + '\'' +
                ", age=" + age +
                '}';
    }
相关标签: Spring Boot