简体   繁体   中英

Spring ApplicationListener is not receiving events

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?

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:

Since you have no lazy loaded beans (according to you) then you are most likely using events for the wrong reason and probably should use something like InitializingBean interface instead:

public class MyBean implements InitializingBean {

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

}

From Spring manual:

To interact with the container's management of the bean lifecycle, you can implement the Spring InitializingBean and DisposableBean interfaces. The container calls afterPropertiesSet() for the former and destroy() for the latter to allow the bean to perform certain actions upon initialization and destruction of your beans. You can also achieve the same integration with the container without coupling your classes to Spring interfaces through the use of init-method and destroy method object definition metadata.

Source: Spring Framework - Lifecycle callbacks

Not sure if this helps, but I vaguely remember having a similar problem, which was solved by preloading and not lazy loading. Here's a quick overview of both

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM