Guice:如何打印模块的绑定?

IAm*_*aja 3 java dependency-injection guice

在过去的两天里,我一直在盯着我的代码中的一个讨厌的bug,围绕着我的Guice模块和我在其中声明的绑定.我在我的模块中声明了大约20个绑定,其中只有1个不起作用.

我已经用尽了这里的所有选项,并且想知道module.print()Guice库中是否有类似的方法,我可以打印出所有模块绑定的String版本; 无论是那个还是以某种方式让Guice记录它在读取我有缺陷的绑定时所做的事情.

IAm*_*aja 7

Injector injector = Guice.createInjector(myModuleInstance);
Map<Key<?>,Binding<?>> map = injector.getBindings();
for(Entry<Key<?>, Binding<?>> e : map.entrySet()) {
    System.out.println(e.getKey() + ": " + e.getValue());
}
Run Code Online (Sandbox Code Playgroud)

  • Nitpick:您可以使用`map.entrySet()`来获取键值对,而无需在循环中调用`map.get(...)`. (2认同)
  • 还有`Map::forEach`,例如`injector.getBindings().forEach((key, value) -&gt; System.out.println(key + ": " + value))` (2认同)