为什么spring 不能对filter,servlet注入

2024-12-02 09:09:55
推荐回答(1个)
回答1:

原因如下:
filter和servlet不受spring管理,所以不能依赖注入spring管理的bean,在servlet里的init方法加入如下代码:
private XxxxService xxxxService;
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext());
xxxxService= (XxxxService) wac.getBean("xxxxService");
即可获得spring管理的bean.
filter代码如下:
wac = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext());
xxxxService= (XxxxService) wac.getBean("xxxxService");