0
我正在创建一个对象的实例(第三方,所以我不能更改它)谁的构造函数需要一个IP地址,直到运行时才知道。所以我不/不能将IP地址硬编码到一个spring配置文件中。将运行时已知的vaues传递给构造函数Spring
那么我怎样才能利用spring创建这个类的一个实例,当它的一个参数的值在运行时是不知道的呢?
我正在创建一个对象的实例(第三方,所以我不能更改它)谁的构造函数需要一个IP地址,直到运行时才知道。所以我不/不能将IP地址硬编码到一个spring配置文件中。将运行时已知的vaues传递给构造函数Spring
那么我怎样才能利用spring创建这个类的一个实例,当它的一个参数的值在运行时是不知道的呢?
您可以使用配置文件,使用UTIL命名空间:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd">
...
<bean id="baseObject" class="...">
<constructor-arg>
<util:property-path path="propertyReader.runtimePropertyValue"/>
</constructor-arg>
</bean>
<bean id="propertyReader" class="PropertyReader"/>
...
</beans>
然后在Java中,你将有
public class PropertyReader {
...
public String getRuntimePropertyValue() {
// Retrieve and return property value
}
...
}
正如你可以看到,价值注入是自动完成由春天。您只需要实现提供注入值的PropertyReader
(类名不重要)。
试试这个答案:http://stackoverflow.com/questions/496711/adding-a-pre-constructed-bean-to-a-spring-application-context/497918#497918,你在那里专门为在启动Spring上下文之前输入“最后一分钟”数据。 – Darien 2011-06-06 18:10:58