Monday 23 July 2018

Spring boot: CommandLineRunner : Run the code only once

If you want to run some specific code only once, after the SpringApplication has started, you can implement the ApplicationRunner or CommandLineRunner interfaces.

Both ApplicationRunner or CommandLineRunner interfaces has run method, which is called just before SpringApplication.run(…) completes.

In this post, I am going to explain about the usage of CommandLineRunner interface.

CommandLineRunner interface
CommandLineRunner is a functional interface, that has run method.

@FunctionalInterface
public interface CommandLineRunner {

         void run(String... args) throws Exception;

}

As you see the definition of run method, it takes String array as an argument, it contains incoming main method arguments.

If you want to access ApplicationArguments instead of the raw String array consider using ApplicationRunner. I will explain about ApplicaitonRunner in my next post. Find the below working application.

MyBean.java
package com.sample.myApp.model;

import org.springframework.stereotype.Component;

@Component
public class MyBean {
 public MyBean() {
  System.out.println("************************");
  System.out.println("Initializing the bean");
  System.out.println("************************");
 }
}

SingleTimeExecutor.java
package com.sample.myApp.model;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;;

@Component
public class SingleTimeExecutor implements CommandLineRunner {

 @Override
 public void run(String... args) throws Exception {

  System.out.println("************************");
  System.out.println("Executing using command line runner");
  if (args != null) {
   for(String arg : args) {
    System.out.println(arg);
   }
  }
  System.out.println("************************");
 }

}

Application.java
package com.sample.myApp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import com.sample.myApp.model.MyBean;

@SpringBootApplication
public class Application {

 public static void main(String args[]) {
  ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args);

  System.out.println("Initializaing bean first time");
  applicationContext.getBean(MyBean.class);

  System.out.println("Initializaing bean second time");
  applicationContext.getBean(MyBean.class);
  applicationContext.close();
 }

}


Run Application.java by passing the command line arguments '--landscape=development --version=14.3 krishna'.

You can able to see below messages in the console.






Previous                                                 Next                                                 Home

No comments:

Post a Comment