Bindings

Untargeted Bindings

qianmoQqianmoQ· 更新于 2026-09-23· 阅读 3 分钟· 0 次阅读

登录后可跨设备保存划线和私人笔记登录

Untargeted Bindings

Creating bindings that don't have targets

You may create bindings without specifying a target. This is most useful for concrete classes and types annotated by either @ImplementedBy or @ProvidedBy. An untargeted binding informs the injector about a type, so it may prepare dependencies eagerly. Untargeted bindings have no to clause, like so:

    bind(MyConcreteClass.class);
    bind(AnotherConcreteClass.class).in(Singleton.class);

When specifying binding annotations, you must still add the target binding, even if it is the same concrete class. For example:

    bind(MyConcreteClass.class)
        .annotatedWith(Names.named("foo"))
        .to(MyConcreteClass.class);
    bind(AnotherConcreteClass.class)
        .annotatedWith(Names.named("foo"))
        .to(AnotherConcreteClass.class)
        .in(Singleton.class);

Untargeted bindings are often used to register a type in a Module to ensure that Guice is aware of the type. Registering those types is required to make them eligible for injection when JIT is disabled.

评论

登录后参与评论

正在加载评论…