🪛 한계점
스프링 부트 어플리케이션을 시작하기 전에 특정 코드를 실행시켜야 함.
- 데이터베이스 초기화
- 무거운 클래스 사전 로딩
- 외부 REST API 연결 테스트
- 외부 API 데이터 사전 로드
위를 해결하기 위해 스프링 부트에서는 CommandLineRunner
인터페이스를 제공한다.
📂 목차
📚 본문
@CommandLineRunner 로 스프링 부트 어플리케이션 시작 시 특정 코드 실행
클래스가 CommandLineRunner
인터페이스를 구현하기만 한다면 클래스를 따로 둬서 사용할 수 있다.
import org.springframework.boot.*;
import org.springframework.core.annotation.*;
import org.springframework.stereotype.*;
@Component
@Order(1)
public class CustomCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("\n\n\n\n\n This is Executed ! \n\n\n\n");
}
}
여기서 @Order
는 서로 같이 실행될때 누가 먼저 실행될지 우선순위를 부여하는 애너테이션이다.
CommandLineRunner 구현체가 언제 실행되는지 궁금할 수 있는데, SpringApplication 이 빈 등록, 초기화 과정 등을 전부 끝마친 뒤에 수행하도록 되어 있기에 어떤 Bean 이든 주입 받아서 CommandLineRunner 컨텍스트에서 사용할 수 있다.