Spring Framework Events
asynchronous, events, java, spring
Solution
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.
Problem
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.