4 ways to bootstrap a Spring Boot Application

There are several ways to bootstrap a Spring Boot standalone application. One way to do it is by implementing the org.springframework.boot.CommandLineRunner interface and implementing the run(String… args) method.

This is useful when you want to execute jobs or services, such as send a notification about the application or execute a SQL statement to update some rows before your application runs. Here is an example:

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication public DemoApplication implements CommandLineRunner {
  public void run(String...args) {
    // This will run after the SpringApplication.run(..)    
    // Do something...    
  }
  public static void main(String[] args) throws Exception {
    SpringApplication.run(MyApplication.class, args);
  }
}

The following code shows you how to use the CommandLineRunner interface as a Bean by annotating the method with @Bean:

@Bean public CommandLineRunner runner() {
  return new CommandLineRunner() {
    public void run(String...args) {
      //Run some process here      
    }

  };

}

Or, if you are using Java 8, you can use the lambdas feature like this:

@Bean public CommandLineRunner runner(Repository repo) {
  return args -> {
    //Run some process here    
  };
}

This following code shows you how to use the CommandLineRunner interface using the Java 8 lambdas. In this case the method’s parameter is a Repository , which is normally useful to do some database tasks.
Maybe you are wondering what you need to do if you need to run some code even before the CommandLineRunner . You can do this by returning an InitializingBean interface.

@Bean InitializingBean saveData(Repository repo) {
  return () -> {
    //Do some DB inserts 
  };
}