class EventListenerMethodProcessor
implements SmartInitializingSingleton, ApplicationContextAware, BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
this.beanFactory = beanFactory;
// 获取EventListenerFactory的Bean
// 在AnnotationConfigUtils.registerAnnotationConfigProcessors(BeanDefinitionRegistry,Object)方法中,和EventListenerMethodProcessor一起保存的
// RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
// RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
Map<String, EventListenerFactory> beans = beanFactory.getBeansOfType(EventListenerFactory.class, false, false);
List<EventListenerFactory> factories = new ArrayList<>(beans.values());
// 排序
AnnotationAwareOrderComparator.sort(factories);
// 保存事件监听的工厂的Bean
this.eventListenerFactories = factories;
}
// 成为bean之后的回调
@Override
public void afterSingletonsInstantiated() {
ConfigurableListableBeanFactory beanFactory = this.beanFactory;
// 找出所有的Bean
String[] beanNames = beanFactory.getBeanNamesForType(Object.class);
for (String beanName : beanNames) {
// 确定beanName是否是在作用域代理中引用目标bean的名称
// 说白了当前beanName是不是被代理了,如果是被代理了,那么beanName就不是原始Bean的beanName,是添加了scopedTarget.为前缀的beanName
// 在原型bean中可能会用到Scope的@Bean的代理
if (!ScopedProxyUtils.isScopedTarget(beanName)) {
// 如果不是scope代理,获取真实beanName对应的目标类的类型
Class<?> type = AutoProxyUtils.determineTargetClass(beanFactory, beanName);
if (type != null) {
// 如果目标类型是ScopedObject类,表示当前类也是一个Scoped的代理类
if (ScopedObject.class.isAssignableFrom(type)) {
// 还需要再次找到最原始的类型
Class<?> targetClass = AutoProxyUtils.determineTargetClass(beanFactory, ScopedProxyUtils.getTargetBeanName(beanName));
if (targetClass != null) {
type = targetClass;
}
}
// 处理Bean
processBean(beanName, type);
{
// 校验这些类不能是Spring内置的类,或者类中没有EventListener注解的类都不会被处理
if (!this.nonAnnotatedClasses.contains(targetType) && AnnotationUtils.isCandidateClass(targetType, EventListener.class) && !isSpringContainerClass(targetType)) {
// 找到类中所有添加了EventListener注解的方法
Map<Method, EventListener> annotatedMethods = MethodIntrospector.selectMethods(targetType, (MethodIntrospector.MetadataLookup<EventListener>) method -> AnnotatedElementUtils.findMergedAnnotation(method, EventListener.class));
// 如果当前类没有EventListener注解,保存下来,下次可以直接忽略了
if (CollectionUtils.isEmpty(annotatedMethods)) {
this.nonAnnotatedClasses.add(targetType);
}
// 存在EventListener注解
else {
ConfigurableApplicationContext context = this.applicationContext;
// 获取EventListenerFactory,在postProcessBeanFactory就处理了
List<EventListenerFactory> factories = this.eventListenerFactories;
// 遍历所有EventListener的方法
for (Method method : annotatedMethods.keySet()) {
// 遍历所有的EventListenerFactory工厂
// 默认的情况只有一个工厂,为DefaultEventListenerFactory,处理普通的EventListener注解
// Spring还提供了一个TransactionalEventListenerFactory,用来处理TransactionalEventListener,带有事务的监听器
for (EventListenerFactory factory : factories) {
// 找到可以处理当前方法的事件工厂
if (factory.supportsMethod(method)) {
// 如果可以处理,校验方法是不是私有的,静态的,如果有就会抛出异常
Method methodToUse = AopUtils.selectInvocableMethod(method, context.getType(beanName));
// 使用事件工厂根据方法创建对应的监听器,这个ApplicationListener才是处理事件的核心接口,执行事件就是回调onApplicationEvent方法
ApplicationListener<?> applicationListener = factory.createApplicationListener(beanName, targetType, methodToUse);
// 如果是ApplicationListenerMethodAdapter适配器类型
// DefaultEventListenerFactory,TransactionalEventListenerFactory这两种工厂,都是返回ApplicationListenerMethodAdapter类型的监听器
// DefaultEventListenerFactory
// return new ApplicationListenerMethodAdapter(beanName, type, method);
// TransactionalEventListenerFactory这两种工厂
// return new ApplicationListenerMethodTransactionalAdapter(beanName, type, method);
if (applicationListener instanceof ApplicationListenerMethodAdapter) {
// 将上下文和事件表达式计算器给applicationListener
((ApplicationListenerMethodAdapter) applicationListener).init(context, this.evaluator);
}
// 将监听器保存到spring容器中,添加到了spring容器,就等着发布事件,执行监听器的onApplicationEvent回调
context.addApplicationListener(applicationListener);
break;
}
}
}
}
}
}
}
}
}
}
}
// 现在讲@TransactionalEventListener的实现
// 因为@EventListener没有什么特殊,使用的就是DefaultEventListenerFactory来创建监听器
// 如果发布事件,最终会执行到对应的监听器
// 上面初始化的逻辑存在执行ApplicationListener<?> applicationListener = factory.createApplicationListener(beanName, targetType, methodToUse);
// 调用工厂创建监听器
/**
* 讲ApplicationListenerMethodTransactionalAdapter监听器,发布了事件会执行ApplicationListenerMethodTransactionalAdapter的onApplicationEvent事件
*/
class TransactionalEventListenerFactory implements EventListenerFactory, Ordered {
@Override
public boolean supportsMethod(Method method) {
return AnnotatedElementUtils.hasAnnotation(method, TransactionalEventListener.class);
}
@Override
public ApplicationListener<?> createApplicationListener(String beanName, Class<?> type, Method method) {
// ApplicationListenerMethodAdapter为ApplicationListenerMethodTransactionalAdapter父类
return new ApplicationListenerMethodTransactionalAdapter(beanName, type, method);
{
public void onApplicationEvent (ApplicationEvent event){
// 如果事务创建了,并且是活动的
if (TransactionSynchronizationManager.isSynchronizationActive() && TransactionSynchronizationManager.isActualTransactionActive()) {
// 创建一个TransactionSynchronizationEventAdapter对象
// TransactionSynchronizationEventAdapter是一个TransactionSynchronization事务同步信息
// 原理就是再别的事务执行的时候,会执行TransactionSynchronizationManager事务同步管理器存在当前线程的所有TransactionSynchronization(事务)信息
// 然后回调TransactionSynchronization的钩子方法,在钩子方法中执行事件
TransactionSynchronization transactionSynchronization = createTransactionSynchronization(event);
{
return new TransactionSynchronizationEventAdapter(this, event, this.annotation.phase());
// 保存了监听器,事件,和触发时机信息
TransactionSynchronizationEventAdapter(ApplicationListenerMethodAdapter listener, ApplicationEvent event, TransactionPhase phase)
{
this.listener = listener;
this.event = event;
this.phase = phase;
}
}
public void beforeCommit ( boolean readOnly){
if (this.phase == TransactionPhase.BEFORE_COMMIT) {
// 调用监听器的执行事件方法
processEvent();
}
}
public void afterCompletion ( int status){
if (this.phase == TransactionPhase.AFTER_COMMIT && status == STATUS_COMMITTED) {
// 调用监听器的执行事件方法
processEvent();
} else if (this.phase == TransactionPhase.AFTER_ROLLBACK && status == STATUS_ROLLED_BACK) {
// 调用监听器的执行事件方法
processEvent();
} else if (this.phase == TransactionPhase.AFTER_COMPLETION) {
// 调用监听器的执行事件方法
processEvent();
}
}
// 执行当前类的processEvent方法
protected void processEvent () {
// 详见下面ApplicationListenerMethodAdapter中的processEvent
this.listener.processEvent(this.event);
}
// 保存当前事务信息到当前线程
TransactionSynchronizationManager.registerSynchronization(transactionSynchronization);
}
// 如果不存在事务,设置了fallbackExecution为true,表示可以在没有事务中执行
else if (this.annotation.fallbackExecution()) {
// 直接执行事件,详见下面ApplicationListenerMethodAdapter中的processEvent
processEvent(event);
}
}
}
}
}
/**
*
*/
class DefaultEventListenerFactory implements EventListenerFactory, Ordered {
@Override
public boolean supportsMethod(Method method) {
return true;
}
@Override
public ApplicationListener<?> createApplicationListener(String beanName, Class<?> type, Method method) {
// ApplicationListenerMethodAdapter为ApplicationListenerMethodTransactionalAdapter父类
return new ApplicationListenerMethodAdapter(beanName, type, method);
{
public void onApplicationEvent (ApplicationEvent event){
// 执行事件
processEvent(event);
{
// 解析参数
Object[] args = resolveArguments(event);
// 是否需要处理,根据条件,参数匹配
if (shouldHandle(event, args)) {
// 开始反射执行
Object result = doInvoke(args);
// 如果有返回值,又会将返回值作为事件发布
if (result != null) {
// 处理结果
handleResult(result);
{
// 如果返回值是CompletionStage,还需要处理一次
if (result instanceof CompletionStage) {
(CompletionStage<?>) result).whenComplete((event, ex) -> {
if (ex != null) {
// 处理异常信息
}
handleAsyncError(ex);
// 再次发布事件
if (event != null) {
publishEvent(event);
}
}
}
// 发布所有的事件
if (result instanceof ListenableFuture) {
((ListenableFuture<?>) result).addCallback(this::publishEvents, this::handleAsyncError);
} else {
// 发布事件
publishEvents(result);
{
// 如果返回值是一个数组
if (result.getClass().isArray()) {
// 将数组元素一个一个发布事件
Object[] events = ObjectUtils.toObjectArray(result);
for (Object event : events) {
publishEvent(event);
}
}
// 是集合
if (result instanceof Collection<?>) {
Collection<?> events = (Collection<?>) result;
for (Object event : events) {
publishEvent(event);
}
}
// 普通大单个返回值
else {
publishEvent(result);
{
// 发布事件
this.applicationContext.publishEvent(event);
}
}
}
}
}
}
}
}
}
}
}
}
@EventListener注解和@TransactionalEventListener注解EventListenerMethodProcessor原理
于 2024-03-05 17:16:59 首次发布