Spring4迁移至Spring5后使用SpringJUnit4ClassRunner的JUnit测试失败
NoSuchFieldError: TRACE的解决方案 Hey there, let's break down this issue you're hitting after moving from Spring 4 to Spring 5. That java.lang.NoSuchFieldError: TRACE buried in the stack trace is the key clue here—it almost always signals a dependency conflict with logging frameworks, which is super common when upgrading major Spring versions.
Why this happens
Spring 5 raises the minimum version requirements for logging libraries like SLF4J and Logback. If your project still has older versions of these libraries (from the Spring 4 era) or mixes conflicting versions via transitive dependencies, the JVM can't find the expected TRACE field in logging API classes (like org.slf4j.event.Level), leading to the bean creation failure for entityManagerFactoryBean.
Step-by-step fixes
Unify SLF4J and Logback versions
Spring 5.x typically requires SLF4J 1.7.25+ and Logback 1.2.x+. Use Maven'sdependencyManagement(or Gradle's platform plugin) to lock these versions across your project, eliminating transitive version mismatches. Example for Maven:<dependencyManagement> <dependencies> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.36</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.11</version> </dependency> </dependencies> </dependencyManagement>Hunt down conflicting dependencies
Runmvn dependency:tree(Maven) orgradle dependencies(Gradle) to generate a dependency tree. Look for multiple versions of SLF4J, Logback, or legacy logging libraries likecommons-loggingorlog4j. Exclude outdated or conflicting dependencies from third-party libraries. For example:<dependency> <groupId>com.example.thirdparty</groupId> <artifactId>legacy-library</artifactId> <version>2.0.0</version> <exclusions> <exclusion> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </exclusion> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency>Ensure consistent Spring dependencies
Double-check that all Spring-related dependencies (includingspring-test) are on the same Spring 5 version. Mixing Spring 4 and 5 artifacts will cause all sorts of compatibility issues, including this one.Clean and rebuild your project
Old cached dependencies can linger and cause problems. Runmvn clean install(Maven) orgradle clean build(Gradle) to wipe local build artifacts and re-download the correct versions of your dependencies.
Final note
This error is a classic case of version mismatch between your logging stack and Spring 5's requirements. By standardizing your logging library versions and eliminating conflicts, you should get those JUnit tests passing again in no time.
内容的提问来源于stack exchange,提问作者TestUser

