Spring源码——ApplicationListener

10 篇文章 0 订阅
7 篇文章 1 订阅

准备

package cn.example.ext;

public class MyApplicationListener implements  ApplicationListener<ApplicationEvent> {
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        System.out.println("收到事件---" + event);
    }
}
package cn.example.ext;

@Configuration
public class ExtConfig {
    @Bean
    public MyApplicationListener myApplicationListener() {
        return new MyApplicationListener();
    }
    @Bean
    public Blue blue() {
        return new Blue();
    }
}
public class Test01 {
    @Test
    public void test01() {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ExtConfig.class);
        applicationContext.publishEvent(new ApplicationEvent(new String("自定义发布事件")) {
        });
        applicationContext.close();
    }
}

结果:

Blue---Constructor
收到事件---org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@67117f44: startup date [Thu May 14 12:28:12 CST 2020]; root of context hierarchy]
收到事件---cn.example.ext.Test01$1[source=自定义发布事件]
收到事件---org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@67117f44: startup date [Thu May 14 12:28:12 CST 2020]; root of context hierarchy]

源码

ApplicationListener是一个函数式接口,自定义的MyApplicationListener 类实现了这个接口,只要容器中有相关事件的发布,就能调用自定义监听器类中重写的onApplicationEvent()方法。容器发布事件的时机是在:容器刷新完成(即所有的Bean都创建完成了)或者是容器关闭的时候

@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {

	/**
	 * Handle an application event.
	 * @param event the event to respond to
	 */
	void onApplicationEvent(E event);

}

分析

将断点打在MyApplicationListeneronApplicationEvent()方法入口处

收到的第一个事件是ContextRefreshedEvent

步骤1、容器创建完成,执行refresh()方法
在refresh()方法中:

@Override
public void refresh() throws BeansException, IllegalStateException {
	//...
	
	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.
		// 1. 先注册事件的多播器(派发器)
		initApplicationEventMulticaster();
	
		// Initialize other special beans in specific context subclasses.
		onRefresh();
	
		// Check for listener beans and register them.
		// 2. 将实现了ApplicationListener接口的Bean注册到applicationEventMulticaster中
		registerListeners();
	
		// Instantiate all remaining (non-lazy-init) singletons.
		finishBeanFactoryInitialization(beanFactory);
	
		// Last step: publish corresponding event.
		finishRefresh();
	}
	//...
}
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) {
		// 将实现了ApplicationListener接口的Bean注册到applicationEventMulticaster中
		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);
		}
	}
}

步骤 2、完成容器刷新,发布事件
在这里插入图片描述
步骤 3、执行监听器方法
在这里插入图片描述
步骤3.1、执行MyApplicationListeneronApplicationEvent()方法,这样,我们的自定义监听器就能监听到事件
在这里插入图片描述

@EventListener

@EventListener注解可以让任意一个普通类中的方法都能监听到事件

public class UserService {
    @EventListener(classes = ApplicationEvent.class)
    public void listen(ApplicationEvent applicationEvent) {
        System.out.println("监听到事件:"+applicationEvent);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值