打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
在servlet、filter、Taglib中获取Spring Bean

在servlet容器中使用spring框架时spring的上下文(WebApplicationContext)被在保存在 ServletContext中。在servlet、filter或jsp标签中获取spring bean的关键在于如何获取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的属性中,可通过如下方式获取:

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

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Spring获取Bean的几种方式
spring的启动过程:
spring在web.xml中和在struts中的不同配置 - gwt600的专栏 - C...
spring阶段性的一点感受
Spring MVC 双亲上下文的说明
SpringMVC源码深度分析DispatcherServlet核心的控制器(初始化)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服