ByteArray资源使用

spr*_*ner 10 java spring-boot

我有一个 pdf 模板,它存储在物理路径或应用程序类路径中。我必须阅读此模板并根据每个请求的用户输入填写每个请求的字段。我想将此文件转换为字节并在应用程序启动期间将其存储在配置 bean 中,而不是每次都读取模板文件。为此,我可以在 Spring 中使用 ByteArrayResource 或其他更好的方法。

我的目标不是每次都读取模板文件。

gme*_*r.m 10

是的,如果您经常需要的话,缓存模板字节数组绝对是个好主意。但请注意,这会增加文件大小的内存使用量。

使用 spring 的ByteArrayResource可能是一个很好的方法,具体取决于您用于处理模板的内容。ByteArrayResourcegetInputStream()方法将始终为您提供一个新的ByteArrayInputStream

您可以提供一个 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);
}
Run Code Online (Sandbox Code Playgroud)

然后简单地自动连接它然后在任何你喜欢的地方,就像这样:

@Autowired 
private ByteArrayResource infomailTemplate
Run Code Online (Sandbox Code Playgroud)