[스프링 데이터 JPA] 스프링 데이터 Common 9. 도메인 이벤트
도메인 Entity 클래스 이벤트 발생시키기
스프링 프레임워크의 이벤트 관련 기능
Core Technologies
In the preceding scenario, using @Autowired works well and provides the desired modularity, but determining exactly where the autowired bean definitions are declared is still somewhat ambiguous. For example, as a developer looking at ServiceConfig, how do
docs.spring.io
ApplicationContext extends ApplicationEventPublisher
- 이벤트: extends ApplicationEvent
- 리스너
- implements ApplicationListener
- @EventListener
ApplicationContext가 이벤트 Publisher 임
BeanFactory, EventPublisher 인터페이스를 상속받았음
스프링 데이터의 도메인 이벤트 Publisher
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#core.domain-events
Spring Data JPA - Reference Documentation
Example 109. Using @Transactional at query methods @Transactional(readOnly = true) public interface UserRepository extends JpaRepository { List findByLastname(String lastname); @Modifying @Transactional @Query("delete from User u where u.active = false") v
docs.spring.io
스프링 데이터의 도메인 이벤트 Publisher
- @DomainEvents
- @AfterDomainEventPublication
- extends AbstractAggregateRoot <E>
- 현재는 save() 할 때만 발생합니다.
- 자동으로 AbstractAggregationRoot를 통해 domainEvents에 모아 둔 이벤트를 발생시킨다.
- EventListener가 동작
AbstractAggregationRoot를 통한 이벤트 등록
@Entity
@Getter
@Setter
@ToString
public class Post extends AbstractAggregateRoot<Post> {
@Id
@GeneratedValue
private Long id;
private String title;
@Lob
private String content;
public Post publish() {
this.registerEvent(new PostPublishedEvent(this));
return this;
}
}
PostPublishedEvent 클래스 생성
public class PostPublishedEvent extends ApplicationEvent {
private final Post post;
public PostPublishedEvent(Object source) {
super(source);
this.post = (Post) source;
}
public Post getPost() {
return post;
}
}
PostListener 클래스 없이, TestConfig 파일에 직접 등록
@Configuration
public class PostRepositoryTestConfig {
// @Bean
public PostListener postListener() {
return new PostListener();
}
@Bean
public ApplicationListener<PostPublishedEvent> applicationListener() {
return new ApplicationListener<PostPublishedEvent>() {
@Override
public void onApplicationEvent(PostPublishedEvent event) {
System.out.println("=======================================================================================");
System.out.println(event.getPost() + " is published !!!");
System.out.println("=======================================================================================");
}
};
}
}