Spring Boot Application Runner and Command Line Runner

Spring Boot Application Runner and Command Line Runner to run code on application start

Application Runner and Command Line Runner are an interfaces that used to execute and run code just before the application startup completes. These interfaces are used to run code that should be executed as soon as the app started like Seeders.

1 Application Runner

package com.yamicode.snippet.runners;

import com.yamicode.snippet.service.YamiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class YamiApplicationRunner implements ApplicationRunner {

    @Autowired
    private YamiService yamiService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        yamiService.printTheMessage("called from yami application runner");
    }
}

package com.yamicode.snippet.service;

import org.springframework.stereotype.Service;

@Service
public class YamiService {

    public void printTheMessage(String message){
        System.out.println(message);
    }

}

2 Command Line Runner

package com.yamicode.snippet.runners;

import com.yamicode.snippet.service.YamiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class YamiCommandLineRunner implements CommandLineRunner {

    @Autowired
    private YamiService yamiService;

    @Override
    public void run(String... args) throws Exception {
        yamiService.printTheMessage("called from yami command line runner");
    }
}


package com.yamicode.snippet.service;

import org.springframework.stereotype.Service;

@Service
public class YamiService {

    public void printTheMessage(String message){
        System.out.println(message);
    }

}

2 Result

Spring Boot Application Runner and Command Line Runner