Passing runtime known vaues to constructor called by Spring
I am creating an instance of an object (third party so I cant change it) who's constructor takes an IP address that isnt known until runtime. So I dont/cant hardcode the IP address into a spring config file.
So how can I ut开发者_JAVA百科ilize spring to create an instance of this class, when the value of one of its arguments isnt known until runtime?
You can use a config file, using the util namespace:
<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>
Then in Java you would have
public class PropertyReader {
...
public String getRuntimePropertyValue() {
// Retrieve and return property value
}
...
}
As you can see, value injection is done automatically by Spring. You just need to implement a PropertyReader
(class name not significant) that provides the injected values.
精彩评论