I was reading through Spring Framework documentation and found a section on raising events in Spring using ApplicationContext
. After reading a few paragraphs I found that Spring events are raised synchronously. Is there any way to raise asynchronous events? your help is much appreciated. I am looking something similar which would help me to complete my module.
Simplest asynchronous ApplicationListener
:
Publisher:
@Autowired
private SimpleApplicationEventMulticaster simpleApplicationEventMulticaster;
@Autowired
private AsyncTaskExecutor asyncTaskExecutor;
// ...
simpleApplicationEventMulticaster.setTaskExecutor(asyncTaskExecutor);
// ...
ApplicationEvent event = new ApplicationEvent("");
simpleApplicationEventMulticaster.multicastEvent(event);
Listener:
@Component
static class MyListener implements ApplicationListener<ApplicationEvent>
public void onApplicationEvent(ApplicationEvent event) {
// do stuff, typically check event subclass (instanceof) to know which action to perform
}
}
You should subclass ApplicationEvent
with your specific events. You can configure SimpleApplicationEventMulticaster
and its taskExecutor
in an XML file.
You might want to implement ApplicationEventPublisherAware
in your listener class and pass a source object (instead of empty string) in the event constructor.
Alternative notification strategies can be achieved by implementing ApplicationEventMulticaster
(see Javadoc) and its underlying (helper) class hierarchy. Typically you use either a JMS based notification mechanism (as David already suggested) or attach to Spring's TaskExecuter
abstraction (see Javadoc).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With