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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With