SSM中同时集成多个框架中存在多个资源文件(xxx.properties)的加载问题的处理方式,如果我们的项目中我们同时要添加MySQL、MongoDB和Redis这样就会有三个配置文件,我们该如何处理?
这两天平台中集成MySQL和MongoDB遇到一个问题
单独集成MySQL和单独集成mongodb时都可以正常启动程序,但是当两个同时集成进去时就会报以下问题
Could not resolve placeholder 'mongo.port' in string value "${mongo.port}
百思不得解后,经多方搜集查证,终于找到问题原因。在SSM的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” 和 这两个属性值必须为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>
#MySQL加载资源文件
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:db.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true" />
</bean>
只要保证ignoreUnresolvablePlaceholders都为true,或这最后一个加载的为false,之前的都为true即可。
本文出处:博客园