gpt4 book ai didi

java - 如何在 Java Web 应用程序中声明启动 Hook

转载 作者:行者123 更新时间:2023-12-01 21:08:24 26 4
gpt4 key购买 nike

我想在网络应用程序启动时进行一些初始化(计时器和日志记录)。我无法使用 ContextListener,因为我没有在其中获取任何 Spring 组件。我需要一个简单的钩子(Hook),例如“afterWebAppHasLoadedAndEverythingyIsSetUp()”。存在吗?

最佳答案

加载 bean 时,ApplicationContext 会发布某些类型的事件。

ApplicationContext 中的事件处理是通过 ApplicationEvent 类和 ApplicationListener 接口(interface)提供的。因此,如果一个 bean 实现了 ApplicationListener,那么每次将 ApplicationEvent 发布到 ApplicationContext 时,都会通知该 bean。

以下事件由 spring 提供

  • ContextRefreshedEvent
  • ContextStartedEvent
  • ContextStoppedEvent
  • ContextClosedEvent

首先创建一个ApplicationListener的实现,如下

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStartedEvent;

public class CStartEventHandler
implements ApplicationListener<ContextStartedEvent>{

public void onApplicationEvent(ContextStartedEvent event) {
System.out.println("ContextStartedEvent Received");
}
}

然后你只需要用 Spring 将该类注册为 bean 即可。

关于java - 如何在 Java Web 应用程序中声明启动 Hook ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41837069/

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