gpt4 book ai didi

android - 创建带有 Dagger 2 的单例的最简单方法?

转载 作者:IT老高 更新时间:2023-10-28 23:21:52 25 4
gpt4 key购买 nike

我需要设置模块、提供程序和接口(interface)(组件)吗?仅仅为了能够注入(inject)一个单例,似乎需要相当多的开销。

有人可以提供一个使用 Dagger 2 的简单单例示例吗? (还展示了如何设置单例的属性,例如上下文,这样您就不需要在每次使用单例时都传递它)

最佳答案

你只需要模块来处理你不能用 @Inject 构造函数注释的东西(例如,框架会为你创建它——比如上下文)。如果不能添加@Inject构造函数,还需要在组件中指定void inject(...)方法。

但是,如果您可以使用 @Inject 构造函数创建它,那么 @Inject 也可以用作字段注释

@Component(modules={ContextModule.class})
@Singleton
public interface SingletonComponent {
void inject(MainActivity mainActivity);
}

@Module
public class ContextModule {
Context context;

public ContextModule(Context context) {
this.context = context;
}

@Provides
Context context() {
return context;
}
}

@Singleton
public class MyOtherSingleton {
@Inject
public MyOtherSingleton() {
}
}


@Singleton
public class MySingleton {
@Inject Context context;
@Inject MyOtherSingleton myOtherSingleton;

@Inject
public MySingleton() {
}
}

你也可以做构造函数参数

private final Context context;
private final MyOtherSingleton myOtherSingleton;

@Inject
public MySingleton(Context context, MyOtherSingleton myOtherSingleton) {
this.context = context;
this.myOtherSingleton = myOtherSingleton;
}

SingletonComponent singletonComponent = DaggerSingletonComponent.builder()
.contextModule(CustomApplication.this)
.build();

// and elsewhere

@Inject
MySingleton mySingleton;

// ...
singletonComponent.inject(this);

验证可以工作:

08-23 04:39:28.418 com.zhuinden.rxrealm D/DogView: My singleton has [com.zhuinden.rxrealm.application.CustomApplication@53348a58] and [com.zhuinden.rxrealm.application.injection.test.MyOtherSingleton@5336bb74]
08-23 04:39:36.422 com.zhuinden.rxrealm D/CatView: My singleton has [com.zhuinden.rxrealm.application.CustomApplication@53348a58] and [com.zhuinden.rxrealm.application.injection.test.MyOtherSingleton@5336bb74]

关于android - 创建带有 Dagger 2 的单例的最简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39091193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com