配置方式:
<util:properties location="classpath:development.properties" id="config" />
<context:property-placeholder location="classpath*:development.properties"
ignore-unresolvable="true" ignore-resource-not-found="true"/>
< !--多個配置使用,分隔-->
1、spring 配置 util:properties和context:property-placeholder 共性:
都可以用於讀取properties配置文件
2、spring 配置 util:properties和context:property-placeholder 區別:
util:properties 以實例化一個bean的方式,默認是單例類型;可以爲其他bean的屬性賦值,進入
java:org.springframework.beans.factory.config.PropertiesFactoryBean類中,查看一下源碼:
而context:property-placeholder 是由Spring加載到上下文中,爲bean的屬性賦值,以${properties的key}取得值
org.springframework.context.support.PropertySourcesPlaceholderConfigurer的類中作處理;一層層代碼跟下去,發現繼承的類------加載properties的類是同一個。
只是需要注意的是<context:property-placeholder location=… />中需要增加,因爲默認都是false,只會找一次配置,找不到就不找了,設置爲true以後,找不到配置中的key,會繼續找下一個,再找不到,會找系統本地JVM環境中的配置。所以要增加:
ignore-unresolvable="true" ignore-resource-not-found="true"
在 util:properties 中定義了id=“config” ,所以在使用的時候通過<context:property-placeholder properties-ref=“config”/> 加載到spring上下文中,在配置文件中就不會報一堆紅色,而是把找到的值顯示在配置中,方便儘早發現文件中的錯誤;
額外:也可以通過直接指定配置bean的方式,這樣也注意要設置true;
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<!– 必須添加下面這句聲明 –>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>classpath:development.properties</value>
</list>
</property>
</bean>