spring的事件(ApplicationEvent)为bean和bean之间的消息通信提供了支持。当bean处理完一个事件之后,希望另一个bean能够知道并做相应的处理。这时另一个bean监听当前bean所发送的事件。
spring的事件流程如下:
- 自己的event需要继承 ApplicationEvent,并且写相应的构造函数
- 定义一个监听器listener,实现ApplicationListener接口,重写onApplicationEvent方法
- 使用ApplicationContext容器发布事件
代码如下:
1.创建一个DemoEvent
package com.xingguo.logistics.service.event;
import org.springframework.context.ApplicationEvent;
public class DemoEvent extends ApplicationEvent{
private static final long serialVersionUID = 1L;
private String message;
public DemoEvent(Object source,String message){
super(source);
this.message = message;
}
public String getMessage() {
return message;
}
}
2.创建一个监听DemoListener
package com.xingguo.logistics.service.event;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
//实现ApplicationListener接口,指定监听的事件类型DemoEvent
@Component
public class DemoListener implements ApplicationListener<DemoEvent>{
//使用onApplicationEvent接收消息
@Override
public void onApplicationEvent(DemoEvent event) {
String msg = event.getMessage();
System.out.println("接收到的信息:"+msg);
}
}
3.创建一个配置类(注意这里使用的是spring4.x)
package com.xingguo.logistics.controller;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan({"com.xingguo.logistics.service.event"})
public class AopConfig {
}
4.事件发布
package com.xingguo.logistics.service.event;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class DemoPublisher {
//容器注入
@Autowired
ApplicationContext applicationContext;
public void publish(String message){
//发布事件
applicationContext.publishEvent(new DemoEvent(this, message));
}
}
5.测试:
package com.xingguo.logistics.controller;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.xingguo.logistics.service.event.DemoPublisher;
public class TestController {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AopConfig.class);
DemoPublisher demoPublisher = context.getBean(DemoPublisher.class);
demoPublisher.publish("发布消息");
context.close();
}
}
测试结果如下: