SpringExamples

Spring boot CommandLineRunner example

By Admin | Filed Under: Spring Boot

In Spring boot projects, CommandLineRunner interface is used to run a code block only once in application’s lifetime – after application is initialized.

CommandLineRunner can be used in two ways:

  1. Using CommandLineRunner as @Component

    ApplicationStartupRunner class implements CommandLineRunner interface.

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.stereotype.Component;
    
    @Component
    public class ApplicationStartupRunner implements CommandLineRunner 
    {
        protected final Log logger = LogFactory.getLog(getClass());
     
        @Override
        public void run(String... args) throws Exception {
            logger.info("ApplicationStartupRunner run method Started !!");
        }
    }
    
  2. Implement CommandLineRunner in @SpringBootApplication

    CommandLineRunner interface is implemented on Application class, so override the run() here itself.

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class Application implements CommandLineRunner 
    {
    	protected final Log logger = LogFactory.getLog(getClass());
    	
        public static void main( String[] args )
        {
        	SpringApplication.run(Application.class, args);
        }
        
        @Override
        public void run(String... args) throws Exception {
        	logger.info("ApplicationStartupRunner run method Started !!");
        }
    }
Sourcecode Download

Ask Questions & Share Feedback Cancel reply

Your email address will not be published. Required fields are marked *

*Want to Post Code Snippets or XML content? Please use [java] ... [/java] tags otherwise code may not appear partially or even fully. e.g.
[java] 
public static void main (String[] args) {
...
}
[/java]

Development Environment

  • Spring Boot 2.0.1.RELEASE
  • Maven
  • JDK 8
  • Eclipse

Spring Boot Tutorial

  • Hello world example
  • Which main class
  • Print all beans
  • Embedded jetty server
  • CommandLineRunner
  • Custom banner
  • Change Root Path and Server Port

Spring Tutorial

  • IoC Container
  • Java Configuration

Spring WebMVC Tutorial

  • Minimum required config

Copyright © 2016 · springexamples.com · All Rights Reserved. | Sitemap