Do you know about
property placeholder in
spring? I do but I always forget about those little tricks to make this work :( So here's the simplest example I could find so that next time I only have to search my blog for this ;)
The purpose of this is to replace, at runtime, a value in the spring xml bean definition, like this: -Dmy.ip=1.2.3.4
The bean:
package test;
public class Model {
private String foo;
public String getFoo() { return foo; }
public void setFoo(String foo) { this.foo = foo;}
}
public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] {"beans.xml"});
BeanFactory factory = (BeanFactory) context;
Model model = (Model) factory.getBean("model");
System.out.println(model.getFoo());
}
}
The xml (don't forget the conf bean!):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="model" class="test.Model">
<property name="foo" value="${my.ip}"/>
</bean>
<bean id="conf" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"/>
</beans>