How do I load a resource and use its contents as a string in Spring

How can I load a Spring resource contents and use it to set a bean property or pass it as an argument constructor?

The resource contains free text.


Solution 1:

In one line try this to read test.xml:

String msg = StreamUtils.copyToString( new ClassPathResource("test.xml").getInputStream(), Charset.defaultCharset()  );

Solution 2:

<bean id="contents" class="org.apache.commons.io.IOUtils" factory-method="toString">
    <constructor-arg value="classpath:path/to/resource.txt" type="java.io.InputStream" />
</bean>

This solution requires Apache Commons IO.

Another solution, suggested by @Parvez, without Apache Commons IO dependency is

<bean id="contents" class="java.lang.String">
    <constructor-arg>
        <bean class="org.springframework.util.FileCopyUtils" factory-method="copyToByteArray">
            <constructor-arg value="classpath:path/to/resource.txt" type="java.io.InputStream" />
        </bean>     
    </constructor-arg>
</bean>