java - 在 Spring 中动态删除 @EventListener
问题描述
我想在我的(测试)代码中动态删除或添加 Spring ApplicationListeners。
使用this questionApplicationEventMulticaster
中概述的Spring对我有用,但是我感兴趣的具体是使用带注释的方法实现的,这会在运行时产生-Object。ApplicationListener
@EventListener
ApplicationListenerMethodAdapter
我怎样才能获得这个 bean 的名称,以便我可以使用ApplicationEventMulticaster
?
eventMulticaster.removeApplicationListenerBean("NAME_OF_APPLICATION_METHOD_ADAPTER_BEAN")
解决方案
从 Spring 5.3.5 开始,@EventListener
获取一个id
属性,然后您可以使用它以编程方式删除侦听器:
eventMulticaster.removeApplicationListeners(l -> l instanceof SmartApplicationListener &&
((SmartApplicationListener) l).getListenerId().startsWith("myrootpackage.mymodule"))
见https://github.com/spring-projects/spring-framework/issues/26638