util:properties和context:property-placeholder區別和共性

配置方式:

<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">
              &lt;!&ndash; 必須添加下面這句聲明 &ndash;&gt;
              <property name="ignoreUnresolvablePlaceholders" value="true"/>
              <property name="locations">
                     <list>
                            <value>classpath:development.properties</value>
                     </list>
              </property>
       </bean>

stackoverflow中的帖子不錯,分享出來

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章