Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: Setting up a simple PropertyPlaceholderConfigurer example

Tags:

spring

The solution to this is probably very simple, but I'm not sure what I'm missing. Here's what I have, and PropertyPlaceholderConfigurer won't replace the ${...}.

/* ---- org/company/springtest/Test.java: ---- */
package org.company.springtest;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

public class Test {
    public static void main( String... args ) {
         Resource res = new FileSystemResource("conf/xml/context2.xml");
             XmlBeanFactory beanFactory = new XmlBeanFactory(res);
             TestApp app = (TestApp) beanFactory.getBean("testApp");
             app.print();
    }   
}


/* ---- org/company/springtest/TestApp.java: ---- */
package org.company.springtest;
import org.springframework.beans.factory.annotation.Required;

public class TestApp {
    private String m_message;

    public void setMessage( String message ) {
         m_message = message;
    }

    public void print() {
        System.out.println(m_message);
    }
}

/* ---- conf/xml/context2.xml: ---- */
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:lang="http://www.springframework.org/schema/lang" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations" value="file:conf/xml/test.properties" />
    </bean>
    <bean id="testApp" class="org.company.springtest.TestApp">
         <property name="message" value="${test.message}"/>
    </bean>
</beans>

/* ---- conf/xml/test.properties: ---- */
test.message=Hello world!

The following is the output when running Test:

Feb 17, 2009 11:23:06 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from file [C:\eclipse\workspace\SpringTest\conf\xml\context2.xml]
${test.message}

It looks like the Configurer is not replacing the property values...

like image 245
Jake Avatar asked Feb 17 '09 16:02

Jake


2 Answers

Perhaps try using an ApplicationContext instead of a BeanFactory?

like image 173
cliff.meyers Avatar answered Oct 06 '22 03:10

cliff.meyers


Instead of Resource res = File..... use the below

ApplicationContext ctx = new FileSystemXmlApplicationContext("conf/xml/context2.xml");
TestApp test = (TestApp) ctx.getBean("testApp");
test.print();

You will get the result.

For Resource it will not read the Property which we have specified in the path.

like image 41
Dhilip Avatar answered Oct 06 '22 04:10

Dhilip