简体   繁体   English

Dagger 2依赖注入不起作用

[英]Dagger 2 Dependency Injection not working

I'm very new to Dagger 2 and I'm trying to get this basic example working with some minor modifications. 我是Dagger 2的新手,我试图通过一些小的修改来使这个基本示例生效。

This is what I have so far: 这是我到目前为止的内容:

Component class 组件类

@Component(modules = {MyModule.class})
public interface MyComponent {
void inject(Object object);
} 

Module class 模块类别

@Module
public class MyModule {

@Provides
@Singleton
public Retrofit getRetrofit(){
  return new Retrofit();
}
}

Static Injector 静态喷油器

public class MyStaticInjector {

private static MyComponent di;

public static void inject(Object object){
    if(di == null){
        di = DaggerMyComponent.builder().build();
    }
    di.inject(object);
}
}

The problem is that whenever I do 问题是我每次做

MyStaticInjector.inject(this);

the annotated fields are still null. 带注释的字段仍然为空。 I suspect the problem is with the type Object in the interface method. 我怀疑问题出在接口方法中的对象类型。 In the example, there's an Activity instead. 在示例中,有一个Activity代替。 But I need to use DI in classes that are not activities. 但是我需要在不是活动的类中使用DI。

Can anyone help me? 谁能帮我? Thank you. 谢谢。

Object has no @Inject annotated fields. Object没有@Inject注释字段。 Thus the injection works just fine—it just has nothing to inject. 这样,注入工作就很好了,没有任何注入。
You will have to use your actual classes with inject(MyClass) instead of Object , so that the code can be generated and fields can be injected. 您将必须使用带有inject(MyClass)实际类而不是Object ,以便可以生成代码并可以注入字段。

Dagger generates source code at compile time . Dagger在编译时生成源代码。 If it does not know about the actual class, it cannot create code for it. 如果不知道实际的类,则无法为其创建代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM