简体   繁体   中英

Dagger component not found error in Java?

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);
    }
}

I am trying to inject ToInject into WillGetInjected as you see above. I have a ToInjectModule and als a ToInjectModuleComponent so I am following the instructions fully completely. I have also imported

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

But I keep getting this error when I do mvn compile :

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

Any idea what is happening and why?

There are two missings.

  1. Add dagger compiler into pom.xml ( Link )
<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. Add annotation scope into component. ( Link see Singletons and Scoped Bindings )
@Component(modules = ToInjectModule.class)
public interface ToInjectModuleComponent {
    WillGetInjected willGetInjectedMaker();
}

to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM