Dagger 2 - Injected Dependency始终为null

时间:2016-01-07 17:50:49

标签: android dagger-2

您好,我一直在疯狂地试图找出我没有正确配置的内容,以便在注入类时获得非null依赖项。以下是我目前的代码

public interface DaggerGraph {

    void inject(SplashActivity splashActivity);
}

DaggerGraph提供注入接口

@Singleton
@Component(modules = {MainModule.class})
public interface DaggerComponent extends DaggerGraph {

    final class Initializer {
        private Initializer() {
        }

        public static DaggerComponent init(Application app) {
            return DaggerDaggerComponent.builder()
                .mainModule(new MainModule(app))
                .build();
        }
    }
}

Dagger组件

@Module
public class MainModule {

    private final Application app;

    public MainModule(Application app) {
        this.app = app;
    }

    @Provides
    @Singleton
    Application provideApplication() {
        return app;
    }

    @Provides
    @Singleton
    Resources provideResources() {
        return app.getResources();
    }
}

主要模块

public class App extends Application {

    private static DaggerComponent daggerComponent;

    @Override
    public void onCreate() {
        super.onCreate();
        daggerComponent = DaggerComponent.Initializer.init(this);
    }

    public static DaggerComponent component() {
        return daggerComponent;
    }

}

申请

public class SplashActivity extends BaseActivity {

    @Inject
    Resources resources;

    @Override
    public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        App.component().inject(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Timber.d(Boolean.toString(resources == null)); //Always true
    }
}

在这项活动中,资源总是空的,它让我疯狂。非常感谢任何帮助。

0 个答案:

没有答案