Spring中如何优雅的使用监听器模式
spring中自带了监听器组件, spring的监听器在其内部代码中得到了广泛的应用,
且是著名框架 SpringBoot 的核心组件, 并且各种第三方框架和spring集成也充分使用的spring的监听器
那么… 我们如何在项目中使用Spring的监听器组件呢??
监听器模式又可以理解为观察者模式
监听器模式的组成有 事件(event) 和 监听器(listener)
监听器可以监听对应的事件,来做对应的业务处理
事件(event) 的创建
只需继承 ApplicationEvent
即可
public class OrderStatusEvent extends ApplicationEvent {
}
监听器的创建
实现ApplicationListener
接口即可, ApplicationListener
中的泛型指定为对应的事件
- 切记要把该监听器注入到Spring中哦 !!!
@Component
public class OrderStatusListener implements ApplicationListener<OrderStatusEvent> {
/**
* Handle an application event.
* @param event the event to respond to
*/
public void onApplicationEvent(OrderStatusEvent event) {
// 监听到 对应的事件
}
}
发送事件
@Service
public class OrderStatusTest {
@Autowired
private ApplicationContext applicationContext;
public void sendEvent() {
// 发送 OrderStatusEvent 事件 , 发送完成后,监听该事件的监听器就会监听到该事件
applicationContext.publishEvent(new OrderStatusEvent("orderID"));
}
}
- 这样就能发送我们想发送事件了, 对业务代码的解耦以及扩展使用该监听器模型非常的有用且方便
抛开现象看本质
Spring真正实现该功能的类是 SimpleApplicationEventMulticaster
, 如果你不想用
ApplicationContext, 你可以使用该对象来发送事件 该对象实现了ApplicationEventMulticaster
接口
该接口定义了 监听器和事件相关的方法
public interface ApplicationEventMulticaster {
/**
添加一个Listener
*/
void addApplicationListener(ApplicationListener<?> listener);
/**
添加一个由spring管理的listener
*/
void removeApplicationListener(ApplicationListener<?> listener);
/**
删除一个 由spring管理的listener
*/
void removeApplicationListenerBean(String listenerBeanName);
/**
删除所有的listener
*/
void removeAllListeners();
/**
发送事件
*/
void multicastEvent(ApplicationEvent event);
/**
发送事件,带有该事件的类型
*/
void multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType);
}
扩展
Spring
上面我们说过spring内部大量的使用了该功能,我们来看看它内部定义了一些什么事件
- 上下文启动时发送的事件
ContextStartedEvent
# ApplicationContext注入到BeanFactory后会执行start方法触发该事件 - 上下文停止时发送的事件
ContextStoppedEvent
, #销毁bean时会调用该事件 - 上下文关闭时发送的事件
ContextClosedEvent
, #销毁bean时会调用该事件 - 上下文刷完成新时发送的事件
ContextRefreshedEvent
, # 刷新完成时会调用该事件
等等…
SpringBoot
springboot大量的使用了"事件驱动"模式,我们看看它又定义了哪些事件呢?
-
SpringBoot 启动启动前发送的事件
ApplicationStartingEvent(application,args)
-
SpringBoot配置环境变量前发送的事件
ApplicationEnvironmentPreparedEvent(application,args,environment)
-
SpringBoot加载上下文前发送的事件
ApplicationContextInitializedEvent(application,args,context)
-
SpringBoot加载上下文完成发送的事件
ApplicationPreparedEvent(application, args, context)
-
SpringBoot started完成, 调用context.refresh方法后
ApplicationStartedEvent(application, args, context)
-
SpringBoot启动异常时发送的事件
ApplicationFailedEvent(this.application, this.args, context, exception)
-
SpringBoot启动完成后发送的事件
ApplicationReadyEvent(application, args, context)
-
除此之外还有很多,就不一一列举了, SpringBoot正是使用了监听器模式,
才使得它整体的扩展性更加的如鱼得水, SpringBoot架构的成功离不开这个监听器组件
我们刚学SpringBoot的时候老说它的架构像个“八爪鱼”一样, 现在明白为什么这么叫了吧…
总结
监听器模式的优势很明显, 在自己项目中灵活运用肯定能让自己的代码健壮性、扩展性、可读性、都有一个提升!
关键是Spring帮我们提供了这个组件,用起来更加的方便!!!
----------------------------------------- 广告时间 -----------------------------------------
各位看官, 欢迎关注公众号,每天推送满满的“干货”哦!!!