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

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

问题描述

我想使用 @Autowire 并使用过滤器。所以我在 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容器调用,因为如果过滤器没有注册为豆,它只会被击中一次。是什么原因以及如何解决?

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将自动注册任何bean带有servlet容器的过滤器。一种选择是不将您的过滤器公开为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.

如果您希望能够将依赖项自动装入您的过滤器,那么它需要是一个豆子。这意味着您需要告诉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天全站免登陆