Get an introduction into the command line runner interface and learn how to use it for building Spring Boot command line applications.
- [Narrator] One of my favorite interfaces in the Spring Boot ecosystem and one that is very seldom talked about is the CommandLineRunner. Now the CommandLineRunner is a very simple and effective tool when you need to do a set amount of work. We don't always need to bring in web or rabitt or any of the other processes. Sometimes we just want to work and we want to deploy it as a task but we want to use Spring in the most efficient way possible. So we feel that Spring Boot is that case.
And that's really where the CommandLineRunner interface shines. Sometimes we just need to do some work. Now the beauty of this interface is you can run it in a standalone Spring Boot application or you can run it in another Spring Boot application, say a web application or a Spring batch application. It allows you to do admin or batch processes as part of your application, or as I alluded to, a standalone fashion. Now the CommandLineRunner interface provides access to the application arguments and often times when we want to write a CommandLine process, that's really what we need, is we need to inject application argument into our java code and then execute based on those arguments.
It can run a simple or complex set of tasks and as I mentioned it can be standalone or with a running application. Because when you get access to it, Springs application context is all up and running and then you get your run task and that's all you have to implement is a single-run method. Now the CommandLineRunner interface has a cousin and that's the ApplicationRunner interface. And really it's a very close cousin because they work the exact same way. They run a single-run method and you have access to the application arguments themselves.
Now one thing to note is that you can put more than one CommandLineRunner or ApplicationRunner interface into a Spring Boot application. And when you do that sometimes you need to control the order in which they execute and you can do that with a very simple annotation called @Order. By doing so, you can choose which order you want them to run instead of letting Spring manage that by its default behavior.
- Creating a Spring Boot application
- Configuring a Spring Boot app
- Leveraging profiles
- Packaging and running Spring Boot web apps
- Building a command-line application
- Using Spring Boot starters: Spring Data, Spring Security, and more
- Extending Spring Boot
- Using Spring Boot Actuator to monitor app health and other metrics