Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for dynamically removing a Spring ApplicationListener?

Tags:

java

spring

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?

like image 876
BPS Avatar asked Dec 22 '25 17:12

BPS


1 Answers

The following works. This is especially useful for prototype beans that implement ApplicationListener and are created/destroyed frequently. If you don't unregister them, you'll end up with a memory leak.

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

aem.removeApplicationListener(appListener);
like image 171
user1500 Avatar answered Dec 24 '25 08:12

user1500