构造函数绑定和参数区分



假设我有一个第三方类:

public class ThirdParty {
    public ThirdParty(String arg1, String arg2);
}

由于这是第三方的,我不能添加自己的@Inject注释,这迫使我使用bind-to-constructor。问题是我如何创建一个第三方与arg1和arg2不同。从本质上讲,就是从外部添加"Named"注释。

不如这样写:

class ProvidesExample {
  static class ThirdParty {
    public ThirdParty(String arg1, String arg2) {}
  }
  static class Module extends AbstractModule {
    @Override
    protected void configure() {
      bindConstant().annotatedWith(Names.named("arg1")).to("Argument 1");
      bindConstant().annotatedWith(Names.named("arg2")).to("Argument 2");
    }
    @Provides
    ThirdParty getThirdParth(@Named("arg1") String arg1, @Named("arg2") String arg2) {
      return new ThirdParty(arg1, arg2);
    }
  }
}

相关内容

最新更新