在 Web 层应用程序中使用Spring

前面已经配置成功后,就可以在Web 层的Servlet或Jsp中调用访问Spring了,如果你 编制的是一个Servlet/Jsp 程序,那么在你的Servlet/Jsp 使用下面的代码通过Spring 创建B 的实例:

ServletContext servletContext =this.getServletContext();

WebApplicationContext appContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

B b = (B) appContext.getBean("b");

上面基本是两句,首先获得WebApplicationContext实例,然后从WebApplicationContext 实例中获得B的实例。 如果你使用的是Web 层应用框架,如Struts或Tapestry,除了Spring说明提供特殊方便 的调用方式,你需要从这个框架中获得当前Servlet容器ServletContext实例,再调用上面代 码即可。

原文地址:https://www.cnblogs.com/smile361/p/3559063.html