BE/Spring & Spring Boot

[Spring Boot] ApplicationRunner

baek-dev 2024. 12. 14. 15:00

ApplicationRunner

Spring Boot 애플리케이션 에서 애플리케이션 이 시작된 후 실행할 코드를 정의하기 위해 사용되는 인터페이스다.

주로 초기화 작업이나 애플리케이션 시작 시 필요한 논리를 실행할 때 활용된다

 

특징

  • 애플리케이션 초기화 작업 수행 : 데이터베이스 초기화, 캐시 로드, 외부 API 호출 등
  • Spring Boot 컨텍스트가 완전히 초기화된 후 실행 : 모든 Bean이 로드되고 애플리케이션 컨텍스트가 준비된 상태에서 실행된다
  • CommandLineRunner와 유사 : 차이점은 `ApplicationRunner`는 `ApplicationArguments`를 사용하여 더 구조화된 방식으로 인수를 처리할 수 있다

 

ApplicationRunner 사용 방법

1. ApplicationRunner 구현

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

@Component
public class MyApplicationRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("Application started with option names: " + args.getOptionNames());
    }
}
public class BaseInitData {

	@Bean
	public ApplicationRunner baseInitDataApplicationRunner() {
        return args -> {

        };
    }
}

 

2. `@Component` 또는 `@Bean`으로 등록

  • `@Component`를 사용하면 자동으로 스프링 컨텍스트에 Bean으로 등록된다
  • 직접 `@Bean`으로 등록할 수 도 있다
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Bean
    public ApplicationRunner myRunner() {
        return args -> System.out.println("Custom ApplicationRunner logic executed.");
    }
}

ApplicationArguments 객체

`ApplicationRunner`의 `run()` 메서드는 `ApplicationArguments` 객체를 통해 프로그램 인수를 구조화된 방식으로 제공한다

 

주요 메서드

1. `getOptionNames()` : 옵션 이름 리스트 반환

2. `getOptionValues(String name)` : 특정 옵션의 값 리스트 반환

3. `containsOption(String name)` : 특정 옵션이 포함되어 있는지 확인

4. `getNonOptionArgs()` : 옵션이 아닌 인수 리스트 반환

@Override
public void run(ApplicationArguments args) throws Exception {
    if (args.containsOption("debug")) {
        System.out.println("Debug mode enabled!");
    }
    System.out.println("Non-option arguments: " + args.getNonOptionArgs());
}

CommandLineRunner와의 차이점

특징 ApplicationRunner CommandLineRunner
인수 처리 방식 `ApplicationArguments` 객체 사용 단순 `String[] args` 사용
구조화된 접근 옵션과 비옵션을 구분 가능 모든 인수를 단순 문자열 배열로 처리
추천 상황 더 복잡하거나 구조화된 초기화 작업이 필요한 경우 간단한 초기화 작업

사용 예시 : 파일 로딩

Spring Boot 애플리케이션 시작 시 특정 파일을 읽어와 초기화하는 작업을 수행할 수 있다

@Component
public class FileLoaderRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (args.containsOption("filePath")) {
            String filePath = args.getOptionValues("filePath").get(0);
            System.out.println("Loading file from path: " + filePath);
            // 파일 로드 로직
        } else {
            System.out.println("No filePath option provided.");
        }
    }
}

 

실행 시 옵션 제공

java -jar myapp.jar --filePath=/path/to/file.txt

활용 예제

1. 데이터베이스 초기화

  • 앱 시작 시 초기 데이터를 삽입하거나 테이블 생성

2. 캐싱

  • 외부 데이터 소스에서 데이터를 미리 가져와 캐싱

3. 외부 API 호출

  • 앱 시작시 외부 서비스와의 연결 테스트

`ApplicationRunner`는 Spring Boot 애플리케이션의 시작 로직을 관리하는데 매우 유용한 도구이다. 초기화 작업을 간결하고 효과적으로 구현할 수 있다.

 

 

 

 

 

 

출처 : ChatGPT

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

[Spring Boot] IoC 컨테이너  (2) 2024.12.21
[Spring Boot] 빈이란  (1) 2024.12.15
[Spring Boot] ORM, @Query  (1) 2024.12.14
[Spring] Spring 과 Spring Boot  (0) 2024.12.13
[Spring Boot] 어노테이션  (0) 2024.12.11