导航

Spring外部化配置

Posted on 2013-03-28 18:26  曙光城邦  阅读(346)  评论(0编辑  收藏  举报

所谓外部化配置,意思就是不要将工程的所有配置信息混合在applicationContext的配置文件中。如数据库的配置信息、系统路径的配置信息等等,这些信息都应该独立出去,方便系统配置人员或者是后期维护关键信息的方便性。

 

如数据库配置信息
c3p0.properties 文件

driverClass=com.mysql.jdbc.Driver
user=root
password=root
acquireIncrement=5
...

 将它的配置信息引入到applicationContext配置文件中的方式有两种,引入后就可以在applicationContext中使用${key}的方式访问该键的值

如${user} 即为root ${driverClass}即为com.mysql.jdbc.Driver

如引用外部文件的applicationContext配置代码段:

 <bean id="resourceLoaderConfig" class="com.chapter2p10.ResourceLoaderConfig" >
 <property name="resource">
     <value>${filepath}</value> <!--引用了外部文件的filepath值-->
 </property>
  </bean>

 

上述是使用方法。引入文件的方法一:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
     <property name="location">
         <value>classpath:com/zk/config.txt</value>
     </property>
 </bean>

使用PropertyPlaceholderConfigurer,location属性用于指定一个配置文件,locations属性则指定多个配置文件

 

方法二:

<context:property-placeholder  location="classpath:com/zk/config.txt"/>

多个文件可用英文逗号分隔。

 

config.txt

filepath=file:e:/hello.txt

 

总结:

PropertyPlaceholderConfigurer是容器的后置处理器,在容器初始化后,处理配置文件。然后实例化bean。方法二比较方便。