问题描述
是否可以同时使用Dagger 2.0构造函数注入和单例。
我在文档中找不到答案。
is it possible to use Dagger 2.0 Constructor injection and singleton at one time.I don't find the answer in the documentation.
示例:
@Singleton
public class MyClass {
private final OtherClass member;
@Inject
public MyClass(OtherClass member){
this.member = member;
}
}
构造函数注入确实可以正常工作。但是,如果我在课程上写@Singleton,是否可以保证将MyClass创建为单例?
Constructor injection does work for sure. But is it guaranteed that MyClass is created as a singleton if I write @Singleton on the class?
谢谢
推荐答案
是。
由于Dagger 2为您生成了源代码,因此很容易检查正在发生的事情。例如,当结合使用以下模块和 MyClass
时:
Since Dagger 2 generates the source code for you, it is easy to inspect what is happening. For example, when using the following module in combination with your 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)
,您可以看到 ScopedProvider
被用作 Provider
为 MyClass
。调用 myClass()
方法时, ScopedProvider
的 get()
方法被调用,以单例形式实现:
In initialize(Builder)
, you can see that a ScopedProvider
is used as a Provider
for MyClass
. When calling the myClass()
method, the ScopedProvider
's get()
method is called, which is implemented as a singleton:
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;
}
这篇关于Dagger 2.0构造函数注入和Singleton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!