1. 程式人生 > >Spring容器啟動過程

Spring容器啟動過程

spring啟動

搞了一年多的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()}


本文出自 “項以奇的博客” 博客,請務必保留此出處http://12854546.blog.51cto.com/12844546/1930134

Spring容器啟動過程