Wednesday, April 28, 2010

Guicing your jars

Through the magic of ServiceLoader you can automate the wiring of your classpath components:

public static void main(final String... args) {
    final Injector injector = Guice.createInjector(
            ServiceLoader.load(Module.class).iterator());
    // Use injector here, etc.
}

For each jar or classpath component, include a META-INF/services/com.google.inject.Module file containing the class name of a Guice module which can configure the jar, e.g., hm.binkley.rice.MobModule.

This makes your jars auto-configuring. Merely including them in the classpath is sufficient to be injected into your application. You will find multibindings useful for each jar to provide a well-known list of services without them colliding.

1 comment:

patient renter said...

This is the exact technique I used in the past, but since I've moved to using an annotation processor (adapted from sezpoz) to auto-load my Guice modules and register other services.