---
title: "Servlet调用Spring bean"
author: "yrandy"
date: "2012-07-13T16:30:03Z"
tags: []
categories: ["移动开发"]
slug: "servlet-spring-bean"
draft: false
lastmod: "2012-07-13T16:33:48Z"
id: 1591794
url: "https://yrandy.iteye.com/blog/1591794"
---

**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中的方法