java听ContextRefreshedEvent [英] java listen to ContextRefreshedEvent

查看:393
本文介绍了java听ContextRefreshedEvent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的spring应用程序中有一个classX,我希望能够在其中找到所有spring bean是否已初始化.为此,我正在尝试监听ContextRefreshedEvent.

I have a classX in my spring application in which I want to be able to find out if all spring beans have been initialized. To do this, I am trying to listen ContextRefreshedEvent.

到目前为止,我有以下代码,但不确定是否足够.

So far I have the following code but I am not sure if this is enough.

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
    }
}

  1. 这种方法是否正确,才能确定所有bean是否都已初始化?
  2. 要监听ContextRefreshedEvent我还需要做什么?我需要在XML文件中的某处注册classX吗?

推荐答案

发生ContextRefreshEvent

ApplicationContext初始化或刷新时.

when an ApplicationContext gets initialized or refreshed.

所以您走在正确的轨道上.

so you are on the right track.

您需要做的是为classX声明一个bean定义.

What you need to do is declare a bean definition for classX.

使用@Component和组件扫描其所在的包中的

Either with @Component and a component scan over the package it's in

@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 will detect that the bean is of type ApplicationListener and register it without any further configuration.

最新的Spring版本支持基于注释的事件侦听器. 文档状态

Later Spring version support annotation-based event listeners. The documentation states

从Spring 4.2开始,您可以在任何公共场所注册事件侦听器 使用@EventListener批注的托管bean的方法.

As of Spring 4.2, you can register an event listener on any public method of a managed bean by using the @EventListener annotation.

在上面的X类中,您可以声明一个带注释的方法,例如

Within the X class above, you could declare an annotated method like

@EventListener
public void onEventWithArg(ContextRefreshedEvent event) {
}

甚至

@EventListener(ContextRefreshedEvent.class)
public void onEventWithout() {

}

上下文将检测到此方法并将其注册为指定事件类型的侦听器.

The context will detect this method and register it as a listener for the specified event type.

文档全面介绍了完整功能集:带有SpEL表达式的条件处理,异步侦听器等.

The documentation goes into way more detail about the full feature set: conditional processing with SpEL expression, async listeners, etc.

仅供参考,Java具有类型,变量等的命名约定.对于类,该约定的名称应以大写字母字符开头.

Just FYI, Java has naming conventions for types, variables, etc. For classes, the convention is to have their names start with an uppercase alphabetic character.

这篇关于java听ContextRefreshedEvent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆