ApplicationContext的事件处理——阅读开源项目中的代码
ApplicationContext中的事件处理是通过ApplicationEvent类和ApplicationListener接口来提供的,通过ApplicationContext的publishEvent()方法发布到ApplicationListener;
组件:被发布的事件,事件发布者,事件监听者
流程演示:
1、定义事件,继承ApplicationEvent
1 import org.springframework.context.ApplicationEvent; 2 3 public class DemoEvent extends ApplicationEvent { 4 5 private String msg; 6 public DemoEvent(Object source,String msg) { 7 super(source); 8 this.msg = msg; 9 } 10 11 public String getMsg() { 12 return msg; 13 } 14 15 public void setMsg(String msg) { 16 this.msg = msg; 17 } 18 }
2、定义事件监听者,实现ApplicationListener<E>接口
import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; @Component public class DemoListener implements ApplicationListener<DemoEvent> { @Override public void onApplicationEvent(DemoEvent demoEvent) { System.out.println("我已经接收到事件:"+demoEvent.getMsg()); } }
3、定义事件推送者:实质是使用ApplicationContext推送事件
1 import org.springframework.beans.factory.annotation.Autowired; 2 import org.springframework.context.ApplicationContext; 3 import org.springframework.stereotype.Component; 4 5 @Component 6 public class DemoPublish { 7 8 @Autowired 9 private ApplicationContext applicationContext; 10 11 public void publish(String msg){ 12 applicationContext.publishEvent(new DemoEvent(this,msg)); 13 } 14 }
参考博客:https://blog.csdn.net/dongwujing/article/details/89339680

浙公网安备 33010602011771号