Guice change binding by property (string in external text file)/ on runtime

女生的网名这么多〃 提交于 2019-12-12 03:14:36

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!