Spring的PropertyPlaceholderConfigurer強制使用默認值的坑


1.問題

dubbo client配置:

	<dubbo:reference id="channelCustomerClient" interface="com.gttown.crm.channel.service.ChannelCustomerService"
    timeout="60000" check="false" filter="clientFilter" retries="0" validation="false"
    url="${dubbo.url.channel:#{null}}"/>

dubbo.properties:

		zipkin.url=http://zipkin.dev.great-tao.com
		dubbo.application=gttown-user-web
		dubbo.register=false
		dubbo.port=20880
		dubbo.url.channel=dubbo://127.0.0.1:20881

dubbo配置時,預期效果:url="${dubbo.url.channel:#{null}}" 會先讀取配置文件dubbo.url.channel的值如果有值則讀取,若配置文件無該值則用默認值null。
但是事實上無論dubbo.properties配置文件是否有dubbo.url.channel。url的值都會強制使用默認值null。

PropertyPlaceholderConfigurer配置參考。 (具體參考http://elim.iteye.com/blog/2387138)

2.原因

spring.xml 里的PropertyPlaceholderConfigurer配置:

	<bean id="placeholderConfigurer" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
	        <property name="locations">
	            <list>
	                <value>classpath*:/*.properties</value>
	            </list>
	        </property>
	        <property name="ignoreUnresolvablePlaceholders" value="true"/>
	    </bean>

db-user.xml 里的PropertyPlaceholderConfigurer配置:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="order" value="-1"/>
        <property name="locations">
            <list>
                <value>classpath:db.properties</value>
            </list>
        </property>
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
    </bean>

spring.xml的PlaceholderConfigurer配置掃描了classpath下的全部文件,但是加載順序order使用的是默認值。
db-user.xml的PlaceholderConfigurer配置只掃描了classpath下的db.properties,加載順序order為-1最后加載。

url="${dubbo.url.channel:#{null}}"配置時由於db-user.xml的PlaceholderConfigurer后加載,而該PlaceholderConfigurer只掃描了db.properties。該文件沒有dubbo.url.channel的值,導致url使用默認值null。

3.解決

  • 方案1:
    spring.xml 里的PropertyPlaceholderConfigurer配置加上

          <property name="order" value="-1"/>
    

建議:掃面范圍越大的PropertyPlaceholderConfigurer越后面加載。

  • 方案2:
    刪除db-user.xml 以及以其他配置文件里的精確掃描指定文件的PropertyPlaceholderConfigurer配置。

  • 方案3:
    spring.xml 里的PropertyPlaceholderConfigurer配置,修改分隔符(默認分隔符為:)

      <property name="valueSeparator" value="&"/>
    

使用& 作為分隔符。

dubbo-clien.xml配置修改為
url="${dubbo.url.channel&#{null}}


免責聲明!

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



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