spring - 有什么方法可以使用从上下文返回的结果 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;
})
解决方案
有一个 hacky 解决方案 - 就像案例研究一样 - 但请不要那样做。
由于您的应用程序listener
实际上是ApplicationListenerMethodAdapter
您可以使用反射来获取method
或targetMethod
来自该类。从那里您可以获得方法注释。
或多或少(这里没有勾选,纯记事本)
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
推荐阅读
- php - 从日历 API 中删除与会者
- asp.net-core - 什么是 Entity Framework Core 中的模型级查询?
- python - 您还需要将对象传递给 views.py 中的模板
- database - JDBC 调用中的参数无效:参数索引超出范围(使用 Ucanaccess)
- linux - 在 Bash 脚本中定义和调用多个项目
- common-lisp - 用于 case 宏的 Defparameter 和相等谓词
- node.js - Redis 在 nodejs 中太慢了?
- python - 尝试使用 python 制作文档扫描仪但无法获得所需的输出图像
- xcode - 将关联域添加到 Expo React-Native 应用程序
- cmake - 如何在 CMake 项目中包含 qwt?