#Spring之浅析事件驱动
简介
ApplicationContext通过ApplicationEvent类和ApplicationListener接口进行事件处理。 如果将实现ApplicationListener接口的bean注入到上下文中,则每次使用ApplicationContext发布ApplicationEvent时,都会通知该bean。
设计模式
在设计模式中,观察者模式可以算得上是一个非常经典的行为型设计模式,猫叫了,主人醒了,老鼠跑了,这一经典的例子,是事件驱动模型在设计层面的体现。
区别于发布订阅模式:发布订阅模式需要有一个调度中心,而观察者模式不需要。观察者模式彼此知道对方的存在,而发布订阅不知道。
相关知识:消息队列
示例
Spring 4.2之后支持注解的事件发布dingyue
UserRegisterEvent
public class UserRegisterEvent extends ApplicationEvent {
public UserRegisterEvent(String name) { //name即source
super(name);
}
}
发布者
@Service
public class TestEvent{
public void testRegister(){
System.out.println("注册");
applicationEventPublisher.publishEvent(new UserRegisterEvent("zhuce"));
}
}
订阅者
@Service
public class EmailService {
@EventListener
public void sendEmail(UserRegisterEvent userRegisterEvent){
System.out.println("email---"+userRegisterEvent.getSource());
}
}