简体   繁体   中英

Constructor parameter injection using guice

This is a slightly different question from the other answered questions about constructor parameter (or at least that's what I think so, course I may be wrong). So am using a MapBinder to store a bunch of implementations and then pick one during runtime based of some criteria. Here is some code:

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();
  }
}

I am unable to figure out how to get the FacebookMessageService with the name parameter? If I use AssistedInject with a Factory then I am not able to figure out how to inject the implementation into the MapBinder .

You can inject the 'name' parameter.

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

Put a debug point in the FacebookMessageService constructor to see whether this works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM