如何在Spring中加载资源并将其内容用作字符串 [英] How do I load a resource and use its contents as a string in Spring

查看:93
本文介绍了如何在Spring中加载资源并将其内容用作字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何加载Spring资源内容并将其用于设置bean属性或将其作为参数构造函数传递?

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

该资源包含自由文本.

推荐答案

<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>

此解决方案需要Apache Commons IO.

This solution requires Apache Commons IO.

@Parvez建议的另一种没有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>

这篇关于如何在Spring中加载资源并将其内容用作字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆