Home >Java >javaTutorial >Why is My Spring Filter Invoked Twice When Defined as a Bean?

Why is My Spring Filter Invoked Twice When Defined as a Bean?

DDD
DDDOriginal
2024-12-05 17:45:13714browse

Why is My Spring Filter Invoked Twice When Defined as a Bean?

Why Does a Filter Invoked Twice When Registered as a Spring 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.

Cause

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.

Solution

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!

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