Spring Boot Console Application with CommandLineRunner
CommandLineRunner is a functional interface for startup tasks that run after the application context has been refreshed and before SpringApplication completes startup. It receives the original command-line argument array; ApplicationRunner receives a parsed ApplicationArguments object. A console Boot application can use the same IoC, persistence and service layers without starting an HTTP server.
Browser-based Spring Boot simulations. Change inputs and trace HTTP requests, bean wiring, SQL, security decisions and tests. No real Java, HTTP server or database operations are executed.
1. Startup runner architecture
Spring registers the runner as a managed bean. After refresh, Boot invokes ordered runners. Web servers may already have started, but the application is not fully ready until runners complete. A non-web app uses the same runner mechanism.
Why this example? Follow context creation and runner invocation for a short task and an exception.
Concept flowchart
Arrows show the actual route; blue identifies the current node. Green indicates visited operations; red nodes show errors or rejected paths.
Current stepSelected path / resultDecision
Why this step happens
See all steps in this scenario
Java / Spring Boot configuration
HTTP / application / test outputConsole
Data operationsCompact blocks
CurrentResultError / rejected
Database rows
Change inputs and step through the example. Code and output are illustrative; actual Spring logs and initialization order may differ. Use the worked examples in a real project.
What this animation explains
Spring registers the runner as a managed bean. After refresh, Boot invokes ordered runners. Web servers may already have started, but the application is not fully ready until runners complete. A non-web app uses the same runner mechanism.
Try and observe
Observe the readiness state after the task.
2. Read command-line arguments
CommandLineRunner receives raw strings, including option prefixes. ApplicationRunner exposes option names, values and non-option arguments. Choose the interface that matches the task instead of manually parsing all flags.
Why this example? Inspect the same --name and positional values through both interfaces.
Concept flowchart
Arrows show the actual route; blue identifies the current node. Green indicates visited operations; red nodes show errors or rejected paths.
Current stepSelected path / resultDecision
Why this step happens
See all steps in this scenario
Java / Spring Boot configuration
HTTP / application / test outputConsole
Data operationsCompact blocks
CurrentResultError / rejected
Database rows
Change inputs and step through the example. Code and output are illustrative; actual Spring logs and initialization order may differ. Use the worked examples in a real project.
What this animation explains
CommandLineRunner receives raw strings, including option prefixes. ApplicationRunner exposes option names, values and non-option arguments. Choose the interface that matches the task instead of manually parsing all flags.
Try and observe
Switch interface and compare raw array with named value.
3. Validate required startup input
A batch application should validate inputs before doing work. A missing argument can either produce a controlled message and return or raise an exception if startup cannot proceed. Here we use a controlled return.
Why this example? Compare valid and missing file argument without performing actual file I/O.
Concept flowchart
Arrows show the actual route; blue identifies the current node. Green indicates visited operations; red nodes show errors or rejected paths.
Current stepSelected path / resultDecision
Why this step happens
See all steps in this scenario
Java / Spring Boot configuration
HTTP / application / test outputConsole
Data operationsCompact blocks
CurrentResultError / rejected
Database rows
Change inputs and step through the example. Code and output are illustrative; actual Spring logs and initialization order may differ. Use the worked examples in a real project.
What this animation explains
A batch application should validate inputs before doing work. A missing argument can either produce a controlled message and return or raise an exception if startup cannot proceed. Here we use a controlled return.
Try and observe
Choose missing input and verify that the service is not called.
4. Multiple runners and execution order
When startup tasks have dependencies, ordering should be explicit. Boot sorts ordered CommandLineRunner and ApplicationRunner beans before calling them. Lower order values execute first; equal order does not establish a reliable relative order.
Why this example? Compare ordering of a seed task and a report task.
Concept flowchart
Arrows show the actual route; blue identifies the current node. Green indicates visited operations; red nodes show errors or rejected paths.
Current stepSelected path / resultDecision
Why this step happens
See all steps in this scenario
Java / Spring Boot configuration
HTTP / application / test outputConsole
Data operationsCompact blocks
CurrentResultError / rejected
Database rows
Change inputs and step through the example. Code and output are illustrative; actual Spring logs and initialization order may differ. Use the worked examples in a real project.
What this animation explains
When startup tasks have dependencies, ordering should be explicit. Boot sorts ordered CommandLineRunner and ApplicationRunner beans before calling them. Lower order values execute first; equal order does not establish a reliable relative order.
Try and observe
Reverse ordering and observe the report reading an empty initial store.
5. Dependency injection into a runner
A runner can receive a service through a @Bean factory parameter, keeping startup orchestration separate from domain logic. A missing required service fails bean creation before runner execution.
Why this example? Follow injected service resolution and use, or observe the missing-bean failure.
Concept flowchart
Arrows show the actual route; blue identifies the current node. Green indicates visited operations; red nodes show errors or rejected paths.
Current stepSelected path / resultDecision
Why this step happens
See all steps in this scenario
Java / Spring Boot configuration
HTTP / application / test outputConsole
Data operationsCompact blocks
CurrentResultError / rejected
Database rows
Change inputs and step through the example. Code and output are illustrative; actual Spring logs and initialization order may differ. Use the worked examples in a real project.
What this animation explains
A runner can receive a service through a @Bean factory parameter, keeping startup orchestration separate from domain logic. A missing required service fails bean creation before runner execution.
Try and observe
Remove the service registration and compare the point of failure.
6. Idempotent database initialization
A runner can seed a database during startup. Repeated starts must not blindly create duplicates. A lookup plus a unique database constraint protects the logical key; concurrent initialization needs an atomic strategy or conflict handling.
Why this example? Compare an empty database with an already seeded database.
Concept flowchart
Arrows show the actual route; blue identifies the current node. Green indicates visited operations; red nodes show errors or rejected paths.
Current stepSelected path / resultDecision
Why this step happens
See all steps in this scenario
Java / Spring Boot configuration
HTTP / application / test outputConsole
Data operationsCompact blocks
CurrentResultError / rejected
Database rows
Change inputs and step through the example. Code and output are illustrative; actual Spring logs and initialization order may differ. Use the worked examples in a real project.
What this animation explains
A runner can seed a database during startup. Repeated starts must not blindly create duplicates. A lookup plus a unique database constraint protects the logical key; concurrent initialization needs an atomic strategy or conflict handling.
Try and observe
Repeat the existing-row case. Observe no second INSERT.
API and configuration reference
Refer to these APIs and settings while building a real Spring project.
API / setting
Why and when to use it
CommandLineRunner.run(String... args)
Consume raw startup arguments
ApplicationRunner.run(ApplicationArguments args)
Inspect parsed options and non-option arguments
@Order(1)
Order runner execution relative to other ordered runners
Follow these procedures with the Java 21 / Spring Boot 3.4.0 teaching project. Unless complete files are provided, the code is a focused snippet requiring the indicated imports, companion classes and configuration.
1. Create a non-web runner
Procedure
Use a Boot Maven project with spring-boot-starter (web not required).
Place this class in demo and run it using Maven.
Pass --name=Anu and inspect the raw arguments.
Code / configuration
package demo;
import java.util.Arrays;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class ConsoleApp {
public static void main(String[] args) { SpringApplication.run(ConsoleApp.class,args); }
@Bean CommandLineRunner startup() { return a -> System.out.println(Arrays.toString(a)); }
}
Expected result: The argument array includes --name=Anu.
2. Read a named option
Procedure
In the ConsoleApp configuration register this bean (import ApplicationRunner and Bean).
Expected result: The named option prints Anu; absence prints Guest.
Predict the outcome before you run
Try answering these questions, then expand each answer and repeat the appropriate simulation.
1. Predict the outcome for Runner throws in Startup runner architecture. Which path is taken and why?
Boot reports startup failure and cleans up the context. Expected state: Context closes.
2. Predict the outcome for No arguments in Validate required startup input. Which path is taken and why?
The guard prints usage and skips the service. Expected state: No import.
3. Predict the outcome for Service missing in Dependency injection into a runner. Which path is taken and why?
The runner cannot be constructed. Expected state: Missing service.
Hands-on practice and assessment
Programming challenge
Implement a startup runner, pass arguments and call a service. Add a second runner with @Order and handle invalid input safely.
Edit this practice scratchpad and copy it into your real Java project. The browser does not compile arbitrary Java.
Quick assessment
Key points and real Spring notes
Runners are not scheduled tasks or HTTP endpoints. An uncaught runner exception causes startup failure; persistent initialization should be idempotent.