今天在开发一个小项目的时候用到filter ,像往常一样直接@Autowired service 层的那个接口,然后进行方法调用,但是程序执行到调用方法的哪一步报错。错误信息是空指针异常。
后来找到解决方案:这块直接先贴代码。
private CustomerService customerService;
public LoginFilter() {
}
@Override
public void destroy() {
// TODO Auto-generated method stub
log.info("销毁");
}
然后再doFilter方法加入:
ServletContext context = req.getSession().getServletContext();
XmlWebApplicationContext cxt = (XmlWebApplicationContext) WebApplicationContextUtils
.getWebApplicationContext(context);
if (cxt != null && cxt.getBean("customerServiceImpl") != null && customerService == null)
customerService = (CustomerService) cxt.getBean("customerServiceImpl");
上面的那些代码是正确的:
1.现在问题来了:当我开始getBean(“customerService”) 时一直报这个bean没有被定义,起始你会发现你的bean也是被spring进行扫描了,为什么会报没有定义。
2.当进行debug的时候你会发现到getBean(“customerService”)时就会空指针异常,那说明Spring上下文里面是没有这个bean的。
3.再次debug 你会发现,它的bean 的名称是 customerServiceImpl。下面贴图:
当我改完之后代码运行正常。
至于为什么不能@Autowired 我没发现原因,不过问题总是解决了。又发现先的朋友可以告诉我。
这个是我参考过的博客:https://www.cnblogs.com/skyer-2013/p/5856280.html