Spring属性文件的覆盖配置:uses of PropertyOverrideConfigurer

来源:互联网 发布:怎样用命令压缩linux下 编辑:程序博客网 时间:2024/04/30 15:46
 

Spring提供了用属性文件配置Spring的功能,方法是使用PropertyPlaceholderConfigurer加载配置文件:

xml 代码
  1. <!-- RESOURCE DEFINITIONS -->  
  2. <bean id="propertyConfigurer"  
  3.     class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  4.     <property name="locations">  
  5.         <list>  
  6.             <value>classpath*:conf/jdbc.properties</value>  
  7.             <value>classpath*:conf/hibernate.properties</value>  
  8.         </list>  
  9.     </property>  
  10. </bean>  

 

加载了配置文件以后,书写占位符 ${property.name}来配置bean的属性,例如

xml 代码
  1. <!-- DataSource Definition, using Apache DBCP connection pool -->  
  2. <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
  3.     <property name="driverClassName" value="${jdbc.driverClassName}" />  
  4.     <property name="url" value="${jdbc.url}" />  
  5.     <property name="username" value="${jdbc.username}" />  
  6.     <property name="password" value="${jdbc.password}" />  
  7. </bean>  

 

在实际开发中,当我们需要不同的配置策略的时候,比如开发和测试很可能用的是不同的数据库,就需要更改配置文件,很麻烦。幸好Spring提供了解觉的办法:PropertyOverrideConfigurer,顾名思义,它允许配置文件加载后动态的覆盖某些bean的属性,当没有显式配置的时候使用默认的配置,否则使用覆盖配置。
具体用法:

xml 代码
  1. <bean id="testPropertyConfigurer" class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">  
  2.     <property name="location" value="classpath:spring/test/test.properties"/>  
  3.     <property name="ignoreInvalidKeys" value="true"/>  
  4. </bean>  

test.properties是一个属性文件,但是具体的写法不一样,PropertyPlaceholderConfigurer中属性文件的key写的是占位符的变量名,而这里是按照bean.property=value的格式来写的,比如你想覆盖datasource的driverClassName属性值,写成dataSource.driverClassName=jdbc:mysql:....

 

注意:对于属性集合的情况,有特殊的写法

xml 代码
  1. <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
  2.     <property name="dataSource" ref="dataSource" />  
  3.     <property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration"/>  
  4.     <property name="hibernateProperties">  
  5.         <props>  
  6.             <prop key="hibernate.dialect">${hibernate.dialect}</prop>  
  7.             <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>  
  8.             <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>  
  9.             <prop key="hibernate.cache.provider_class">${hibernate.cache.provider_class}</prop>  
  10.         </props>  
  11.     </property>        
  12. </bean>  

hibernate.dialect是属性集合hibernateProperties中的一项,如果写成sessionFactory.hibernateProperties.hibernate.dialect就会报错,这时候要写成sessionFactory.hibernateProperties[hibernate.dialect],这一点,Spring的任何文档里都没有提及,是被我给蒙出来的,吼吼^ ^