java 使用 Spring 将文本文件直接注入到 String

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13739823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:50:33  来源:igfitidea点击:

Use Spring to inject text file directly to String

javaspringinject

提问by rozner

So I have this

所以我有这个

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

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

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.

我想知道的是,是否可以不使用 readFile() 方法并将 sampleHtmlData 注入文件的内容。如果没有,我将不得不忍受这个,但这将是一个不错的捷径。

回答by Tomasz Nurkiewicz

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?

从技术上讲,您可以使用 XML 以及工厂 bean 和方法的笨拙组合来做到这一点。但是,当您可以使用 Java 配置时,何必费心呢?

@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);
        }
    }
}

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

请注意,我还sampleHtml.getInputStream()使用try-with-resources习惯用法关闭了从返回的流。否则你会得到内存泄漏。

回答by abalogh

There is no built-in functionality for this to my knowledge but you can do it yourself e.g. like this:

据我所知,没有内置功能,但您可以自己完成,例如:

<bean id="fileContentHolder">
  <property name="content">
    <bean class="CustomFileReader" factory-method="readContent">
      <property name="filePath" value="path/to/my_file"/>
    </bean>
   </property>
</bean>

Where readContent() returns a String which is read from the file on path/to/my_file.

其中 readContent() 返回从 path/to/my_file 上的文件读取的字符串。