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=

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");

The xml (don't forget the conf bean!):

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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 id="conf" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"/>

Technorati tags:


Anonymous said...

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


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"
<context:property-placeholder location="classpath:*config.properties,file:///c:/config/*config.properties" system-properties-mode="OVERRIDE" />