Google Guice and varying injections at runtime

只愿长相守 提交于 2019-12-23 05:32:29

问题


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.

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.

Thanks for any help!

-Joe


回答1:


I think that if the version can be known only at runtime, you must provide the versioned "services" manually with custom provider. Possibly something like this:

@Singleton
public abstract class VersionedProvider<T, V> {

    private Map<V, T> objects;

    T get(V version) {
        if (!objects.containsKey(version)) {
            objects.put(version, generateVersioned(version));
        }
        return objects.get(version);
    }

    // Here everything must be done manually or use some injected
    // implementations
    public abstract T generateVersioned(V version);
}



回答2:


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));

}


来源:https://stackoverflow.com/questions/7651980/google-guice-and-varying-injections-at-runtime

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