Home >Java >javaTutorial >Why is my Spring Filter Invoked Twice When Registered as a Bean?
Problem:
An attempt to utilize @Autowire with a Filter results in an unexpected double invocation of the filter. Upon closer examination, it is observed that Spring container triggers this additional invocation when the filter is registered as a bean.
To resolve this issue, consider implementing one of the following approaches:
Disable Automatic Filter Registration:
Avoid exposing the filter as a bean and manually register it with Spring Security instead. This prevents Spring Boot from automatically registering the filter twice.
Use FilterRegistrationBean:
If dependency injection into the filter is necessary, it must be registered as a bean. However, to prevent automatic registration, a FilterRegistrationBean can be employed with the "enabled" property set to false. Example implementation:
@Bean public FilterRegistrationBean registration(MyFilter filter) { FilterRegistrationBean<MyFilter> registration = new FilterRegistrationBean<>(filter); registration.setEnabled(false); return registration; }
The above is the detailed content of Why is my Spring Filter Invoked Twice When Registered as a Bean?. For more information, please follow other related articles on the PHP Chinese website!