javaspringinject

Use Spring to inject text file directly to String


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.


Solution

  • 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, StandardCharsets.UTF_8);
            }
        }
    }
    

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