filter里使用spring 注入实例失败

在web开发中我们有时候会想要在请求的过滤器中做一些事情,此时可能依赖其他的对象。这些对象由spring来管理,假如在启动时候已经由容器帮助你实例化了。这时你想在filter里使用,并注入到filter里,在使用对象的时候就会报空指针,意味着注入失败。

后来仔细分析了下web.xml加载顺序,才明白是怎么回事。
不管你的xml元素位置在哪,最终的启动顺序是这样的。
context-param -> listener -> filter -> servlet


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

解决方法是我们可以在 context-param节点中的spring context 里去扫下你的对象包,或在里面配置对象bean

另外在filter 里我们是这样获取spring上下文的

public void init(FilterConfig filterConfig) throws ServletException {
ServletContext context = filterConfig.getServletContext();

ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
对象 =  ctx.getBean(对象.class);
}


猜你喜欢

转载自wangchuanyin.iteye.com/blog/2214739