filter,interceptor,controllerAdvice,aspect,controller执行顺序

1、filter,这是java的过滤器,和框架无关的,是所有过滤组件中最外层的,从粒度来说是最大的。

配置方式,有直接实现Filter+@component,@Bean+@configuration(第三方的filter)

2、interceptor,spring框架的拦截器

配置方式,@configuration+继承WebMvcConfigurerAdapter或WebMvcConfigurationSupport类添加过滤器。

  • 继承WebMvcConfigurationSupport不需要声明@EnableWebMvc注解,继承WebMvcConfigurerAdapter需要 @see org.springframework.web.servlet.config.annotation.EnableWebMvc
  • @RestController的类和带@ResponseBody的方法在被调用后response会直接写入输出流,在postHandle和afterCompletion这两个方法执行之前就已经把数据返回,导致这两个方法里面的response根本获取不到响应数据
    https://blog.csdn.net/codeblf2/article/details/102732255

3、aspect,可以自定义要切入的类甚至再细的方法,粒度最小。加个注解用效果更佳。

4、controllerAdvice,是controller的增强,和ExceptionHandler一起用来做全局异常。也可以配合ResponseBodyAdvice接口来对@ResponseBody的返回数据进行加工再返回(同理还有RequestBodyAdvice-> @RequestBody等)

@ControllerAdvice
public class StringResponseBodyAdvice implements ResponseBodyAdvice<String> {


    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }


    @Override
    public String beforeBodyWrite(String body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response)             
    {
        return body;
    }
}

总结:

filter:和框架无关,可以控制最初的http请求,但是更细一点的类和方法控制不了。

interceptor:可以控制请求的控制器和方法,但控制不了请求方法里的参数。

aspect : 可以自定义切入的点,有方法的参数,但是拿不到http请求,可以通过其他方式如RequestContextHolder获得。


https://blog.csdn.net/m0_37664906/article/details/88546641
https://www.jianshu.com/p/2d1fa2834d9c
https://mp.weixin.qq.com/s/Z3ZemxPHBDAUWE-YEHyyDg
过滤器拦截器区别:https://my.oschina.net/u/4455409/blog/4767381

https://www.cnblogs.com/java-spring/p/12742984.html

posted @ 2020-09-23 19:40  guardWei  阅读(1109)  评论(0编辑  收藏  举报