Spring Boot Command Line Runner Example.

Spring Boot Command Line Runner Example.

Do want to look cool, and pretend to be some hacker just on terminal  printing some random this,Then you can use this command line runner :-P, jokes apart, Usually when we need to work on some Shell Script which is very complicated or you perform certain repeated task clearing redis cache, or  adding required value to Database this Spring Boot Command line runner comes in handy.

Spring boot command line runner provides and interface to run the piece of program which you need to execute as soon the spring boot context is started, so command line runner does not require any additional dependency. just Spring Boot parent and Starter package.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>

So we shall write the command line runner as component

@Component
public class commandRunners implements CommandLineRunner {
    
   @Override
    public void run(String... args) throws Exception {
        logger.info("Application has started");
    }
}

Another method implementing command line runner is at main spring boot application.

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