首先在web.xml中配置加载容器
<!-- load spring context -->
<servlet>
<servlet-name>InitSpringContextServlet</servlet-name>
<servlet-class>cn.com.*.core.spring.InitSpringContextServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
其次新建一个SpringUtils工具类
package cn.com.*.core.spring;
import org.springframework.web.context.WebApplicationContext;
public class SpringUtils {
private static WebApplicationContext applicationContext = null;
public static void setWebApplicationContext(WebApplicationContext context){
applicationContext = context;
}
public static WebApplicationContext getWebApplicationContext(){
return applicationContext;
}
/**
* 方法名称: getBean<br>
* 描述:获取spring容器中的实体
* @param name
* @return 返回实体
*/
public static Object getBean(String name){
return applicationContext.getBean(name);
}
/**
* 方法名称: getBean<br>
* 描述:通过类类型获取spring容器中的尸体
* @param clazz
* @return 返回实体
*/
public static <T> T getBean(Class<T> clazz){
return applicationContext.getBean(clazz);
}
}
最后初始化容器
package cn.com.*.core.spring;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class InitSpringContextServlet extends HttpServlet {
public void init() throws ServletException {
ServletContext servletContext = this.getServletContext();
WebApplicationContext context =
WebApplicationContextUtils.getWebApplicationContext(servletContext);
SpringUtils.setWebApplicationContext(context);
}
}