【问题标题】:Spring ApplicationListener is not receiving eventsSpring ApplicationListener 没有接收到事件
【发布时间】:2011-08-09 08:38:45
【问题描述】:

我有以下 ApplicationListener:

package org.mycompany.listeners;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStartedEvent;

public class MyApplicationListener implements ApplicationListener<ContextStartedEvent> {

  public MyApplicationListener() {
    super();
    System.out.println("Application context listener is created!");
  }

  /**
   * {@inheritDoc}
   */
  public void onApplicationEvent(final ContextStartedEvent event) {
    System.out.println("Context '" + event.getApplicationContext().getDisplayName() + "' is started!");
  }

}

还有下面的bean定义:

<bean name="myApplicationListener" class="org.mycompany.listeners.MyApplicationListener" />

我可以看到 bean 是在打印来自构造函数的消息时创建的,但从未收到上下文启动事件。我错过了什么?

【问题讨论】:

  • 应该有@Component注解吗?

标签: java spring listener applicationcontext


【解决方案1】:

ContextStartedEvent 在上下文中显式调用 ConfigurableApplicationContext.start() 时发布。如果您需要在初始化上下文时发布的事件,请使用ContextRefreshedEvent

另请参阅:

【讨论】:

  • 请注意,ContextRefreshedEvent 可能会多次发布,因此它也可能在所有 bean 初始化之前发布(例如,使用 CXF 2.4.2 时...)。然而,在最常见的设置中,ContextRefreshedEvent 确实只有在上下文启动完成后才会发布。
  • 非常有帮助,但这种约定看起来不合适:(
【解决方案2】:

不确定这是否有帮助,但我隐约记得有一个类似的问题,这是通过预加载而不是延迟加载解决的。这是两者的quick overview

【讨论】:

  • 我的上下文中没有延迟初始化的 bean。
【解决方案3】:

由于您没有延迟加载的 bean(根据您的说法),那么您很可能出于错误的原因使用事件,并且可能应该改用 InitializingBean 接口之类的东西:

public class MyBean implements InitializingBean {

    @Override
    public void afterPropertiesSet() throws Exception {
        // ...
    }

}

来自 Spring 手册:

要与容器对 bean 生命周期的管理进行交互,您 可以实现 Spring InitializingBean 和 DisposableBean 接口。容器为前者调用 afterPropertiesSet() 和 destroy() 后者允许 bean 执行某些 初始化和销毁​​ bean 时的操作。你可以 也实现了与容器相同的集成,无需耦合 通过使用 init-method 和 Spring 接口你的类 销毁方法对象定义元数据。

来源:Spring Framework - Lifecycle callbacks

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多