问题
how to change/set a binding by a property/string given in a property/text file? in my case i want to implement a kind of "demo mode". In normal mode a property gives an url to an external service but if url is "demo" the binding of the according interface should be changed like this:
normal:
bind(SasDatenProvider.class).to(SasDataProviderHttpImpl.class);
demo
bind(SasDataProvider.class).to(SasDataProviderFileImpl.class);
how to achieve that? thx in advance
回答1:
You can use a method annotated with @Provides
in your module. Then you can do something like this:
public class MyModule extends AbstractModule {
@Provides
SasDatenProvider provideSas(SasDataProviderHttpImpl http,
SasDataProviderFileImpl file){
boolean isDemo = false; /* do you property lookup logic here */
return isDemo ? file : http;
}
}
You can read more about @Provides
-methods in the guice docs:
http://code.google.com/p/google-guice/wiki/ProvidesMethods
If your don't want this kind of logic in you module, you can consider creating your own provider: http://code.google.com/p/google-guice/wiki/ProviderBindings
来源:https://stackoverflow.com/questions/8257863/guice-change-binding-by-property-string-in-external-text-file-on-runtime