使用guice

时间:2015-06-18 18:27:12

标签: java guice

这与其他有关构造函数参数的回答问题略有不同(至少我认为是这样,当然我可能错了)。所以我使用MapBinder来存储一堆实现,然后根据一些标准在运行时选择一个。这是一些代码:

public interface MessageService {
  void send();
}

public class FacebookMessageService implements MessageService {
  private final String name;

  @Inject
  public FacebookMessageService(String name) {
    this.name = name;
  }

  public void send() {
    System.out.println("Sending message via facebook service to " + name);
  }
}

public class MessageModule extends AbstractModule {
  @Override
  protected void configure() {
    MapBinder<String, MessageService> mapBinder = MapBinder.newMapBinder<.....>
    mapBinder.addBinding("facebook").to(FacebookMessageService.class);
  }
}

public class MessageClient {
  @Inject
  Map<String, MessageService> map; //Mapbinder being injected

  public void callSender() {
    Injector injector = Guice.createInjector(new MessageModule());
    injector.injectMembers(this);

    MessageService service = map.get("facebook");
    service.send();
  }
}

我无法弄清楚如何使用FacebookMessageService参数获取name?如果我将AssistedInjectFactory一起使用,那么我无法弄清楚如何将实现注入MapBinder

1 个答案:

答案 0 :(得分:0)

您可以注入'name'参数。

public class FacebookMessageService implements MessageService {
    private final String name;

    @Inject
    public FacebookMessageService(@Named("facebookServiceName") String name) {
       this.name = name;
    }
}

public class MessageModule extends AbstractModule {
    @Override
    protected void configure() {
        // bind the "facebookServiceName"
        // I think this binding should exist before the map binding
        bindConstant().annotatedWith(Names.named("facebookServiceName"))
                      .to("insert your argument here");

        MapBinder<String, MessageService> mapBinder = MapBinder.newMapBinder<.....>
        mapBinder.addBinding("facebook").to(FacebookMessageService.class);
    }
}

在FacebookMes​​sageService构造函数中放置一个调试点,看看是否有效。