搞了一年多的Java了,每个项目都在用Spring,这几天没事看了看Spring源码,总结了下Spring容器的启动过程,想把它记录下来,免得忘了


spring容器的启动方式有两种:

1、自己提供ApplicationContext自己创建Spring容器

2、Web项目中在web.xml中配置监听启动

org.springframework.web.context.ContextLoaderListener


先介绍第一种(自创建)

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml")
User user = (User) context.getBean()}

当通过ClassPathApplicationContext初始化容器时,它会根据定位加载spring.xml配置,然后解析配置文件,生成Bean,注册Bean,最后我们在通过getBean获取对象,这一现象就跟IOC容器的初始化过程一样,资源定位、资源加载、资源解析、生成Bean、Bean注册


我们再来说说第二种初始化方式:

第二种在web.xml文件中进行配置,根据web容器的启动而启动

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

ContextLoaderListener实现了ServletContextListener接口,实现了两个方法

//初始化WebApplicationContext容器
public void contextInitialized(ServletContextEvent event) {
    this.initWebApplicationContext(event.getServletContext());
}

//销毁WebApplicationContext容器
public void contextDestroyed(ServletContextEvent event) {
    this.closeWebApplicationContext(event.getServletContext());
    ContextCleanupListener.cleanupAttributes(event.getServletContext());
}

参数ServletContextEvent能直接获取servletContext也就是java web容器的上下文

在父类中调用了intitWebApplicationContext方法,传入了ServletContext,在父类方法中对ServletContext进行了判断,检测servletContext的属性中是否存在spring的根上下文属性如果存在则是错误的,因为表明已经有一个根上下文已经启动,再启动会冲突,所以避免重复启动!

(servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != ) {
    IllegalStateException()}