首先我們都知道要使用spring,則需要在web.xml中增加如下代碼:
web.xml:
1:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
spring是如何加載配置文件肯定也跟 ContextLoaderListener類有關,該類可以作為listener 使用,它會在創建時自動查找WEB-INF/ 下的applicationContext.xrnl 文件。因此,
如果只有一個配置文件,並且文件名為applicationContext.xml ,則只需在web.xml加上面代碼即可。
如果有多個配置文件需要載入,則考慮使用<context-param>即元素來確定配置文件的文件名。
由於ContextLoaderListener加載時,會查找名為contextConfigLocation的參數。因此,配置context-param時參數名字應該是
contextConfigLocation。所以context-param參數的名字是固定的contextConfigLocation.
如下面的實例:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value> /WEB-INF/applicationContext*.xml </param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
多個配置文件用","分開,也可以使用通配符"*"加載多個配置文件。如上例!
如果applicationContext.xml文件需要放在src下,在在web.xml中配置如下:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
2:
通過一個父配置文件將所有子配置文件導入
在配置文件中有一個標簽import,它能把其它的bean定義配置文件導入到父文件夾中
實例:
web.xml配置:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/spring/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
在applicationContext.xml配置中:
<import resource="applicationContext-persistence.xml" />
……