πββοΈ Runners in Spring Boot β What They Are and How to Use Them
Ever wondered how to run some code automatically when your Spring Boot application starts? Thatβs where runners come in!
Spring Boot gives you two simple ways to run logic right after the app starts:
CommandLineRunner
ApplicationRunner
Letβs break them down in a very easy way π
β What is a Runner?
A Runner is just a special class in Spring Boot that runs some code after the application starts, before the actual business logic begins.
Think of it as:
βDo this setup/check before the app starts fully!β
1οΈβ£ CommandLineRunner
β Simple and Easy
- You get the arguments passed to the app (
String... args
) - Best when you donβt need fancy argument handling
β¨ Example:
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class MyStartupRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("β
App has started! CommandLineRunner running...");
}
}
As soon as your app runs, it will print that message in the console.
2οΈβ£ ApplicationRunner
β Smarter with Arguments
- It gives you
ApplicationArguments
so you can easily check--options
passed - Great when you want to parse command-line inputs in a clean way
β¨ Example:
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class MyAppRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("β
ApplicationRunner running...");
System.out.println("π Option names: " + args.getOptionNames());
}
}
π― When to Use Runners?
Here are some real-world use cases:
Use Case | Example |
---|---|
Load data into DB | Seed test data in dev environment |
Startup checks | Validate file paths or connections |
Cache setup | Call external API and store config |
Log start info | Print custom banner or info |
π’ What if You Have Multiple Runners?
No problem! You can control the order they run using @Order
:
@Component
@Order(1)
public class FirstRunner implements CommandLineRunner {
public void run(String... args) {
System.out.println("π First runner executed");
}
}
π§ TL;DR (Quick Summary)
Feature | CommandLineRunner |
ApplicationRunner |
---|---|---|
Arguments Type | String[] |
ApplicationArguments |
Simple Usage | β | β |
Structured Arg Parsing | β | β |
Real Use Cases | Setup, logs, loading data | Same, with better arg handling |
β Final Thoughts
Runners are a neat way to run code at startup without touching controllers or services. They're simple, powerful, and often used in real-world Spring Boot apps.
Top comments (0)