Last active
March 17, 2021 19:28
-
-
Save mpaltun/003e4dee311239a241091b1af7ca1fdb to your computer and use it in GitHub Desktop.
Auto register guice services annotated with Subscribe to EvenBus
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.common.eventbus.EventBus; | |
import com.google.common.eventbus.Subscribe; | |
import com.google.inject.AbstractModule; | |
import com.google.inject.TypeLiteral; | |
import com.google.inject.matcher.Matchers; | |
import com.google.inject.spi.InjectionListener; | |
import com.google.inject.spi.TypeEncounter; | |
import com.google.inject.spi.TypeListener; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import java.lang.reflect.Method; | |
class EventBusAutoRegisterSampleModule extends AbstractModule { | |
private static final Logger log = LoggerFactory.getLogger(EventBusAutoRegisterSampleModule.class); | |
@Override | |
protected void configure() { | |
// bind your services which have methods annotated with @Subscribe | |
EventBus eventBus = new EventBus(); | |
bind(EventBus.class).toInstance(eventBus); | |
bindListener(Matchers.any(), new TypeListener() { | |
@Override | |
public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) { | |
encounter.register((InjectionListener<I>) injectee -> { | |
for (Method m : injectee.getClass().getDeclaredMethods()) { | |
if (m.isAnnotationPresent(Subscribe.class)) { | |
log.debug("registering {} as event listener", injectee.getClass()); | |
eventBus.register(injectee); | |
break; | |
} | |
} | |
}); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment