Spring上下文

一丶 启动Web容器创建ServletContext

在ServletAPI中, 有一个ServletContextListener接口, 这个接口能够监控ServletContext的声明周期, 实际就是监控整个Web容器的生命周期,当Servlet容器启动或者终止Web应用程序的时候,都会触发一个ServletContextEvent事件(该事件中包含一个ServletContext), 事件会被Servlet-ContextListener处理, 涉及到的两个方法:

1.contextInitialized(ServletContextEvent event)当Servlet容器启动Web应用时会调用该方法,调用完该方法后会进行
Filter初始化, 然后对Servlet进行初始化

2.contextDestroyed(ServletContextEvent event) 当Servlet容器关闭Web应用是会调用该方法,并销毁之前创建的Filter和Servlet

    1. Servlet容器启动时会将读取到context-param 然后以键值对的形式存储到ServletContext中

    2.然后触发ContextLoaderListener中的initWebApplicationContext方法并传入一个ServletContextEvent事件

然后从传入的事件中获取到ServletContext,调用initWebApplicationContext方法初始化WebApplicationContext, 相信到这里
就很熟悉了吧.
 
  
public void contextInitialized(ServletContextEvent event) {
   initWebApplicationContext(event.getServletContext());
}

总结一下上述流程: 1. 当Servlet容器启动Web应用时, 会首先去查看web.xml中的两个节点

2.紧接着, Servlet容器会创建一个ServletContext, 在该应用内全局共享.

3. 然后Servlet容器会将以键值对的形式存放到ServletContext中

4.Servlet容器会创建中的实例对象, 该类必须继承ServletContextListener接口.

5.调用Listener实例对象中的contextInitialized方法, 并从传入的Event中获取到ServletContext.从此开始, 才进入到Spring上下文创建.

二丶 Spring上下文创建

在Spring中已经帮我们实现好了一个监听类org.springframework.web.context.ContextLoaderListener(上下文初始化监听器). 既然需要Spring提供IOC容器, 就需要给他指定配置文件, 要指定文件名称以及文件地址,然后初始化监听器就会创建IOC容器, 注意: 文件名称一定要是contextConfiguration

    
        contextConfigLocation
        WEB-INF/configs/spring/applicationContext*.xml
    

    
    
        
            org.springframework.web.context.ContextLoaderListener
        
     

三丶Spring配置文件加载后, 初始化监听器做了什么? 

1.Servlet容器启动的时候, 创建了全局的ServletContext.
2.然后调用监听器中的contextInitialized方法, 然后调用方法内的initWebApplicationContext初始化上下文环境(实际是XmlWebApplicationContext)即SpringIOC容器.
3.加载中的配置文件信息到IOC容器中, 且IOC容器以键值对的形式存储在ServletContext中. 并将ContextLoaderListener创建的IOC容器设为根上下文.
4.Servlet容器初始化web.xml 中的所有Servlet, 为其初始化自己的ServletContext并加载其配置的配置信息到上下文中, 并将 ContextLoaderListener创建的IOC容器设为自己的父容器, 余下的Servlet重复这一步.

对于作用域而言, DispathcerServlet对应的context可以应用ContextLoaderListener创建的ApplicationContext中的内容, 反过来不行即子context可以使用父context中的内容, 而父不能引用子的. 这也解释了为什么我们可以在DispatcherServlet中获取到由ContextLoaderListener对应的ApplicationContext中的bean。

你可能感兴趣的:(JavaEE)