Spring ApplicationListener源碼解析
正文
對于ApplicationListener使用Spring的應(yīng)該也熟悉,因?yàn)檫@就是我們平時(shí)學(xué)習(xí)的觀察者模式的實(shí)際代表。
Spring基于Java提供的EventListener實(shí)現(xiàn)了一套以Spring容器為基礎(chǔ)的觀察者模式的事件監(jiān)聽功能,
用于只要實(shí)現(xiàn)Spring提供的接口完成事件的定義和監(jiān)聽者的定義,那么就可以很快速的接入觀察者模式的實(shí)現(xiàn)。
ApplicationListener介紹
說ApplicationListener之前先要知道EventListener。
EventListener本身是一個(gè)接口,它的作用跟前面講到的Aware類似,都是只定義最頂級的接口,并沒有實(shí)習(xí)對應(yīng)的方法,并且該接口也是由JDK提供的,并不是直接由Spring提供,Spring只是基于該接口實(shí)現(xiàn)了自己的一套事件監(jiān)聽功能。
在Spring中實(shí)現(xiàn)事件監(jiān)聽的接口是ApplicationListener,該接口繼承了EventListener,并做了對應(yīng)的實(shí)現(xiàn)。
源碼如下:
package java.util;
/**
* A tagging interface that all event listener interfaces must extend.
* @since JDK1.1
*/
public interface EventListener {
}
@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
//監(jiān)聽者監(jiān)聽事件的邏輯處理
void onApplicationEvent(E event);
static <T> ApplicationListener<PayloadApplicationEvent<T>> forPayload(Consumer<T> consumer) {
return event -> consumer.accept(event.getPayload());
}
}
ApplicationListener使用
對于ApplicationListener的使用,因?yàn)镾pring已經(jīng)做了自己的封裝,并且以Spring容器為基礎(chǔ)做了實(shí)現(xiàn),那么開發(fā)者使用時(shí)也可以很快的上手,只要簡單的配置即可。
定義事件:
//事件繼承Spring中的ApplicationEvent
public class MyEvent extends ApplicationEvent {
private String name;
public MyEvent(ApplicationContext source,String name) {
super(source);
this.name = name;
}
public String getName() {
return name;
}
}
定義事件的監(jiān)聽者
//定義監(jiān)聽者實(shí)現(xiàn)ApplicationListener,并通過泛型聲明監(jiān)聽的事件
@Component
public class MyEventListener implements ApplicationListener<MyEvent> {
@Override
public void onApplicationEvent(MyEvent event) {
System.out.println("監(jiān)聽MyEvent:收到消息時(shí)間:"+event.getTimestamp()+"【消息name:"+event.getName() + "】");
}
}
@Component
public class MyEventProcessor implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
}
發(fā)布事件
@SpringBootApplication
public class BootApplication {
@Resource
private DefaultListableBeanFactory defaultListableBeanFactory;
@Resource
private MySpringAware mySpringAware;
@Resource
private MyEventProcessor myEventProcessor;
public static void main(String[] args) {
SpringApplication.run(BootApplication.class,args);
}
@PostConstruct
public void init() {
ApplicationContext applicationContext = myEventProcessor.getApplicationContext();
//發(fā)布事件,事件發(fā)布之后,前面訂閱的監(jiān)聽者就會監(jiān)聽到該事件發(fā)布的消息
applicationContext.publishEvent(new MyEvent(applicationContext,"陳湯姆"));
applicationContext.publishEvent(new MyEvent(applicationContext,"陳湯姆2"));
}
}
監(jiān)聽者收到發(fā)布的事件信息

ApplicationListener作用
從以上的例子中可以看到ApplicationListner的模式就是設(shè)計(jì)模式中的觀察者模式。
觀察者模式的作用很好的解決了同步交互的問題。
以發(fā)送者和接收者為例,接收者接收消息如果同步場景下需要與發(fā)送者實(shí)現(xiàn)同步調(diào)用,但是這樣就導(dǎo)致兩者之間無法解耦,而ApplicationListener就是解決同步的問題,ApplicationListener可以提供半解耦的方式實(shí)現(xiàn)兩者之間的交互,即發(fā)送者發(fā)送消息不需要與接收者之間實(shí)現(xiàn)同步通知,只要訂閱發(fā)送者的事件即可完成雙發(fā)的交互。
這里為什么是半解耦,因?yàn)閮烧咧g還是有一定交互的,交互的點(diǎn)就在于發(fā)送者的發(fā)送方需要維護(hù)一個(gè)接收者的集合,發(fā)送方在發(fā)送時(shí)需要將具體的接收者放在集合中,在發(fā)送時(shí)通過遍歷集合發(fā)送給接收方,執(zhí)行接收方的業(yè)務(wù)處理。
在ApplicationListener這個(gè)集合就是public final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<>(); 這個(gè)集合中就存儲了接收者的實(shí)例,最終會遍歷該集合執(zhí)行接收者的業(yè)務(wù)邏輯。
這里拋一個(gè)問題,其實(shí)ApplicationListener的功能通過MQ也可以實(shí)現(xiàn),那么觀察者模式和發(fā)布訂閱模式的區(qū)別是什么呢?歡迎評論區(qū)一起討論!
ApplicationListener注冊
對于ApplicationListener的注冊比較好梳理的,只要找到存儲ApplicationListener的集合就可以知道怎么add集合的。
在Spring中ApplicationListener的注冊也是在Spring中實(shí)現(xiàn)的。
具體的梳理邏輯如下:
org.springframework.context.support.AbstractApplicationContext#refresh
org.springframework.context.support.AbstractApplicationContext#registerListeners
org.springframework.context.event.AbstractApplicationEventMulticaster#addApplicationListener
源碼梳理如下:
public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext {
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
//注冊觀察者
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
//將觀察者注入到集合中
protected void registerListeners() {
// Register statically specified listeners first.
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let post-processors apply to them!
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
//調(diào)用集合的add操作
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// Publish early application events now that we finally have a multicaster...
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (earlyEventsToProcess != null) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
//獲取觀察者的集合
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
}
public abstract class AbstractApplicationEventMulticaster
implements ApplicationEventMulticaster, BeanClassLoaderAware, BeanFactoryAware {
private class ListenerRetriever {
//存儲觀察者的集合
public final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<>();
public final Set<String> applicationListenerBeans = new LinkedHashSet<>();
private final boolean preFiltered;
public ListenerRetriever(boolean preFiltered) {
this.preFiltered = preFiltered;
}
//獲取觀察者的集合
public Collection<ApplicationListener<?>> getApplicationListeners() {
List<ApplicationListener<?>> allListeners = new ArrayList<>(
this.applicationListeners.size() + this.applicationListenerBeans.size());
allListeners.addAll(this.applicationListeners);
if (!this.applicationListenerBeans.isEmpty()) {
BeanFactory beanFactory = getBeanFactory();
for (String listenerBeanName : this.applicationListenerBeans) {
try {
ApplicationListener<?> listener = beanFactory.getBean(listenerBeanName, ApplicationListener.class);
if (this.preFiltered || !allListeners.contains(listener)) {
allListeners.add(listener);
}
}
catch (NoSuchBeanDefinitionException ex) {
// Singleton listener instance (without backing bean definition) disappeared -
// probably in the middle of the destruction phase
}
}
}
if (!this.preFiltered || !this.applicationListenerBeans.isEmpty()) {
AnnotationAwareOrderComparator.sort(allListeners);
}
return allListeners;
}
}
}
從以上的源碼可以看到核心的集合就是applicationListeners??梢愿鶕?jù)該集合梳理注冊和執(zhí)行流程。
ApplicationListener執(zhí)行
注冊梳理清晰,那么執(zhí)行自然也很好梳理了, 畢竟使用的都是同一個(gè)集合。
ApplicationListener的執(zhí)行其實(shí)就是觀察者的執(zhí)行,也就是在使用篇章中的MyEventListener,在MyEventListener中重寫了onApplicationEvent,其中實(shí)現(xiàn)了自己的邏輯,那么執(zhí)行就是將MyEventListener中重寫的方式如何在沒有同步調(diào)用的情況下執(zhí)行。
執(zhí)行的實(shí)現(xiàn)就是依賴觀察者的集合,在注冊中我們已經(jīng)將所有的觀察者添加到了ApplicationListener集合中,只要將該集合中的觀察者取出執(zhí)行,即可完成半解耦的執(zhí)行。
梳理流程如下:
org.springframework.context.ApplicationEventPublisher#publishEvent(org.springframework.context.ApplicationEvent)
org.springframework.context.support.AbstractApplicationContext#publishEvent(java.lang.Object, org.springframework.core.ResolvableType)
org.springframework.context.event.SimpleApplicationEventMulticaster#multicastEvent(org.springframework.context.ApplicationEvent, org.springframework.core.ResolvableType)
org.springframework.context.event.SimpleApplicationEventMulticaster#invokeListener
org.springframework.context.event.SimpleApplicationEventMulticaster#doInvokeListener
源碼如下:
public class SimpleApplicationEventMulticaster extends AbstractApplicationEventMulticaster {
@Override
public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
//getApplicationListeners就是獲取ApplicationListener的集合
for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
Executor executor = getTaskExecutor();
if (executor != null) {
//執(zhí)行監(jiān)聽者的
executor.execute(() -> invokeListener(listener, event));
}
else {
invokeListener(listener, event);
}
}
}
//執(zhí)行監(jiān)聽者邏輯
protected void invokeListener(ApplicationListener<?> listener, ApplicationEvent event) {
ErrorHandler errorHandler = getErrorHandler();
if (errorHandler != null) {
try {
doInvokeListener(listener, event);
}
catch (Throwable err) {
errorHandler.handleError(err);
}
}
else {
doInvokeListener(listener, event);
}
}
//最終執(zhí)行邏輯
private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
try {
//調(diào)用監(jiān)聽者重寫的onApplicationEvent方法
listener.onApplicationEvent(event);
}
catch (ClassCastException ex) {
String msg = ex.getMessage();
if (msg == null || matchesClassCastMessage(msg, event.getClass())) {
// Possibly a lambda-defined listener which we could not resolve the generic event type for
// -> let's suppress the exception and just log a debug message.
Log logger = LogFactory.getLog(getClass());
if (logger.isDebugEnabled()) {
logger.debug("Non-matching event type for listener: " + listener, ex);
}
}
else {
throw ex;
}
}
}
}
總結(jié)
從以上的梳理中,對ApplicationListener的邏輯做一個(gè)總結(jié),對于ApplicationListener整體邏輯梳理如下:
- 定義事件:MyEvent就是自定義的事件
- 定義監(jiān)聽者:MyEventListener就是自定義的MyEvent的事件監(jiān)聽者,只要MyEvent事件被觸發(fā),那么MyEventListener就會自動(dòng)執(zhí)行
- 監(jiān)聽者注冊:將MyEventListener注冊到ApplicationListener集合中
- 發(fā)布事件:將自定的MyEvent發(fā)布,發(fā)布之后監(jiān)聽者就會收到通知
- 讀取注冊的監(jiān)聽者:將前面注冊到ApplicationListner集合的數(shù)據(jù)讀取
- 執(zhí)行監(jiān)聽者監(jiān)聽邏輯:將讀取到的ApplicationListner集合執(zhí)行MyEventListner的onApplicationEvent
以上就是自己關(guān)于Spring中ApplicationListener的理解,更多關(guān)于Spring ApplicationListener的資料請關(guān)注腳本之家其它相關(guān)文章!
- Spring ApplicationListener監(jiān)聽器用法詳解
- Spring ApplicationListener的使用詳解
- SpringBoot中ApplicationEvent和ApplicationListener用法小結(jié)
- SpringBoot ApplicationListener事件監(jiān)聽接口使用問題探究
- Spring事件監(jiān)聽器ApplicationListener源碼詳解
- SpringBoot中的ApplicationListener事件監(jiān)聽器使用詳解
- Spring中ApplicationListener的使用解析
- spring中ApplicationListener的使用小結(jié)
相關(guān)文章
java Long類型轉(zhuǎn)為String類型的兩種方式及區(qū)別說明
這篇文章主要介紹了java Long類型轉(zhuǎn)為String類型的兩種方式及區(qū)別說明,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
java 中模擬TCP傳輸?shù)目蛻舳撕头?wù)端實(shí)例詳解
這篇文章主要介紹了java 中模擬TCP傳輸?shù)目蛻舳撕头?wù)端實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下2017-03-03
基于java實(shí)現(xiàn)DFA算法代碼實(shí)例
這篇文章主要介紹了基于java實(shí)現(xiàn)DFA算法代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09
Spring框架開發(fā)IOC兩種創(chuàng)建工廠方法詳解
這篇文章主要介紹了Spring框架IOC兩種創(chuàng)建工廠方法詳解,文中附含詳細(xì)的代碼示例分別對靜態(tài)方法和實(shí)例方法創(chuàng)建工廠作了簡要的分析2021-09-09
一文總結(jié)RabbitMQ中的消息確認(rèn)機(jī)制
RabbitMQ消息確認(rèn)機(jī)制指的是在消息傳遞過程中,發(fā)送方發(fā)送消息后,接收方需要對消息進(jìn)行確認(rèn),以確保消息被正確地接收和處理,本文為大家整理了RabbitMQ中的消息確認(rèn)機(jī)制,需要的可以參考一下2023-06-06
Nacos配合SpringBoot實(shí)現(xiàn)動(dòng)態(tài)線程池的基本步驟
使用Nacos配合Spring Boot實(shí)現(xiàn)動(dòng)態(tài)線程池,可以讓你的應(yīng)用動(dòng)態(tài)地調(diào)整線程池參數(shù)而無需重啟,這對于需要高度可配置且需要適應(yīng)不同負(fù)載情況的應(yīng)用來說非常有用,本文給大家介紹實(shí)現(xiàn)動(dòng)態(tài)線程池的基本步驟,需要的朋友可以參考下2024-02-02

