guice:运行时注入/绑定在命令行。 [英] guice: runtime injection/binding at command line.

查看:259
本文介绍了guice:运行时注入/绑定在命令行。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我有以下问题。

Hi I have the following problem.

   @inject
   MyClass(Service service) {
      this.service = service;
   }

   public void doSomething() {
      service.invokeSelf(); 
   }

我有一个模块

bind(service).annotatedWith(Names.named("serviceA").to(ServiceAImpl.class);
bind(service).annotatedWith(Names.named("serviceB").to(ServiceBImpl.class);

现在我的问题是我想允许用户根据命令行参数在运行时动态选择hte注入。

Now my problem is i want to allow user to dynamically choose hte injection on runtime base on command line parameter.

public static void Main(String args[]) {
   String option = args[0];
   ..... 
}



How would i do this? Do i have to create multiple modules just to do this? what is best way.

推荐答案

您有以下配置:

@Override
protected void configure() {
  MapBinder<String, Service> mapBinder = MapBinder.newMapBinder(binder(), String.class, Service.class);
  mapBinder.addBinding("serviceA").to(ServiceAImpl.class);
  mapBinder.addBinding("serviceB").to(ServiceBImpl.class);
}

然后在您的代码中注入地图并获得正确的服务选择:

Then in your code just inject the map and obtain the right service based on your selection:

@Inject Map<String, Service> services;

public void doSomething(String selection) {
  Service service = services.get(selection);
  // do something with the service
}

注册人与所选服务的自定义范围

这篇关于guice:运行时注入/绑定在命令行。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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