spring中ServletContextAware接口使用理解 (转载)

在Spring中,凡是实现ServletContextAware接口的类,都可以取得ServletContext。实现如下:

    // 获取上下文
    private ServletContext servletContext;
    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

那么Spring是在什么时候把ServletContext放置进去的呢?通过对Spring的学习,终于明白了。

在web项目中,Spring容器的加载是通过XmlWebApplicationContext进行的。

它的父类AbstractRefreshableWebApplicationContext,在postProcessBeanFactory方法中进行了如下操作(postProcessBeanFactory方法被AbstractApplicationContext的refresh方法调用)

beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext, this.servletConfig));  
beanFactory.ignoreDependencyInterface(ServletContextAware.class);  
beanFactory.ignoreDependencyInterface(ServletConfigAware.class);
WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext);  
WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext, this.servletConfig);

代码的第一句就是添加了一个ServletContextAwareProcessor。

该类的postProcessBeforeInitialization方法如下:

public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {  
    if (this.servletContext != null && bean instanceof ServletContextAware) {  
        ((ServletContextAware) bean).setServletContext(this.servletContext);  
    }  
    if (this.servletConfig != null && bean instanceof ServletConfigAware) {  
        ((ServletConfigAware) bean).setServletConfig(this.servletConfig);  
    }  
    return bean;  
}

而所有的BeanPostProcessor都将在AbstractAutowireCapableBeanFactory类的initializeBean方法中,通过调用applyBeanPostProcessorsBeforeInitialization方法完成所有实现BeanPostProcessor接口的postProcessBeforeInitialization的调用。

XmlWebApplicationContext使用的BeanFactory是DefaultListableBeanFactory。

DefaultListableBeanFactory继承了AbstractAutowireCapableBeanFactory,因此可以完成上述操作。

如此完成了只要实现了ServletContextAware接口的,都可以获取ServletContext。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值