0

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>

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

no it does not because I would like the file to be kept as is rather than being converted to a properties file.
@Archimedes Trajano How is your text file formatted ? Does it respect the .properties file format?
in my case it was a JSON file not a properties file.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.