gpt4 book ai didi

java - ContextStartedEvent 未在自定义监听器中触发

转载 作者:行者123 更新时间:2023-11-30 06:04:55 25 4
gpt4 key购买 nike

我正在尝试使用像这样的自定义应用程序监听器连接到上下文的创建

@Component
public class ContextStartedListener implements ApplicationListener<ContextStartedEvent> {

@Override
public void onApplicationEvent(ContextStartedEvent event) {
System.out.println("Context started"); // this never happens
}
}

但是 onApplicationEvent 方法永远不会触发。如果我使用不同的事件,例如 ContextRefreshedEvent,那么它工作得很好,但我需要在创建它之前 Hook 。有什么建议吗?谢谢!

最佳答案

[编辑]

由于否决票,编辑答案添加了更多信息。

您没有收到监听器回调的原因是您没有显式调用 LifeCycle start() 方法 ( JavaDoc )。

这通常通过 AbstractApplicationContext 级联到您的 ApplicationContext 在 Spring Boot 案例中通过 ConfigurableApplicationContext

下面的工作代码示例演示了您的回调将如何工作(只需显式调用 start() 方法)

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);
applicationContext.start();
}

@Component
class ContextStartedListener implements ApplicationListener<ContextStartedEvent> {

@Override
public void onApplicationEvent(ContextStartedEvent event) {
System.out.println("Context started");
}
}
}

我之所以在 ContextRefreshedEvent 回调下面建议,是因为在幕后调用了 refresh() 代码。

如果您向下钻取 SpringApplication#run() 方法 you'll eventually see it .

这里还有一个使用 ContextRefreshedEvent 的工作示例:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}

@Component
class ContextStartedListener implements ApplicationListener<ContextRefreshedEvent> {

@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
System.out.println("Context refreshed");
}
}
}

[编辑前]

将通用类型更改为 ContextRefreshedEvent,然后它应该可以工作。

有关更多详细信息,请阅读 this article from the Spring Blog .只是引用有关 ContextRefreshedEvent 的部分:

[..]This allows MyListener to be notified when the context has refreshed and one can use that to run arbitrary code when the application context has fully started.[..]

关于java - ContextStartedEvent 未在自定义监听器中触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48099355/

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