最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring ApplicationListener源碼解析

 更新時間:2023年01月15日 14:58:40   作者:陳湯姆  
這篇文章主要為大家介紹了Spring ApplicationListener源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

正文

對于ApplicationListener使用Spring的應(yīng)該也熟悉,因為這就是我們平時學(xué)習(xí)的觀察者模式的實際代表。

Spring基于Java提供的EventListener實現(xiàn)了一套以Spring容器為基礎(chǔ)的觀察者模式的事件監(jiān)聽功能,

用于只要實現(xiàn)Spring提供的接口完成事件的定義和監(jiān)聽者的定義,那么就可以很快速的接入觀察者模式的實現(xiàn)。

ApplicationListener介紹

說ApplicationListener之前先要知道EventListener。

EventListener本身是一個接口,它的作用跟前面講到的Aware類似,都是只定義最頂級的接口,并沒有實習(xí)對應(yīng)的方法,并且該接口也是由JDK提供的,并不是直接由Spring提供,Spring只是基于該接口實現(xiàn)了自己的一套事件監(jiān)聽功能。

在Spring中實現(xiàn)事件監(jiān)聽的接口是ApplicationListener,該接口繼承了EventListener,并做了對應(yīng)的實現(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的使用,因為Spring已經(jīng)做了自己的封裝,并且以Spring容器為基礎(chǔ)做了實現(xiàn),那么開發(fā)者使用時也可以很快的上手,只要簡單的配置即可。

定義事件:

//事件繼承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)聽者實現(xiàn)ApplicationListener,并通過泛型聲明監(jiān)聽的事件
@Component
public class MyEventListener implements ApplicationListener<MyEvent> {
    @Override
    public void onApplicationEvent(MyEvent event) {
        System.out.println("監(jiān)聽MyEvent:收到消息時間:"+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è)計模式中的觀察者模式。

觀察者模式的作用很好的解決了同步交互的問題。

以發(fā)送者和接收者為例,接收者接收消息如果同步場景下需要與發(fā)送者實現(xiàn)同步調(diào)用,但是這樣就導(dǎo)致兩者之間無法解耦,而ApplicationListener就是解決同步的問題,ApplicationListener可以提供半解耦的方式實現(xiàn)兩者之間的交互,即發(fā)送者發(fā)送消息不需要與接收者之間實現(xiàn)同步通知,只要訂閱發(fā)送者的事件即可完成雙發(fā)的交互。

這里為什么是半解耦,因為兩者之間還是有一定交互的,交互的點就在于發(fā)送者的發(fā)送方需要維護一個接收者的集合,發(fā)送方在發(fā)送時需要將具體的接收者放在集合中,在發(fā)送時通過遍歷集合發(fā)送給接收方,執(zhí)行接收方的業(yè)務(wù)處理。

在ApplicationListener這個集合就是public final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<>(); 這個集合中就存儲了接收者的實例,最終會遍歷該集合執(zhí)行接收者的業(yè)務(wù)邏輯。

這里拋一個問題,其實ApplicationListener的功能通過MQ也可以實現(xiàn),那么觀察者模式發(fā)布訂閱模式的區(qū)別是什么呢?歡迎評論區(qū)一起討論!

ApplicationListener注冊

對于ApplicationListener的注冊比較好梳理的,只要找到存儲ApplicationListener的集合就可以知道怎么add集合的。

在Spring中ApplicationListener的注冊也是在Spring中實現(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í)行自然也很好梳理了, 畢竟使用的都是同一個集合。

ApplicationListener的執(zhí)行其實就是觀察者的執(zhí)行,也就是在使用篇章中的MyEventListener,在MyEventListener中重寫了onApplicationEvent,其中實現(xiàn)了自己的邏輯,那么執(zhí)行就是將MyEventListener中重寫的方式如何在沒有同步調(diào)用的情況下執(zhí)行。

執(zhí)行的實現(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的邏輯做一個總結(jié),對于ApplicationListener整體邏輯梳理如下:

  • 定義事件:MyEvent就是自定義的事件
  • 定義監(jiān)聽者:MyEventListener就是自定義的MyEvent的事件監(jiān)聽者,只要MyEvent事件被觸發(fā),那么MyEventListener就會自動執(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)文章!

相關(guān)文章

  • SpringCloudAlibaba極簡入門整合Grpc代替OpenFeign的詳細過程

    SpringCloudAlibaba極簡入門整合Grpc代替OpenFeign的詳細過程

    本文介紹了如何將OpenFeign替換為Grpc進行服務(wù)通信,并通過實際案例展示了如何在Spring?Boot項目中整合Grpc,Grpc提供了高性能、低延遲的服務(wù)間通信,而OpenFeign則注重簡化開發(fā)流程,感興趣的朋友跟隨小編一起看看吧
    2024-11-11
  • Spring?Boot自定義監(jiān)控指標的詳細過程

    Spring?Boot自定義監(jiān)控指標的詳細過程

    這篇文章主要介紹了Spring?Boot如何自定義監(jiān)控指標?,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-03-03
  • java如何獲取本機IP地址

    java如何獲取本機IP地址

    這篇文章主要為大家詳細介紹了java如何獲取本機IP地址,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-03-03
  • Java基礎(chǔ)知識之I/O流和File類文件操作

    Java基礎(chǔ)知識之I/O流和File類文件操作

    眾所周知java語言提供給程序員非常多的包供編程時使用,方便又快捷,下面這篇文章主要給大家介紹了關(guān)于Java基礎(chǔ)知識之I/O流和File類文件操作的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-04-04
  • spring AOP自定義注解方式實現(xiàn)日志管理的實例講解

    spring AOP自定義注解方式實現(xiàn)日志管理的實例講解

    下面小編就為大家分享一篇spring AOP自定義注解方式實現(xiàn)日志管理的實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-01-01
  • SpringMVC請求參數(shù)的使用總結(jié)

    SpringMVC請求參數(shù)的使用總結(jié)

    在日常使用SpringMVC進行開發(fā)的時候,有可能遇到前端各種類型的請求參數(shù),本文主要接介紹了SpringMVC請求參數(shù)的使用總結(jié),感興趣的可以了解一下
    2021-06-06
  • SSL證書部署+SpringBoot實現(xiàn)HTTPS安全訪問的操作方法

    SSL證書部署+SpringBoot實現(xiàn)HTTPS安全訪問的操作方法

    文章介紹了SSL和HTTPS的工作原理,包括握手階段和安全數(shù)據(jù)傳輸階段,通過模擬HTTPS請求,展示了如何生成自簽名證書并配置Spring Boot應(yīng)用程序以支持HTTPS,總結(jié)指出,SSL和HTTPS對于保護網(wǎng)絡(luò)安全至關(guān)重要,感興趣的朋友一起看看吧
    2025-02-02
  • SpringBoot隨機數(shù)設(shè)置及參數(shù)間引用的操作步驟

    SpringBoot隨機數(shù)設(shè)置及參數(shù)間引用的操作步驟

    在Spring Boot配置文件中設(shè)置屬性時,除了可以像前面示例中顯示的配置屬性值外,還可以使用隨機值和參數(shù)間引用對屬性值進行設(shè)置。下面給大家介紹SpringBoot參數(shù)間引用隨機數(shù)設(shè)置的操作步驟,感興趣的朋友一起看看吧
    2021-06-06
  • spring security登錄成功后跳轉(zhuǎn)回登錄前的頁面

    spring security登錄成功后跳轉(zhuǎn)回登錄前的頁面

    這篇文章主要介紹了spring security登錄成功后跳轉(zhuǎn)回登錄前的頁面,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • mybatis 批量將list數(shù)據(jù)插入到數(shù)據(jù)庫的實現(xiàn)

    mybatis 批量將list數(shù)據(jù)插入到數(shù)據(jù)庫的實現(xiàn)

    這篇文章主要介紹了mybatis 批量將list數(shù)據(jù)插入到數(shù)據(jù)庫的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07

最新評論

灌阳县| 柳河县| 固原市| 莆田市| 通海县| 游戏| 禄丰县| 昭平县| 涟源市| 广平县| 荔浦县| 恩平市| 永年县| 晋中市| 扬州市| 新兴县| 东乌| 准格尔旗| 疏附县| 睢宁县| 湄潭县| 光泽县| 海阳市| 田林县| 临潭县| 化隆| 宜阳县| 苍南县| 松桃| 长治市| 汝州市| 高陵县| 周口市| 邻水| 临城县| 大英县| 温宿县| 夹江县| 阿坝| 新干县| 边坝县|