问题
刚才在读Spring-data-mongodb的文档,读到7.7的时候就发现了@DomainEvents
和@AfterDomainEventPublication
这么两个注解。
就看懂了最后一句每次调用Spring Data存储库的save(…)方法时,都会调用这些方法。哎,有意思,但是官方给的这个例子真的有点瞎。。自己试试吧。
试验
一个用户
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private LocalDateTime createTime;
@DomainEvents
public List<Object> domainEvents() {
System.out.println("domainEvents什么时候调用呢");
System.out.println(this);
return Stream.of(this).collect(Collectors.toList());
}
@AfterDomainEventPublication
public void callbackMethod() {
System.out.println("callbackMethod什么时候调用呢");
}
//省略getter setter 构造 toString等
}
试了一下如果这两个方法放在其他类里面是不会触发的,难道必须得放在模型里面吗。
测试save和saveAll方法
@Test
public void testSave() {
Customer customer = new Customer("a","a");
customerDao.save(customer);
}
@Test
public void testSaveAll() {
List<Customer> list = Stream.of(new Customer("b", "b"),
new Customer("c", "c")).collect(Collectors.toList());
customerDao.saveAll(list);
}
testSave()方法调用之后输出
Hibernate: insert into t_customer (create_time, password, username) values (?, ?, ?)
domainEvents什么时候调用呢
Customer{id=8, username='a', password='a', createTime=2018-06-08T18:22:11.665}
callbackMethod什么时候调用呢
testSaveAll()方法调用之后输出
Hibernate: insert into t_customer (create_time, password, username) values (?, ?, ?)
Hibernate: insert into t_customer (create_time, password, username) values (?, ?, ?)
domainEvents什么时候调用呢
Customer{id=9, username='b', password='b', createTime=2018-06-08T18:23:15.853}
callbackMethod什么时候调用呢
domainEvents什么时候调用呢
Customer{id=10, username='c', password='c', createTime=2018-06-08T18:23:15.853}
callbackMethod什么时候调用呢
结论
就如文档所说的那样
@DomainEvents可以返回单个事件实例或事件集合
所有事件发布后@AfterDomainEventPublication用于潜在地清理要发布的事件列表
@DomainEvents用来发布时间,触发机制在保存的时候。
@AfterDomainEventPublication在事件发布之后触发。
有趣的一件事是@AfterDomainEventPublication只在@DomainEvents存在时才起作用。
具体怎么使用有更理解的小伙伴分享一下。