天天看點

Spring的配置檔案中加載配置檔案

Spring 系列-spring 配置檔案中加載配置檔案       

1.通過PropertyPlaceholderConfigurer在Spring中加載其他外部配置檔案或者屬性檔案:
在很多javaEE工程中,Spring的角色非常重要,是一個管理其他子產品群組件的輕量級容器,Spring經常需要管理Struts、Ibatis、Hibernate等,這些開源架構的配置檔案就通過Spring的PropertyPlaceholderConfigurer加載在Spring中進行管理,另外,資料庫連接配接資訊、JNDI連接配接資訊屬性檔案等也可以通過PropertyPlaceholderConfigurer加載到Spring中來管理。用法如下:
(1).通過PropertyPlaceholderConfigurer将其他檔案加載到Spring中:
在spring配置檔案中添加如下配置:
<bean class=“org.springframework.beans.factory.config.PropertyPlaceholderConfigurer“>  
    <property name=“locations“>  
      <value>classpath:要加載的檔案名</value>  
              ……  
	       </property>  
</bean>  
           

2.使用<context:Property-Placeholderlocation=”classpath:要加載的檔案名”/>

附: 在做java開發時,如果用到spring,那麼在做j2ee開發都可能用到spring的配置檔案,那麼spring的配置檔案名到底應是什麼呢?預設的情況下spring會從web-inf目錄下去找spring的配置檔案,并且spring的配置檔案名是applicationContext.xml,如果不想讓spring的配置檔案名為applicationContext.xml,而是把配置檔案名改成beans.xml,那麼就應在目前程式的web.xml中加入下面的話,

Xml代碼  

Spring的配置檔案中加載配置檔案
  1. <context-param>  
  2.      <param-name>contextConfigLocation</param-name>  
  3.      <param-value>/WEB-INF/beans.xml</param-value>  
  4. </context-param>  
<context-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>/WEB-INF/beans.xml</param-value>
</context-param>
      

這樣就可以對spring配置檔案進行改名了

如果有多個spring配置檔案,那麼就可以用逗号把相應的檔案名隔開,如下所示

Xml代碼  

Spring的配置檔案中加載配置檔案
  1. <context-param>  
  2.      <param-name>contextConfigLocation</param-name>  
  3.      <param-value>/WEB-INF/beans_1.xml,/WEB-INF/beans_2.xml</param-value>  
  4. </context-param>