非目标绑定与`toInstance()`绑定 [英] untargeted bind vs. `toInstance()` bind

查看:88
本文介绍了非目标绑定与`toInstance()`绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to Guice and I'm not sure I understand the difference between

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

1) untargeted bind - when do I need to use this?

bind(Logger.class);

2)'toInstance()`绑定-如何初始化具有ctor依赖项的对象?还是仅不具有依赖项的数据对象?

2 )'toInstance()` bind - how do I init an object that has ctor with dependencies? or is it for data object with no dependencies only?

bind(Logger.class).toInstance(new Logger(..?..));

3)不在

    @Override
    protected void configure() {
}

我跑步时以上任何情况发生了什么

what happens in any of the above when I run

我什么时候应该选择它们中的任何一个?

and when should I choose any of them?

推荐答案

  1. 非目标绑定:您很少需要使用它们,但是如果需要,它们是必需的
  1. Untargetted bindings: you rarely need to use them, but they're necessary if
    • You want to specify a scope (bind(Untargetted.class).in(Scopes.SINGLETON);, for example)
    • You want to keep the binding inside a PrivateModule
    • You have required explicit bindings

未目标绑定和 toInstance()绑定之间的主要区别是 toInstance()绑定将是单例(显然"-只有一个实例!),但是像大多数其他绑定一样,非目标绑定默认情况下没有作用域.因此,如果不同的类注入 Untargeted ,则除非获得作用域,否则它们将获得不同的实例.

The major difference between untargetted and toInstance() bindings is that toInstance() bindings will be singletons ("obviously" -- there's only one instance!), but untargetted bindings, like most other bindings, have no scope by default. So if different classes inject an Untargetted, they'll get different instances unless you put a scope on it.

另一个差异是,当您不使用 toInstance()时,Guice会为您创建实例,从而启用

Another difference is that when you don't use toInstance(), Guice creates the instance for you, enabling things like aspect-oriented programming.

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

Generally, you should prefer not to use toInstance() bindings unless you have to. Untargetted bindings have the advantage of being more explicit, but it can be verbose to list them all, so just-in-time bindings are often used instead. Especially in cases like this:

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

// Technically, Guice creates a just-in-time binding for Implementation here

这篇关于非目标绑定与`toInstance()`绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆