Spring切面处理日志

业务场景:在web服务中添加日志,要求在刚进入方法和结束方法的时候打印开始和结束日志;进入方法好说,直接在第一行打印即可,但是return的时候可能会有很多分支,所以我们必须要在更上一层进行处理

实现步骤:
1.创建TestRequestBodyAdvice并实现RequestBodyAdvice接口,类上添加注解@ControllerAdvice
2.创建TestResponseBodyAdvice并实现ResponseBodyAdvice接口,类上添加注解@ControllerAdvice
3.修改其中的默认返回值;例如null改为对应值,false改为true(这个不要盲目的改)
4.引入logger类
5.在关键位置写入要打印的日志
具体代码如下:

@ControllerAdvice
public class TestRequestBodyAdvice implements RequestBodyAdvice {

    private Logger logger= LoggerFactory.getLogger(TestRequestBodyAdvice.class);

    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        return httpInputMessage;
    }

    public Object afterBodyRead(Object object, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        logger.debug("即将进入{}方法",methodParameter.getMethod().getName());
        return object;
    }

    public Object handleEmptyBody(Object object, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return object;
    }
}




@ControllerAdvice
public class TestResponseBodyAdvice implements ResponseBodyAdvice {

    private Logger logger= LoggerFactory.getLogger(TestResponseBodyAdvice.class);

    public boolean supports(MethodParameter methodParameter, Class aClass) {
        if (aClass.isAssignableFrom(MappingJackson2CborHttpMessageConverter.class)){
            return true;
        }
        return false;
    }

    public Object beforeBodyWrite(Object object, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        logger.debug("即将进入{}方法",methodParameter.getMethod().getName());
        return object;
    }
}
* 以上两个类并非只是打印日志的作用,他可以在所有请求的进入和返回时刻进行处理,例如进行简单的参数校验,或者查询为空时在此处理给前端一个默认返回值等

* 以上代码采用了适配器模式,通过supports函数来判断是否进入下面的函数进行逻辑处理

发表评论

电子邮件地址不会被公开。 必填项已用*标注