You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Spring Boot DevTools避免类加载器冲突引发的接口加载失败

多模块Spring Boot项目DevTools RestartClassLoader冲突问题解决

问题现象

触发如下LinkageError错误:

java.lang.LinkageError: loader constraint violation: loader 'app' wants to load
interface com.company.core.AnInterface. A different interface with the same name was
previously loaded by org.springframework.boot.devtools.restart.classloader.RestartClassLoader
@7ee94bd7. (com.company.core.AnInterface is in unnamed module of loader
org.springframework.boot.devtools.restart.classloader.RestartClassLoader
@7ee94bd7, parent loader 'app')

项目结构

com.company.parent (整合所有模块)
com.company.app (依赖core和module模块)
com.company.core
com.company.module

相关代码

core模块的AnInterface接口

public interface AnInterface {
    String getInterfaceId();
    boolean isInterface(AnInterface anInterface);
}

module模块的AbstractEntity抽象类

@Data
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractEntity implements AnInterface {
    private String interfaceId;
    private abstract boolean isInterface(AnInterface anInterface);
}

app模块的SubEntity类

@Data
@Entity
@EntityListeners(AuditingEntityListener.class)
public class SubEntity extends AbstractEntity implements Serializable {
    @Override
    public boolean isInterface(AnInterface  anInterface) {
        // 省略空值检查
        return anInterface.getId().equals(getInterfaceId());
    }
}

问题原因

DevTools采用双类加载器机制:app类加载器负责加载第三方依赖,RestartClassLoader负责加载项目自身代码。但AnInterface被两个类加载器重复加载,JVM判定同一全限定名但不同类加载器加载的类为不同类,从而引发冲突。

解决方案

核心是确保AnInterface及其关联实现类仅由一个类加载器加载,具体配置如下:

方法1:使用spring-devtools.properties配置

在项目根目录或src/main/resources下创建spring-devtools.properties文件,添加规则指定目标模块由app类加载器加载:

# 匹配core模块的Jar包,让其由app加载器处理
restart.include.core=/com.company.core-.*\.jar
# 若module模块存在关联依赖,同步添加规则
restart.include.module=/com.company.module-.*\.jar

方法2:通过系统属性配置

在主启动类的main方法中,启动SpringApplication前设置系统属性:

public static void main(String[] args) {
    System.setProperty("restart.include.core", "com.company.core-.*\\.jar");
    System.setProperty("restart.include.module", "com.company.module-.*\\.jar");
    SpringApplication.run(AppApplication.class, args);
}

关键注意事项

  • 正则表达式需精准匹配模块Jar包名称(Maven构建的Jar包格式通常为{artifactId}-{version}.jar)
  • DevTools优先读取专属的spring-devtools.properties,避免与application.properties混用配置规则

验证

配置完成后重启项目,修改代码测试热重启功能,确认LinkageError不再出现,同时热加载正常工作。

内容的提问来源于stack exchange,提问作者Kerdos Media

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 14:02:38