Home >Java >javaTutorial >Why is my Spring Filter Invoked Twice When Registered as a Bean?

Why is my Spring Filter Invoked Twice When Registered as a Bean?

DDD
DDDOriginal
2024-12-09 15:55:12704browse

Why is my Spring Filter Invoked Twice When Registered as a Bean?

Filter Invoked Twice upon Registration as Spring 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.

Solution:

To resolve this issue, consider implementing one of the following approaches:

  1. 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.

  2. 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!

Statement:
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