9

I need to run a method after the Spring Application Context of my web app has started up. I looked at this question but it refers to Java Servlet startup, and none of the Spring stuff has run at that point.

Is there a "SpringContext.onStartup()" method I can hook into?

Community
  • 1
  • 1
user3120173
  • 1,758
  • 7
  • 25
  • 39

3 Answers3

15

Use something like the following code:

@Component
public class StartupListener implements ApplicationListener<ContextRefreshedEvent> {

  @Override
  public void onApplicationEvent(final ContextRefreshedEvent event) {
    // do your stuff here 
  }
}

Of course StartupListener will need to be within the component scan's reach

Take note however that if your application uses multiple contexts (for example a root context and a web context) this method will be run once for each context.

geoand
  • 60,071
  • 24
  • 172
  • 190
4

You can write listener like this:

@Component
public class SpringContextListener implements ApplicationListener<ApplicationEvent> {
    public void onApplicationEvent(ApplicationEvent arg0) {
        System.out.println("ApplicationListener");
    };
}

Just add component scan path like this:

<context:component-scan base-package="com.controller" />
Krishna
  • 7,154
  • 16
  • 68
  • 80
4

Have a look at Better application events in Spring Framework 4.2

@Component
public class MyListener {

    @EventListener
    public void handleContextRefresh(ContextRefreshedEvent event) {
       ...
    }
}

Annotate a method of a managed-bean with @EventListener to automatically register an ApplicationListener matching the signature of the method. @EventListener is a core annotation that is handled transparently in a similar fashion as @Autowired and others: no extra configuration is necessary with java config and the existing < context:annotation-driven/> element enables full support for it.

Reva
  • 118
  • 2
  • 7