简体   繁体   中英

java.lang.NoClassDefFoundError: com/google/inject/Module using Guice

I am trying to use the DI mechanism provided by Google , but when I run my application, I am getting the following error:

Exception in thread "main" java.lang.NoClassDefFoundError: com/google/inject/Module
at challenge.App.main(App.java:19)
Caused by: java.lang.ClassNotFoundException: com.google.inject.Module
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more

The pom.xml file looks like:

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.inject</groupId>
      <artifactId>guice</artifactId>
      <version>4.1.0</version>
      <classifier>no_aop</classifier>
    </dependency>
  </dependencies>

And the code where I am using it looks like:

    Injector injector = Guice.createInjector(new DependenciesModule());
    IndexerController indexer = injector.getInstance(IndexerController.class);

And I have imported com.google.inject.Guice and com.google.inject.Injector

I have been checking for several places but I cannot see any relevant solution for this problems, I would appreciate a lot any glue.

This appears like the usual issue with Maven in that at runtime , the dependency classes (eg the Guice classes) are not available to the JVM.

The easiest solution is to use explicit classpath specification while running your app :

java -cp 
/path/to/guice.jar:
/path/too/your-app.jar:
/path/to/other/classes/not/bundled/in/your-app.jar 
main.MyClass

(this is all on one line, split for better viewing).

The other solution is to use Maven Shade Plugin which facilitates the creation of the executable JAR which you can simply run as java -jar uber.jar .

我能够使用以下方法安装丢失的 jar:

sudo apt-get install libguice-java

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