在 Dagger 裡需要以下四大重要的 annotation:
在 build.gradle 向 dependencies 添加( https://github.com/google/dagger/releases 可以找到最新版本的 Dagger):
dependencies {
implementation 'com.google.dagger:dagger:2.21'
annotationProcessor 'com.google.dagger:dagger-compiler:2.21'
}
UserRepository:
public class UserRepository {
private final UserLocalDataSource userLocalDataSource;
private final UserRemoteDataSource userRemoteDataSource;
@Inject
public UserRepository(UserLocalDataSource userLocalDataSource, UserRemoteDataSource userRemoteDataSource) {
this.userLocalDataSource = userLocalDataSource;
this.userRemoteDataSource = userRemoteDataSource;
}
}
UserLocalDataSource:
public class UserLocalDataSource {
@Inject
public UserLocalDataSource() {}
}
public class UserRemoteDataSource {
private final LoginRetrofitService loginRetrofitService;
@Inject
public UserRemoteDataSource(LoginRetrofitService loginRetrofitService) {
this.loginRetrofitService = loginRetrofitService;
}
}
LoginViewModel:
public class LoginViewModel {
private final UserRepository userRepository;
@Inject
public LoginViewModel(UserRepository userRepository) {
this.userRepository = userRepository;
}
}
ApplicationComponent:
@Component(modules = NetworkModule.class)
public interface ApplicationComponent {
// 注入 LoginActivity
void inject(LoginActivity loginActivity);
}
MyApplication:
public class MyApplication extends Application {
ApplicationComponent appComponent = DaggerApplicationComponent.create();
}
LoginActivity:
public class LoginActivity extends Activity {
@Inject
LoginViewModel loginViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
((MyApplication) getApplicationContext()).appComponent.inject(this);
super.onCreate(savedInstanceState);
}
}
NetworkModule:
@Module
public class NetworkModule {
@Provides
public LoginRetrofitService provideLoginRetrofitService() {
return new Retrofit.Builder()
.baseUrl("https://example.com")
.build()
.create(LoginService.class);
}
}
謝謝大家願意花時間閱讀,小弟弟我在此鞠躬