Spring-web源代码阅读之入口程序

使用的源码版本如下:

spring-web-5.0.6 ,本次阅读的对象。

spring-framework-1.0,用做对照,看一下两者的不同。

Spring-web模块概要说明

spring-web模块是从spring3.x起独立打包,主要作用是集成了spring的bean管理以及依赖注入,并加入了Java Web的特征,例如对servletContext的封装,以及对请求参数的封装和统一外部资源的加载方式等等,核心是通过spring来管理Java Web中的各种bean组件。

Spring集成到java Web的方式

 将spring集成到Java Web中的方式是利用了servlet容器(如tomcat)中的监听器,spring实现了一个ServletContextListener监听器,来监听servlet容器的启动和停止,并在相关方法中实现初始化和销毁工作。

spring-web中实现ServletContextListener的类就是下面这个类,ContextLoaderListener,其中实现了ServletContextListener监听器的两个方法,contextInitialized和contextDestroyed,分别用于初始化web应用的上下文和销毁web应该的上下文。

可以看到该类还继承了ContextLoader类,那么ContextLoader类的作用请往下看。

/**

Bootstrap listener to start up and shut down Spring’s root.

启动入口监听,用来初始化和销毁spring的root(WebApplicationContext)。

*/

public class ContextLoaderListener extends ContextLoader implements ServletContextListener{

@Override

public void contextInitialized(ServletContextEvent event){

  initWebApplicationContext(event.getServletContext());

}

@Override

public void contextDestroyed(ServletContextEvent event){

  closeWebApplicationContext(event.getServletContext());

ContextCleanupListener.cleanupAttributes(event.getServletContext());

}

}

Spring集成java web的核心步骤

ContextLoad类,是初始化工作的实际执行者,上述的ContextLoaderListener只是作为入口,不做任何的具体工作,所有的具体工作都委托给了ContextLoader类,其中核心方法是initWebApplictionContext和closeWebApplicationContext

其中在initWebApplicationContext中主要做了以下步骤:

1、创建WebApplicationContext的对象实例

2、将ServletContext和web的初始化参数保存起来

3、加载外部属性资源

4、对WebAppliCationContext做个性化处理

5、正式初始化和加载相关的bean(后续的文章会详细该部分)

/**

  • Perform the actual initialization work for the root application context.

初始化根应用上下文的实际执行者

*/

public class ContextLoader{

}

通过上述步骤,就完成了将spring集成到Java web,通过监听器加载了spring的相关组件,并在spring中集成了servletContext和web的初始化参数,将spring容器和servlet容器紧密的结合到一起。

对两个入口类设计的理解

我对ContextLoaderListener和ContextLoader两个类的设计有一下几点想说:

1、由于ContextLoaderListener和ContextLoader是继承关系,所以可以说ContextLoaderListener就是ContextLoader,关系纯粹。

2、利用继承关系实现了委托关系

3、如下代码是1.0的代码,可以看到在1.0的时候,ContextLoaderListener并没有继承ContextLoader,而是使用了更弱的关联,使用一个ContextLoader类型的属性来实现委托。

public class ContextLoaderListener implements ServletContextListener{

private ContextLoader contextLoader;

public void contextInitialized(ServletContextEvent event){

    this.contextLoader = createContextLoader();

    this.contextLoader.initWebApplicationContext(event.getServletContext());

}

protected ContextLoader createContextLoader(){

      return new ContextLoader();

}

....

}

   在1.0中,两者的关系更加松散,我们可以很容易的替换ContenxtLoader类型的属性,但在5.0.6中,使用了继承,使其关系更加紧密,也更加的单纯,ContextLoaderListener就是一个ContextLoader,只是通过Servlet容器的监听器来作为一个入口,切入java web中。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值