Filter invoke twice when register as Spring bean

2020-01-23 03:43发布

问题:

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();
    }

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

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?

回答1:

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.

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;
}