@Inject 带注解的构造函数,没有定义作用域

@Inject annotated constructor without defined Scope

有一个 class 带有 @Inject 注释 constructor 但没有定义 Scope。注入后Scope属于什么?

// No scope
public class A {

@Inject public A() {}

}

class/binding 将 未限定范围 并且将为每次注入创建一个新实例。

无论组件的范围如何,Dagger 都允许无范围的依赖项 bound in any component

  • Any type with an @Inject constructor that is unscoped or has a @Scope annotation that matches one of the component’s scopes

当 类 或组件 do 分配了有效范围时,它们会跟踪 1:1 到声明它们的组件的生命周期:

Since Dagger 2 associates scoped instances in the graph with instances of component implementations, the components themselves need to declare which scope they intend to represent. For example, it wouldn’t make any sense to have a @Singleton binding and a @RequestScoped binding in the same component because those scopes have different lifecycles and thus must live in components with different lifecycles.

换句话说,如果您将作用域视为 "conditions in which an instance is kept and reused",其中 @Singleton 表示 "always keep or reuse this instance",@RequestScoped 表示 "keep or reuse this instance within the same request (as long as the request-scoped component exists)",那么 unscoped实际上意味着 "never keep or reuse this instance".