Archimedes Trajano
Archimedes Trajano

Reputation: 41290

How does one make Spring read from a file to string property?

I have a bean that has a string property that I would like to set, but I would like it set from a file without changing the bean code. The bean is something like this.

public class SomeBean {
    public void setSomeProperty(String string) { ... }
}

I was looking for something like this in the beans.xml file

<beans>
   <bean class="SomeBean">
      <property name="someProperty">
         <util:string src="classpath:foo.txt" />
      </property>
   </bean>
</beans>

Upvotes: 0

Views: 654

Answers (2)

Archimedes Trajano
Archimedes Trajano

Reputation: 41290

I found a way using the Guava classes though it looks really bad.

(The value attribute is all in one line)

<property name="someProperty"
  value="#{ T(com.google.common.io.Resources).toString(
              T(com.google.common.io.Resources).getResource('foo.txt'),
              T(java.nio.charset.Charset).forName('UTF-8')) }"/>

Hopefully someone can find a better answer.

Upvotes: 0

AxxA Osiris
AxxA Osiris

Reputation: 1209

Try using the PropertyPlaceholderConfigurer to load a value from a properties file:

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
        <property name="ignoreUnresolvablePlaceholders" value="true" />
        <property name="ignoreResourceNotFound" value="true" />
        <property name="locations">
            <list>
                <value>classpath:foo.properties</value>
            </list>
        </property>
        </bean>

<bean class="SomeBean">
       <property name="someProperty" value="${myBean.someProperty}" />

Then, in the foo.properties file, you set the property to whatever value you want:

myBean.someProperty = value

Hope this helps

Upvotes: 1

Related Questions