在servlet、filter、Taglib中獲取Spring Bean

在servlet容器中使用spring框架時spring的上下文(WebApplicationContext)被在保存在 ServletContext中。在servlet、filter或jsp標籤中獲取spring bean的關鍵在於如何獲取ServletContext。java


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的屬性中,可經過以下方式獲取:

Object ob = servletContext
.getAttribute( web

     WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
WebApplicationContext context = (WebApplicationContext) ob;

      在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()
spring

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;
    }
}
jsp

相關文章
相關標籤/搜索