Spring Boot - ApplicationRunner and CommandLineRunner

ApplicationRunner and CommandLineRunner interfaces lets you to execute the code after the Spring Boot application is started.

ApplicationRunner

ApplicationRunner interface allows you to run some code after Sprint Boot starts.

MyApplicationRunner.java

1
2
3
4
5
6
7
8
9
@Component
public class MyApplicationRunner implements ApplicationRunner{
private static final Logger LOG = LoggerFactory.getLogger(MyApplicationRunner.class);

@Override
public void run(ApplicationArguments args) throws Exception {
args.getOptionNames().forEach(LOG::info);
}
}

CommandLineRunner

CommandLineRunner interface allows you to run some code after Sprint Boot starts. The difference between CommandLineRunner and ApplicationRunner is run() method’s parameter. With CommandLineRunner you get raw unprocessed arguments.

MyCommandListRunner.java

1
2
3
4
5
6
7
8
9
@Component
public class MyCommandListRunner implements CommandLineRunner {
private static final Logger LOG = LoggerFactory.getLogger(MyCommandListRunner.class);
@Override
public void run(String... args) throws Exception {
Stream.of(args).forEach(LOG::info);
}
}

sample output with application argument --foo=bar:

1
2
2019-05-02 22:59:35.261  INFO 15067 --- [  restartedMain] com.example.demo.MyApplicationRunner                  : foo
2019-05-02 22:59:35.261 INFO 15067 --- [ restartedMain] com.example.demo.MyCommandListRunner : --foo=bar

Reference