首页 > 解决方案 > 在 Spring 中动态删除 @EventListener

问题描述

我想在我的(测试)代码中动态删除或添加 Spring ApplicationListeners。

使用this questionApplicationEventMulticaster中概述的Spring对我有用,但是我感兴趣的具体是使用带注释的方法实现的,这会在运行时产生-Object。ApplicationListener@EventListenerApplicationListenerMethodAdapter

我怎样才能获得这个 bean 的名称,以便我可以使用ApplicationEventMulticaster?

eventMulticaster.removeApplicationListenerBean("NAME_OF_APPLICATION_METHOD_ADAPTER_BEAN")

标签: javaspring

解决方案


从 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


推荐阅读