Spring 事件记录

⒈定义一个事件,继承 ApplicationEvent 接口。

 1 package cn.coreqi.eventdemo.event;
 2 
 3 import org.springframework.context.ApplicationEvent;
 4 
 5 public class ProjectEvent extends ApplicationEvent {
 6     private String id;
 7     private String projectStatus;
 8 
 9     public String getId() {
10         return id;
11     }
12 
13     public String getProjectStatus() {
14         return projectStatus;
15     }
16 
17     public ProjectEvent(Object source, String id, String projectStatus){
18         super(source);
19         this.id = id;
20         this.projectStatus = projectStatus;
21     }
22 }

2.定义一个监听者,实现 ApplicationListener,以下二选其一,需要注意Spring的版本,以1为优先选项。

  1.

 1 package cn.coreqi.eventdemo.listener;
 2 
 3 import cn.coreqi.eventdemo.event.ProjectEvent;
 4 import org.springframework.context.ApplicationListener;
 5 import org.springframework.stereotype.Component;
 6 
 7 @Component
 8 public class ProjectListener implements ApplicationListener<ProjectEvent> {
 9     @Override
10     public void onApplicationEvent(ProjectEvent event) {
11         System.out.println("接收到的项目id: " + event.getId());
12         System.out.println("接受到的项目类型: " + event.getProjectStatus());
13         //开始业务处理
14     }
15 }

  2.

1     @EventListener
2     public void registerProjectEventListener(ProjectEvent event){
3         System.out.println("这是第二种监听方式");
4         System.out.println("接收到的项目id: " + event.getId());
5         System.out.println("接受到的项目类型: " + event.getProjectStatus());
6         //开始业务处理
7     }

3.发布【这里是手动发布,一般是以quartz等任务框架去推动发布】

1     public static void main(String[] args) {
2         //SpringApplication.run(ApplicationMain.class, args);
3         ConfigurableApplicationContext context = SpringApplication.run(ApplicationMain.class, args);
4         context.publishEvent(new ProjectEvent(context,"7777","开始"));
5     }

【可选】4.异步

 1 package cn.coreqi.eventdemo.config;
 2 
 3 import org.springframework.context.annotation.Bean;
 4 import org.springframework.context.annotation.Configuration;
 5 import org.springframework.context.event.ApplicationEventMulticaster;
 6 import org.springframework.context.event.SimpleApplicationEventMulticaster;
 7 import org.springframework.core.task.SimpleAsyncTaskExecutor;
 8 
 9 @Configuration
10 public class AsynchronousSpringEventsConfig {
11 
12     @Bean(name = "applicationEventMulticaster")
13     public ApplicationEventMulticaster simpleApplicationEventMulticaster()
14     {
15         SimpleApplicationEventMulticaster eventMulticaster = new SimpleApplicationEventMulticaster();
16         eventMulticaster.setTaskExecutor(new SimpleAsyncTaskExecutor());    //不是最优选择
17         return eventMulticaster;
18     }
19 
20 }

 

posted @ 2022-04-01 14:52  SpringCore  阅读(48)  评论(0编辑  收藏  举报