Spring ApplicationListener is not receiving events

Andrey Adamovich picture Andrey Adamovich · Apr 20, 2011 · Viewed 43.4k times · Source

I have the following 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!");
  }

}

And the following bean definition:

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

I can see that bean is created as message from the constructor is printed, but context start event is never recieved. What am I missing?

Answer

axtavt picture axtavt · Apr 20, 2011

ContextStartedEvent is published when you explicitly invoke ConfigurableApplicationContext.start() on the context. If you need an event that is published when context is initialized, use ContextRefreshedEvent.

See also: