是的。
由于 Dagger 2 为您生成源代码,因此很容易检查正在发生的事情。例如,将以下模块与您的 结合使用时MyClass
:
@Component
@Singleton
public interface MyComponent {
MyClass myClass();
}
生成以下实现:
@Generated("dagger.internal.codegen.ComponentProcessor")
public final class DaggerMyComponent implements MyComponent {
private Provider<MyClass> myClassProvider;
private DaggerMyComponent(Builder builder) {
assert builder != null;
initialize(builder);
}
public static Builder builder() {
return new Builder();
}
public static MyComponent create() {
return builder().build();
}
private void initialize(final Builder builder) {
this.myClassProvider = ScopedProvider.create(MyClass_Factory.create(OtherClass_Factory.create()));
}
@Override
public MyClass myClass() {
return myClassProvider.get();
}
public static final class Builder {
private Builder() {
}
public MyComponent build() {
return new DaggerMyComponent(this);
}
}
}
在initialize(Builder)
中,您可以看到 aScopedProvider
被用作Provider
for MyClass
。调用myClass()
方法时,会调用ScopedProvider
'sget()
方法,实现为单例:
public T get() {
// double-check idiom from EJ2: Item 71
Object result = instance;
if (result == UNINITIALIZED) {
synchronized (this) {
result = instance;
if (result == UNINITIALIZED) {
instance = result = factory.get();
}
}
}
return (T) result;
}