Gradle整合Spring Boot排除日志依赖引发NoClassDefFoundError求助
NoClassDefFoundError: org/apache/commons/logging/LogFactory in Spring Boot + Gradle with Log4j Got it, let's work through this issue together. That error pops up because your project is missing the necessary bridge or dependency to handle Spring's underlying logging requirements when you switch to Log4j. Here's how to fix it step by step:
Why This Happens
Spring Framework relies on Apache Commons Logging as its default logging abstraction. When you replace the default Logback setup with Log4j, you need to either:
- Provide a bridge that redirects Commons Logging calls to Log4j, or
- Use Spring Boot's pre-configured Log4j starter that handles this automatically.
Step 1: Update Your Gradle Dependencies
The easiest way to resolve this is to use Spring Boot's official spring-boot-starter-log4j2 (recommended over legacy Log4j 1.x) and exclude the default logging starter. Here's what your build.gradle dependencies block should look like:
dependencies { // Exclude Spring Boot's default Logback and Commons Logging dependencies implementation('org.springframework.boot:spring-boot-starter') { exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging' exclude group: 'commons-logging', module: 'commons-logging' } // Add the Log4j 2 starter (includes all necessary bridges like jcl-over-slf4j) implementation 'org.springframework.boot:spring-boot-starter-log4j2' // If you *must* use legacy Log4j 1.x (not recommended), use these instead: // implementation 'org.slf4j:jcl-over-slf4j:1.7.36' // implementation 'org.slf4j:slf4j-log4j12:1.7.36' }
The spring-boot-starter-log4j2 includes jcl-over-slf4j, which acts as a drop-in replacement for Commons Logging. It redirects all of Spring's logging calls to SLF4J, which then routes them to Log4j 2.
Step 2: Verify Your Dependency Tree
To make sure Commons Logging isn't being pulled in accidentally by another dependency, run this Gradle command to inspect your dependency tree:
./gradlew dependencies --configuration compileClasspath
Search the output for commons-logging. If you see it listed, check which dependency is bringing it in and add an exclude rule for that dependency as well.
Step 3: Confirm Your Log4j Configuration
While this error isn't caused by a bad config, double-check that your Log4j config file (e.g., log4j2.xml, log4j2.properties) is placed in src/main/resources and is properly formatted. This ensures your logging works once the dependency issue is fixed.
内容的提问来源于stack exchange,提问作者frozencure

