14 Jun 2007

Spring property placeholder

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;}
}

The main (I tried with FileSystemResource and XmlBeanFactory instead of ApplicationContext but it doesn't seem to work):

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>

Technorati tags:

2 comments:

Anonymous said...

colud you invite me to be a joost user? my my email is : jorge_luis_espinoza@hotmail.com

thanks

Benjamin Francisoud said...

Can be replace with

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:property-placeholder location="classpath:*config.properties,file:///c:/config/*config.properties" system-properties-mode="OVERRIDE" />
</beans>