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:
- You never actually have to invoke this constructor. It gets automatically invoked by the Spring Boot framework
- You never have to invoke the constructor for the
HelloService
instance either. As long as there is someBean
that Spring knows about that implementsHelloService
, it will automatically instantiate thatBean
and pass the instance into the constructor.
This allows you to change the implementation of HelloService
while minimizing the changes to the code.
More on Spring Boot: Command Line
- Spring Boot: Ajax—Communicating between front-end JavaScript and backend Java using XMLHTTP requests
- Spring Boot: Annotations—The various things starting with @ that are particular to Spring and Spring Boot
- Spring Boot: Command Line—A Command Line program within the Spring Boot framework
- Spring Boot: Configuration—The src/resources/application.yml file, and how to fix 'Could not resolve placeholder ${salt}' type errors
- Spring Boot: Controllers—The component where you map routes to the model and view
- Spring Boot: Example Projects—Links to various Spring Boot Projects of interest
- Spring Boot: Heroku—Running Spring Boot Applications On Heroku
- Spring Boot: HTTPS—Enabling HTTPS
- Spring Boot: Logging—How to handle logging in Spring Boot
- Spring Boot: main—What the main program looks like in a Spring Boot Application
- Spring Boot: OAuth—Social login with Spring Boot
- Spring Boot: Starter Parent—What does the `parent` section in the pom.xml do?