Question

I'm trying to create a Guice 2 Module to wrap a third party API using @Provides methods. The problem is I'm not exactly sure how to properly bind to the @Provides methods. The 3rd library doesn't expose interfaces for its singletons, so I'm just calling bind(ThirdPartySingleton.class).

Guice is complaining with an error similar to: Could not find a suitable constructor in ThirdPartySingleton1

I'm aware that I could use a separate Provider<> for each of the third party singletons, but I'd like to use the succinct @Provide methods if possible.

public class ThirdPartyModule extends AbstractModule {

    public ThirdPartyModule() {
    }

    @Override
    public void configure() {
        bind(ThirdPartySingleton1.class);
        bind(ThirdPartySingleton2.class);
    }

    @Provides
    @Singleton
    ThirdPartySingleton1 provideThirdPartySingleton1(){
        return ThirdPartySingleton1.getInstance();
    }

    @Provides
    @Singleton
    ThirdPartySingleton2 provideThirdPartySingleton2() {
        ThirdPartySingleton2 singleton2 = ThirdPartySingleton2.getInstance();
        singleton2 .setParam1( "param1");
        singleton2 .setParam2( "param2");

        return singleton2 ;
    }

}

Was it helpful?

Solution

That seems to be about right, but you don't need the bind statements: that tells Guice to construct instances itself using a no-arg public constructor, which it can't find. Your @Provides ThirdPartySingleton1 tells Guice everything it needs to know.

You still need a configure method, because it's abstract, but you can leave that empty or put a comment in it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top