Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 732
springbootlearner Avatar asked Nov 06 '18 14:11

springbootlearner


People also ask

What is ByteArrayResource in Java?

public class ByteArrayResource extends AbstractResource. Resource implementation for a given byte array. Creates a ByteArrayInputStream for the given byte array. Useful for loading content from any given byte array, without having to resort to a single-use InputStreamResource .

What is InputStreamResource in Java?

public class InputStreamResource extends AbstractResource. Resource implementation for a given InputStream . Should only be used if no other specific Resource implementation is applicable. In particular, prefer ByteArrayResource or any of the file-based Resource implementations where possible.

What is byte array InputStream in Java?

The ByteArrayInputStream class of the java.io package can be used to read an array of input data (in bytes). It extends the InputStream abstract class. Note: In ByteArrayInputStream , the input stream is created using the array of bytes. It includes an internal array to store data of that particular byte array.


1 Answers

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
like image 126
gmeiner.m Avatar answered Sep 20 '22 21:09

gmeiner.m