android - Dagger : Why does dagger require a @inject constructor for an object that does't depend on another object

标签 android dagger-2 dagger android-architecture-lifecycle

我想我错过了一些东西。我收到此错误:

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/

相关文章:

java - 上传文件时出现致命异常错误,但文件仍然可以正常上传

android - Unresolved reference : DaggerTestComponent (Kotlin with Dagger for Test)

android - Dagger 2 的作用域可以比 Activity 生命周期短吗?

android - 使用 Dagger 注入(inject)依赖项时出现 ClassCastException

dependency-injection - 业务逻辑和演示者中的 Dagger

android - 我们如何使用数据绑定(bind)从字符串资源中获取 SpannedString 对象?

android - 无法在 android 中使用 Facebook 图形 API 找到喜欢和评论计数

android - 如何使用 setcontent 通过按钮更改内容 View

android - Kotlin 缺少提供程序的 Dagger 2 错误

android - dagger 简单示例给出了 IllegalStateException