filter过滤器解决SpringMVC框架bean注入失败问题

1.很多filter不仅仅是过滤请求,往往都需要注入service来获取数据判断如下所示:

filter过滤器解决SpringMVC框架bean注入失败问题

类似于此,当启动项目是访问会报空指针异常,两个service都为null,bean注入失败,后来仔细分析了下web.xml加载顺序,才明白是怎么回事。 

不管你的xml元素位置在哪,最终的启动顺序是这样的。 
    context-param -> listener -> filter -> servlet 
public void init(FilterConfig filterConfig) throws ServletException { 
    ServletContext context = filterConfig.getServletContext(); 
    ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context); 
    对象 =  ctx.getBean(对象.class); 

        也就是说你在容器启动过程中filter先实例化,此时根本没实例化org.springframework.web.servlet.DispatcherServlet 。所有导致了spring管理的对象没有被加载。

2.解决办法:我们可以在 context-param节点中的spring context 里去扫下你的对象包,或在里面配置对象bean 。另外在filter 里我们是这样获取spring上下文的 

如下图所示:

filter过滤器解决SpringMVC框架bean注入失败问题

如有更好建议欢迎留言或入群讨论:

filter过滤器解决SpringMVC框架bean注入失败问题