티스토리 뷰

Spring

Spring ApplicationEvent

SonSeungWoo 2019. 10. 10. 13:27

Spring에서 이벤트를 사용하는 방법에 대해 알아보자. 이벤트는 프레임 워크에서 간과 된 기능 중 하나이지만 더 유용한 기능 중 하나입니다. 그리고 Spring의 다른 많은 것들과 마찬가지로 이벤트 퍼블리싱은 ApplicationContext가 제공하는 기능 중 하나입니다. Spring ApplicationEvent는 기본적으로 동기입니다.

 

먼저 간단한 이벤트 메세지 클래스를 작성합니다.

public class CustomEvent extends ApplicationEvent {
    private String message;

    public CustomEvent(Object source, String message) {
        super(source);
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

 

해당 이벤트의 publisher를 만들어 보겠습니다. publisher는 이벤트 객체를 만들어 듣고있는 사람에게 게시합니다.

@Configuration
public class CustomEventPublisher {
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    public void doStuffAndPublishAnEvent(final String message) {
        System.out.println("Publishing custom event. ");
        CustomEvent customSpringEvent = new CustomEvent(this, message);
        applicationEventPublisher.publishEvent(customSpringEvent);
    }
}

 

ApplicationEventPublisherAware 인터페이스를 구현할 수 있습니다. 하지만 필자는 간단하게 ApplicationEventPublisher 를 @Autowire를 주입해서 하겠습니다. 이제 Listener를 구현하자. Spring 4.2부터는 이벤트 리스너가 ApplicationListener 인터페이스를 구현하는 Bean 일 필요는 없습니다. @EventListener 주석을 통해 관리 Bean의 공용 메소드에 등록 할 수 있습니다. @Async 어노테이션을 달면 비동기로 이벤트를 처리 할 수 있다.

@Configuration
public class CustomEventListener {
    @EventListener
    public void handleContextStart(CustomEvent customEvent) {
        log.info("Handling context started event. message : {}", customEvent.getMessage());
    }
}

 

이제 간단하게 테스트를 해보자. publisher에 이벤트를 발생시키고 Listener가 메세지를 잘 처리하는지 보자.

private final CustomEventPublisher customEventPublisher;

@GetMapping("/event")
public void event() {
	customEventPublisher.doStuffAndPublishAnEvent("event test");
}

localhost:8080/event를 실행하면 Handling context started event. message : event test 로그가 찍히는걸 확인 할 수 있다.

'Spring' 카테고리의 다른 글

Restful API 버전관리  (2) 2019.10.25
HandlerMethodArgumentResolver  (0) 2019.10.02
IoC란  (0) 2019.04.24
Spring Aop  (0) 2019.04.23
스프링에서 @Async로 비동기처리하기  (0) 2017.04.21
공지사항
최근에 올라온 글
최근에 달린 댓글
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함