1、概述
1.1、Spring的事件 为Bean与Bean之间的消息通信提供了支持;
当一个Bean处理完一个任务后,希望另一个Bean知道并能做出相应的处理,这时我们需要 让另一个Bean 监听 当前Bean所发送的事件;
1.2、Spring的事件需要遵循如下流程:
a,自定义事件,继承ApplicationEvent
b,定义事件监听器,实现ApplicationListener
c,使用容器发布事件
1.3、eg:
package com.an.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; /** * @description: 事件配置类 * @author: anpeiyong * @date: Created in 2019/11/19 16:41 * @since: */ @Configuration @ComponentScan(value = "com.an") public class EventConfig { }
package com.an.event; import org.springframework.context.ApplicationEvent; /** * @description: 自定义事件 * @author: anpeiyong * @date: Created in 2019/11/19 16:32 * @since: */ public class MyEvent extends ApplicationEvent { private String msg; public MyEvent(Object source,String msg) { super(source); this.msg=msg; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
package com.an.event; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; /** * @description: 自定义事件监听器 * 实现ApplicationListener接口,并指定监听的事件类型ApplicationListener<MyEvent> * 使用onApplicationEvent()方法对消息进行接收处理 * @author: anpeiyong * @date: Created in 2019/11/19 16:34 * @since: */ @Component public class MyListener implements ApplicationListener<MyEvent> { @Override public void onApplicationEvent(MyEvent event) { String msg=event.getMsg(); System.out.println("我接收到的消息:" msg); } }
package com.an.event; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; /** * @description: * @author: anpeiyong * @date: Created in 2019/11/19 16:38 * @since: */ @Component public class MyPublisher { //注入ApplicationContext,用来发布事件 @Autowired ApplicationContext applicationContext; public void publish(String msg){ //使用ApplicationContext.publishEvent()发布 applicationContext.publishEvent(new MyEvent(this,msg)); } }
package com.an.main; import com.an.config.EventConfig; import com.an.event.MyPublisher; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * @description: * @author: anpeiyong * @date: Created in 2019/11/19 16:41 * @since: */ public class EventMainTest { public static void main(String[] args) { AnnotationConfigApplicationContext annotationConfigApplicationContext=new AnnotationConfigApplicationContext(EventConfig.class); MyPublisher myPublisher=annotationConfigApplicationContext.getBean(MyPublisher.class); myPublisher.publish("hello"); annotationConfigApplicationContext.close(); } }
结果:
我接收到的消息:hello