본문 바로가기

Java/Spring Boot

[Spring Boot] Application Events and Listener

1. Application Context가 만들어지기 이전에 발생되는 이벤트

  • ex) ApplicatonStartingEvent : 애플리케이션 맨 처음에 발생하는 이벤트
  • Bean으로 등록하더라도 Listener가 동작하지 않음 (즉, @Component 어노테이션 불필요)
  • addListeners()를 사용해서 직접 등록해줘야 함

 

① EventListener 생성

import org.springframework.boot.context.event.ApplicationStartingEvent;
import org.springframework.context.ApplicationListener;
//import org.springframework.stereotype.Component;

//@Component
public class SampleListener implements ApplicationListener<ApplicationStartingEvent> {

   @Override
   public void onApplicationEvent(ApplicationStartingEvent event) {
      System.out.println("=======================");
      System.out.println("Application is starting");
      System.out.println("=======================");
   }
}

 

-> 이 상태로 실행하면 아무것도 찍히지 않음

 

 

 

② addListeners()로 Listener 등록하기

SpringApplication app = new SpringApplication(Application.class);
app.addListeners(new SampleListener());
app.run(args);

 

 

 

③ 실행

 

-> Banner 출력 전에 "Application is starting" 확인 가능

 

 

 

 

 

 

 

 

 

 

 

 

2. Application Context가 만들어진 이후에 발생되는 이벤트

  • ex) ApplicationStartedEvent
  • Applicaton Context가 만들어진 이후에 발생된 이벤트들은 Bean을 실행할 수 있음
  • 이벤트들의 리스너가 Bean이면 알아서 호출 (즉, @Component 어노테이션 필요)
  • addListeners() 불필요

 

① EventListener 생성

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

@Component
public class SampleListener implements ApplicationListener<ApplicationStartedEvent> {

   @Override
   public void onApplicationEvent(ApplicationStartedEvent event) {
      System.out.println("=======================");
      System.out.println("Application is started");
      System.out.println("=======================");
   }
}

 

 

 

② 실행

-> 애플리케이션 마지막에 "Application is started"가 출력되는 것 확인 가능

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8/dashboard

 

스프링 부트 개념과 활용 - 인프런 | 강의

스프링 부트의 원리 및 여러 기능을 코딩을 통해 쉽게 이해하고 보다 적극적으로 사용할 수 있는 방법을 학습합니다., - 강의 소개 | 인프런...

www.inflearn.com

https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.spring-application.application-events-and-listeners

 

Core Features

Spring Boot lets you externalize your configuration so that you can work with the same application code in different environments. You can use a variety of external configuration sources, include Java properties files, YAML files, environment variables, an

docs.spring.io