简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM