guice:命令行的运行时注入/绑定

问题描述:

我遇到以下问题:

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

现在我的问题是我想允许用户通过命令行参数在运行时基础上动态选择注入。

Now my problem is I want to allow user to dynamically choose the injection on runtime base through command line parameter.

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

我怎么能这样做?我必须创建多个模块吗?

How could I do this? Do I have to create multiple modules just to do this?

如果你需要在运行时反复选择使用 mapbinder 的实现是非常合适的。

If you need to choose repeatedly at runtime which implementation to use the mapbinder is very appropriate.

您的配置如下:

@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
}

你甚至可以填充使用自定义范围的所选服务的注射器。

You can even populate the injector with the selected service using custom scopes.