gpt4 book ai didi

java - Spring ApplicationEvent onApplicationEvent 方法

转载 作者:行者123 更新时间:2023-12-01 16:20:42 25 4
gpt4 key购买 nike

预期:当我在 Debug模式下运行应用程序并拉出端点时,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();
}

}

关于java - Spring ApplicationEvent onApplicationEvent 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62290490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com