Home >Java >javaTutorial >Why is My Spring Filter Invoked Twice When Defined as a Bean?
To leverage Spring dependency injection, it is common to register filters as beans in Spring Boot, typically using @Autowire. However, this can result in the filter being invoked twice.
As you noticed, Spring Boot automatically registers filters marked as beans with the servlet container. This means that your filter registered via @Bean gets invoked both by Spring Security and the container.
There are two primary approaches to solve this issue:
1. Prevent Automatic Registration:
If you don't need to autowire dependencies into your filter, simply avoid exposing it as a bean. Instead, define it as a regular Java class and register it manually with Spring Security only:
http.addFilterBefore(new YourFilter(), BasicAuthenticationFilter.class);
2. Disable Spring Boot Registration:
To register your filter manually and still use dependency injection, you can leverage FilterRegistrationBean:
@Bean public FilterRegistrationBean registration(YourFilter filter) { FilterRegistrationBean<YourFilter> registration = new FilterRegistrationBean<>(filter); registration.setEnabled(false); // Disable Spring Boot registration return registration; }
This configuration prevents Spring Boot from registering your filter but allows you to specify the filter bean for Spring dependency injection.
The above is the detailed content of Why is My Spring Filter Invoked Twice When Defined as a Bean?. For more information, please follow other related articles on the PHP Chinese website!