【问题标题】:Dagger : Why does dagger require a @inject constructor for an object that does't depend on another objectDagger : 为什么 dagger 需要一个不依赖于另一个对象的对象的 @inject 构造函数
【发布时间】:2017-06-21 08:35:58
【问题描述】:

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

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();
}

在活动中:

@Inject
public         ViewModelProvider.Factory factory;

@Override
protected void onCreate(Bundle savedInstanceState) {
    InjectorClass.inject(this);

如您所见,为 PostVM 类提供的示例不依赖任何东西,为什么我需要一个 @inject 构造函数?

【问题讨论】:

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


    【解决方案1】:

    tl;dr 防止错误并遵守约定。


    @Inject的JavaDoc你可以阅读:

    可注入构造函数使用@Inject 进行注释,并接受零个或多个依赖项作为参数。 @Inject 每个类最多可以应用一个构造函数。

    遵循约定/文档总是好的做法。


    所以@Inject 为 Dagger 标记了一个入口点,以指示它如何以及在哪里创建你的类。这清楚地表明了您打算如何使用您的课程。

    • 如果您有多个构造函数怎么办?
    • 如果您需要额外的设置并且应该改用@Module 怎么办?

    仅默认使用无参数构造函数(如果可能的话),事情可能会很容易开始崩溃,如果您只是假设 Dagger 完成了它的工作,您可能无法轻松地查明源头。

    __ cannot be provided without an @Inject constructor or from an @Provides-annotated method.
    

    另一方面,这个错误给你一个强烈的信号,你错过了一些东西,不能被忽视。

    【讨论】:

    • 好的,我现在知道了,所以@Inject 既在需要依赖的类上,又在提供依赖的类上?
    • @Relm @Inject 在您要创建的类的构造函数和要注入的字段中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-31
    相关资源
    最近更新 更多