java - Spring ApplicationEvent onApplicationEvent 方法
问题描述
预期:当我在调试模式下运行应用程序并拉出端点时,bytes
仍然显示为空,但是我确实实现了 ApplicationEvent 并传递了 ApplicationStartedEvent,然后我覆盖了 onApplicationEvent 并在那里调用了我的方法,这应该会导致应用程序启动后代码执行并且bytes
应该已经有值了。我错过了什么吗
public class FaqAttachment implements ApplicationListener<ApplicationStartedEvent> {
private final String fileName = "FAQ.pdf";
private byte[] bytes;
public Attachment asAttachment() {
return new Attachment(pdfToBytes(), fileName);
}
private byte[] pdfToBytes() {
if (bytes == null) {
try (FileInputStream inputStream = new FileInputStream(new File(ClassLoader.getSystemResource(fileName).getFile()))) {
this.bytes = ByteStreams.toByteArray(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return bytes;
}
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
pdfToBytes();
}
解决方案
这应该工作:
@Component
public class FaqAttachment {
private final String fileName = "FAQ.pdf";
private byte[] bytes;
public Attachment asAttachment() {
return new Attachment(pdfToBytes(), fileName);
}
private byte[] pdfToBytes() {
if (bytes == null) {
try (FileInputStream inputStream = new FileInputStream(new File(ClassLoader.getSystemResource(fileName).getFile()))) {
this.bytes = ByteStreams.toByteArray(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return bytes;
}
@EventListener
public void onApplicationStartedEvent(ApplicationStartedEvent event) {
pdfToBytes();
}
}
推荐阅读
- laravel - 控制器中的循环图像
- highcharts - Highchart 图例涵盖图表内容
- angular - Passport.js,Auth0 CORS 错误
- json - 节奏天堂混音编辑器 3:自定义 JSON 文件返回“意外字符('}'(代码 125)):期待双引号开始字段名称”
- sqoop - 使用 sqoop 导出数据
- installshield-2010 - (installshield)我想知道不管包程序中的文件如何运行
- javascript - 用javascript解析二进制点数据
- python - 嵌套类属性未被识别为 int
- r - 如何在 R 的 dplyr::mutate 函数中创建方程?
- javascript - 在行内使用 checkox 隐藏表格行