ddd项目开发过程中使用的到事件,主要业务流程发布事件,不影响主流程处理的操作事件消费。
使用ApplicationContext 实现事件的生成与消费
使用时建议对每个阶段进行区分
创建事件类,
监听类对事件进行处理
ApplicationContext 调用即可,
主业务数据->填充事件类->ApplicationContext发送事件->监听类对事件处理
流程:
填充:当前主业务类,TestMain
创建事件类:类继承ApplicationEvent;
如 public class TestEvent extends ApplicationEvent{
private TestMain testmain;
public TestEvent(TestMain testmain){
super(testmain);
this.testmain = testmain;
}
}
创建事件监听类 :监听 TestEvent
public class TestListener implements ApplicationListener<TestEvent > {
public void onApplicationEcent(TestEvent event){
需要处理的业务
}
}
由于使用的为应用程序上下文,如果想要异步需要结合线程使用,发布事件放入线程内
private ApplicationContext applicationContext;
public void save(){
//主要业务代码
try{
//发布事件
TestEvent test = new TestEvent();
test.setName("测试");
applicationContext.publishEvent(test);
}catch(Exception e)
//日志记录等
}