Annoation that marks a method as a listener for application events.
-Stephane Nicoll, Sam Brannen-
타겟은 메서드, 유지 범위는 런타임이다.
주로 단일 이벤트 핸들링을 하겠지만, 여러 이벤트 핸들링을 해야한다면, classes 조건을사용할 것 같습니다.
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface EventListener {
@AliasFor("classes")
Class<?>[] value() default {};
@AliasFor("value")
Class<?>[] classes() default {};
String condition() default "";
String id() default "";
}
@Component
public class AppEventListener {
@EventListener(classes = {PlayEvent.class, WorkEvent.class})
public void handleEvent() {
System.out.println("if play or work event on I'm going to work out!");
}
}
@Slf4j
@RequiredArgsConstructor
@RestController
public class TestController {
private final ApplicationEventPublisher applicationEventPublisher;
@GetMapping("/event")
public void onEvent() {
log.info("event on!!!!");
applicationEventPublisher.publishEvent(new PlayEvent());
log.info("another event on!!!");
applicationEventPublisher.publishEvent(new WorkEvent());
}
}
2023-08-04 20:17:59.353 INFO 2350 --- [nio-8080-exec-3] e.f.f.event.TestController : event on!!!!
if play or work event on I'm going to work out!
2023-08-04 20:17:59.353 INFO 2350 --- [nio-8080-exec-3] e.f.f.event.TestController : another event on!!!
if play or work event on I'm going to work out!
디테일한 사항에 대한 레퍼런스입니다.
An EventListener that is invoked according to a TransactionPhase.
- Stephane Nicoll, Sam Brannen, Oliver Drotbohm
정보에 감사드립니다.