0

I would like to use Spring Application Events synchronously and asynchronously in the same app.

I know that per default, events are processed synchronously. To change to an async event processing, I have the following config class:

@Configuration
public class SpringEventsConfig {

    @Bean(name = "applicationEventMulticaster")
    public ApplicationEventMulticaster simpleAsyncApplicationEventMulticaster() {
        SimpleApplicationEventMulticaster eventMulticaster =
                new SimpleApplicationEventMulticaster();
        eventMulticaster.setTaskExecutor(new SimpleAsyncTaskExecutor());
        return eventMulticaster;
    }
}

When I inject ApplicationEventPublisher in my class, it holds the configured ApplicationEventMulticaster as a member which works now asynchronously using the SimpleAsyncTaskExecutor.

How can I have another ApplicationEventPublisher at the same time, that is configured in the default way to handle events synchronously?

I was thinking of something like this:

@Qualifier("applicationEventMulticasterAsync")
private ApplicationEventPublisher asyncPublisher;
@Qualifier("applicationEventMulticasterSync")
private ApplicationEventPublisher syncPublisher;

And

@Configuration
public class SpringEventsConfig {

    @Bean(name = "applicationEventMulticasterAsync")
    public ApplicationEventMulticaster simpleAsyncApplicationEventMulticaster() {
        SimpleApplicationEventMulticaster eventMulticaster =
                new SimpleApplicationEventMulticaster();
        eventMulticaster.setTaskExecutor(new SimpleAsyncTaskExecutor());
        return eventMulticaster;
    }
    @Bean(name = "applicationEventMulticasterSync")
    public ApplicationEventMulticaster simpleSyncApplicationEventMulticaster() {
        SimpleApplicationEventMulticaster eventMulticaster =
                new SimpleApplicationEventMulticaster();
        eventMulticaster.setTaskExecutor(new SyncTaskExecutor());
        return eventMulticaster;
    }

}

This does not work obviously. I need two different instances of ApplicationEventPublisher that are differently configured.

Any suggestions on how to do that?

kerner1000
  • 3,382
  • 1
  • 37
  • 57

0 Answers0