强制/建议使用requireExplicitBindings

osh*_*hai 5 java dependency-injection guice

我正在使用guice并看到了一个binder().requireExplicitBindings() 在这里使用的例子.
该示例如下所示:

Injector injector = Guice.createInjector(new SandwichModule(), new AbstractModule() {
    @Override
    protected void configure() {
        binder().requireExplicitBindings();
        bind(GuiceFilter.class);
    }
});
Run Code Online (Sandbox Code Playgroud)

这导致例外

com.google.inject.ConfigurationException: Guice configuration errors:

1) Explicit bindings are required and ...
Run Code Online (Sandbox Code Playgroud)

使用它是强制性的,还是只是推荐使用?如果它只是推荐我只是想知道为什么要使用它?

Jan*_*ski 4

它既不是强制性的(那么这将是默认设置,无需激活)也不是必需的。通常,在使用 guice 时,您希望拥有所有“魔力”来帮助您将应用程序粘合在一起。所以默认行为是:不需要explicitBindings。但时不时地,你会发现你的机械性行为会妨碍你。在极少数情况下,您会使用 require 开关。我没有阅读您提供的整篇文章,所以我无法判断他们是否正在处理这些“特殊情况”之一,或者他们是否只是使用标志而没有真正考虑原因。无论如何,如果您编写绑定模块,请将其省略。