45

我有以下应用程序侦听器:

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 是在打印来自构造函数的消息时创建的,但从未收到上下文启动事件。我错过了什么?

4

3 回答 3

66

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

也可以看看:

于 2011-04-20T10:10:24.733 回答
7

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

public class MyBean implements InitializingBean {

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

}

来自 Spring 手册:

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

来源:Spring Framework - 生命周期回调

于 2012-11-28T14:17:45.803 回答
0

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

于 2011-04-20T10:03:37.797 回答