在servlet容器中使用spring框架時spring的上下文(WebApplicationContext)被在保存在 ServletContext中。在servlet、filter或jsp標(biāo)簽中獲取spring bean的關(guān)鍵在于如何獲取ServletContext。
servlet中: public void init(ServletConfig config){ servletContext= config.getServletContext(); }
filter中: public void init(FilterConfig config) throws ServletException { ServletContext servletContext =config.getServletContext(); }
jsp taglib中: ServletContext servletContext = this.pageContext.getServletContext();
spring的上下文(WebApplicationContext)存在ServletContext以 WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE為key的屬性中,可通過如下方式獲?。?BR> Object ob = servletContext .getAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); WebApplicationContext context = (WebApplicationContext) ob;
或者
WebApplicationContext context =WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
或者WebApplicationContextUtils.getWebApplicationContext(servletContext);
在WebApplicationContext中獲取bean: protected Object getBean(String name){ return this.getWebApplicationContext().getBean(name); }
一個抽像的servlet基類: import javax.servlet.ServletContext; import javax.servlet.ServletConfig; import javax.servlet.Servlet; import org.springframework.web.context.WebApplicationContext; public abstract class BaseServlet implements Servlet { protected ServletContext servletContext;
public void init(ServletConfig config){ servletContext= config.getServletContext(); } public ServletContext getServletContext(){ return servletContext; } public void destroy(){ } public String getServletInfo(){ return ""; } protected WebApplicationContext getWebApplicationContext()
throws RuntimeException{ Object ob = servletContext.getAttribute(WebApplicationContext
.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); WebApplicationContext context = (WebApplicationContext) ob; return context; } protected Object getBean(String name){ return this.getWebApplicationContext().getBean(name); } public ServletConfig getServletConfig(){ return null; } }
|