IT IT 인터넷 Spring Core ApplicationListener@EventListener@PostConstructApplicationRunnerCommandLineRunner

http://java21.net/blog/marco?post_id=2410

Spring Application 시작 시점및 초기화

Spring 6에서는 애플리케이션 시작 시점에 작업을 수행하려면 다양한 방법이 있습니다. 주로 ApplicationListener 인터페이스, @EventListener 애너테이션, 또는 **CommandLineRunner**와 ApplicationRunner 인터페이스를 사용하여 애플리케이션 초기화 작업을 처리할 수 있습니다.

여기서는 각 방법에 대해 설명하겠습니다.

1. ApplicationListener 인터페이스 사용

ApplicationListener 인터페이스를 사용하여 애플리케이션 이벤트가 발생할 때 작업을 수행할 수 있습니다. 예를 들어, ApplicationReadyEvent 이벤트는 Spring 애플리케이션이 시작된 후에 발생합니다.

import org.springframework.context.ApplicationListener;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.stereotype.Component;

@Component
public class StartupApplicationListener implements ApplicationListener<ApplicationReadyEvent> {

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        // 애플리케이션이 준비된 후 실행할 작업
        System.out.println("Application Started and Ready!");
    }
}

ApplicationReadyEvent는 애플리케이션이 시작되고 모든 Bean이 초기화된 후에 발생합니다. 따라서 애플리케이션이 완전히 시작된 후 작업을 처리할 때 유용합니다.

2. @EventListener 애너테이션 사용

Spring 6에서는 @EventListener 애너테이션을 통해 이벤트 리스너를 더 간결하게 정의할 수 있습니다.

import org.springframework.context.event.EventListener;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.stereotype.Component;

@Component
public class StartupEventListener {

    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationReady() {
        // 애플리케이션이 준비된 후 실행할 작업
        System.out.println("Application Started and Ready!");
    }
}

이 방법은 코드가 더 간단하고 직관적이며, ApplicationListener 인터페이스를 구현하는 방식보다 코드가 깔끔합니다.

3. CommandLineRunner 인터페이스 사용

CommandLineRunner는 애플리케이션이 시작될 때, Spring Boot 애플리케이션이 구동을 완료한 후 자동으로 실행되는 인터페이스입니다. run() 메서드 안에 애플리케이션 시작 후 실행할 작업을 넣을 수 있습니다.

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class StartupCommandLineRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        // 애플리케이션 시작 시 실행할 작업
        System.out.println("Application Started with CommandLineRunner!");
    }
}

CommandLineRunner는 애플리케이션이 준비된 후, ApplicationReadyEvent보다 먼저 실행됩니다. 다만, 이 메서드는 애플리케이션이 시작된 후, 애플리케이션 컨텍스트가 로드된 후 실행됩니다.

4. ApplicationRunner 인터페이스 사용

ApplicationRunnerCommandLineRunner와 비슷하지만, run() 메서드에서 ApplicationArguments 객체를 매개변수로 받습니다. 이 객체를 사용하면 애플리케이션 시작 시 커맨드라인 인수(arguments)를 처리할 수 있습니다.

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class StartupApplicationRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 애플리케이션 시작 시 실행할 작업
        System.out.println("Application Started with ApplicationRunner!");
        System.out.println("Arguments: " + args.getOptionNames());
    }
}

5. @PostConstruct 애너테이션 사용

애플리케이션 시작 시점에서 초기화 작업을 해야 할 경우, @PostConstruct 애너테이션을 사용할 수 있습니다. 이 애너테이션은 빈의 초기화 메서드에 붙여주며, 모든 빈이 생성된 후 초기화 작업을 수행합니다.

import javax.annotation.PostConstruct;
import org.springframework.stereotype.Component;

@Component
public class StartupBean {

    @PostConstruct
    public void init() {
        // 빈 초기화 후 실행할 작업
        System.out.println("PostConstruct: Bean Initialized!");
    }
}

어떤 방법을 선택할까요?

  • @EventListener 또는 ApplicationListener: 이벤트 기반 방식으로, 애플리케이션의 상태(예: 애플리케이션 준비 완료 등)에 따라 작업을 수행할 때 유용합니다.

  • CommandLineRunner / ApplicationRunner: 애플리케이션 실행 직후에 커맨드라인 인수도 포함하여 작업을 처리하려는 경우 유용합니다.

  • @PostConstruct: 빈이 초기화된 후 간단한 초기화 작업을 수행할 때 적합합니다.

각 방식은 상황에 맞게 선택하여 사용하면 됩니다.