Spring配置文件讀取引用properties文件的值


使用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中的值。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM