@bindsInstance 用于从模块中移除构造函数并链接在获取组件时使用的模块。
没有 @BindsInstance
@Module
public class AppModule {
private final Application application;
public AppModule(Application application) {
this.application = application;
}
@Provides
@Singleton
Application provideApplication() {
return application;
}
@Provides
@Singleton
public SharedPreferences providePreferences() {
return application.getSharedPreferences("store",
Context.MODE_PRIVATE);
}
}
这些模块(ToastMakerModule 和 SensorControllerModule)是为了学习目的而设计的,它们会获取上下文并实例化,可能对于真实的示例不太实用。
public class ToastMaker {
private Application application;
public ToastMaker(Application application) {
this.application = application;
}
public void showToast(String message) {
Toast.makeText(application, message, Toast.LENGTH_SHORT).show();
}
}
@Module
public class ToastMakerModule {
@Singleton
@Provides
ToastMaker provideToastMaker(Application application) {
return new ToastMaker(application);
}
}
@Singleton
@Component(modules = {AppModule.class, ToastMakerModule.class, SensorControllerModule.class})
public interface AppComponent {
void inject(MainActivity mainActivity);
@Component.Builder
interface Builder {
AppComponent build();
Builder appModule(AppModule appModule);
Builder sensorControllerModule(SensorControllerModule sensorControllerModule);
Builder toastMakerModule(ToastMakerModule toastMakerModule);
}
}
像这样构建组件
appComponent = DaggerAppComponent
.builder()
.appModule(new AppModule(this))
.sensorControllerModule(new SensorControllerModule())
.toastMakerModule(new ToastMakerModule())
.build();
使用@BindsInstance
@Module
public class AppModule {
@Provides
@Singleton
public SharedPreferences providePreferences(Application application) {
return application.getSharedPreferences("data",
Context.MODE_PRIVATE);
}
}
组件
@Singleton
@Component(modules = {AppModule.class, ToastMakerModule.class, SensorControllerModule.class})
public interface AppComponent {
void inject(MainActivity mainActivity);
@Component.Builder
interface Builder {
AppComponent build();
@BindsInstance
Builder application(Application application);
}
}
并且构建像这样的组件
appComponent = DaggerAppComponent
.builder()
.application(this)
.build();