我在我的spring应用程序中有一个classX,我希望能够找出所有spring bean是否已经初始化.为此,我正在尝试监听ContextRefreshedEvent.
到目前为止,我有以下代码,但我不确定这是否足够.
import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; public classX implements ApplicationListener{ @Override public void onApplicationEvent(ContextRefreshedEvent event) { //do something if all apps have initialised } }
这种方法是否正确,以确定是否所有bean都已初始化?
为了能够收听ContextRefreshedEvent,我还需要做些什么?我需要在xml文件中的某处注册classX吗?
Sotirios Del.. 20
A ContextRefreshEvent
发生了
当
ApplicationContext
初始化或刷新时.
所以你走在正确的轨道上.
您需要做的是为bean声明一个bean定义classX
.
使用@Component
和组件扫描它所在的包
@Component public classX implements ApplicationListener{ @Override public void onApplicationEvent(ContextRefreshedEvent event) { //do something if all apps have initialised } }
或
声明
Spring将检测bean是否为类型ApplicationListener
并在没有任何进一步配置的情况下注册它.
仅供参考,Java具有类型,变量等的命名约定.对于类,约定是使其名称以大写字母字符开头.
A ContextRefreshEvent
发生了
当
ApplicationContext
初始化或刷新时.
所以你走在正确的轨道上.
您需要做的是为bean声明一个bean定义classX
.
使用@Component
和组件扫描它所在的包
@Component public classX implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { //do something if all apps have initialised } }
或<bean>
声明
<bean class="some.pack.classX"></bean>
Spring将检测bean是否为类型ApplicationListener
并在没有任何进一步配置的情况下注册它.
仅供参考,Java具有类型,变量等的命名约定.对于类,约定是使其名称以大写字母字符开头.
您可以使用注释驱动的事件侦听器,如下所示:
@Component public class classX { @EventListener public void handleContextRefresh(ContextRefreshedEvent event) { } }
要注册的ApplicationListener是在方法的签名中定义的.