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

如何检测Spring Boot Devtools是否处于激活状态

Spring Boot Devtools 激活相关问题解答

一、激活判断的技术细节查询

直接查看Spring Boot Devtools的核心源码即可,关键逻辑集中在两个类:

  • DevToolsProperties:存储Devtools的配置项,其中restart.enabled控制是否开启功能。
  • DevToolsEnablementDeducer:负责自动推导是否激活Devtools,核心判断逻辑包括:
    • 检查应用是否为打包后的JAR/WAR(通过类加载器类型、构建任务标识判断);
    • 读取spring.devtools.restart.enabled配置的值;
    • 判断当前运行环境是否为开发环境(比如是否由IDE直接启动)。

二、运行时检测Devtools是否激活

推荐两种可靠的实现方式:

方式一:结合配置与类加载器判断

注入DevToolsProperties,同时检查当前上下文类加载器是否为Devtools专属的RestartClassLoader,兼顾配置状态与实际运行状态:

import org.springframework.boot.devtools.autoconfigure.DevToolsProperties;
import org.springframework.stereotype.Component;

@Component
public class DevtoolsStatusChecker {
    private final DevToolsProperties devToolsProperties;

    public DevtoolsStatusChecker(DevToolsProperties devToolsProperties) {
        this.devToolsProperties = devToolsProperties;
    }

    public boolean isDevtoolsActive() {
        boolean isConfigEnabled = devToolsProperties.getRestart().isEnabled();
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        boolean isRestartClassLoader = contextClassLoader.getClass().getName().equals("org.springframework.boot.devtools.restart.classloader.RestartClassLoader");
        return isConfigEnabled && isRestartClassLoader;
    }
}

方式二:直接检查类加载器类型

Devtools激活后会自动替换应用的上下文类加载器为RestartClassLoader,直接判断该类加载器是否存在即可:

public class DevtoolsUtils {
    public static boolean isDevtoolsActive() {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        return "org.springframework.boot.devtools.restart.classloader.RestartClassLoader".equals(classLoader.getClass().getName());
    }
}

内容的提问来源于stack exchange,提问作者Garret Wilson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 22:32:12