Filter invoke twice when register as Spring bean


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

    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(getA(), BasicAuthenticationFilter.class);

    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?


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:

public FilterRegistrationBean registration(MyFilter filter) {
    FilterRegistrationBean registration = new FilterRegistrationBean(filter);
    return registration;

Answered By – Andy Wilkinson

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published