Harshana Harshana - 11 months ago 118
Java Question

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 is extends spring GenericFilterBean.

I get below out put 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 onlt get hits once. What is the reason and how can I fix it?

Answer Source

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;