在servlet容器中使用spring框架时spring的上下文(WebApplicationContext)被在保存在 ServletContext中。在servlet、filter或jsp标签中获取spring bean的关键在于如何获取ServletContext。
servlet中:
spring的上下文(WebApplicationContext)存在ServletContext以 WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE为key的属性中,可通过如下方式获取:
Object ob = servletContext .getAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
WebApplicationContext context = (WebApplicationContext) ob;
或者
WebApplicationContext context =WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
或者WebApplicationContextUti
在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;
}
}
联系客服