Home > Java > javaTutorial > Why is My Spring Security Filter Invoking Twice When Using @Autowired?

Why is My Spring Security Filter Invoking Twice When Using @Autowired?

Patricia Arquette
Release: 2024-12-13 11:56:10
Original
418 people have browsed it

Why is My Spring Security Filter Invoking Twice When Using @Autowired?

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template