What is CommandLineRunner in Spring Boot ?

Interface used to indicate that a bean should run when it is contained within a SpringApplication.

Multiple CommandLineRunner beans can be defined within the same application context and can be ordered using the Ordered interface or @Order annotation.

If you need access to ApplicationArguments instead of the raw String array consider using ApplicationRunner.

Table of Content :

Advantages of Spring boot Command Line Runner

1). It adds a lot of flexibility to your "bootstrapping code".
2). It can be implemented multiple times.
3). The capability to start any scheduler or log any message before application starts to run.
4). The command line runners are spring @Beans, so you can activate/deactivate them at run-time.
5). We can use them in an ordered fashion by appending the @Order annotation.
6). We can unit test them just like regular classes.
7). We can inject dependencies into them. Each runner can then have its own dependencies.

There are Different ways in which we can use the Command line Runner for Spring boot Application

1). CommandLineRunner as @Component

@Component public class MySpringBootApp implements CommandLineRunner { protected final Log logger = LogFactory.getLog(getClass()); @Override public void run(String... args) throws Exception { logger.info("MySpringBootApp Started ..."); } }

2). CommandLineRunner in @SpringBootApplication

@SpringBootApplication public class MySpringBootApp extends SpringBootServletInitializer implements CommandLineRunner { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(MySpringBootApp.class); } public static void main(String[] args) throws Exception { SpringApplication.run(MySpringBootApp.class, args); } @Override public void run(String... args) throws Exception { logger.info("MySpringBootApp Started ..."); } }


3). Using CommandLineRunner as Bean

public class MySpringBootApp implements CommandLineRunner { protected final Log logger = LogFactory.getLog(getClass()); @Override public void run(String... args) throws Exception { logger.info("MySpringBootApp Started ..."); } }




In this article, we have seen Spring Boot command line runner with Examples.

Previous Post Next Post