Web/환경설정 관련

스프링 부트 애플리케이션 시작 시 코드 실행 (CommandLineRunner)

now0204 2024. 5. 10. 19:39
  • 스프링 부트 애플리케이션을 시작할 때 특정 코드를 실행해야 할 때가 있다. 
  • ex) 애플리케이션 초기화 이전에 데이터 베이스 초기화 스크립트를 실행, 혹은 외부 REST 서비스를 호출해서 데이터를 가져오는 등
  • 이를 위해 CommandLineRunner와 ApplicationRunner가 있다. 둘 다 run() 메서드만 있음으로, 적절히 구현 후 빈으로 등록해서 사용하자 (ApplicationRunner와 매우 유사하므로, CommandLineRunner만 다룸)
  • CommandLineRunner는 args파라미터에 접근할 수 있기 때문에, 초기화 작업을 편리하게 할 수 있는 장점이 있다. 
  • 스프링 부트 애플리케이션 초기화 직전에 run(String... args)이 호출 된다.

 

-  CommandLineRunner는 다양한 방법으로 만들 수 있다.

1. 스프링 부트 메인 클래스에 해당 인터페이스를 구현하게 만든다

2. CommandLineRunner 구현체를 @Bean으로 등록한다. 

3. CommandLineRUnner 구현체에 @Component를 붙여서 빈으로 등록한다.

 

 

 

1. 메인 클래스에 인터페이스 구현 

package com.manning.sbip.ch02;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class CourseTrackerApplication implements CommandLineRunner {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    public static void main(String[] args) {
        SpringApplication.run(CourseTrackerApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        logger.info("CourseTrackerApplication CommandLineRunner has executed");
    }

    @Bean
    public CommandLineRunner commandLineRunner() {
        return args -> {
            logger.info("CommandLineRunner executed as a bean definition with "+args.length +" arguments");
            for(int i=0; i<args.length;i++){
                logger.info("Argument: "+args[i]);
            }
        };

    }
}

 

2. @Component로 구현 

package com.manning.sbip.ch02.commandline;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Order(1)
@Component
public class MyCommandLineRunner implements CommandLineRunner {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void run(String... args) throws Exception {
        logger.info("MyCommandLineRunner executed as a Spring Component");
    }

}

 

  • 다른 Bean들과 마찬가지로 CommandLineRunner는 여러개 등록 해서 사용할 수 있다.
  • @Order로 우선 순위만 잘 조정해 주자
package com.manning.sbip.ch02.commandline;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Order(2)
@Component
public class AnotherCommandLineRunner implements CommandLineRunner {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void run(String... args) throws Exception {
        logger.info("AnotherCommandLineRunner executed as a Spring Component");
    }
}

 

 

참고자료 

https://www.yes24.com/Product/Goods/122002340

 

실전 스프링 부트 - 예스24

인류에겐 이런 스프링 부트 가이드북이 필요했다방대한 스프링 부트 공식 문서 중 실무에서 잘 쓰이는 팁을 찾기란 어렵다. 이 책은 초급에서 중급 수준의 독자를 대상으로 스프링 부트의 기본

www.yes24.com