Spring的事件为Bean与Bean的消息通信提供的支持。当一个Bean处理完了一个任务以后,希望另一个Bean知道并能做出相应的处理,这是我们就需要让另一个Bean监听当前Bean所发送的事件。
Spring中使用事件的大概流程如下:
(1)定义事件
(2)定义事件***
(3)使用容器发布事件
示例:
(1)定义事件
自定义事件需要实现ApplicationEvent接口。
package learnspring.learnspring.event;
import org.springframework.context.ApplicationEvent;
/**
 * @author 肖政宇
 * @date 2019-09-23 14:36
 * 说明:自定义事件
 */
public class DemoEvent extends ApplicationEvent {
 private static final long serialVersionUID = 1L;
 private String msg;
 DemoEvent(Object source, String msg) {
 super(source);
 this.msg = msg;
 }
 String getMsg() {
 return msg;
 }
 public void setMsg(String msg) {
 this.msg = msg;
 }
}
  
(2)定义事件***
package learnspring.learnspring.event;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
/**
 * @author 肖政宇
 * @date 2019-09-23 14:39
 * 说明:事件***
 * 实现ApplicationListener接口,同时声明监听的事件类型
 */
@Component
public class DemoListener implements ApplicationListener<DemoEvent> {
 @Override
 public void onApplicationEvent(DemoEvent event) {
 String msg = event.getMsg();
 System.out.println("我(bean-demoListener)接收到了bean-demoPublisher发布的消息:" + msg);
 }
}
      
(3)使用容器发布事件
package learnspring.learnspring.event;
package learnspring.learnspring.event;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
/**
 * @author 肖政宇
 * @date 2019-09-23 14:43
 * 说明:事件发布者
 */
@Component
public class DemoPublisher {
 private ApplicationContext applicationContext;
 @Autowired
 public void setApplicationContext(ApplicationContext applicationContext) {
 this.applicationContext = applicationContext;
 }
 public void publish(String msg) {
 applicationContext.publishEvent(new DemoEvent(this, msg));
 }
}
     测试:
package learnspring.learnspring;
import learnspring.learnspring.event.DemoPublisher;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class LearnspringApplicationTests {
 DemoPublisher publisher;
 @Autowired
 public void setPublisher(DemoPublisher publisher) {
 this.publisher = publisher;
 }
 @Test
 public void contextLoads() {
 System.out.println("事件发生!");
 publisher.publish("Hello World!");
 }
}
      运行结果:

京公网安备 11010502036488号