Tomcat容器是如何启动,创建 和集成Spring 容器的?

一、引言
手动创建一个 Spring 容器,然后调用容器的 getBean() 方法获取Spring容器中对应的Bean:

 public static void main(String[] args) {
        ApplicationContext apx = new ClassPathXmlApplicationContext("bean-factory.xml");
        Car car = (Car) apx.getBean("car");
        System.out.println(car);
    }

但在现实的项目开发中,我们不会手动创建容器。比如,在Web工程中,我们根本不用管 Spring 容器的启动和创建,只需要在web.xml文件中配置一下,就可以使用 Spring 提供的能力。

二、Tomcat项目是如何启动的?

  • 在启动 Web 项目时,容器(比如 Tomcat )会读取 web.xml
    配置文件中的两个节点和;那 Tomcat 为什么会读取呢?因为
    ServletContextListener
  • 接着 Tomcat 会创建一个 ServletContext (上下文) 对象,该对象的应用范围,是整个 Web 项目都能使用这个上下文;
  • 接着 Tomcat 会将读取到转化为键值对,并交给 ServletContext;
  • 接着 Tomcat会创建 中的类实例,即创建监听器。该监听器能够监听 ServletContext对象的生命周期,实际上就是监听 Web 应用的生命周期。
  • 当Tomcat启动或终止时,会触发ServletContextEvent事件,该事件由ServletContextListener来处理。
ServletContextListener有下面两个方法:
1)、初始化方法:contextInitialized(ServletContextEvent event)
在这个方法中可以通过event.getServletContext().getInitParameter("XXXXX") ,来得到context-param设定的值;
2)、销毁方法:  contextDestroyed(ServletContextEvent event)
在这个方法中,多用于关闭应用前释放资源,比如说数据库连接的关闭;

得到这个 context-param 的值之后,你就可以做一些操作了。
注意,这个时候 Web 项目还没有完全启动完成,这个动作会比所有的Servlet都要早!

三、Tomcat启动时如何集成Spring?
1. web.xml配置文件



  ssm

  
    index.jsp
  
  
  
  
    contextConfigLocation
    classpath:applicationContext.xml
  

  
    org.springframework.web.context.ContextLoaderListener
  
  

  
    dispatcherServlet
    org.springframework.web.servlet.DispatcherServlet
    
    
      
      contextConfigLocation
      classpath:springMVC.xml
    
    
    1
  
  
  
    dispatcherServlet
    /
  
  

  
    CharacterEncodingFilter
    org.springframework.web.filter.CharacterEncodingFilter
    
      encoding
      utf-8
    
    
      forceRequestEncoding
      true
    
    
      forceResponseEncoding
      true
    
  
  
    CharacterEncodingFilter
    /*
  
  


    HiddenHttpMethodFilter
    org.springframework.web.filter.HiddenHttpMethodFilter
  
  
    HiddenHttpMethodFilter
    /*
  

你可能感兴趣的:(笔记)