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

Spring的事件發(fā)布與監(jiān)聽(tīng)方式案例講解

 更新時(shí)間:2023年03月27日 11:16:16   作者:T.Y.Bao  
今天去官網(wǎng)查看spring?boot資料時(shí),在特性中看見(jiàn)了系統(tǒng)的事件及監(jiān)聽(tīng)章節(jié),所以下面這篇文章主要給大家介紹了關(guān)于SpringBoot事件發(fā)布和監(jiān)聽(tīng)的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下

事件

主要代碼在org.springframework.context,org.springframework.context.event包中

事件發(fā)布與監(jiān)聽(tīng)主要包含以下角色:

  • 事件:ApplicationEvent
  • 事件監(jiān)聽(tīng)器:ApplicationListener SmartApplicationListener GenericApplicationListener
  • 事件發(fā)布器:ApplicationEventPublisher
  • 事件廣播器:ApplicationEventMulticaster

引入ApplicationListener有兩種方式:

  • spring spi
  • 手動(dòng)注入bean

手動(dòng)注入bean有兩種方式:

  • 類(lèi)上注解@Component等注解+實(shí)現(xiàn)ApplicationListener接口
  • 類(lèi)上注解@Component等注解+方法上注解@EventListener

案例如下:

// bean注入方式一,實(shí)現(xiàn)ApplicationListener+@Component注入bean
@Component
public class HelloEventListener implements SmartApplicationListener {
    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
        return false;
    }
    @Override
    public void onApplicationEvent(ApplicationEvent event) {

    }
}
// bean注入方式二,@EventListener+@Component
@Component
public class Test {
    @EventListener
    public void listen(Object obj){
        System.out.println("listening");
    }
    @EventListener(classes={ApplicationEvent.class},condition="springEL")
    public void listen(ApplicationEvent event){
        System.out.println("listening");
    }
}

關(guān)于@EventListener注解方法注入是通過(guò)EventListenerMethodProcessor的一個(gè)SmartInitializingSingleton,同時(shí)該類(lèi)也是一個(gè)BeanFactoryPostProcessor,但掃描@EventListener方法和注入邏輯不在該接口的postProcess方法中,而是SmartInitializingSingleton接口的afterSingletonsInstantiated方法。

關(guān)于SmartInitializingSingleton的接口作用注釋如下:

Callback interface triggered at the end of the singleton pre-instantiation phase during BeanFactory bootstrap. This interface can be implemented by singleton beans in order to perform some initialization after the regular singleton instantiation algorithm, avoiding side effects with accidental early initialization (e.g. from ListableBeanFactory.getBeansOfType calls). In that sense, it is an alternative to InitializingBean which gets triggered right at the end of a bean’s local construction phase.

看到其作用和 InitializingBean 類(lèi)似,用于構(gòu)造函數(shù)后的初始化操作,不過(guò)該接口是所有bean被創(chuàng)建之后被調(diào)用。在所有 bean的構(gòu)造方法、初始化(@PostConstruct、InitializingBean)、BeanPostProcessor都執(zhí)行完畢后再執(zhí)行該接口方法,注意是所有bean都執(zhí)行完這些方法。

Invoked right at the end of the singleton pre-instantiation phase, with a guarantee that all regular singleton beans have been created already.

public class EventListenerMethodProcessor
		implements SmartInitializingSingleton, ApplicationContextAware, BeanFactoryPostProcessor {
	// 負(fù)責(zé)設(shè)置EventListenerFactory
	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		// 回調(diào)beanFactory賦值
		this.beanFactory = beanFactory;
		// 拿到所有的EventListenerFactory
		Map<String, EventListenerFactory> beans = beanFactory.getBeansOfType(EventListenerFactory.class, false, false);
		List<EventListenerFactory> factories = new ArrayList<>(beans.values());
		AnnotationAwareOrderComparator.sort(factories);
		// 設(shè)置eventListenerFactories
		this.eventListenerFactories = factories;
	}
	@Override
	public void afterSingletonsInstantiated() {
		...
		processBean(beanName, type);
		...
	}
	private void processBean(final String beanName, final Class<?> targetType) {
		if (
				// 不包含@EventListener的類(lèi)的備忘錄是否有該類(lèi)型
				!this.nonAnnotatedClasses.contains(targetType) &&
				// 該類(lèi)型的type, method or field 是否能被注解@EventListener
				AnnotationUtils.isCandidateClass(targetType, EventListener.class) &&
				// 不能是org.springframework開(kāi)頭的類(lèi),或者被注解了@Component,注意是或者
				!isSpringContainerClass(targetType)
			) {
			// 提取所有的方法
			Map<Method, EventListener> annotatedMethods = null;
			try {
				annotatedMethods = MethodIntrospector.selectMethods(targetType,
						(MethodIntrospector.MetadataLookup<EventListener>) method ->
								AnnotatedElementUtils.findMergedAnnotation(method, EventListener.class));
			}
			...
			if (CollectionUtils.isEmpty(annotatedMethods)) {
				// 備忘錄,加入已掃描的沒(méi)有注解@EventListener的類(lèi)
				this.nonAnnotatedClasses.add(targetType);
				...
			}
			else {
				// Non-empty set of methods
				ConfigurableApplicationContext context = this.applicationContext;
				Assert.state(context != null, "No ApplicationContext set");
				List<EventListenerFactory> factories = this.eventListenerFactories;
				Assert.state(factories != null, "EventListenerFactory List not initialized");
				for (Method method : annotatedMethods.keySet()) {
					for (EventListenerFactory factory : factories) {
						if (factory.supportsMethod(method)) {
							Method methodToUse = AopUtils.selectInvocableMethod(method, context.getType(beanName));	
							// 生成ApplicationListener
							ApplicationListener<?> applicationListener =
									factory.createApplicationListener(beanName, targetType, methodToUse);
							if (applicationListener instanceof ApplicationListenerMethodAdapter) {
								((ApplicationListenerMethodAdapter) applicationListener).init(context, this.evaluator);
							}
							context.addApplicationListener(applicationListener);
							break;
						}
	...

ApplicationListener監(jiān)聽(tīng)到事件后的執(zhí)行是同步過(guò)程,如果需要異步,可搭配@Async+@EventListener

事務(wù)消息監(jiān)聽(tīng)器

spring-tx包下提供TransactionalApplicationListener接口和@TransactionalEventListener注解。

TransactionalApplicationListener接口:An ApplicationListener that is invoked according to a TransactionPhase. NOTE: Transactional event listeners only work with thread-bound transactions managed by a PlatformTransactionManager.

到此這篇關(guān)于Spring的事件發(fā)布與監(jiān)聽(tīng)方式案例講解的文章就介紹到這了,更多相關(guān)Spring事件發(fā)布與監(jiān)聽(tīng)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Spring?Boot如何接入Security權(quán)限認(rèn)證服務(wù)

    Spring?Boot如何接入Security權(quán)限認(rèn)證服務(wù)

    Spring Security?是一個(gè)高度可定制的身份驗(yàn)證和訪(fǎng)問(wèn)控制的框架,提供了完善的認(rèn)證機(jī)制和方法級(jí)的授權(quán)功能,本文通過(guò)案例將Spring Security整合到SpringBoot中,要實(shí)現(xiàn)的功能就是在認(rèn)證服務(wù)器上登錄,然后獲取Token,再訪(fǎng)問(wèn)資源服務(wù)器中的資源,感興趣的朋友一起看看吧
    2024-07-07
  • 基于Spring的RPC通訊模型的使用與比較

    基于Spring的RPC通訊模型的使用與比較

    這篇文章主要介紹了基于Spring的RPC通訊模型的使用與比較,詳細(xì)的介紹了RMI、Caucho的Hessian和Burlap以及Spring自帶的HTTP invoker,感興趣的可以了解一下
    2018-09-09
  • 最新評(píng)論

    吴堡县| 宝清县| 乌鲁木齐市| 潍坊市| 米林县| 布拖县| 青河县| 丰城市| 安陆市| 庆云县| 苏尼特左旗| 郸城县| 综艺| 宜昌市| 南召县| 合川市| 天长市| 靖远县| 准格尔旗| 玛沁县| 贞丰县| 乐昌市| 德兴市| 蒙自县| 哈巴河县| 新绛县| 如皋市| 安乡县| 上虞市| 漯河市| 丰镇市| 正镶白旗| 宽甸| 芦山县| 肥东县| 平舆县| 棋牌| 武鸣县| 大宁县| 汾阳市| 吴川市|