Home > database >  What is the exact purpose of the CommandLineRunner in Spring Boot
What is the exact purpose of the CommandLineRunner in Spring Boot

Time:10-26

I would appreciate a lot if someone could explain why a class annotated with @SpringBootApplication implements CommandLineRunner as well quite often. From what I have read Spring Boot will automatically call the run method of all beans implementing this interface after the application context has been loaded. So run() method is run between the first and the last instructions present in the main() method after beans have been registered. Then what is the specific need to implement CommandLineRunner, I mean why not just to add code from the run() to the main()

CodePudding user response:

CommandLineRunner is an interface that has run() method. Which is used to execute some code just after the spring boot application has started. The main application should implement this interface and override its run method. In this run method, we write code like initializing our database with some value or any other logic which should be executed just after the app starts.

CodePudding user response:

Say you have to create an admin user for your application. And only an admin can create a user. In that case, an admin user needs to be created in boot time. CommandLineRunner can do that work for you. You can add a method for creating users inside CommandLineRunner annotated class. It will be an example for reference.

  • Related