3

I would like to register and unregister Spring ApplicationListeners dynamically at run-time and not in a Spring config file.

If I can't remove them dynamically, I'll have a memory leak.

Here's my best guess:

I could call AbstractApplicationContext.getApplicationEventMulticaster().add/removeApplicationListener().

Is that the recommended method?

Does anyone remove listeners dynamically?

4

3 回答 3

4

以下作品。这对于实现 ApplicationListener 并经常创建/销毁的原型 bean 尤其有用。如果您不取消注册它们,您将最终导致内存泄漏。

ApplicationEventMulticaster aem = context.getBean(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);

aem.removeApplicationListener(appListener);
于 2016-07-21T22:32:21.327 回答
1

这可以使用 2 中的方法解决AbstractApplicationEventMulticaster

  1. removeApplicationListenerBean(String listenerBeanName)
  2. removeApplicationListener(ApplicationListener<?> listener)

前任:

//Listener class.
@Component
public class CustomEventListener implements ApplicationListener <CustomEvent>{
    @Override
    public void onApplicationEvent(CustomEvent event) {
      //Your logic goes here
    }
}
//Event Publisher class
@Component
public class CustomEventListener {
    
    @Autowired
    private SimpleApplicationEventMulticaster multicaster;
    
    
    @Autowired
    private CustomEventListener listener;
    
    public void doStuffAndPublishAnEvent(CustomEvent customEvent) {
        multicaster.removeApplicationListener(listener);
        multicaster.removeApplicationListenerBean(listener.getClass().getSimpleName());
        multicaster.multicastEvent(customEvent);
}

注意:SimpleApplicationEventMulticaster 扩展AbstractApplicationEventMulticaster.

于 2020-07-21T13:39:54.183 回答
0

我认为您推荐的方法很好。您还可以使用相同或相似的技术使您的侦听器自行移除。

但是我会问自己另一个问题:为什么我有内存泄漏,有没有办法在不移除监听器的情况下修复它?

于 2013-04-10T15:48:20.477 回答