Spring’s PropertyPlaceholderConfigurer as a PropertiesFactoryBean

March 6, 2008 – 7:45 pm

For a couple of past days I have been struggling with a problem with Spring’s PropertyPlaceholderConfigurer. I coudn’t get it to work in a way PropertiesFactoryBean is working. I wanted it to act in a similar way:

    <bean id="properties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:MaNaWa.properties" />
    </bean>

    <bean id="config" class="com.netia.manawa.Config">
        <constructor-arg ref="properties" />
    </bean>

Unfortunately this code does not work. Everything you get is just an exception saying PropertyPlaceholderConfigurer can’t be cast to java.util.Properties. So, for a good deal of time I have been doing something ugly:

    <bean id="properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="location" value="classpath:MaNaWa.properties" />
    </bean>  

    <context:property-placeholder location="classpath:MaNaWa.properties"/>  

    <bean id="config" class="com.netia.manawa.Config">
        <constructor-arg ref="properties" />
    </bean>

Which, of course, resulted in a properties file being loaded two times.

Then, while I was sleeping, came a solution. I dreamed I could use a PropertiesFactoryBean in a PropertyPlaceholderConfigurer and guess what… it works. Just like that. See for yourselves:

    <bean id="properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="location" value="classpath:MaNaWa.properties" />
    </bean>

    <bean id="placeholder"  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="properties" ref="properties" />
    </bean>

    <bean id="config" class="com.netia.manawa.Config">
        <constructor-arg ref="properties" />
    </bean>

Gee. Now, to think about code while sleeping? That’s geeky, isn’t it? Well, I guess I have to live with that :)

  1. 4 Responses to “Spring’s PropertyPlaceholderConfigurer as a PropertiesFactoryBean”

  2. Hey mate, that’s great!
    BTW if you want to override some of properties you can use

    env.properties

    By Tanya on Jul 3, 2009

  3. s… it ate the code :(
    I meant PropertyOverrideConfigurer

    By Tanya on Jul 3, 2009

  4. Nice tip, but now I cannot see the point of having a PropertyPlaceholderConfigurer (the “placeholder” bean, in your case), that is not referenced by anything.

    By Eugenio on Sep 2, 2009

  5. Uh, nevermind, I tried the code myself, and spotted te difference:
    The PropertiesFactoryBean plus the “config” does it in setting the “properties” instance in the bean that references it. But if you also want to use some of that properties in the xmlfile itself, then you need the PropertyPlaceholderConfigurer to do dat job for you.
    Thank you again.

    By Eugenio on Sep 2, 2009

Post a Comment