Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Framework Events

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.

like image 309
CuriousMind Avatar asked Sep 05 '09 06:09

CuriousMind


2 Answers

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.

like image 61
laffuste Avatar answered Oct 13 '22 01:10

laffuste


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).

like image 43
Oliver Drotbohm Avatar answered Oct 13 '22 00:10

Oliver Drotbohm