引言:
在剛開始我們接觸IOC時,我們加載並啟用SpringIOC是通過如下代碼手動加載 applicationContext.xml 文件,new出context對象,完成Bean的創建和屬性的注入。
public class TestIOC { @Test public void testUser() { // 1.加載Spring配置文件,創建對象
ApplicationContext context = new ClassPathXmlApplicationContext("/spring/applicationContext.xml"); // 2.得到配置創建的對象
Person person = (Person) context.getBean("person"); // 3.調用bean對象中的方法
person.test1(); } }
注意:這只是測試代碼,我們使用 Junit 進行單元測試,如果我們在實際生產過程中,每次創建對象都使用該代碼加載配置文件,再創建對象。這種方法當然不可取,太浪費資源。其實,Spring早就幫我們解決了這個問題。
Spring和Web項目整合原理:
1、實現思想:
把加載配置文件和創建對象的過程,在服務器啟動時完成。
2、實現原理:
(1)ServletContext對象
(2)監聽器
3、具體使用:
(1)在服務器啟動時候,會為每個項目創建一個ServletContext對象
(2)在ServletContext對象創建的時候,使用監聽器(ServletContextListener)可以知道ServletContext對象在什么時候創建
(3)監聽到ServletContext對象創建的時候,即在監聽器的 contextInitialized()方法中加載Spring的配置文件,把配置文件配置對象創建
(4) 把創建出來的對象放到ServletContext域對象里面(setAttribute方法),獲取對象的時候,從ServletContext域里得到(getAttribute方法)
Spring整合Web項目演示
1、演示問題(Struts2項目整合Spring時,不寫監聽,只通過代碼加載Spring配置文件)
(1)action調用service,service調用dao
(2)每次訪問 Action 的時候,都會重新加載Spring配置文件
2、解決方案:
(1)在服務器啟動的時候,創建對象加載配置文件
(2)底層使用監聽器、ServletContext對象
3、使用Spring框架,不需要我們寫代碼實現,幫我們進行了封裝
(1)封裝了一個監聽器,我們只需要配置監聽器就可以了
(2)配置監聽器之前做的事:導入Spring整合 web 項目的 jar 包(Maven項目)
4、實際操作
(1)pom.xml中引入以下依賴:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.0.2.RELEASE</version>
</dependency>
(2)web.xml中配置監聽器:
<!-- 配置監聽器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
(3)web.xml中指定加載Spring配置文件的位置
注意:如果我們不指定Spring配置文件的位置,容器會自動去 WEB-INF 目錄下找 applicationContext.xml 作為默認配置文件。如果找不到,就會報如下錯誤。
<!-- 指定Spring配置文件的位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext.xml</param-value>
</context-param>
控制台打印日志: