ApplicationListener接口拥有一个子接口SmartApplicationListener,springboot中有一些重要的定制化监听器都是直接或间接的通过实现SmartApplicationListener接口来实现的,这个接口中拥有一个supportsEventType抽象方法,源码如下:
public interface SmartApplicationListener extends ApplicationListener<ApplicationEvent>, Ordered {
boolean supportsEventType(Class<? extends ApplicationEvent> var1);
default boolean supportsSourceType(@Nullable Class<?> sourceType) {
return true;
}
default int getOrder() {
return 2147483647;
}
}
该方法主要通过调用Class类中的isAssignableFrom来判断监听的事件类是否和参数传递的事件类相同或者是参数事件类的子类,如果是则返回true并监听,反之则返回false,不监听。所以,如果我们想监听多个事件,可以建一个事件类数组,将想监听的事件类放入其中,然后通过遍历事件类数组并比较参数事件类。源码如下:
public class CustomeGenericApplicationListener implements SmartApplicationListener {
private static final Class<?>[] EVENT_CLASS = {ApplicationContextInitializedEvent.class, ApplicationPreparedEvent.class};
@Override
public boolean supportsEventType(Class<? extends ApplicationEvent> aClass) {
for (Class cls:EVENT_CLASS) {
if (cls.isAssignableFrom(aClass)){
return true;
}
}
return false;
}
@Override
public void onApplicationEvent(ApplicationEvent applicationEvent) {
System.out.println("CustomeGenericApplicationListener监听到"+applicationEvent.getClass()+"类型事件");
}
}
isAssignableFrom方法:
官方解释:确定此 Class 对象表示的类或接口是否与指定的 Class 参数表示的类或接口相同,或者是其超类或超接口。如果是,则返回 true;否则返回false。如果此 Class 对象表示原始类型,则如果指定的 Class 参数正是此 Class 对象,则此方法返回 true;否则返回false。