WebApplicationContextUtils

 好多时候,我们都想在过滤器里面获取到spring的容器,从而可以拿到spring容器里面的一些bean。但要认识到一点,过滤器里面是否可以直接拿到,tomcat容器启动的时候,首先加载context-param的配置文件,也就是spring容器。然后加载监听器,再加载过滤器。所以过滤器肯定可以拿到spring的容器。

WebApplicationContext代表着spring容器,而且它是以WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE 为键,存放在ServletContext里面的,所以我们可以使用

WebApplicationContext wac = (WebApplicationContext)servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

获得spring容器,但是这样很麻烦,好多人并不知道它的键是什么。所以我们可以使用工具类实现:

     这个工具类在org.springframework.web.context.support包中。

WebApplicationContext wac =WebApplicationContextUtils.getWebApplicationContext(servletContext);

     当 ServletContext 属性列表中不存在 WebApplicationContext 时,getWebApplicationContext() 方法不会抛出异常,它简单地返回 null。如果后续代码直接访问返回的结果将引发一个 NullPointerException 异常,而 WebApplicationContextUtils 另一个 getRequiredWebApplicationContext(ServletContext sc) 方法要求 ServletContext 属性列表中一定要包含一个有效的 WebApplicationContext 对象,否则马上抛出一个 IllegalStateException 异常。我们推荐使用后者,因为它能提前发现错误的时间,强制开发者搭建好必备的基础设施。

     写个实例吧:

      public void init(FilterConfig conf) throws ServletException {
        ServletContext servletContext = conf.getServletContext();
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(servletContext);


        this.configHelper = (ConfigHelper) wac.getBean("configHelper");
        this.authService = (IAuthService) wac.getBean("authService");
        this.userValidateService = (IUserValidateService) wac.getBean("userValidateService");
        this.stringTemplateMerger = (StringTemplateMerger) wac.getBean("stringTemplateMerger");
        this.userTenantDao = (IUserTenantDao) wac.getBean("userTenantDao");
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值