Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 871
Adrian Ber Avatar asked Dec 24 '12 14:12

Adrian Ber


People also ask

What is @resource annotation in spring?

The @Resource annotation in spring performs the autowiring functionality. This annotation follows the autowire=byName semantics in the XML based configuration i.e. it takes the name attribute for the injection.

How do I get resources from spring boot?

How to get resource reliably. To reliably get a file from the resources in Spring Boot application: Find a way to pass abstract resource, for example, InputStream , URL instead of File. Use framework facilities to get the resource.


2 Answers

In one line try this to read test.xml:

String msg = StreamUtils.copyToString( new ClassPathResource("test.xml").getInputStream(), Charset.defaultCharset()  ); 
like image 130
N Piper Avatar answered Oct 13 '22 06:10

N Piper


<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> 
like image 22
Adrian Ber Avatar answered Oct 13 '22 04:10

Adrian Ber