本篇文章介绍了 Java 中的 java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory 错误。

解决java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory

使用 Apache Commons 和 Spring 时,注入依赖项时可能会出现错误 java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory。 该错误通常如下所示:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory

at org.springframework.context.support.AbstractApplicationContext.(AbstractApplicationContext.java:119)

at org.springframework.context.support.AbstractXmlApplicationContext.(AbstractXmlApplicationContext.java:55)

at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:77)

at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:65)

at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:56)

at com.client.StoryReader.main(StoryReader.java:15)

出现此错误的原因有:

Apache Commons Logging jar 文件不正确或不存在。Commons Logging 未添加到依赖项中。

针对上述原因,解决此问题的方法如下:

添加正确的 Apache Commons 日志 jar

如果 Apache Commons Logging jar 没有添加到项目的构建路径中或者添加的文件不正确,那么它将抛出 java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory 错误。

请按照以下步骤解决此问题:

从此处下载 Apache Commons Logging jar。将 jar 添加到项目的构建路径中。

上述两个步骤应该可以解决错误 java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory。 如果您使用的是Maven或Spring,则需要添加依赖项。

将 Commons 日志记录添加到依赖项

如果您使用 Maven 并且依赖项中缺少 Apache Commons-Logging,则会抛出 java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory 错误。 将以下依赖项添加到 pom.xml:

commons-logging

commons-logging

1.2

添加上述依赖即可解决Maven的问题。

在使用 Spring 应用程序的情况下,开发人员有时会排除 Commons Logging,但忘记插入另一个日志框架,因为应用程序需要日志框架:

org.springframework

spring-webmvc

${spring.version}

commons-logging

commons-logging

上面的pom.xml是针对Spring应用程序的,我们可以看到,Commons-Logging被排除在外; 这就是它抛出 java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory 错误的原因。

为了解决这个问题,我们必须添加另一个日志框架; 大多数时候,开发人员使用 SLF4j 日志记录。 我们还需要使用桥来重定向 Spring 的日志记录。

将以下内容添加到 Spring 应用程序的 pom.xml 中:

org.springframework

spring-webmvc

${spring.version}

commons-logging

commons-logging

org.slf4j

jcl-over-slf4j

${jcl.slf4j.version}

ch.qos.logback

logback-classic

${logback.version}

对 Maven 和 Spring 执行上述过程将修复 java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory 错误。

相关文章

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。