
CommandLineRunner는 스프링 부트에서 애플리케이션이 완전히 구동된 후에 특정 코드를 실행할 수 있도록 해주는 함수형 인터페이스이다.
✍️ CommandLineRunner 인터페이스
@FunctionalInterface
public interface CommandLineRunner {
void run(String... args) throws Exception;
}
CommandLineRunner는 run(String... args) 메서드만 있는 단일 추상 메서드를 가진 인터페이스이다. 이 때문에 람다식으로 간편하게 구현할 수 있다.
스프링 부트 애플리케이션이 시작되고, 스프링 컨테이너가 모든 빈(bean)들을 초기화한 후에, CommandLineRunner 빈으로 등록된 모든 객체들의 run() 메서드가 실행된다. 이걸 활용해서, 애플리케이션 시작 직후에 초기 데이터 설정, 배치 작업, 혹은 테스트 코드를 실행할 수 있다.
주요 사용 예시는 다음과 같다.
CommandLineRunner 활용 예시로는 2가지가 있다.
✍️ 예시 코드 작성
@SpringBootApplication
public class MyApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
// 애플리케이션 구동 후 실행될 코드
System.out.println("Application started using CommandLineRunner implementation!");
}
}
✍️ 예시 코드 작성
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@Bean
public CommandLineRunner demo() {
return args -> {
// 애플리케이션 구동 후 실행될 코드
System.out.println("Application started using CommandLineRunner bean!");
};
}
}
멋쟁이사자처럼 강의자료
[Spring Boot] ApplicationRunner, CommandLineRunner란?