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.
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 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.
In one line try this to read test.xml:
String msg = StreamUtils.copyToString( new ClassPathResource("test.xml").getInputStream(), Charset.defaultCharset() );
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With