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
}

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