BE/Spring & Spring Boot

[Spring Boot] CommandLineRunner

baek-dev 2025. 5. 5. 16:06

CommandLineRunner 란 무엇인가?

CommandLineRunnerSpring Boot 애플리케이션이 시작된 후 실행할 로직을 정의할 수 있는 인터페이스임.
애플리케이션이 완전히 초기화되고, ApplicationContext까지 로딩된 후에 실행되기 때문에,
초기 데이터 세팅, 로그 출력, 외부 시스템 연결 확인 등 '앱 실행 직후에 한 번 실행해야 할 로직'을 처리할 때 유용함.


1. CommandLineRunner의 동작 시점

  • Spring Boot에서 main() 함수로 앱이 시작됨
  • 내부적으로 SpringApplication.run() 호출
  • ApplicationContext가 초기화된 이후
    CommandLineRunner의 run() 메서드가 자동으로 호출됨

2. 기본 사용 방법

예시 코드

@Component
public class AppStartupRunner implements CommandLineRunner {

    @Override
    public void run(String... args) {
        System.out.println("애플리케이션 시작 직후 실행됨");
    }
}
  • 클래스에 @Component 를 붙이면 자동으로 빈으로 등록되며,
    스프링 부트가 구동된 직후 run() 메서드를 실행해 줌
  • String... args 는 프로그램 실행 시 전달된 인자 배열임 (--spring.profiles.active=dev 등)

3. 다중 CommandLineRunner 처리

CommandLineRunner 구현체가 여러 개일 경우, @Order 또는 Ordered 인터페이스를 통해 실행 순서를 지정할 수 있음.

@Component
@Order(1)
public class InitDbRunner implements CommandLineRunner {
    public void run(String... args) {
        System.out.println("DB 초기화 실행");
    }
}

@Component
@Order(2)
public class InitCacheRunner implements CommandLineRunner {
    public void run(String... args) {
        System.out.println("캐시 로딩 실행");
    }
}

4. 실무에서 자주 쓰는 활용 예시

목적 설명
초기 데이터 삽입 테스트용 계정, 설정값, 상품 데이터 등을 자동 삽입함
서버 구동 확인 로그 특정 포트를 사용 중인지, 외부 API 연결 여부를 확인함
캐시, 큐 등 외부 자원 초기화 Redis, Kafka 등 외부 시스템을 연결하고 초기화함
프로파일별 조건 실행 @Profile("local") 같은 어노테이션과 함께 사용함

5. ApplicationRunner 와의 차이

CommandLineRunner와 유사한 기능을 하는 것으로 ApplicationRunner가 있음.

항목 CommandLineRunner ApplicationRunner
메서드 시그니처 run(String... args) run(ApplicationArguments args)
인자 처리 직접 문자열 배열 받음 이름 기반 인자 파싱 가능
장점 단순한 구조 더 유연한 파라미터 처리 가능함

예를 들어 --user=admin 처럼 실행 인자를 줄 경우,
ApplicationRunner는 args.getOptionNames() 를 통해 처리 가능함.


6. 테스트 시 주의점

  • Spring Context를 무조건 실행한 후 동작하므로 단위 테스트에서는 실행되지 않음
  • @SpringBootTest 환경에서는 함께 실행되므로, 테스트 중 DB 초기화나 로그가 출력되는지 주의해야 함
  • 필요에 따라 @ConditionalOnProperty 또는 @Profile 로 분기하여 조건부 실행을 권장함

정리

CommandLineRunner는 Spring Boot 애플리케이션이 시작된 후 자동으로 실행되는 커스텀 로직을 정의할 수 있는 인터페이스임.
초기 설정, 테스트 데이터 삽입, 연결 테스트, 캐시 로딩 등 다양한 용도로 활용할 수 있으며,
간단하게 @Component 로 등록하고 run() 메서드를 구현하면 자동 실행됨.

애플리케이션 라이프사이클 중 실행 위치가 명확하기 때문에 초기화용 로직 처리에 매우 적합한 구조임.

 

 

 

 

출처 : ChatGPT

'BE > Spring & Spring Boot' 카테고리의 다른 글

[Spring Boot] 웹소켓 하트비트  (0) 2025.05.07
[Spring Boot] PRG 패턴  (1) 2025.05.06
[Spring Boot] 퍼사드 패턴  (0) 2025.05.02
[Spring Boot] E2E 테스트  (0) 2025.04.29
[Spring Boot] Redis pub/sub  (0) 2025.04.27