您的位置:首页 > 编程语言 > Java开发

Spring的属性文件properties使用注意

2017-02-11 18:56 405 查看

Spring的属性文件properties使用注意

Spring 中属性文件的配置

通常我们会使用properties文件来设置一些属性,如数据库连接信息,避免进行硬编码,

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

<property name="locations">

<list>

<value>classpath:db.properties</value>

//if you want you can add more here.

</list>

</property>

</bean>

[/code]

或 在Spring 3.1.x. 之后使用 PropertySourcesPlaceholderConfigurer

<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">

<property name="locations">

<list>

<value>classpath:db.properties</value>

//if you want you can add more here.

</list>

</property>

</bean>

[/code]



更简洁的方法是使用

<context:property-placeholder location="classpath*:config/db.properties" />


问题

在一个多模块maven项目中,不同的模块需要不同的属性配置,因此使用
context:property-placeholder
配置了两个properties文件:
db.properties
email.properties
,但程序启动时遇到下述错误

caused by java.lang.illegalargumentexception could not resolve placeholder 'mail.sender.password' in string value ${mail.sender.password}


不能处理第二个属性文件中的配置信息

因为Spring不允许定义多个
PropertyPlaceholderConfigurer
<context:property-placeholder/>



spring中 context:property-placeholder 导入多个独立的 .properties配置文件?

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

换句话说,即Spring容器仅允许最多定义一个
PropertyPlaceholderConfigurer
(或
<context:property-placeholder/>
),其余的会被Spring忽略掉(其实Spring如果提供一个警告就好了)。

拿上来的例子来说,如果A和B模块是单独运行的,由于Spring容器都只有一个
PropertyPlaceholderConfigurer
, 因此属性文件会被正常加载并替换掉。如果A和B两模块集成后运行,Spring容器中就有两个
PropertyPlaceholderConfigurer
Bean了,这时就看谁先谁后了, 先的保留,后的忽略!因此,只加载到了一个属性文件,因而造成无法正确进行属性替换的问题。

来源: http://blog.csdn.net/yu870646595/article/details/50979338



问题的解决方案

方案1:通配符解决、逗号分隔

使用通配符让spring一次性读取多个属性文件到一个
PropertyPlaceholderConfigurer
bean中

<context:property-placeholder location="classpath*:conf/*.properties"/>




或者使用

<context:property-placeholder location="classpath*:conf/db.properties,conf/email.properties"/>


注意: 如果后一个文件中有和前面某一个文件中属性名是相同的,最终取的值是后加载的值

方案2:一个PropertySourcesPlaceholderConfigurer中包含多个属性文件,和方案1原理相同

<bean id="propertyConfigurer" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">

<property name="locations">

<list>

<value>classpath:db.properties</value>

<value>classpath:email.properties</value>

</list>

</property>

[/code]

方案3:使用
ignore-unresolvable

如果一定要分开定义,则在每个
PropertySourcesPlaceholderConfigurer
配置中添加

<property name="ignoreUnresolvablePlaceholders" value="true"/>


或者在每个
context:property-placeholder
中都加上
ignore-unresolvable="true"


因为在你使用
@Value("${xx}")
或在xml中使用
${xx}
获取属性时,Spring会在第一个读取到的属性文件中去找,如果没有就直接抛出异常,而不会继续去第二个属性文件中找



null
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: