spring错误<context:property-placeholder>:Could not resolve placeholder XXX in string value XXX

spring同时集成redis和mongodb时遇到多个资源文件加载的问题

这两天平台中集成redis和mongodb遇到一个问题

单独集成redis和单独集成mongodb时都可以正常启动程序,但是当两个同时集成进去时就会报以下问题

Could not resolve placeholder 'mongo.port' in string value "${mongo.port}

 百思不得解后,经多方搜集查证,终于找到问题原因。

在spring的xml配置文件中当有多个*.properties文件需要加载时。

应该这样使用使用

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

 或者 

<context:property-placeholder location="classpath*:redis.properties" ignore-unresolvable="true" />

 但是 ignore-unresolvable="true" 和 <property name="ignoreUnresolvablePlaceholders" value="true" /> 这两个属性值必须为true

原因如下(摘自于文章最后的链接)

Spring容器采用反射扫描的发现机制,在探测到Spring容器中有一个org.springframework.beans.factory.config.PropertyPlaceholderConfigurer的Bean就会停止对剩余PropertyPlaceholderConfigurer的扫描(Spring 3.1已经使用PropertySourcesPlaceholderConfigurer替代PropertyPlaceholderConfigurer了)。 

而<context:property-placeholder/>这个基于命名空间的配置,其实内部就是创建一个PropertyPlaceholderConfigurer Bean而已。换句话说,即Spring容器仅允许最多定义一个PropertyPlaceholderConfigurer(或<context:property-placeholder/>),其余的会被Spring忽略掉(其实Spring如果提供一个警告就好了)。 


原文章中提到最后是把所有的资源文件中的资源放在一起加载 

如下:

#mongo的资源属性
mongo.host=192.168.111.230
mongo.port=40000
mongo.connectionsPerHost=8
mongo.threadsAllowedToBlockForConnectionMultiplier=4
mongo.connectTimeout=1500
mongo.maxWaitTime=1500
mongo.autoConnectRetry=true
mongo.socketKeepAlive=true
mongo.socketTimeout=1500
mongo.slaveOk=true
mongo.write.number=1
mongo.write.timeout=0
mongo.write.fsync=true

mongo.dbname=test

#redis的资源属性
redis.host=192.168.111.225  
redis.port=6379  
redis.pass=  
  
redis.maxIdle=300
redis.maxTotal=600
redis.minIdle=100  

 但是本人认为这样加载不利于系统的拆分,耦合较高。因此本人推荐还是使用单独加载每个子系统自己的资源文件最好,如:

#mongo加载资源文件
	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath*:mongodb.properties</value>
			</list>
		</property>
		<property name="ignoreUnresolvablePlaceholders" value="true" /> 
	</bean>

#redis加载资源文件
	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath*:redis.properties</value>
			</list>
		</property>
		<property name="ignoreUnresolvablePlaceholders" value="true" /> 
	</bean>

 只要保证ignoreUnresolvablePlaceholders都为true,或这最后一个加载的为false,之前的都为true即可。

参考地址:http://www.myexception.cn/database/1705284.html

http://www.iteye.com/topic/1131688

原文地址:https://www.cnblogs.com/king1302217/p/3890277.html