CommandLineRunner in Spring Boot

Kritika gupta
3 min readMay 26, 2021

--

Spring boot provides one interface — CommandLineRunner.
Command line runner is used to run something when application is fully started.
It provides access to application arguments as String array.

As per definition — “CommandLineRunner is an interface used to indicate that a bean should run when it is contained within a SpringApplication”.

Example-

Suppose there is an interface having method getMessage() and message is in application.properties file -

AppMessage.java
application.properties

Now, to access this message as value, use @Value annotation and register this AppMessage interface as bean so that it can be used as dependency injection.

inside main class

Using CommandLineRunner, we can access this bean just after application started.

CommandLineRunner implementation

CommandLineRunner provides run() method which is called after application context is loaded but before the execution of the main method is complete

Application can have multiple classes that implement CommandLineRunner, the order of execution can be specified using @Order Annotation.

Note — Don’t forget to annotate the class with @Component. this class must be registered in Spring context so that Spring can find this class and execute overridden run()

output

Use-Cases

Command Line Runner are very popular for console based applications but sometimes we can use it in web application too in the scenarios like -

  • Insert some specific data into db which must be available when application is ready (just for testing purpose).
  • Print configuration logs to provide info about all the configurations i.e. there must be several AWS SQS queue, S3 buckets used in the project. print all the configured queue names or bucket name for reference when application starts.

--

--

Kritika gupta
Kritika gupta

Written by Kritika gupta

Fertile minded Web Application Developer . Love to explore JavaScript,Angular,Java and looking to increase work productivity. Developer @ Xoriant Solutions

No responses yet