无目标绑定与 `toInstance()` 绑定

Ela*_*da2 3 java dependency-injection inversion-of-control guice

我是 Guice 的新手,我不确定我是否理解两者之间的区别

1) 无目标绑定 - 我什么时候需要使用它?

bind(Logger.class);
Run Code Online (Sandbox Code Playgroud)

2 )'toInstance()` 绑定 - 如何初始化一个具有依赖关系的 ctor 的对象?还是仅用于没有依赖关系的数据对象?

bind(Logger.class).toInstance(new Logger(..?..));
Run Code Online (Sandbox Code Playgroud)

3)不写任何绑定

    @Override
    protected void configure() {
}
Run Code Online (Sandbox Code Playgroud)

当我跑步时,上述任何情况会发生什么

我什么时候应该选择其中任何一个?

Tav*_*nes 5

  1. 非目标绑定:您很少需要使用它们,但如果需要,它们是必要的
  2. 你是对的,通常你不能toInstance()用于具有构造函数依赖关系的对象。它对于非 Guicey 对象更有用,例如您必须使用new.
  3. 当您注入一个未绑定到 any 的类型时Module,Guice 会为其创建一个即时绑定。行为几乎相同bind(Untargetted.class);

非目标toInstance()绑定和绑定之间的主要区别在于toInstance()绑定将是单例(“显然”——只有一个实例!),但非目标绑定,像大多数其他绑定一样,默认没有范围。因此,如果不同的类注入Untargetted,除非您在其上放置范围,否则它们将获得不同的实例。

另一个区别是,当您不使用 时toInstance(),Guice 会为您创建实例,从而实现面向方面编程之类的功能

通常,toInstance()除非必须,否则您不应该使用绑定。非目标绑定的优点是更明确,但将它们全部列出可能会很冗长,因此通常使用即时绑定。尤其是在这样的情况下:

bind(Interface.class)
        .to(Implementation.class);

// Technically, Guice creates a just-in-time binding for Implementation here
Run Code Online (Sandbox Code Playgroud)