Springboot @ WebFilter failed to inject sample issues for other Bean

  • 2021-11-13 01:38:35
  • OfStack

Sample problem code:


@WebFilter(filterName = "authorizeFilter", urlPatterns = {"*.htm", "*.html"}, asyncSupported = true)
public class AuthorizeFilter implements Filter {

	@Autowired
	private OtherBean otherBean;

	@Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        // true
		System.out.println(otherBean == null);
	}
}

Phenomena:

The local running test can pass, and the running injection bean is empty after going to the test environment
Phenomenon: It can be triggered when using external tomcat, but it has no problem when using internal tomcat locally

Resolution code


@Component
public class AuthorizeFilter implements Filter {

	@Autowired
	private OtherBean otherBean;

	@Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        // false
		System.out.println(otherBean == null);
	}
}

@Configuration
public class WebFilterConfig implements WebMvcConfigurer {

    @Autowired
    private AuthorizeFilter authorizeFilter;

    @Bean("authorizeFilterBean")
    public FilterRegistrationBean authorizeFilterBean() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(authorizeFilter);
        registration.addUrlPatterns(new String[]{"*.htm", "*.html"});
        registration.setName("authorizeFilter");
        registration.setAsyncSupported(true);
        return registration;
    }

}

Startup class plus: @ ServletComponentScan ({"com. hybase. site. filter"})


Related articles: