简体   繁体   中英

Java: Exception in thread “main” java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory

I have a project structured as

myproject/
         moduleA/
         moduleB/
         moduleC/

myproject has pom.xml as

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.4</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.0.3</version>
            <scope>provided</scope>
        </dependency>

Now moduleC needs moduleB code so it references the dependency as

       <dependency>
            <groupId>com.org.myproject</groupId>
            <artifactId>moduleB</artifactId>
            <version>${project.version}</version>
        </dependency>

But when I execute the class in moduleC , it complains

Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
......
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory

This happens when my moduleC class executes moduleB code.

What is that I am doing wrong? how can I fix this?

You are setting your dependencies to 'provided' which means that they won't be included in your runtime classpath. You are basically telling Maven that you will provide these files at runtime, so they are there for compilation, but unless you put them in your classpath manually they won't be there when you run.

Have a look here: http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Scope for more information on each of the scope levels.

If you specify nothing then the scope will be compile:

Compile is the default scope, used if none is specified. Compile dependencies are available in all classpaths of a project. Furthermore, those dependencies are propagated to dependent projects.

So you can omit your scope tag or explicitly add it as compile and when you run your app the dependencies will be included on the runtime classpath.

as per comment by @Dave, I did added the following to my pom.xml and things started to work as usual

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.6</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.0.6</version>
        </dependency>

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