使用Spring提供的 org.springframework.beans.factory.config.PropertyPlaceholderConfigurer可以 引入properties文件,并且在Spring配置文件的其他部分用${}引用其中的值。
1:创建cfgs.properties文件
1 #hibernate.dialect=org.hibernate.dialect.MySQLDialect 2 hibernate.dialect=org.hibernate.dialect.Oracle10gDialect 3 hibernate.show_sql=true 4 hibernate.hbm2ddl.auto=update 5 hibernate.connection.release_mode=after_transaction 6 hibernate.transaction.factory_class=org.hibernate.transaction.JDBCTransactionFactory 7 hibernate.generate_statistics=true 8 hibernate.validation.mode=none
2.在Spring配置文件中导入该文件。
1 <bean 2 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 3 <property name="locations"> 4 <list> 5 <!-- 所有的应用程序全局变量配置,请集中在这里配置 --> 6 <value>classpath:cfgs.properties</value> 7 </list> 8 </property> 9 </bean>
3:这样就可以在Spring配置文件中通过${}调用cfgs.properties中的值
1 <property name="hibernateProperties"> 2 <props> 3 <prop key="hibernate.dialect">${hibernate.dialect}</prop> 4 <prop key="hibernate.jdbc.batch_size">20</prop> 5 <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> 6 <prop key="hibernate.format_sql">true</prop> 7 <prop key="hibernate.connection.isolation">2</prop> 8 <prop key="hibernate.jdbc.use_streams_for_binary">true</prop> 9 <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop><!-- --> 10 <prop key="hibernate.connection.release_mode">${hibernate.connection.release_mode}</prop> 11 <prop key="hibernate.current_session_context_class">thread</prop> 12 <prop key="hibernate.transaction.factory_class">${hibernate.transaction.factory_class}</prop> 13 <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop> 14 <prop key="javax.persistence.validation.mode">${hibernate.validation.mode}</prop> 15 <prop key="hibernate.cache.provider_class">com.opensymphony.oscache.hibernate.OSCacheProvider 16 </prop> 17 18 </props> 19 </property>
4:使用org.springframework.beans.factory.config.PropertyOverrideConfigurer可以 用properties文件中的值覆盖spring中定义的bean的property值。
1 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyOverrideConfigurer"> 2 <property name="location" value="classpath:cfgsproperties"/> 3 <property name="ignoreInvalidKeys" value="true"/> 4 </bean>
如果Spring配置文件通过该方式加载了cfgs2.properties 则将使用该文件中的值,而不会使用cfgs.properties中的值。