CommandLineRunner에 대해서 알아보기

CJI0524·2025년 3월 21일

Spring Boot

목록 보기
19/21

1. CommandLineRunner란?

CommandLineRunner는 스프링 부트에서 애플리케이션이 완전히 구동된 후에 특정 코드를 실행할 수 있도록 해주는 함수형 인터페이스이다.

1.1. CommandLineRunner 인터페이스

✍️ CommandLineRunner 인터페이스

@FunctionalInterface
public interface CommandLineRunner {
    void run(String... args) throws Exception;
}

CommandLineRunner는 run(String... args) 메서드만 있는 단일 추상 메서드를 가진 인터페이스이다. 이 때문에 람다식으로 간편하게 구현할 수 있다.

1.2. CommandLineRunner의 실행 시점

스프링 부트 애플리케이션이 시작되고, 스프링 컨테이너가 모든 빈(bean)들을 초기화한 후에, CommandLineRunner 빈으로 등록된 모든 객체들의 run() 메서드가 실행된다. 이걸 활용해서, 애플리케이션 시작 직후에 초기 데이터 설정, 배치 작업, 혹은 테스트 코드를 실행할 수 있다.

주요 사용 예시는 다음과 같다.

  • 데이터 초기화 : DB에 초기 데이터를 넣거나 설정 작업을 하고 싶을 때 사용.
  • 테스트 및 검증 : 애플리케이션이 올바르게 구동되었는지 확인하는 간단한 로직을 넣을 수 있음.
  • 간단한 실행 작업: 부팅 후 바로 처리해야 하는 작업들을 넣어두면, 스프링 부트가 준비되자마자 실행되니까 유용.

1.3. 활용 예시

CommandLineRunner 활용 예시로는 2가지가 있다.

클래스가 CommandLineRunner를 구현하는 방법

✍️ 예시 코드 작성

@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!");
    }
}

빈(bean)으로 등록하여 람다식으로 구현

✍️ 예시 코드 작성

@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!");
        };
    }
}

2. 이 글을 작성하는데 참고한 글 목록

멋쟁이사자처럼 강의자료
[Spring Boot] ApplicationRunner, CommandLineRunner란?

profile
개발돌이

0개의 댓글