Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a method only at Spring Application Context startup?

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?

like image 880
user3120173 Avatar asked Apr 27 '14 16:04

user3120173


People also ask

Which method must be called to start Spring application?

Similar to CommandLineRunner, Spring Boot also provides an ApplicationRunner interface with a run() method to be invoked at application startup. However, instead of raw String arguments passed to the callback method, we have an instance of the ApplicationArguments class.

How do you make sure some default code executes when the Spring boot applications starts up?

Best way to execute block of code after Spring Boot application started is using PostConstruct annotation. Or also you can use command line runner for the same.


1 Answers

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.

like image 178
geoand Avatar answered Oct 25 '22 13:10

geoand