Guice:如何避免模块中的冗余

时间:2016-07-17 18:24:17

标签: java dependency-injection guice

目前,我的Guice模块的冗余看起来像这样:

public GuiceModule extends AbstractModule {

  @Provides
  @Named("Thing1")
  String Thing1Provider() {
    return someFunction("Thing1");
  }

  @Provides
  @Named("Thing2")
  String Thing2Provider() {
    return someFunction("Thing2");
  }

  .......

  @Provides
  @Named("Thing5")
  String Thing5Provider() {
    return someFunction("Thing5");
  }

}

显然,这非常笨拙。我该如何避免这种情况?

1 个答案:

答案 0 :(得分:1)

List<String> names = ...;
for (String name : names) {
    bind(String.class)
            .annotatedWith(Names.named(name))
            .toProvider(() -> doSomething(name));
}

但正如评论建议的那样,我会考虑使用MapBinder,或者直接在需要时调用doSomething,而不是在任何地方使用@Named