Class BoundFieldModule

  • All Implemented Interfaces:

    public final class BoundFieldModule
    extends Object
    implements Module
    A Guice module that automatically adds Guice bindings into the injector for all Bind annotated fields of a specified object.

    This module is intended for use in tests to reduce the amount of boilerplate code needed to bind local fields (usually mocks) for injection.

    The following rules are followed in determining how fields are bound using this module:

    Example use:

     public class TestFoo {
       // bind(new TypeLiteral<List<Object>>() {}).toInstance(listOfObjects);
       {@literal @}Bind private List<Object> listOfObjects = Lists.of();
       // private String userName = "string_that_changes_over_time";
       // bind(String.class).toProvider(new Provider() { public String get() { return userName; }});
       {@literal @}Bind(lazy = true) private String userName;
       // bind(SuperClass.class).toInstance(aSubClass);
       {@literal @}Bind(to = SuperClass.class) private SubClass aSubClass = new SubClass();
       // bind(String.class).annotatedWith(MyBindingAnnotation.class).toInstance(myString);
       {@literal @}Bind
       {@literal @}MyBindingAnnotation
       private String myString = "hello";
       // bind(Object.class).toProvider(myProvider);
       {@literal @}Bind private Provider<Object> myProvider = getProvider();
       {@literal @}Before public void setUp() {
    See Also:
    • Method Detail

      • of

        public static BoundFieldModule of​(Object instance)
        Create a BoundFieldModule which binds the Bind annotated fields of instance.
        instance - the instance whose fields will be bound.
        a module which will bind the Bind annotated fields of instance.
      • getBoundFields

        public ImmutableSet<BoundFieldModule.BoundFieldInfo> getBoundFields()
        Returns information about the fields bound by this module.

        Note this is available immediately after construction, fields with errors won't be included but their error messages will be deferred to configuration time.

        Fields with invalid null values are included but still cause errors at configuration time.

      • configure

        public void configure​(Binder binder)
        Description copied from interface: Module
        Contributes bindings and other configurations for this module to binder.

        Do not invoke this method directly to install submodules. Instead use Binder.install(Module), which ensures that provider methods are discovered.

        Specified by:
        configure in interface Module