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