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()}