Tuesday, December 04, 2012

Guicing your jars, part 2

In Guicing your jars I mention using Java's service loader feature to automate finding modules for Guice, along these lines:

public class MetaInfServicesModule
        extends AbstractModule {
    @Override
    protected void configure() {
        for (final Module module : ServiceLoader.load(Module.class))
            install(module);
    }
}

What I did not mention was the secret sauce, Kohsuke's MetaInfServices annotation processor which creates the META-INF/services file for you:

@MetaInfServices(Module.class)
public class FooModule
        extends AbstractModule {
    @Override
    protected void configure() {
        // Awesome foo-ness here
    }
}

Now using your Maven runtime dependencies to control the classpath, Guice automatically installs your modules:

Guice.createInjector(new MetaInfServicesModule());

(Dependencies between modules is beyond the scope of this post!)

No comments: