错误:找不到符号变量DaggerAppComponent

问题描述 投票:9回答:6

在尝试集成最新的Dagger 2版本时,我遇到了Dagger自动生成的问题。尽管有几个Rebuild和Make Module App进程,但Dagger并没有自动生成DaggerAppComponent。

申请类:

public class BaseApplication extends Application
{
    private AppComponent appComponent;

    @Override
    public void onCreate()
    {
        super.onCreate();
        initAppComponent();
    }

    private void initAppComponent()
    {
        DaggerAppComponent.builder()
                .appModule(new AppModule(this))
                .build();
    }

    public AppComponent getAppComponent()
    {
        return appComponent;
    }
}

AppComponent

@Singleton
@Component(modules = AppModule.class)
public interface AppComponent
{
    void inject(BaseApplication application);
}

的AppModule:

@Module
public class AppModule
{
    private BaseApplication application;

    public AppModule(BaseApplication app)
    {
        application = app;
    }

    @Provides
    @Singleton
    Context provideContext()
    {
        return application;
    }

    @Provides
    Application provideApplication()
    {
        return application;
    }
}

使用的依赖:

compile 'com.google.dagger:dagger-android:2.11'
compile 'com.google.dagger:dagger-android-support:2.11'
annotationProcessor 'com.google.dagger:dagger-android-processor:2.11'
androidTestCompile 'com.google.code.findbugs:jsr305:3.0.1'

在这方面的任何帮助将受到高度赞赏。

android dependency-injection dagger-2 dagger
6个回答
23
投票

好像我使用了错误的依赖项:

compile 'com.google.dagger:dagger-android:2.x'
compile 'com.google.dagger:dagger-android-support:2.x' // if you use the support libraries
annotationProcessor 'com.google.dagger:dagger-android-processor:2.x'

如果您在dagger.android中使用类,则应使用上述依赖项。

正确的依赖关系是:

compile 'com.google.dagger:dagger:2.x'
annotationProcessor 'com.google.dagger:dagger-compiler:2.x'

2
投票

添加以下依赖项为我解决了问题:

annotationProcessor 'com.google.dagger:dagger-compiler:2.12'

1
投票

你需要这两行

implementation 'com.google.dagger:dagger:2.16'
kapt 'com.google.dagger:dagger-compiler:2.16'

使用kotlin时使用kapt而不是annotationProcessor。生成的类,如Dagger + AppComponentClass,例如:DaggerAppComponent


1
投票

尝试,转到文件和

无效并重新启动


0
投票

我遇到了同样的问题......解决了我的问题实际上是将视图模型添加到ViewmodelModulle然后将注释@Inject添加到我的视图模型的构造函数中。这可能是一个不同的问题,但在我的情况下,这真的有帮助。我的代码编译没有任何问题

@Inject <-----这是构造函数中的缺失。

public MessageViewModel(Application application) {
    super(application);
    mApp = application;

-1
投票

将代码更改为此,

 private void initAppComponent()
{
/*    DaggerAppComponent.builder()
                    .appModule(new AppModule(this))
                    .build();*/
        appComponent = DaggerAppComponent.builder()
                .appModule(new AppModule(this))
                .build();
        appComponent .inject(this)
    }

其他的事情是

@Singleton
@Component(modules = AppModule.class)
public interface AppComponent
{
    void inject(BaseApplication application);
}

为什么需要在构建组件的地方注入相同的类,您可以轻松地在Application类上获取上下文和应用程序。 Dagger可以帮助您找到一个依赖类。

© www.soinside.com 2019 - 2024. All rights reserved.