1. Command-Line Arguments
- To take argument from command line or passing values to main method and access them using
CommandLineRunnerApplicationRunnerSpringApplication.getRunArguments()- or even with
@Valueinjection
- Example
main(String[]args): passing values to main method via command line arguments.
2. CommandLineRunner and ApplicationRunner
- executed immediately after SpringApplication.run() completes.
- Having abstract method.
Example:
@SpringBootApplication
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
// Runners execute AFTER this
}
3. Runner class
A component class that implements CommandLineRunner or ApplicationRunner and is registered as a Spring bean is called a Spring Boot runner class.
Why is it called a Spring Boot runner class?
beacuse such a class :
- Runs automatically at startup.
- Is a Spring-managed bean.
- Implements
CommandLineRunnerorApplicationRunnerto define startup logic
Key Points
- impementing abstract method .
- Executed only once and run automatically.
- Executed logic which write inside implemented of Runner interface .
- used to define logic for loading configuration values, properties.
Spring Boot application startup lifecycle
- Spring Boot App
- Start
- Run method
- IoC Container
- Bean Object created
- Runners
- Started (Application is ready to use. perform operation)
How many Runners can we add in Spring Boot Application?
Answer: Can add unlimited runner classes.
Multiple Runner class Execution Order
- Execute randomly.
- Control execution order :using
@Orderleast number : higher priority
Example Code
@Order(1) //executed second
@Component
public class FirstRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("FirstRunner ");
}
}
@Order(-5) //executed first
@Component
public class SecondRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("SecondRunner");
}
}
@Order(2) //executed third
@Component
public class ThirdRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("ThirdRunner ");
}
}
4. Difference between CommandLineRunner and ApplicationRunner?
-
CommandLineRunner
- Method : run(String... args)
- Argument Type : String of Array
- alamgirPassasArguemts -> main(String[] args)-> SpringApplication.run(MyApplication.class, args)->run(String... args)
- passing arguemt share the all Runners.
-
ApplicationRunner
- Method : run(ApplicationArguments args)
- Argument Type : Object (ApplicationArguments)
- alamgirPassasArguemts -> main(String[] args)-> SpringApplication.run(MyApplication.class, args)-> run(ApplicationArguments args)
Github Code : Spring Runner : Spring Boot