Java中找不到Dagger组件错误?

时间:2019-02-03 02:04:33

标签: java dagger

public class ToInject {
    public int val = 0;

    public ToInject(){
        System.out.println("Default");
    }
}
@Module
public class ToInjectModule {
    @Provides
    @Singleton
    public ToInject provideToInject(){
        return new ToInject();
    }
}
@Component(modules = ToInjectModule.class)
public interface ToInjectModuleComponent {
    WillGetInjected willGetInjectedMaker();
}
public class WillGetInjected {
    private ToInject toInject;
    @Inject
    public WillGetInjected(ToInject toInject){
        this.toInject = toInject;
        System.out.println(this.toInject.val);
    }
}

如上所述,我正在尝试将ToInject注入WillGetInjected中。我有一个ToInjectModule,也有一个ToInjectModuleComponent,所以我完全完全按照说明进行操作。我还导入了

<dependency>
            <groupId>com.google.dagger</groupId>
            <artifactId>dagger</artifactId>
            <version>2.0</version>
        </dependency>

但是当我执行mvn compile时,我仍然收到此错误:

Fatal error compiling: java.lang.NoClassDefFoundError: dagger/Subcomponent$Builder: dagger.Subcomponent$Builder -> [Help 1]

知道发生了什么,为什么?

1 个答案:

答案 0 :(得分:0)

有两个失踪案。

  1. dagger compiler添加到pom.xmlLink
<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.6.1</version>
      <configuration>
        <annotationProcessorPaths>
          <path>
            <groupId>com.google.dagger</groupId>
            <artifactId>dagger-compiler</artifactId>
            <version>2.x</version>
          </path>
        </annotationProcessorPaths>
      </configuration>
    </plugin>
  </plugins>
</build>
  1. annotation scope添加到组件中。 (Link参见Singletons and Scoped Bindings
@Component(modules = ToInjectModule.class)
public interface ToInjectModuleComponent {
    WillGetInjected willGetInjectedMaker();
}

@Singleton
@Component(modules = ToInjectModule.class)
public interface ToInjectModuleComponent {
    WillGetInjected willGetInjectedMaker();
}