标签:serial 实战 end tms list 类型 event div 流程
Spring的事件为Bean与Bean之间的消息通信提供了支持,当一个Bean处理完一个任务之后,希望另外一个Bean知道并能做相应的处理,这时我们就需要让一个Bean监听当前Bean所发送的事件。
Spring的事件需要遵循如下流程:
一、自定义事件
package com.cenobitor.appevent.event; import org.springframework.context.ApplicationEvent; public class DemoEvent extends ApplicationEvent { private static final long serialVersionUID = 1L; private String msg; public DemoEvent(Object source,String msg) { super(source); this.msg = msg; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
二、事件监听器
package com.cenobitor.appevent.listener; import com.cenobitor.appevent.event.DemoEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component;
//实现ApplicationListener接口,并指定监听的事件类型 @Component public class DemoListener implements ApplicationListener<DemoEvent> { @Override
//使用onApplicationEvent方法对消息进行接收处理 public void onApplicationEvent(DemoEvent demoEvent) { String msg = demoEvent.getMsg(); System.out.println("(bean-demoListener)接收到了bean-demoPublisher发布的消息:"+msg); } }
三、事件发布类
package com.cenobitor.appevent.publisher; import com.cenobitor.appevent.event.DemoEvent; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; @Component public class DemoPublisher { @Autowired
//注入ApplicationContext用来发布事件 ApplicationContext applicationContext; //使用ApplicationContext的publishEvent方法来发布 public void publish(String msg){ applicationContext.publishEvent(new DemoEvent(this,msg)); } }
四、运行
package com.cenobitor.appevent; import com.cenobitor.appevent.publisher.DemoPublisher; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppeventApplication.class); DemoPublisher demoPublisher = context.getBean(DemoPublisher.class); demoPublisher.publish("hello application event"); context.close(); } }
结果:(bean-demoListener)接收到了bean-demoPublisher发布的消息:hello application event
注:摘抄自《JavaEE开发的颠覆者SpringBoot 实战》。
SpringBoot -- 事件(Application Event)
标签:serial 实战 end tms list 类型 event div 流程
原文地址:https://www.cnblogs.com/gdwkong/p/9309459.html