Duplicate Filter Invocation in Spring Security with @Autowire
When an attempt is made to inject dependencies into a filter through @Autowire in Spring Security, it can lead to an issue where the filter gets invoked twice. This occurs because Spring Boot automatically registers any filter bean with the servlet container.
To prevent this double invocation, there are two options:
1. Avoid Registering Filter as Bean
This can be achieved by not exposing the filter as a bean and only registering it with Spring Security. This ensures that Spring Boot does not automatically register the filter with the servlet container.
2. Use FilterRegistrationBean
If autowiring dependencies into the filter is essential, then the filter must be a bean. However, Spring Boot needs to be explicitly instructed not to register the filter as a Filter. This can be done using FilterRegistrationBean, as shown below:
@Bean public FilterRegistrationBean registration(MyFilter filter) { FilterRegistrationBean<MyFilter> registration = new FilterRegistrationBean<>(filter); registration.setEnabled(false); return registration; }
This approach prevents Spring Boot from registering the filter with the servlet container while still allowing the filter to be autowired by Spring Security.
The above is the detailed content of Why is My Spring Security Filter Invoking Twice When Using @Autowired?. For more information, please follow other related articles on the PHP Chinese website!