Spring ApplicationListener未接收事件

And*_*ich 39 java spring listener applicationcontext

我有以下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!");
  }

}
Run Code Online (Sandbox Code Playgroud)

以下bean定义:

<bean name="myApplicationListener" class="org.mycompany.listeners.MyApplicationListener" />
Run Code Online (Sandbox Code Playgroud)

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

axt*_*avt 62

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

也可以看看:

  • 请注意,`ContextRefreshedEvent`可能会多次发布,因此也可能在所有bean初始化之前发布(例如,在使用CXF 2.4.2时).但是,在最常见的设置中,只有在完成上下文启动时才会发布`ContextRefreshedEvent`. (8认同)

Mik*_*cki 7

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

public class MyBean implements InitializingBean {

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

}
Run Code Online (Sandbox Code Playgroud)

从Spring手册:

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

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