Dagger2找不到带注释的方法

时间:2019-06-19 15:00:00

标签: java gradle dagger-2

我正在使用Gradle构建Java项目,并使用Dagger2作为依赖项注入器。我收到此错误:

<path to the class>/MyComponent.java:13: error: [Dagger/MissingBinding] <package>.ConnectionDTO cannot be provided without an @Inject constructor or an @Provides-annotated method.
    ConnectionDTO sourceConnectionDTO();
                  ^
      <package>.ConnectionDTO is provided at
          <package>.MyComponent.sourceConnectionDTO()
<path to the class>/MyComponent.java:14: error: [Dagger/MissingBinding] <package>.ConnectionDTO cannot be provided without an @Inject constructor or an @Provides-annotated method.
    ConnectionDTO destinationConnectionDTO();
                  ^
      <package>.ConnectionDTO is provided at
          <package>.MyComponent.destinationConnectionDTO()

Java版本1.8 Gradle版本:5.4.1(也曾在4.5.1中尝试过)

匕首依赖项:

dependencies {
    annotationProcessor 'com.google.dagger:dagger-compiler:2.17'

    compile 'com.google.dagger:dagger:2.17'
    ...
}

模块类:

@Module
public class MyModule {
    private final MyConfiguration config;

    @Inject
    public MetaStoreModule(MyConfiguration config){
        this.config = config;
    }

    @Provides
    @Singleton
    @Named("sourceConnection")
    public ConnectionDTO sourceConnectionDTO() {
        return new ConnectionDTO(config.sourceHost(), config.sourceUser(),
                config.sourcePassword(), config.sourceDataBaseName());
    }

    @Provides
    @Singleton
    @Named("destinationConnection")
    public ConnectionDTO destinationConnectionDTO() {
        return new ConnectionDTO(config.destinationHost(), config.destinationUser(),
                config.destinationPassword(), config.destinationDataBaseName());
    }
}

组件类:

import dagger.Component;

import javax.inject.Singleton;

@Singleton
@Component(modules = MyModule.class)
public interface MyComponent{
    ConnectionDTO sourceConnectionDTO();
    ConnectionDTO destinationConnectionDTO();
}

不确定为什么要对方法进行注释,而构建无法识别

1 个答案:

答案 0 :(得分:2)

您没有在任何地方添加ConnectionDTO,这就是Dagger抱怨找不到它的原因。

您同时添加了@Named("sourceConnection") ConnectionDTO@Named("destinationConnection") ConnectionDTO,因此您还应该请求那些

@Singleton
@Component(modules = MyModule.class)
public interface MyComponent{
    @Named("sourceConnection")
    ConnectionDTO sourceConnectionDTO();

    @Named("destinationConnection")
    ConnectionDTO destinationConnectionDTO();
}