Running code after Spring Boot starts – Dev

The best answers to the question “Running code after Spring Boot starts” in the category Dev.


I want to run code after my spring-boot app starts to monitor a directory for changes.

I have tried running a new thread but the @Autowired services have not been set at that point.

I have been able to find ApplicationPreparedEvent, which fires before the @Autowired annotations are set. Ideally I would like the event to fire once the application is ready to process http requests.

Is there a better event to use, or a better way of running code after the application is live in spring-boot?



public class Application extends SpringBootServletInitializer {

    public static void main(final String[] args) {
        ConfigurableApplicationContext context =, args);

        context.getBean(Table.class).fillWithTestdata(); // <-- here


It is as simple as this:

public void doSomethingAfterStartup() {
    System.out.println("hello world, I have just started up");

Tested on version 1.5.1.RELEASE


Why not just create a bean that starts your monitor on initialization, something like:

public class Monitor {
    @Autowired private SomeService service

    public void init(){
        // start your monitoring in here

the init method will not be called until any autowiring is done for the bean.


Have you tried ApplicationReadyEvent?

public class ApplicationStartup 
implements ApplicationListener<ApplicationReadyEvent> {

   * This event is executed as late as conceivably possible to indicate that 
   * the application is ready to service requests.
  public void onApplicationEvent(final ApplicationReadyEvent event) {

    // here your code ...


Code from:

This is what the documentation mentions about the startup events:

Application events are sent in the following order, as your application runs:

An ApplicationStartedEvent is sent at the start of a run, but before
any processing except the registration of listeners and initializers.

An ApplicationEnvironmentPreparedEvent is sent when the Environment to be used in the context is known, but before the context
is created.

An ApplicationPreparedEvent is sent just before the refresh is started, but after bean definitions have been loaded.

An ApplicationReadyEvent is sent after the refresh and any related callbacks have been processed to indicate the application is ready to
service requests.

An ApplicationFailedEvent is sent if there is an exception on startup.