有时需要在servlet中使用spring管理的bean,servlet不能被spring管理,通过配置注入的方式来得到需要的bean实例, 这时可以通过获取WebApplicationContext 来得到spring的上下文,从而得到需要的bean的实例。
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
ServletContext application = getServletContext();
WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(application);
//获取bean
UserDAO userDao = (UserDAO) wac.getBean("userDAO");
...
}