requireBinding for a BindingAnotation possible?

717 views
Skip to first unread message

Steve Storck

unread,
Sep 19, 2016, 9:25:03 AM9/19/16
to google-guice
Some of my modules require a binding from another module.  I want to set up a requireBinding in the dependent modules' configure() method, but it doesn't seem to be working for me.  Here is an example of what I am doing:

@BindingAnnotation
@Target([FIELD, PARAMETER, METHOD])
@Retention(RUNTIME)
@interface MyMap {
}

class ModuleA extends AbstractModule {
    protected void configure() {
    }

    @Provides
    @Singleton
    @MyMap
    static def Map<String, String> myMap() {
        ImmutableMap.copyOf(
                [A: 'val1',
                 B: 'val2']
        )
    }
}

class ModuleB extends AbstractModule {
    protected void configure() {
        requireBinding(Key.get(Map, MyMap))
        bind Foo
    }
}

class ModuleIT extends Specification {
    def 'Test module configuration'() {
        setup:
        def injector = Guice.createInjector new ModuleA(), new ModuleB()

        when:
        def result = injector.getInstance Foo

        then:
        result instanceof Foo
        result.someMap instanceof Map<String, String>
    }
}


This results in an error when createInjector is called:
com.google.inject.CreationException: Unable to create injector, see the following errors:
1) No implementation for java.util.Map annotated with interface a.b.c.MyMap was bound.

On the other hand, it works fine if I don't specify requreBinding.  However, since this dependent module has no notion of the map that is bound, I want to ensure that the binding is present when the dependent module is created.

Thomas Broyer

unread,
Sep 19, 2016, 9:29:50 AM9/19/16
to google-guice
You need to require the Map<String,String>, not the raw Map class.

 requireBinding(Key.get(new TypeLiteral<Map<String,String>>(){}, MyMap))

Steve Storck

unread,
Sep 19, 2016, 10:50:43 AM9/19/16
to google-guice
Thank you, Thomas.  That worked well and immediately.
Reply all
Reply to author
Forward
0 new messages