實現(xiàn)思想
- 加載Spring 核心配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
- new 對象,功能可以實現(xiàn)砾莱,效率低
實現(xiàn)思想:把加載配置文件和創(chuàng)建對象過程槽片,在服務器啟動時候完成。
-
實現(xiàn)原理:
- ServletContext 對象
- 監(jiān)聽器
-
具體使用
- 在服務器啟動時候福荸,為每個項目創(chuàng)建一個ServletContext對象
- 在ServletContext 對象創(chuàng)建時候蕴坪,使用監(jiān)聽器可以具體到ServletContext 對象在什么時候創(chuàng)建。
3.使用監(jiān)聽器監(jiān)聽到ServletContext 對象創(chuàng)建時候敬锐。 - 加載Spring配置文件背传,把配置文件配置對象創(chuàng)建。
- 把創(chuàng)建出來的對象放到ServletContext域?qū)ο罄锩妫╯etAttribute方法)
- 獲得對象時候台夺,到ServletContext 域得到(getAttribute方法)
實現(xiàn)步驟
通過配置web.xml 文件径玖,設置在啟動時加載spring的配置文件。
下面是web.xml 文件配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
從上面配置文件中可以看出颤介,只要兩步:
- 配置參數(shù)
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
key | value | 說明 |
---|---|---|
param-name |
contextConfigLocation |
contextConfigLocation 是固定的挺狰,在ContextLoader 類中可以找到 |
param-value |
classpath:spring.xml |
classpath: + spring 的配置文件位置 |
這里需要對參數(shù)進行說明:
key | value | 說明 |
---|---|---|
param-name |
contextConfigLocation |
contextConfigLocation 是固定的,在ContextLoader 類中可以找到 |
param-value |
classpath:spring.xml |
classpath: + spring 的配置文件位置 |
注意: 如果沒有如上配置买窟,在啟動時丰泊,將會拋出java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml]
- 添加監(jiān)聽
固定學法:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>