개요
실전 스프링 부트 책을 읽으며,
스프링에 이벤트와 이벤트 리스너가 존재한다는 사실을 알게 되었다.
리스너의 구현 방식과 등록 방법에 대해서 정리해보고자 이 포스트를 작성한다.
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
배운 점
이벤트 리스너를 구현하는 방법마다 등록 방법이 다른가 고민했었는데,
등록 방법은 동일하다는 점을 배울 수 있었다!
'Spring Framework > Spring Boot' 카테고리의 다른 글
| [Spring Boot] 커스텀 프로퍼티 완벽 가이드 (2) | 2025.08.28 |
|---|---|
| [Spring Boot] 환경별 설정 어떻게 해야할까? (2) | 2025.07.28 |
| [Spring Boot] SpringApplication.run() 메서드 인자에 관해서 (0) | 2025.07.17 |
| [Spring Boot] 리액티브 프로그래밍이란? (0) | 2025.07.17 |
| [Spring Boot] 스프링 부트 애플리케이션 종료 (1) | 2025.07.02 |