Google Guice和运行时的各种注入 [英] Google Guice and varying injections at runtime

查看:147
本文介绍了Google Guice和运行时的各种注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想基于直到运行时才知道的东西来改变注入的实现.具体来说,我希望我的应用能够以不同的版本运行,在请求执行之前,版本"是无法确定的.另外,版本"可能会因请求而异.

I'd like to vary the injected implementations based on something that's not known until runtime. Specifically, I'd like my app to operate as different versions where the "version" is not determined until a request is executing. Also, the "version" could vary per request.

阅读文档后,似乎可以在需要基于版本"在运行时选择实现的情况下实现提供程序.另外,我可以自己榨汁.

After reading the docs it seems that I could implement a providers in cases where I need to choose an implementation at runtime based on the "version". Additionally, I could roll my own on top of juice.

在这种情况下,实现提供程序是最好的方法吗?我想知道是否有最佳实践,或者是否有人尝试使用Guice解决此问题.

Is implementing a provider the best way to go in this scenario? I'd like to know if there is a best practice or if anyone else out there has tried to use Guice to tackle this problem.

感谢您的帮助!

-乔

推荐答案

public class MyRuntimeServiceModule extends AbstractModule {
  private final String runTimeOption;

  public ServiceModule(String runTimeOption) {
    this.runTimeOption = runTimeOption;
  }

  @Override protected void configure() {

    Class<? extends Service> serviceType = option.equals("aServiceType") ?
        AServiceImplementation.class : AnotherServiceImplementation.class;
    bind(Service.class).to(serviceType);
  }
}

  public static void main(String[] args) {
  String option = args[0];
  Injector injector = Guice.createInjector(new MyRuntimeServiceModule(option));

}

这篇关于Google Guice和运行时的各种注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆