如何保证Spring bean的订单? PropertyPlaceHolder问题 [英] How to guarantee Spring bean order? PropertyPlaceHolder issue
问题描述
我正在使用spring进行非常简单的小型服务. 要配置数据库连接,我有一个DataSource bean,并且使用了一个使用.
I have a very simple and small service which I am using spring. To configure the database connection I have a DataSource bean and I use a "datasource.properties" file that is loaded using .
交易是Spring在读取属性文件之前初始化了数据源bean,这样,数据源bean尝试使用"$ {datasource.driver}"驱动程序.
The deal is that Spring is initializing the datasource bean before reading the properties file and this way, the datasource bean is trying use the "${datasource.driver}" driver.
如何保证在初始化数据源bean之前已加载属性?
How can I guarantee that the properties are loaded before initializing the datasource bean?
请参见下面的一段代码:
See a piece of code below:
<context:property-placeholder location="classpath:config/datasource.properties"/>
<import resource="classpath:spring/spring-*.xml"/>
<bean id="bdsDatasource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${datasource.bds.driver}" />
<property name="jdbcUrl" value="${datasource.bds.url}" />
<property name="user" value="${datasource.bds.user}" />
<property name="password" value="${datasource.bds.password}" />
</bean>
推荐答案
if
-
property-placeholder
用于同一应用上下文中,并且 -
<import resource="classpath:spring/spring-*.xml"/>
没有自己的property-placeholder
,该property-placeholder
会覆盖import语句之前定义的property-placeholder
,并且 -
datasource.properties
确实有一个datasource.bds.driver
property-placeholder
is used in the same app context, and<import resource="classpath:spring/spring-*.xml"/>
does not have its ownproperty-placeholder
that overrides the one defined before the import statement, anddatasource.properties
really has adatasource.bds.driver
- 在导入语句之后定义
property-placeholder
:
if
bdsDatasource
的${datasource.bds.driver}
应该没有问题的解决.
bdsDatasource
's ${datasource.bds.driver}
should be resolved with no problems.
有一个 是另一个property-placeholder
,它覆盖了import
语句之前定义的那个,这里有两个尝试:
there is another property-placeholder
somewhere that overrides the one defined before the import
statement, here are two things to try:
<import resource="classpath:spring/spring-*.xml"/>
<context:property-placeholder location="classpath:config/datasource.properties"/>
<bean id="bdsDatasource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${datasource.bds.driver}" />
<property name="jdbcUrl" value="${datasource.bds.url}" />
<property name="user" value="${datasource.bds.user}" />
<property name="password" value="${datasource.bds.password}" />
</bean>
- 将
order
属性添加到property-placeholder
: - add an
order
attribute to theproperty-placeholder
:
<context:property-placeholder
location="classpath:config/datasource.properties"
order="0"/>
可能会覆盖多个property-placeholder
bean的顺序
to potentially override the order of several property-placeholder
beans
这篇关于如何保证Spring bean的订单? PropertyPlaceHolder问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!