CommandLineRunner
CommandLineRunner는 구동 시점에 실행할 코드가 있을 때 사용합니다. @Component가 붙은 클래스에 인터페이스를 생성하거나 @SpringBootApplication이 붙은 클래스에 사용해도 됩니다.
@SpringBootApplication
public class PianoScoreApplication implements CommandLineRunner {
public static void main(String[] args) throws Exception {
SpringApplication.run(PianoScoreApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
System.out.println("CommandLineRunner-Test");
}
}
@Component
public class Initializationdb implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
System.out.println("Initialization");
}
}
ApplicationRunner
ApplicationRunner 인터페이스도 CommandLineRunner와 마찬가지로 구동 시점에 run()을 호출해 준다.
해당 클래스에 @Componet를 붙여줘야 합니다.
@Override
public void run(ApplicationArguments args) throws Exception {
// TODO Auto-generated method stub
System.out.println("Initialization");
}
ApplicationReadyEvent
@EventLister를 사용하여 스프링 프레임워크가 구동되어 서비스 요청을 받을 준비가 되었을 때 ApplicationReadEvent 발생시켜 초기화를 해줍니다.
@EventListener(ApplicationReadyEvent.class)
public void init() {
System.out.println("============ApplicationReadyEvent============");
}
CommandLineRunner와 ApplicationRunner
만일 순서를 지정하지 않을 경우 ApplicationRunner가 CommandLineRunner 보다 먼저 실행됩니다.
@Order 어노테이션을 사용하여 순서를 정해준다면 정해진 순서대로 실행됩니다.
// SpringApplication 클래스에 있는 함수입니다. 직접만든거 아님...
public class SpringApplication{
private void callRunners(ApplicationContext context, ApplicationArguments args) {
List<Object> runners = new ArrayList<>();
// ApplicationRunner
runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
//CommandLineRunner
runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
// order 어노테이션이 있는 경우.
AnnotationAwareOrderComparator.sort(runners);
for (Object runner : new LinkedHashSet<>(runners)) {
if (runner instanceof ApplicationRunner) {
callRunner((ApplicationRunner) runner, args);
}
if (runner instanceof CommandLineRunner) {
callRunner((CommandLineRunner) runner, args);
}
}
}
}
전체적인 실행 순서

참고
https://madplay.github.io/post/run-code-on-application-startup-in-springboot
'Spring > 스프링 부트' 카테고리의 다른 글
| 2021-12-21 (스프링) 데이터 바인딩 (0) | 2021.12.21 |
|---|---|
| 2021-12-20(알고리즘 풀이) 백준 2231번 - 분해합 (0) | 2021.12.20 |
| 2021-12-18 (스프링) @PathVariable 어노테이션 (0) | 2021.12.18 |
| 2021-12-17(JPA) @MappedSuperClass 공부 내용 정리 (0) | 2021.12.17 |
| 2021-12-13(스프링) HandlerInterceptor는 무엇일까 (0) | 2021.12.13 |