简体   繁体   English

ByteArrayResource的用法

[英]ByteArrayResource usage

I have a template pdf which is stored in either in physical path or in application classpath. 我有一个模板pdf,它存储在物理路径或应用程序类路径中。 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. 我想将此文件转换为字节,并在应用程序启动期间将其存储在Configuration bean中,而不是每次读取模板文件。 For this can I use ByteArrayResource in Spring or another better approach. 为此,我可以在Spring中使用ByteArrayResource或其他更好的方法。

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. 使用spring的ByteArrayResource可能是一个很好的方法,具体取决于您用于处理模板的内容。 ByteArrayResource 's getInputStream() method will always give you a fresh ByteArrayInputStream ByteArrayResourcegetInputStream()方法将始终为您提供新鲜的ByteArrayInputStream

You can provide a ByteArrayResource bean with the content like this: 您可以提供具有以下内容的ByteArrayResource bean:

@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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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