Dagger2 未在 android 中生成 类

Dagger2 is not generating classes in android

我在 android 应用程序中使用 Dagger2,我的应用程序中有两个组件。第一个对于整个应用程序是全局的,第二个是特定于 activity 个实例。

NetComponent.java

@Singleton
@Component(modules = {AppModule.class, NetModule.class})
public interface NetComponent {
    void inject(AuthenticationActivity authenticationActivity);

    void inject(PaymentActivity paymentActivity);
}

ValidationComponent.java

@Singleton
@Component(modules = {ValidatorModule.class})
public interface ValidationComponent {
    void inject(Activity activity);
}

AppModule.java

@Module
public class AppModule {

    private Application application;

    public AppModule(Application application) {
        this.application = application;
    }

    @Provides
    @Singleton
    Application providesApplication() {
        return application;
    }
}

NetModule.java

@Module
public class NetModule {

    @Provides
    @Singleton
    SharedPreferences providesSharedPreferences(Application application) {
        return PreferenceManager.getDefaultSharedPreferences(application);
    }

    @Provides
    @Singleton
    Cache provideOkHttpCache(Application application) {
        int cacheSize = 10 * 1024 * 1024; // 10 MiB
        Cache cache = new Cache(application.getCacheDir(), cacheSize);
        return cache;
    }

    @Provides
    @Singleton
    Gson provideGson() {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
        return gsonBuilder.create();
    }

    @Provides
    @Singleton
    OkHttpClient provideOkHttpClient(Cache cache) {
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newBuilder()
                //.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
                .cache(cache)
                .build();
        return okHttpClient;
    }

    @Provides
    @Singleton
    @Named("authRetrofit")
    Retrofit provideAuthRetrofit(Gson gson, OkHttpClient okHttpClient) {
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gson))
                .baseUrl(PAYMENT_SERVICE)
                .client(okHttpClient)
                .build();
        return retrofit;
    }

    @Provides
    @Singleton
    @Named("paymentRetrofit")
    Retrofit providePaymentRetrofit(Gson gson, OkHttpClient okHttpClient) {
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gson))
                .baseUrl(LOGIN_SERVICE)
                .client(okHttpClient)
                .build();
        return retrofit;
    }


}

ValidatorModule.java

@Module
public class ValidatorModule {

    private final Activity activity;


    public ValidatorModule(Activity activity) {
        this.activity = activity;
    }

    @Provides
    com.mobsandgeeks.saripaar.Validator providesValidator() {
        return new com.mobsandgeeks.saripaar.Validator(activity);
    }
}

AppApplication.java

public class AppApplication extends Application {

    private NetComponent mNetComponent;

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

        mNetComponent = DaggerNetComponent.builder()
                .appModule(new AppModule(this))
                .build();
    }

    public NetComponent getmNetComponent() {
        return mNetComponent;
    }

}

AuthenticationActivity.java

public class AuthenticationActivity extends BaseActivity implements View.OnClickListener, Validator.ValidationListener {

    @Inject
    Validator validator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ....

        ((AppApplication) getApplication()).getmNetComponent().inject(this);

        ValidationComponent validationComponent = DaggerValidationComponent.builder()
                .validatorModule(getValidatorModule())
                .build();

        validationComponent.inject(this);

        ...

        // apply click and validation listeners
        validator.setValidationListener(this);
    }
}   

protected ValidatorModule getValidatorModule() {
    return new ValidatorModule(this);
}

正在生成 ValidationComponent 但未生成 DaggerNetComponent

以上是我的模块,我的应用程序的组件。当我编译和构建应用程序时,出现以下错误 -

错误

Information:Gradle tasks [clean, :app:generateDebugSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies, :app:generateDebugAndroidTestSources, :app:compileDebugSources, :app:compileDebugUnitTestSources, :app:compileDebugAndroidTestSources]
C:\Users\xyz\AndroidStudioProjects\ICICIAppathon\app\src\main\java\com\icici\iciciappathon\AppApplication.java
Error:(24, 48) error: cannot find symbol class DaggerNetComponent
C:\Users\xyz\AndroidStudioProjects\ICICIAppathon\app\src\main\java\com\icici\iciciappathon\login\AuthenticationActivity.java
Error:(35, 48) error: cannot find symbol class DaggerValidationComponent
Error:(39, 43) error: package com.icici.iciciappathon.databinding does not exist
C:\Users\xyz\AndroidStudioProjects\ICICIAppathon\app\src\main\java\com\icici\iciciappathon\checkout\PaymentActivity.java
Error:(28, 43) error: package com.icici.iciciappathon.databinding does not exist
C:\Users\xyz\AndroidStudioProjects\ICICIAppathon\app\src\main\java\com\icici\iciciappathon\dashboard\DashboardActivity.java
Error:(32, 43) error: package com.icici.iciciappathon.databinding does not exist
C:\Users\xyz\AndroidStudioProjects\ICICIAppathon\app\src\main\java\com\icici\iciciappathon\shopping\ScanBarcodeActivity.java
Error:(41, 43) error: package com.icici.iciciappathon.databinding does not exist
C:\Users\xyz\AndroidStudioProjects\ICICIAppathon\app\src\main\java\com\icici\iciciappathon\ui\GetStartedActivity.java
Error:(27, 43) error: package com.icici.iciciappathon.databinding does not exist
C:\Users\xyz\AndroidStudioProjects\ICICIAppathon\app\src\main\java\com\icici\iciciappathon\dagger\component\NetComponent.java
Error:(34, 10) error: com.mobsandgeeks.saripaar.Validator cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method.
com.icici.iciciappathon.login.AuthenticationActivity.validator
[injected field of type: com.mobsandgeeks.saripaar.Validator validator]
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
Information:BUILD FAILED
Information:Total time: 11.373 secs
Information:9 errors
Information:0 warnings
Information:See complete output in console

在您的 onCreate() 中,您有以下代码:

((AppApplication) getApplication()).getmNetComponent().inject(this);

ValidationComponent validationComponent = DaggerValidationComponent.builder()
        .validatorModule(getValidatorModule())
        .build();

validationComponent.inject(this);

并且您已声明愿意@Inject一个Validator实例。

因此,当达到 getmNetComponent().inject(this) 时,Dagger 将尝试注入该依赖项,但它无法在该组件中找到,因为它将由 ValidatorComponent 提供(稍后将执行)。

在这种情况下,您必须使用 subcomponents。基本上,您的 ValidatorComponent 需要查看 NetworkComponent 提供的所有依赖项,并添加一些自己的依赖项。

应进行以下更改:

NetComponent.java



    @Singleton
    @Component(modules = {AppModule.class, NetModule.class})
    public interface NetComponent {
        void inject(AuthenticationActivity authenticationActivity);

        void inject(PaymentActivity paymentActivity);

        ValidatorComponent validatorComponent(ValidatorModule validatorModule);
    }


ValidationComponent.java



    @YourCustomScope
    @Subcomponent(modules = {ValidatorModule.class})
    public interface ValidationComponent {
        void inject(Activity activity);
    }


AuthenticationActivity.java



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ((AppApplication) getApplication()).getmNetComponent()
                                           .validatorModule(new ValidatorModule(this))
                                           .inject();

    }


YourCustomScope.java



    @Scope
    @Documented
    @Retention(RUNTIME)
    public @interface YourCustomScope {}    


这里的一般说明是 Dagger 在遇到错误时不会生成 类,通常是当您在绑定图中执行不可能的操作时。就是这样。

C:\Users\xyz\AndroidStudioProjects\ICICIAppathon\app\src\main\java\com\icici\iciciappathon\dagger\component\NetComponent.java Error:(34, 10) error: com.mobsandgeeks.saripaar.Validator cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method. com.icici.iciciappathon.login.AuthenticationActivity.validator [injected field of type: com.mobsandgeeks.saripaar.Validator validator]

我同意 的观点,问题是您试图从 AuthenticationActivity 中注入 Validator,并告诉 NetComponent 尝试这样做而不指示它如何这样做(在 ValidationModule 中)。

在您发布的代码中,NetComponent 没有理由注入 AuthenticationActivity;它没有什么可以提供的。所以你可以删除这两行并完成:

// In NetComponent
void inject(AuthenticationActivity authenticationActivity);

// In AuthenticationActivity
((AppApplication) getApplication()).getmNetComponent().inject(this);

但是,也有可能您只是没有向我们展示您在 AuthenticationActivity 中所需的 NetComponent 依赖项。在这种情况下,您将需要通过子组件或组件依赖性来组合对象图。 您仍然需要删除上面列出的两行,因为在任何情况下 NetComponent 都没有注入 AuthenticationActivity 所需的依赖项。

子组件

要使用 subcomponents 做到这一点,只需在 NetComponent 上创建一个构建器,通过它您可以获取 ValidationActivity。欢迎您提供示波器,但您不一定需要示波器,我认为将其添加到组合中可能会造成混淆。那时,您的 ValidationComponent 将有权访问您的 NetComponent 中的所有绑定以及 ValidationComponent 中列出的所有绑定。这实际上与 azizbekian 的答案相同,尽管值得注意的是这是通过子组件而不是组件依赖项。一会儿再说组件依赖

// After removing the inject(AuthenticationActivity) call, add this to NetComponent
ValidatorComponent validatorComponent(ValidatorModule validatorModule);

// And call the implementation from AuthenticationActivity
((AppApplication) getApplication()).getmNetComponent()
    .validatorModule(new ValidatorModule(this))
    .inject();

您还需要将 ValidationComponent@Component 切换到 @Subcomponent,并删除 @Singleton 实例(这是有道理的,因为您正在创建一个新的Android 创建的每个 AuthenticationActivity 实例一个。

实际上,这将 NetComponent 变成了 ValidationComponent 实例的 工厂。 Dagger 同时为两者生成代码,因此 ValidationComponent 可以自动从 NetComponent 访问它需要的任何内容。但是,这种方式不可能为每个单独生成代码,或者在没有 NetComponent 实例的情况下获得 ValidationComponent(除非通过将其包含在另一个组件中)。

组件依赖关系

Component dependencies 的工作方式略有不同。它们是独立的组件,因此可以分别独立生成。相反,您可以传入一个接口(通常但不一定是另一个 Dagger 组件,如 NetComponent),每个单独的无参数方法都会成为另一个图中的自动提供程序。这意味着,例如,您可以列出 NetComponent 中 ValidationComponent 可用的特定依赖项,将 dependencies={NetComponent.class} 添加到您的 ValidationComponent 定义,然后更改您的 DaggerValidationComponent 构建器以调用 .netComponent(((AppApplication getApplication()).getmNetComponent()) 来挂接确切的实例。 (同样,您可以对该接口的任何实现执行此操作,无论 Dagger 是否生成它;这有助于测试。)您还需要删除 @Singleton 的使用,因为 Dagger 会非常混乱让两个单独的组件都声称存在于单例范围内——毕竟必须先创建一个组件。

您没有列出您从 NetComponent 使用的确切依赖项,所以我没有可以展示的示例更改。但是,对于这种情况,我还是建议使用子组件;绑定更加自动化,您可能不会从组件依赖性中获得的松散耦合中受益,并且您更接近 Dagger's official Android support package 的设计,因此以后更容易迁移到该设计。

如果您使用的是 kotlin,则必须添加

apply plugin: 'kotlin-kapt'

在您的 build.gradle 文件中 并在依赖项中使用 kapt 而不是 annotationProcessor

改变这个:

implementation 'com.google.dagger:dagger:2.22'
annotationProcessor 'com.google.dagger:dagger-compiler:2.22'
implementation 'com.google.dagger:dagger-android:2.22'
implementation 'com.google.dagger:dagger-android-support:2.22'
annotationProcessor 'com.google.dagger:dagger-android-processor:2.22'

对此:

kapt 'com.google.dagger:dagger-compiler:2.22'
implementation 'com.google.dagger:dagger-android:2.22'
implementation 'com.google.dagger:dagger-android-support:2.22'
kapt 'com.google.dagger:dagger-android-processor:2.22'