servlet中直接调用spring时会出现NullpointException,原因是由于servlet加载是多线程,你调用的是当前线程的bean,初始化的bean并不在当前线程。所以会导致Nullpoint
需要在你的servlet的方法中加入以下几行代码,从整个web应用中去加载bean
WebApplicationContext wc = WebApplicationContextUtils
.getWebApplicationContext(req.getSession().getServletContext()); //req HttpServletRequest
SpringBeanService bean = (SpringBeanService)wc.getBean("springBean");
//SpringBeanService你定义的Spring bean, "springbean" 在配置文件中定义的bean id
bean.方法(...); //可以直接调用bean中的方法

本文介绍了解决Servlet直接调用Spring Bean时出现NullPointerException的方法。通过从整个Web应用上下文中获取Bean,确保了正确加载并初始化了Bean,避免了线程间的问题。
236

被折叠的 条评论
为什么被折叠?



