Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters to Guice @Provides method

Tags:

guice

I have a Guice module that has a @Provides method that takes 2 parameters and returns the implementation of the interface:

public class **ClientModule** extends **AbstractModule**{

@Override
protected void configure(){

}

@Singleton
@Provides
protected ClientInterfaces provideService(String param1, String param2){
   returns something
 }

}

In my main class that injects the module, how do I pass the params to the @Provides method?

public MainClass{
main(){
Injector injector = Guice.createInjector( new ClientModule());
MainClass mainClass = injector.getInstance(MainClass.class);

}

This throws a Null pointer exception param1

like image 927
jwesonga Avatar asked Aug 27 '12 07:08

jwesonga


2 Answers

You don't call a provides method yourself, it is called by Guice when you first need to access (in this case) your ClientInterfaces Implementation.

I assume, you need configuration parameters to initialize your ClientInterfaces.

So try Binding-Annotation, the simplest is @Named:

configure() {
   bindConstant().annotatedWith(Names.named("hostName")).to("myHost");
   bindConstant().annotatedWith(Names.named("port")).to("8080");
}
@Provides
@Singleton
public MyService provideMyService(@Named("hostName") String host, @Named("port") String port) {
   // init MyService 
   return ....
}

Of course, you normally will read myHost and "8080" from a properties file System.props instead of hard coding constants.

The first time you need to Inject a MyService, Guice will notice that it needs to annotated Strings to fulfill the requirements of the provide method and search for the values bound to the Annotatioon name ...

like image 93
Jan Galinski Avatar answered Nov 11 '22 07:11

Jan Galinski


You don't pass parameters to the provider method. Guice needs to be able to create the parameters itself. It doesn't make sense for you to pass the parameters yourself because then there's no need for Guice.

If you want Guice to be able to provide the parameters to provideService, those parameters will either need a binding annotation on each parameter. Since they both have the same type, Guice can't know which String values it knows how to provide should be passed for which parameter.

If you know what to pass for param1 and param2 from your main code path, then move provideService somewhere that it can be called directly. No need for Guice in that situation.

like image 34
smjZPkYjps Avatar answered Nov 11 '22 07:11

smjZPkYjps