Java Spring如何过滤ApplicationEvents

Java Spring如何过滤ApplicationEvents,java,spring,generics,Java,Spring,Generics,我一直在研究Spring中的事件侦听器,并偶然发现了这个接口。哪种方法可以使用泛型,例如: public class CStopEventHandler implements ApplicationListener<ContextStoppedEvent>{ public void onApplicationEvent(ContextStoppedEvent event) { System.out.println("ContextStoppedEvent

我一直在研究Spring中的事件侦听器,并偶然发现了这个接口。哪种方法可以使用泛型,例如:

public class CStopEventHandler 
   implements ApplicationListener<ContextStoppedEvent>{

   public void onApplicationEvent(ContextStoppedEvent event) {
      System.out.println("ContextStoppedEvent Received");
   }
}
公共类CStopEventHandler
实现ApplicationListener{
ApplicationEvent上的公共无效(ContextStoppedEvent事件){
System.out.println(“接收到ContextStoppedEvent”);
}
}

当泛型类型在运行时被擦除时,事件调度器如何在运行时知道
ApplicationListener
的类型?它是否使用反射或类似的方法检查方法签名?

在大多数代码库中,事件侦听器存储在不同的容器中,例如:

private List<ApplicationListener<ContextStoppedEvent>> contextStoppedEventListeners;
private List contextstoppedeventlisters;

private列出其他事件监听器;

在大多数代码库中,事件侦听器存储在不同的容器中,例如:

private List<ApplicationListener<ContextStoppedEvent>> contextStoppedEventListeners;
private List contextstoppedeventlisters;

private列出其他事件监听器;

Spring将使用它的
simpleapplicationeventmulticast
使用继承自
AbtractApplicationEventMulticaster的
getApplicationListeners(ApplicationEvent事件)
方法获取事件侦听器。要查看监听器是否支持给定的事件类型,它通常将监听器包装在一个
GenericApplicationListenerAdapter
中,该适配器提供
supportsEventType(类Spring将使用它的
SimpleApplicationEventMultiMaster
使用
getApplicationListeners(ApplicationEvent事件)获取事件监听器
方法继承自
AbtractApplicationEventMulticaster
。要查看侦听器是否支持给定的事件类型,它通常将侦听器包装在
通用应用程序ListenerAdapter
中,该适配器提供
支持SeventType(类您是对的。Spring(当然还有整个Java)在运行时使用反射从提供的类中确定
泛型类型

在我们的案例中,应用程序上下文扫描bean以查找
ApplicationListener
implenetation,并将它们全部存储在列表中

当您引发
ApplicationEvent
时,将处理
ApplicationListener
s列表,以确定特定事件类型的侦听器,并将它们存储在缓存中以供将来优化

但是在此之前,
ApplicationListener
被包装到
GenericApplicationListenerAdapter
以使用提供的
ApplicationListener
中的泛型类型调用其
supportsEventType

我想你想知道这个方法:

static Class<?> resolveDeclaredEventType(Class<?> listenerType) {
        return GenericTypeResolver.resolveTypeArgument(listenerType, ApplicationListener.class);
    }
静态类resolveDeclaredEventType(类listenerType){
返回GenericTypeResolver.resolveTypeArgument(listenerType,ApplicationListener.class);
}
当您需要在运行时了解
泛型类型时,可以在代码的任何位置使用
泛型解析器

您是对的。Spring(当然,整个Java)在运行时使用反射从提供的类中确定
泛型类型

在我们的案例中,应用程序上下文扫描bean以查找
ApplicationListener
implenetation,并将它们全部存储在列表中

当您引发
ApplicationEvent
时,将处理
ApplicationListener
s列表,以确定特定事件类型的侦听器,并将它们存储在缓存中以供将来优化

但是在此之前,
ApplicationListener
被包装到
GenericApplicationListenerAdapter
以使用提供的
ApplicationListener
中的泛型类型调用其
supportsEventType

我想你想知道这个方法:

static Class<?> resolveDeclaredEventType(Class<?> listenerType) {
        return GenericTypeResolver.resolveTypeArgument(listenerType, ApplicationListener.class);
    }
静态类resolveDeclaredEventType(类listenerType){
返回GenericTypeResolver.resolveTypeArgument(listenerType,ApplicationListener.class);
}
当您需要在运行时了解
泛型类型时,可以在代码的任何位置使用
GenericTypeResolver