Guava EventBus Spring Advanced Integration

Guava EventBus Spring Advanced Integration

In previous tutorials you saw how to use Google Guava EventBus and integrate it with Spring framework. Today I will show you advance technique how to integrate EventBus with Spring.

Project set up is same as previous tutorial but for recap I will be showing here as well:

  • Maven project structure:

Guava EventBus Spring Advanced Integration

  • pom.xml:

If you are working on big project and want to integrate EventBus you should follow below approach where you don’t need to explicitly register your subscriber every time and below class will take care subscription part automatically:

  • EventBusSubscriberProcessor.java: This class implements BeanPostProcessor where you will have to override two method postProcessAfterInitialization and postProcessBeforeInitialization and during application initialization time we are checking if bean method has @Subscribe annotation then register with EventBus:

Important: Don’t use EventBusSubscriberProcessorShorten.java or it’s your choice: Google Guava EventBus is smart enough to find if bean has @Subscribe annotation defined or not then register and you could shorten above EventBusSubscriberProcessor.java as below but my preference is use above class where we are checking @Subscribe annotation:

  • EventBusSubscriberProcessorShorten.java:

  • DeadEventProcessor.java:

  • SendPostThourghClass.java:

  • Subscriber1.java:

  • Subscriber2.java:

  • spring-context.xml:

  • MainApplication.java: Main class to test application:

  • That’s it. Please run MainApplication.java as java application you will see below output:

EventBusSubscriberProcessorShorten.java:

Most important: People who are expert in Spring definitely raise question what if Subscriber is not Singleton then it will cause memory leak and in that case use below class:

  • EventBusPostProcessorSingletonTest.java:

  • For test use this class: Subscriber3NotSingleton.java:

  • For more information please visit Google Guava EventBus official documentation here

download Download Project:  EventBusSpringIntegration

Leave a Reply

Your email address will not be published. Required fields are marked *