springboot-What is the difference between CommandLineRunner and ApplicationRunner in Spring Boot.
1. The purpose of this post
I would demo the difference between CommandLineRunner and ApplicationRunner in Spring Boot.
2. Environments
springboot 1.x and 2.x
3. What is the difference between CommandLineRunner and ApplicationRunner in Spring Boot.
3.1 The question
Sometimes, we want to run some specific code when springboot app starts,there are two ways to do this job via CommandLineRunner and ApplicationRunner, you can follow this article to have a test. But what’s the difference between these two interface, and why do the fellows of Spring supply both of them instead of one of them?
3.2 Test the CommandLineRunner
We can test the below codes with these command in IntelliJ IDEA:
We set VM options and program parameters in IntelliJ IDEA’s run configurations like this:
Run the code ,The real java command is:
VM options are passed to java, and program parameters are passed to our main class.
After run we got this result:
You can see that only program arguments are parsed by CommandLineRunner, and the VM options are not parsed.
3.3 Test the ApplicationRunner
Use the above run configurations ,and we run the code below to test the ApplicationRunner:
You can see that ApplicationRunner can parse NonOptionArgs and OptionArgs, the difference is as follows:
When you pass –optionName=optionValue as program arguments, then the optionName is recognized as an option
If you pass program arguments whose format is not –key=value, then they are parsed as NonOptionArgs
The real java command is:
We run the above code and got this:
You can see that, k2 and k3 are parsed as NonOptionArgs ,and k4 is parsed as OptionArg, because we defined it as –k4=v4.
4. Conclusion
We can see that the CommandLineRunner is simpler ,but ApplicationRunner is more sophisticated in parsing the program arguments.