Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Dependency injection requireBinding有什么用?_Dependency Injection_Guice - Fatal编程技术网

Dependency injection requireBinding有什么用?

Dependency injection requireBinding有什么用?,dependency-injection,guice,Dependency Injection,Guice,我对Guice比较陌生,试图了解requireBinding的用法以及何时/为什么使用它 据我所知,在创建注入器时,Guice会遍历所有模块的configure()方法代码,并构建一个依赖关系图 如果Guice自己构建依赖关系图,那么为什么模块需要添加requireBinding?只要我能理解requireBinding的用法就是在一个类上添加一个显式的依赖项,guice的依赖关系图似乎无论如何都在这样做 我想了解什么时候应该使用requireBinding,以及在模块中不使用它会产生什么影响

我对Guice比较陌生,试图了解requireBinding的用法以及何时/为什么使用它

据我所知,在创建注入器时,Guice会遍历所有模块的configure()方法代码,并构建一个依赖关系图

如果Guice自己构建依赖关系图,那么为什么模块需要添加requireBinding?只要我能理解requireBinding的用法就是在一个类上添加一个显式的依赖项,guice的依赖关系图似乎无论如何都在这样做

我想了解什么时候应该使用requireBinding,以及在模块中不使用它会产生什么影响

我已经阅读了Guice的官方文档,并在Stackoverflow/任何其他博客上搜索了所有现有问题,但未能找到上述问题的满意答案

添加到原始问题。

查看AbstractModule的源代码,实现如下所示

protected void requireBinding(Key<?> key) {
    this.binder().getProvider(key);
}

protected void requireBinding(Class<?> type) {
    this.binder().getProvider(type);
}
protectedvoid-requireBinding(键){
this.binder().getProvider(键);
}
受保护的void requireBinding(类类型){
this.binder().getProvider(类型);
}
你会认为这不会有任何副作用,因为这是一个“获取”电话。 但另一方面,从活页夹本身看,它向类型为“ProviderLookup”的元素列表中添加了一些元素

public <T> Provider<T> getProvider(Dependency<T> dependency) {
        ProviderLookup<T> element = new ProviderLookup(this.getElementSource(), dependency);
        this.elements.add(element);
        return element.getProvider();
    }
公共提供程序getProvider(依赖项){
ProviderLookup元素=新的ProviderLookup(this.getElementSource(),依赖项);
this.elements.add(element);
返回元素。getProvider();
}

我一直认为requireBinding()是模块的契约

如果调用
#get()
或尝试注入依赖于绑定的对象,则图形最终将失败,这是正确的。但是,我认为创建喷油器时,与创建对象时(通过喷油器)相比,requireBinding会导致故障。当我在谷歌工作时,它的功能更多的是作为一种契约,而不是作为一种具有后果性行为的东西。

FWIW我们(内部)通常不鼓励
requireBinding()
。一般来说,
requireBinding()
引入了一个实际上并不存在的“需求”(否则您会在不需要它的情况下得到一个绑定错误),这使得模块比严格需要的更脆弱。我认为如果使用
String
参数,那么它(稍微)会更有用,这样您就可以提供比默认情况下更有用的错误消息,但事实上,它并不比依赖它实际需要绑定要好。