我想我错过了一些东西。我收到此错误:
PostsVM cannot be provided without an @Inject constructor or from an
@Provides-annotated method.
假设类如下:
@Module
public class AppModule {
private final Application mApplication;
@Singleton
@Provides
ViewModel provideListViewModel() {
return new PostsVM();
}
}
还有一个类PostVM
@Singleton
public class PostsVM extends ViewModel {
public boolean get(){
return true;
}
}
还有一个组件:
@Singleton
@Component(modules = AppModule.class)
public interface AppComponent {
void inject(Global global);
void inject(MainActivity mainActivity);
@Architecture.ApplicationContext
Context getContext();
Application getApplication();
}
在 Activity 中:
@Inject
public ViewModelProvider.Factory factory;
@Override
protected void onCreate(Bundle savedInstanceState) {
InjectorClass.inject(this);
正如您所看到的,为 PostVM 类给出的示例不依赖于任何东西,为什么我需要一个 @inject 构造函数?
最佳答案
tl;dr 为了防止错误并遵循约定。
从@Inject
的JavaDoc中你可以读到:
Injectable constructors are annotated with @Inject and accept zero or more dependencies as arguments. @Inject can apply to at most one constructor per class.
遵循约定/文档始终是一个好习惯。
因此,@Inject
标记了 Dagger 的入口点,以指示它如何以及在何处创建类。这是您打算如何使用您的类的明确标志。
- 如果您有多个构造函数怎么办?
- 如果您需要额外设置并应使用
@Module
该怎么办?
通过默认使用无参数构造函数(如果可能的话),事情可能会很容易崩溃,并且如果您只是假设 Dagger 完成了它的工作,您可能无法轻松找到源。
__ cannot be provided without an @Inject constructor or from an @Provides-annotated method.
另一方面,此错误向您发出强烈信号,表明您遗漏了某些内容并且不能被忽略。
关于android - Dagger : Why does dagger require a @inject constructor for an object that does't depend on another object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44670859/