Domain Event usage in Spring Data
1. DDD and Spring Data
DDD: domain-driven design (domain-driven design) is an implementation method for software development under complex requirements. I will talk about DDD in time.
Spring Data is designed in many places according to the DDD principles (such as Repository). Here Spring Data mainly implements the aggregate and domain event of DDD:
- Aggregate: a collection of domain objects that can be viewed as single units. For example, order and line-items are independent objects, but they are treated as an independent unit (aggregate ). Each aggregate has an aggregate root. Any external interaction must be performed through aggregate root, so that aggregate root can ensure the integrity of aggregate. An aggregate has a transaction (Data Consistency) boundary.
- Domain event: to ensure data consistency, Event-Driven Architecture (Eventual consistency) is used between aggregates to achieve final data consistency ). These events are domain events published through aggregate root.
The following example shows how to update the statistics of male and female by GenderStat, the statistical entity, after the aggregate root of Person is successfully saved.
2. Demo
2.1 Person Aggregate Root
As the Aggregate Root, Person can publish domain events. There are two implementation methods in Spring Data:
- -Inherit AbstractAggregateRoot and use its registerEvent () method to register a publishing event
- -Use the @ DomainEvents annotation method to publish an event
For example:
@Entity@Data@AllArgsConstructor@NoArgsConstructor@ToString(exclude = "domainEvents")public class Person { @Id @GeneratedValue private Long id; private String name; private Integer gender;//1:male;2:female @DomainEvents Collection<Object> domainEvents() { List<Object> events= new ArrayList<Object>(); events.add(new PersonSavedEvent(this.id,this.gender)); return events; } @AfterDomainEventPublication void callbackMethod() { // }}
Or
@Entity@Data@AllArgsConstructor@NoArgsConstructor@ToString(exclude = "domainEvents")public class Person extends AbstractAggregateRoot{ @Id @GeneratedValue private Long id; private String name; private Integer gender;//1:male;2:female public Person afterPersonSavedCompleted(){ registerEvent(new PersonSavedEvent(this.id,this.gender)); return this; }}
2.2 handle listener events
@Componentpublic class GenderStatProcessor { @Autowired GenderRepository genderRepository; @Async @TransactionalEventListener public void handleAfterPersonSavedComplete(PersonSavedEvent event){ GenderStat genderStat = genderRepository.findOne(1l); if(event.getGender()==1){ genderStat.setMaleCount(genderStat.getMaleCount()+1); }else { genderStat.setFemaleCount(genderStat.getFemaleCount()+1); } genderRepository.save(genderStat); }}
3 Source Code address: Https://github.com/wiselyman/spring-data-domain-event
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.