'ByteArrayResource usage

I have a template pdf which is stored in either in physical path or in application classpath. I have to read this template and fill its fields for each request based on user input for every request. I want to convert this file into byte and store this in Configuration bean during application startup instead reading template file every time. For this can I use ByteArrayResource in Spring or another better approach.

My goal is not to read template file every time.



Solution 1:[1]

Yes it is definitely a good idea to cache the template byte array if you need it frequently. But be aware that this will increase your memory usage by the size of the file.

Using spring's ByteArrayResource can be a good approach for this, depending on what you are using for processing the template. ByteArrayResource's getInputStream() method will always give you a fresh ByteArrayInputStream

You can provide a ByteArrayResource bean with the content like this:

@Bean
public ByteArrayResource infomailTemplate(@Value("classpath:infomail-template.html") Resource template) throws IOException {
    byte[] templateContent = org.springframework.util.FileCopyUtils.copyToByteArray(template.getFile());
    return new ByteArrayResource(templateContent);
}

and then simply autowire it then everywhere you like, like this:

@Autowired 
private ByteArrayResource infomailTemplate

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gmeiner.m