Spring| Spring與Web整合


1.整合目的

將所有對象的創建與管理任務交給Spring容器,降低程序的耦合度。


2.整合途徑

將Spring容器注入到Web容器中。


3.具體實現

使用ServletContextListener監聽ServletContext,當ServletContexxt創建時同時創建Spring容器,並將創建完成的容器放到ServletContext即application中,在Web中獲取Spring容器,就可以訪問對象了。ContextLoadListener是ServletContextListener的一個實現類,精簡配置如下:

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

默認情況下,Spring的配置文件只能放在WEB-INF目錄下,而且名稱爲applicationContext.xml


如果需要自定義創建IOC容器的配置文件路徑和名稱可以通過找web.xml中配置上下文參數的方式實現,比如需要加載classpath下名稱爲spring-config.xml的配置文件做如下配置既可:

<context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath:spring-config.xml</param-value>
</context>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

注意: 參數上下文參數名稱固定爲contextConfigLocation

實質在實例化web項目的時候,會觸發監聽器上下文ContextLoaderListener的初始化方法,我們看一下該監聽器的實現

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {

	public ContextLoaderListener() {
	}

	public ContextLoaderListener(WebApplicationContext context) {
		super(context);
	}

	@Override
	public void contextInitialized(ServletContextEvent event) {
		initWebApplicationContext(event.getServletContext());
	}

	@Override
	public void contextDestroyed(ServletContextEvent event) {
		closeWebApplicationContext(event.getServletContext());
		ContextCleanupListener.cleanupAttributes(event.getServletContext());
	}
}

web上下文初始化時,contextInitialized方法會被執行,也就是initWebApplicationContext方法將被執行接着我們看一下initWebApplicationContext的源碼,發現程序爲SpringIOC容器創建一個上下文,而且該上線文是WebApplicationContext,實際返回的是ConfigurableWebApplicationContext(繼承自WebApplicationContext接口),所以this.context instanceof ConfigurableWebApplicationContext條件爲true,但是生成可配置的上下文不是激活的(cwac.isActive()爲false),因爲isActive()在抽象類中的默認實現是返回屬性active的值,active的值默認爲false,該值需要調用prepareRefresh()後才變成true,所以接下來會執行configureAndRefreshWebApplicationContext(cwac, servletContext);在改方法中我們能看到給SpringIOC容器上下文設置配置文件的方式是從web的上下文獲取上下文參數名稱爲contextConfigLocation的參數的值作爲了Spring的配置文件.

在這裏插入圖片描述

在這裏插入圖片描述

在這裏插入圖片描述


4.獲取Spring容器

WebApplicationContext context=WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章