Reputation: 1819
I have encountered the @DomainEvents and @AfterDomainEventsPublication annotation in spring Data JPA Reference Documentation. But I am not able to find the perfect example to explain about these annotaions
Upvotes: 9
Views: 5472
Reputation: 2827
You can see sample in the original unit tests for EventPublishingRepositoryProxyPostProcessor
EventPublishingRepositoryProxyPostProcessorUnitTests.java by Oliver Gierke in GitHub Repository of Spring Data Commons.
Description in base issue of Spring Jira DATACMNS-928 Support for exposing domain events from aggregate roots as Spring application events was useful for me.
UPDATE
This is simple and really working example by Zoltan Altfatter: Publishing domain events from aggregate roots
Upvotes: 8
Reputation: 357
Here is my example code:
package com.peaceelite.humanService;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.springframework.data.domain.AfterDomainEventPublication;
import org.springframework.data.domain.DomainEvents;
import java.util.*;
@Entity
public class SalesmanCustomerRelationship{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String firstName;
private String lastName;
/*getters & setters*/
@DomainEvents
Collection<Object> domainEvents() {
List<Object> result = new ArrayList<Object>();
result.add("Here should be an Event not a String, but, anyway");
return result;
}
@AfterDomainEventPublication
void callbackMethod() {
System.out.println("DATA SAVED!\n"+"WELL DONE");
}
}
This is an entity class managed by a spring data repository. Both @DomainEvents and @AfterDomainEventPublication happens after CrudRepository.save() being executed. One thing that is interesting is that @AfterDomainEventPublication ONLY works when @DomainEvents exists.
I'm learning Spring Data reference too, both this question and Dmitry Stolbov's answer helped me a lot.
Upvotes: 6