Reputation: 33
I have a Guice module that has a @Provides method that takes 2 parameters and returns one of the two implementations of an interface
public class ClientModule extends AbstractModule{
@Override
protected void configure(){
}
@Singleton
@Provides
protected ClientInterfaces provideService(Class1 objectOfClass1, String runTimeGeneratedString){
if(condition){
return new firstImplementation();
} else {
return new someImplementation(objectOfClass1, runTimeGeneratedString);
}
}
}
I have seen this question which is almost similar to mine - Passing parameters to Guice @Provides method . But here the OP of this question wants to pass constant String variables to the @Provides method whereas in my case I want to pass a string that will be generated on runtime. How to solve this issue? Any kind of help will be appreciated.
Thank you
Upvotes: 1
Views: 1575
Reputation: 18346
Two possibilities, depending on what you mean exactly. First, it is possible to still use constants, but determine the value of those constants at runtime - in your main() (or other startup code) before the module is created, work out what those values should be, and pass them into ClientModule's constructor, and keep them as fields, and bind them as constants.
On the other hand, passing a unique parameter each time you get a new instance isn't quite the same as injection - this is instead more of a factory method, such that you can request an instance with parameters. To do this, consider either assisted injection or autofactory. These tools will help you make a factory, an instance that you can pass runtime parameters to, and obtain an instance which was created through injection but still incorporates those parameters.
https://github.com/google/guice/wiki/AssistedInject
https://github.com/google/auto/tree/master/factory
How to use Guice's AssistedInject?
Upvotes: 2