Spring的事件为Bean与Bean之间的通信提供了支持,当我们系统中某个Spring管理的Bean处理完某件事后,希望让其他Bean收到通知并作出相应的处理,这时可以让其他Bean监听当前这个Bean所发送的事件。
要实现事件的监听,我们要做两件事: 1:自定义事件,继承ApplicationEvent接口 2:定义事件监听器,实现ApplicationListener 3:事件发布类
/** * @TODO // 自定义事件,继承ApplicationEvent接口 * @Author Lensen * @Date 2018/7/22 * @Description */public class SendMsgEvent extends ApplicationEvent { private static final long serialVersionID = 1L; // 收件人 public String receiver; // 收件内容 public String content; public SendMsgEvent(Object source) { super(source); } public SendMsgEvent(Object source, String receiver, String content) { super(source); this.receiver = receiver; this.content = content; } public void output(){ System.out.println("I had been sand a msg to " + this.receiver); }}
/** * @TODO //定义事件监听器,实现ApplicationListener * @Author Lensen * @Date 2018/7/22 * @Description */@Componentpublic class MsgListener implements ApplicationListener{ @Override public void onApplicationEvent(SendMsgEvent sendMsgEvent) { sendMsgEvent.output(); System.out.println(sendMsgEvent.receiver + "received msg : " + sendMsgEvent.content ); }}
事件发布类
@Componentpublic class Publisher { @Autowired ApplicationContext applicationContext; public void publish(Object source, String receiver, String content){ applicationContext.publishEvent(new SendMsgEvent(source, receiver, content)); }}
测试消息:WebConfig.class主要是为了扫描Publisher 和Listener类。里面有两个注解@ComponenScan和@Configuration。
public static void main(String[] args) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(WebConfig.class); Publisher publisher = applicationContext.getBean(Publisher.class); publisher.publish("Hello,World!","Mr.Lensen", "I Love U"); }
结果:
I had been sand a msg to Mr.LensenMr.Lensen received msg : I Love U