Spring Boot: Command Line

A Command Line program within the Spring Boot framework

To write a command line program that works inside the Spring Boot framework, you can use:


import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;


@Component
public class MyCommandLineRunner implements CommandLineRunner {

  @Override
  public void run(String args...) throws Exception {
  
  }
}

This video shows an example: https://content.pivotal.io/springone-platform-2017/its-a-kind-of-magic-under-the-covers-of-spring-boot-brian-clozel-st%C3%A9phane-nicoll

The @Component annotation is explained here: http://zetcode.com/springboot/component/

Part of the magic of Spring is that you can create a constructor for this class, e.g.

  private final HelloService helloService;
  public MyCommandLineRunner(HelloService helloService) {
    this.helloService = helloService;
  }

And the cool thing is that:

This allows you to change the implementation of HelloService while minimizing the changes to the code.

More on Spring Boot: Command Line