注册为 Spring bean 时过滤器调用两次 [英] Filter invoke twice when register as Spring bean

查看:29
本文介绍了注册为 Spring bean 时过滤器调用两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 @AutowireFilter 一起使用.所以我在 SecurityConfig 中定义了我的过滤器,如下所示:

I want to use @Autowire with a Filter. So I define my filter in the SecurityConfig as below:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.addFilterBefore(getA(), BasicAuthenticationFilter.class);
        http.csrf().disable();
    }

    @Bean
    public A getA(){
        return new A();
    }

这个过滤器A扩展了Spring的GenericFilterBean.

This filter A extends Spring's GenericFilterBean.

当我调用控制器时,输出低于输出,显示过滤器命中了两次.

I get below output when I invoke the controller, which shows the filter hits twice.

filter A before
filter A before
mycontroller invoke
filter A after
filter A after

我的观察是,这个额外的调用使用 Spring 容器调用,因为如果过滤器没有注册为 bean,它只会得到一次点击.是什么原因,我该如何解决?

My observation is, this extra invocation invoke with Spring container because if filter is not register as bean, it only get hits once. What is the reason and how can I fix it?

推荐答案

正如您所观察到的,Spring Boot 会自动向 servlet 容器注册任何 Filter bean.一种选择是不将您的过滤器公开为 bean,而仅将其注册到 Spring Security.

As you have observed, Spring Boot will automatically register any bean that is a Filter with the servlet container. One option is to not expose your filter as a bean and only register it with Spring Security.

如果您希望能够将依赖项自动装配到您的过滤器中,那么它需要是一个 bean.这意味着您需要告诉 Spring Boot 不要将其注册为过滤器.作为 在文档中描述,你使用FilterRegistrationBean来做到这一点:

If you want to be able to autowire dependencies into your Filter then it needs to be a bean. That means you need to tell Spring Boot not to register it as a filter. As described in the documentation, you do that using a FilterRegistrationBean:

@Bean
public FilterRegistrationBean registration(MyFilter filter) {
    FilterRegistrationBean registration = new FilterRegistrationBean(filter);
    registration.setEnabled(false);
    return registration;
}

这篇关于注册为 Spring bean 时过滤器调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆