首页 > 解决方案 > 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();
}

标签: javaspring

解决方案


这应该工作:

@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();
    }

}

推荐阅读