首页 > 解决方案 > 有什么方法可以使用从上下文返回的结果 ApplicationListener 在使用 EventListeners 注释的方法上找到其他注释?

问题描述

看起来 ApplicationListenerMethodAdapter 隐藏了它被注释的方法,使得无法查看该方法是否可能包含其他注释。还有其他方法可以解决这个问题吗?

如果我有这样的事件监听器

@EventListener
@SomeOtherAnnotation
public void onSomeEvent(SomeEvent e) {
    ...
}

和一个自定义事件多播器

public class CustomEventMulticaster extends SimpleApplicationEventMulticaster {

    public <T extends ApplicationEvent> void trigger(final T event,
        Function<ApplicationListener<T>, Boolean> allowListener) {
        ...
    }

}

仅当存在某些注释时,我才想做类似触发的事情

customEventMulticaster.trigger(someEvent, (listener) -> {
    return listener.getClass().getAnnotation(SomeOtherAnnotation.class) == null;
})

标签: spring

解决方案


有一个 hacky 解决方案 - 就像案例研究一样 - 但请不要那样做。

由于您的应用程序listener实际上是ApplicationListenerMethodAdapter您可以使用反射来获取methodtargetMethod来自该类。从那里您可以获得方法注释。

或多或少(这里没有勾选,纯记事本)

customEventMulticaster.trigger(someEvent, (listener) -> {
    Field f=((ApplicationListenerMethodAdapter)listener).getDeclaredField("method"); // or 'targetMethod' - consult ApplicationListenerMethodAdapter to get the difference
    f.setAccessible(true);
    Method m=f.get(listener); // cast again if required
    anno=m.getAnnotation(yourAnno); // here you can access annotation
    return anno == null;
})

为了使这至少假装不安全,添加 nullchecks 并检查 listener 是否确实可以转换为ApplicationListenerMethodAdapter


推荐阅读