Filter Registered Twice with Spring Bean Annotation
When registering a filter as a Spring bean, it is important to consider the potential for multiple invocations. In certain scenarios, the filter may be triggered twice, as observed in the following issue:
Issue:
A user defines a filter, A, which extends Spring's GenericFilterBean. When this filter is registered as a bean in the Spring Security configuration, an additional invocation is observed, resulting in the following output:
filter A before filter A before mycontroller invoke filter A after filter A after
Query:
Why is the filter being called twice, and how can this issue be resolved?
Answer:
The extra invocation occurs because Spring Boot automatically registers any bean of type Filter with the servlet container. To prevent this, there are two options:
Option 1: Register Filter with Spring Security Only
Avoid exposing the filter as a bean and register it solely with Spring Security, as follows:
@Override protected void configure(HttpSecurity http) throws Exception { http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.addFilterBefore(new A(), BasicAuthenticationFilter.class); http.csrf().disable(); }
Option 2: Use FilterRegistrationBean with Annotation
If autowiring dependencies into the filter is necessary, one can register it as a bean but disable its automatic registration with the servlet container using a FilterRegistrationBean:
@Bean public FilterRegistrationBean registration(MyFilter filter) { FilterRegistrationBean<MyFilter> registration = new FilterRegistrationBean<MyFilter>(filter); registration.setEnabled(false); return registration; }
The above is the detailed content of Why is My Spring Filter Being Invoked Twice, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!