Springboot @WebFilter無法註入其他Bean的示例問題

示例問題代碼:

@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);
	}
}

現象:

本地運行測試均可通過,上測試環境後運行註入bean為空
現象:使用外置tomcat可觸發,本地使用內置tomcat則無此問題

解決代碼

@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;
    }

}

啟動類加上:@ServletComponentScan({“com.hybase.site.filter”})

到此這篇關於Springboot @WebFilter無法註入其他Bean的示例問題的文章就介紹到這瞭,更多相關Springboot 無法註入Bean內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: