我在我的 spring 应用程序中有一个 classX,我希望能够找出是否所有的 spring bean 都已初始化。为此,我正在尝试收听 ContextRefreshedEvent。
到目前为止,我有以下代码,但我不知道这是否足够。
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
public classX implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
//do something if all apps have initialised
}
}
这种方法是否正确,以找出是否所有的 bean 已初始化?
我还需要做什么才能收听 ContextRefreshedEvent?我需要在 xml 文件中注册 classX 吗?
ContextRefreshEvent
occurs
当ApplicationContext
被初始化或刷新时。
所以你在正确的轨道上。
您需要做的是为classX
声明一个 bean 定义。
使用@Component
和组件扫描它所在的包
@Component
public class X implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
//do something if all apps have initialised
}
}
或使用<bean>
声明
<bean class="some.pack.X"></bean>
Spring 将检测到 bean 的类型为ApplicationListener
,并在不进行任何进一步配置的情况册它。
更高版本的 Spring 支持基于注释的事件。documentation状态
从 Spring 4.2 开始,您可以使用@EventListener
注释在托管 bean 的任何公共方法上注册事件。
在上面的X
类中,您可以声明一个带注释的方法,如
@EventListener
public void onEventWithArg(ContextRefreshedEvent event) {
}
或者甚至
@EventListener(ContextRefreshedEvent.class)
public void onEventWithout() {
}
上下文将检测此方法并将其注册为指定事件类型的。
文档更详细地介绍了完整的功能集:使用 SpEL 表达式进行条件处理,异步等。
仅供参考,Java 有类型,变量等命名约定对于类,约定是让他们的名字以大写字母字符开头。
弹簧 & gt;= 4.2
您可以使用注释驱动的事件,如下所示:
@Component
public class classX {
@EventListener
public void handleContextRefresh(ContextRefreshedEvent event) {
}
}
要注册的 ApplicationListener 在方法的签名中定义。
(ContextRefreshedEvent 事件)被调用两次,一次在 init 中,第二次在 init 之后。
您可以使用(ApplicationReadyEvent 事件),并且在 init 之后只进行一次调用。
public class InvokeCatalogOne implements IInvokeCatalogOne {
@EventListener
public void fetchChargeCode(ApplicationReadyEvent event) {
}
}
我会更喜欢 ApplicationReadyEvent。我发现 ContextRefreshedEvent 在我的 http 服务器启动之前被调用。ApplicationReadyEvent 将确保您的应用程序已准备好接受请求。
@EventListener(ApplicationReadyEvent.class)
public void startApp() {
LOGGER.info("Application is now ready!");
}
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(59条)