본문 바로가기

Spring Framework/Spring Boot

[Spring Boot] 스프링 부트 이벤트 리스너 구현과 등록

개요 

실전 스프링 부트 책을 읽으며,

스프링에 이벤트와 이벤트 리스너가 존재한다는 사실을 알게 되었다.

 

리스너의 구현 방식과 등록 방법에 대해서 정리해보고자 이 포스트를 작성한다.

 

 

1. 이벤트 리스너 구현 방법

1. @EventListener 어노테이션 방식 (Spring 4.2+)

@Component
public class MyEventListener {
    
    @EventListener
    public void handleApplicationReady(ApplicationReadyEvent event) {
        // 처리 로직
    }
    
    @EventListener
    public void handleContextRefresh(ContextRefreshedEvent event) {
        // 처리 로직
    }
}
 

장점:

  • 간단하고 직관적
  • 하나의 클래스에 여러 이벤트 처리 가능
  • 조건부 처리 가능 (condition 속성)

 

2. ApplicationListener 인터페이스 구현 방식 (전통적)

@Component
public class MyEventListener implements ApplicationListener<ApplicationReadyEvent> {
    
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        // 처리 로직
    }
}

 

특징:

  • 타입 안전성 보장
  • 하나의 클래스당 하나의 이벤트 타입만 처리
  • Spring 초기 버전부터 지원

 

 

2. 이벤트 리스너 등록 방법

1. @Component 방식 (가장 일반적)

// @EventListener 방식
@Component
public class EventListenerA {
    @EventListener
    public void handleEvent(ApplicationReadyEvent event) { }
}

// ApplicationListener 구현 방식
@Component  
public class EventListenerB implements ApplicationListener<ApplicationReadyEvent> {
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) { }
}

 

2. @Bean 등록 방식

@Configuration
public class EventConfig {
    
    @Bean
    public EventListenerA eventListenerA() {
        return new EventListenerA();
    }
    
    @Bean
    public EventListenerB eventListenerB() {
        return new EventListenerB();
    }
}

 

3. 직접 등록 방식

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(DemoApplication.class);
        
        // 두 방식 모두 동일하게 등록
        app.addListeners(new EventListenerA());
        app.addListeners(new EventListenerB());
        
        app.run(args);
    }
}

 

4. spring.factories 방식

# src/main/resources/META-INF/spring.factories
org.springframework.context.ApplicationListener=\
com.example.demo.EventListenerA,\
com.example.demo.EventListenerB

 

 

배운 점

이벤트 리스너를 구현하는 방법마다 등록 방법이 다른가 고민했었는데,

등록 방법은 동일하다는 점을 배울 수 있었다!