开发者

springboot filter配置多个时,执行顺序问题

开发者 https://www.devze.com 2023-12-12 10:35 出处:网络 作者: 小布的世界
目录springboot filter配置多个时,执行顺序springboot也提供了注解的方式总结springboot filter配置多个时,执行顺序
目录
  • springboot filter配置多个时,执行顺序
  • springboot也提供了注解的方式
  • 总结

springboot filter配置多个时,执行顺序

在 spring boot 配置Filter过滤器 中简单介绍了spring boot 中如何添加过滤器,有人问到如果配置多个怎么控制,先经过哪个过滤器,后经过哪个过滤器。

在web.XML中,我们知道,执行顺序是谁在前边执行谁。

在spring boot中的FilterRegistrationBean注册过滤器的类中有个order属性,

private int order = Ordered.LOWEpythonST_PRECEDENCE;

细看源码可以知道,这个order的默认值是Integer.MAX_VALUE 也就是int的最大值,

spring boot 会按照order值的大小,从小到大的顺序来依次过滤。

spring boot 配置Filter过滤器 中可以这样修改

    /**
     * 配置过滤器
     * @return
     */
    @Bean
    public FilterRegistrationBean someFilterRegistr编程客栈ation() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.s编程客栈etFilter(sessionFilter());
        registration.addUrlPatterns("/*");
        registration.addInitParameter("paramName", "paramValue");
        registration.setName("sessionFilter");
        registration.setOrder(Integer.编程MAX_VALUE);
        return registration;
    }

再有一个过滤器的话,可以设置成

registration.setOrder(Integer.MAX_VALUE - 1)

springboot也提供了注解的方式

例如:

/**
     * 配置过滤器
     * @return
     */
    @Bean
    @Order(Integer.MAX_VALUE)
    public FilterRegistrationBean someFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(sessionFilter());
        registration.addUrlPatterns("/*");
  编程      registration.addInitParameter("paramName", "paramValue");
        registration.setName("sessionFilter");
        return registration;
    }

上面两种方法都行,想用那种看你喜欢。。。。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号