Run a method only at Spring Application Context startup?

22,331

Solution 1

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.

Solution 2

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" />

Solution 3

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.

Share:
22,331
user3120173
Author by

user3120173

Java Programmer for five years SQL Server Developer for five years IT Department Manager for three years Participated in several web startups

Updated on March 02, 2020

Comments

  • user3120173
    user3120173 about 4 years

    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?