报错信息:
java.lang.ClassCastException: class com.xxx.xxx.model.entity.User cannot be cast to class com.xxx.xxx.model.entity.User (com.xxx.xxx.model.entity.User is in unnamed module of loader 'app'; com.xxx.xxx.model.entity.User is in unnamed module of loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader @aa9f719)
造成原因:
- 重复加载类:当同一个类被两个不同的类加载器加载时,即使它们来自同一个
.class文件,Java 也会认为它们是不同的类。因此,不能互相转换。在堆栈跟踪中,可以看到RestartClassLoader和应用程序默认的类加载器都在加载User类,这导致了类型不兼容的问题。 - Spring Boot DevTools:在 Spring Boot 应用程序中使用了 DevTools 时,DevTools 提供了一个重启功能,它会使用自己的类加载器(即
RestartClassLoader)来加载某些类,以便支持热部署。如果User类是在重启功能生效的情况下被加载的,那么它可能会与同一项目中的其他部分使用的User类不兼容。
解决办法:
方案一、注释或删除 pom.xml 文件中的 spring-boot-devtools 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
方案二、在启动类或配置文件中禁用 spring-boot-devtools 热部署功能
// 启动类
@SpringBootApplication
@MapperScan("com.xxx.xxx.mapper")
public class MainApplication {
public static void main(String[] args) {
System.setProperty("spring.devtools.restart.enabled", "false");
SpringApplication.run(MainApplication.class, args);
}
}
# application.yaml
spring:
devtools:
restart:
enabled: false