DEV/Spring

[Spring] Data Rest Event 사용하기

l-eazzy 2023. 8. 22. 00:49

0. 저번 Data Rest 포스팅

* [Spring] Spring Data Rest 란?

 

 

1. Data Rest Event Handler 종류

Spring Data Rest 에서,

사용 가능한 이벤트의 종류는 8가지가 있다.

  • BeforeCreateEvent
  • AfterCreateEvent
  • BeforeSaveEvent
  • AfterSaveEvent
  • BeforeLinkSaveEvent
  • AfterLinkSaveEvent
  • BeforeDeleteEvent
  • AfterDeleteEvent

각 이벤트가 발생하는 트리거는

Create 생성, Save 수정, Link Save 연관관계 저장, Delete 삭제 시에 발생하게 된다.

Http Method 관점에서 보면 POST, PUT, PATCH, DELETE 로 보면 된다.

 

 

2. 사용 방법

공식 홈페이지 에서는 ApplicationListenerAnnotated Handler 이 두가지의 작성방법을 알려주고 있다.

 

a. Writing an ApplicationListener

ApplicationListener 사용에 있어서는 추상클래스인 AbstractRepositoryEventListener를 상속받아,

미리 정의된 메소드를 Override 하여 사용하는 방식이다.

 

public class BeforeSaveEventListener extends AbstractRepositoryEventListener {

  @Override
  public void onBeforeSave(Object entity) {
    ... logic to handle inspecting the entity before the Repository saves it
  }

  @Override
  public void onAfterDelete(Object entity) {
    ... send a message that this entity has been deleted
  }
}

 

이 방법을 사용할때는 모든 Entity의 이벤트가 일괄적으로 적용 되지만,

Entity가 Object 타입으로 정의되어있어 Entity 유형별 구분과는 맞지 않는다.

 

전체적인 로깅 기능에 대한 이벤트를 달아두는 등의 공용 기능 EventListener에 적합해보인다.

 

 

b. Writing an Annotated Handler

다음 방법은 @RepositoryEnventHandler 를 이용한 방법인데,

BeanPostProcessor 해당 주석이 작성된 Bean을 찾으면 노출된 메서드를 반복하여 이벤트에 해당하는 주석을 찾는 방식이다.

@RepositoryEventHandler
public class PersonEventHandler {

  @HandleBeforeSave
  public void handlePersonSave(Person p) {
    // … you can now deal with Person in a type-safe way
  }

  @HandleBeforeSave
  public void handleProfileSave(Profile p) {
    // … you can now deal with Profile in a type-safe way
  }
}

 

해당 핸들러 클래스가 어떤 Entity의 이벤트를 핸들링 할것인지 어노테이션에 정의해서 사용이 가능하다.

@RepositoryEventHandler(Person.class)

 

등록할 Handler를 아래와 같이 Bean 등록을 하면,

애플리케이션이 실행될 때, 해당 Handler 클래스를 인식하여 ApplicationEvent에 등록이 되게 된다.

@Configuration
public class RepositoryConfiguration {

  @Bean
  PersonEventHandler personEventHandler() {
    return new PersonEventHandler();
  }
}

 

 

조금 더 자세한 이해를 돕기 위해서 아래 인터페이스와 클래스를 보면 되는데,

@RepositoryEventHandler 어노테이션으로 등록하고자 하는 Handler 클래스를 가리키고

 

 

 

AnnotatedEventHandlerInvoker 클래스에 재정의 된,

postProcessAfterInitialization() 메소드에서 RepositoryEventHandler 어노테이션을 감지,

=> 각 이벤트로 정의된 method 들을 등록하게 된다.

 

 

 

아래 이미지는 AnnotatedEventHandlerInvoker 클래스와 연결된 인터페이스와 클래스에 대한 다이어그램이다.

(이 부분에 대해서 조금 더 알아보고 싶다면 Spring Event에 대해 알아보면 이해하기 한결 수월할 것 같다.)

 

 

 

공식 문서에 보면 Spring Data Rest Events 들은 기본적으로 동기방식으로 등록되기 때문에,

비동기 방식으로 만드려면 추가적인 공수가 들어가게 된다. 이 부분은 참고하도록 하자! 

 

 

3. 마무리

이벤트 등록이 Runtime 시에 진행이 되기 때문에,

처음 등록이 되는 부분에 디버그 모드로 걸어두면 작성해둔 이벤트 타입이 등록이 되는걸 볼 수 있다.

 

Event 부분은 쉽게 구현해서 테스트 해볼수있다 생각되서 따로 테스트한 부분을 적어두진 않았지만,

깃허브에 샘플용으로 (진짜 진짜 진짜) 간단하게 올려두었으니 정 필요하다면 받아다가 테스트 해보면 되겠다.

 

ApplicationEvent 를 활용한 Eventpublisher, EventListener 글이 괜찮은게 있어서 아래 링크 남긴다.

https://wildeveloperetrain.tistory.com/217

 

spring 이벤트 사용하기(event publisher, event listener)

최근 프로젝트에서 'Spring Event'를 사용하게 되면서 정리한 내용입니다. 아래 내용에서 자세하게 볼 수 있겠지만 Spring Framework 4.2부터 스프링 이벤트의 사용이 간편해졌는데요. 기본적인 적용은

wildeveloperetrain.tistory.com

 

 

4. 깃허브

https://github.com/mk1-p/spring-data-rest-test

 

GitHub - mk1-p/spring-data-rest-test: Test for Spring Data Rest

Test for Spring Data Rest. Contribute to mk1-p/spring-data-rest-test development by creating an account on GitHub.

github.com

 

 

5. 참고자료

https://docs.spring.io/spring-data/rest/docs/current/reference/html/#events

 

Spring Data REST Reference Guide

Spring Data REST presents a default view of the domain model you export. However, sometimes, you may need to alter the view of that model for various reasons. This section covers how to define projections and excerpts to serve up simplified and reduced vie

docs.spring.io

https://docs.spring.io/spring-framework/reference/core/beans/context-introduction.html#context-functionality-events

 

Additional Capabilities of the ApplicationContext :: Spring Framework

As discussed in the chapter introduction, the org.springframework.beans.factory package provides basic functionality for managing and manipulating beans, including in a programmatic way. The org.springframework.context package adds the ApplicationContext i

docs.spring.io

 

728x90