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

查看:322
本文介绍了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.

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

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