Java ByteArrayResource使用

Java ByteArrayResource使用,java,spring-boot,Java,Spring Boot,我有一个pdf模板,它存储在物理路径或应用程序类路径中。我必须阅读此模板,并根据每个请求的用户输入填写每个请求的字段。我想将这个文件转换成字节,并在应用程序启动期间将其存储在配置bean中,而不是每次都读取模板文件。为此,我可以在Spring中使用ByteArrayResource或其他更好的方法 我的目标不是每次都读取模板文件。是的,如果您经常需要,缓存模板字节数组绝对是一个好主意。但请注意,这将增加文件大小对内存的使用 使用spring的ByteArrayResource可能是一种很好的方法

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


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

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

使用spring的ByteArrayResource可能是一种很好的方法,具体取决于您用于处理模板的内容。ByteArrayResource的getInputStream()方法将始终为您提供一个新的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);
}
@Autowired 
private ByteArrayResource infomailTemplate
然后只需将其自动连接到您喜欢的任何地方,如下所示:

@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);
}
@Autowired 
private ByteArrayResource infomailTemplate