CuriousMind
CuriousMind

Reputation: 3173

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.

Upvotes: 11

Views: 8587

Answers (4)

laffuste
laffuste

Reputation: 17085

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.

Upvotes: 6

Amit
Amit

Reputation: 2130

Try this override the ApplicationEventMulticaster bean in resources.groovy so that it uses a thread pool:

Some thing like this worked for me, i.e. I used

import java.util.concurrent.*
import org.springframework.context.event.*

beans = {
    applicationEventMulticaster(SimpleApplicationEventMulticaster) {
        taskExecutor = Executors.newCachedThreadPool()
    }
}

Upvotes: 0

Oliver Drotbohm
Oliver Drotbohm

Reputation: 83081

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

Upvotes: 3

David Rabinowitz
David Rabinowitz

Reputation: 30448

Spring itself (AFAIK) work synchronously, but what you can do is to create your own ApplicationListener proxy - a class that implements this interface but instead of handling the event it just delegates it by sending to another (or new) thread, sending JMS message, etc.

Upvotes: 2

Related Questions