Skip to content

Module Dependencies

elandau edited this page Dec 18, 2014 · 5 revisions

Overview

Governator simplifies Guice module transitive dependencies using the @Modules annotation as an alternative to Guice’s binder.install(). Using @Modules a module may specify its dependent module classes instead of module instances required by binder.install(). This is an alternative to @AutoBindSingleton which tends to pull in more bindings than an application requires or needs.

Defining module dependencies

An application is likely to define a single module class which includes all of its direct dependent modules. This top level module’s Guice module dependencies are specified using the @Modules annotation.

// This application has a dependency on LibraryAModule and LibraryBModule. 
// It will pull in LibraryCModule transitively.  
@Modules(include={LibraryAModule.class, LibraryBModule.class}
public class MyApplicationModule extends AbstractModule {
    public void configure() { 
        // Bindings for MyApplication
    }
}

@Modules(include={LibraryCModule.class})
public class LibraryAModule extends AbstractModule {
    public void configure() { 
        // Bindings for LibraryA
    }
}

@Modules(include={LibraryCModule.class})
public class LibraryBModule extends AbstractModule {
    public void configure() { 
        // Bindings for LibraryB
    }
}

public class LibraryCModule extends AbstractModule {
    public void configure() { 
        // Bindings for LibraryC
    }
}

// When creating the injector it is only necessary to specify the top level module
LifecycleInjector.builder()
   .withAdditionalModuleClasses(ApplicationModule.class)
   .build().createInjector();

Overriding bindings

A complex module dependency graph may eventually create conflicting bindings. Governator installs all bindings in module dependency order (derived from the @Modules annotations) just like Guice instantiates object in dependency order. This property makes it possible to have each parent module override bindings from its transitive dependencies. This feature is disabled by default by can be turned on like this,

LifecycleInjector.builder()
    .withModuleTransformer(new OverrideAllDuplicateBindings())
    ...