• 解耦
  • 对同一种事件有多种处理方式
  • 不干扰主线(main line)

起源

要讲spring的事件通知机制,就要先了解一下spring中的这些接口和抽象类:

  • ApplicationEventPublisherAware        接口:用来 publish event

  • ApplicationEvent                  抽象类,记录了source和初始化时间戳:用来定义Event

  • ApplicationListener<E extends ApplicationEvent>  :用来监听事件

构建自己的事件机制案例

测试案例

测试入口

 1 package com.meituan.spring.testcase.listener;
 2 
 3 import org.springframework.context.support.ClassPathXmlApplicationContext;
 4 
 5 import java.util.concurrent.TimeUnit;
 6 
 7 /**
 8  * Created by zhangxiaoguang on 16/1/27 下午11:40.
 9  * -----------------------------
10  * Desc:
11  */
12 public class TestPortal {
13    public static void main(String[] args) throws InterruptedException {
14 
15       final ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
16 
17       String[] definitionNames = applicationContext.getBeanDefinitionNames();
18       System.out.println("==============bean====start=================");
19       for (String definitionName : definitionNames) {
20          System.out.println("bean----:" + definitionName);
21       }
22       System.out.println("==============bean====end=================");
23       System.out.println();
24       final CustomizePublisher customizePublisher = applicationContext.getBean(CustomizePublisher.class);
25 
26 
27       Thread thread = new Thread(new Runnable() {
28          @Override
29          public void run() {
30             try {
31                System.out.println("开始吃饭:");
32 
33                MealEvent lunchEvent = new MealEvent("A吃午饭了", MealEnum.lunch);
34                MealEvent breakfastEvent = new MealEvent("B吃早饭了", MealEnum.breakfast);
35                MealEvent dinnerEvent = new MealEvent("C吃晚饭了", MealEnum.dinner);
36                customizePublisher.publish(lunchEvent);
37                TimeUnit.SECONDS.sleep(1l);
38                customizePublisher.publish(breakfastEvent);
39                TimeUnit.SECONDS.sleep(1l);
40                customizePublisher.publish(dinnerEvent);
41                TimeUnit.SECONDS.sleep(1l);
42 
43                System.out.println("他们吃完了!");
44             } catch (InterruptedException e) {
45                e.printStackTrace();
46             }
47          }
48       });
49       thread.setName("meal-thread");
50       thread.start();
51 
52       System.out.println(Thread.currentThread().getName() + " is waiting for ....");
53       thread.join();
54       System.out.println("Done!!!!!!!!!!!!");
55    }
56 }
TestPortal

相关文章: