使用Spring将文本文件直接注入String [英] Use Spring to inject text file directly to String

查看:348
本文介绍了使用Spring将文本文件直接注入String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个

@Value("classpath:choice-test.html")
private Resource sampleHtml;
private String sampleHtmlData;

@Before
public void readFile() throws IOException {
    sampleHtmlData = IOUtils.toString(sampleHtml.getInputStream());
}

我想知道的是,是否有可能没有readFile()方法,而有没有将sampleHtmlData注入文件的内容.如果不是这样,我只需要忍受这一点,但这将是一个不错的捷径.

What I'd like to know is if it's possible to not have the readFile() method and have sampleHtmlData be injected with the contents of the file. If not I'll just have to live with this but it would be a nice shortcut.

推荐答案

技术上,您可以使用XML以及工厂bean和方法的笨拙组合来完成此任务.但是,什么时候可以使用Java配置呢?

Technically you can do this with XML and an awkward combination of factory beans and methods. But why bother when you can use Java configuration?

@Configuration
public class Spring {

    @Value("classpath:choice-test.html")
    private Resource sampleHtml;

    @Bean
    public String sampleHtmlData() {
        try(InputStream is = sampleHtml.getInputStream()) {
            return IOUtils.toString(is);
        }
    }
}

请注意,我也使用 try-with-resources 习惯用法关闭了sampleHtml.getInputStream()返回的流.否则会导致内存泄漏.

Notice that I also close the stream returned from sampleHtml.getInputStream() by using try-with-resources idiom. Otherwise you'll get memory leak.

这篇关于使用Spring将文本文件直接注入String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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