[编辑]
编辑答案添加更多信息,因为否决票。
您没有收到侦听器的回调的原因是,您没有显式调用
生命周期
start()
方法(
JavaDoc
).
这将级联到您的
应用程序上下文
通常通过
AbstractApplicationContext
在弹簧防尘套中通过
配置应用程序上下文
.
下面的工作代码示例演示了回调的工作方式(只需显式调用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
.
这里还有一个工作示例,说明如何使用
上下文刷新事件
:
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");
}
}
}
[编辑前]
将泛型类型更改为
上下文刷新事件
相反,它应该会起作用。
有关更多详细信息,请阅读
this article from the Spring Blog
. 仅引用有关
上下文刷新事件
:
[..]这样,当上下文
已刷新
当应用程序
上下文已完全启动。[..]