springboot 热启动配置方案

Spring Boot 的热启动(热部署)主要通过 **`spring-boot-devtools`** 模块实现,它能在代码修改后自动重启应用(无需手动停止再启动),大幅提升开发效率。以下是详细配置和使用指南:


一、核心机制

spring-boot-devtools 通过两阶段实现热更新:

  1. 自动重启(Restart)
    检测到 classpath 下的文件变动(如 Java 类、配置文件)→ 触发应用重启(速度比冷启动快)。
  2. 实时重载(LiveReload)
    配合浏览器插件,静态资源(HTML/CSS/JS)修改后自动刷新页面。

二、快速配置(3步)

1. 添加依赖

xml

<!-- Maven pom.xml -->
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional> <!-- 避免依赖传递 -->
    </dependency>
</dependencies>

gradle

// Gradle build.gradle
dependencies {
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
}
2. 开启 IDEA 自动编译
  • 设置路径
    Settings > Build, Execution, Deployment > Compiler
    ✅ 勾选 Build project automatically
  • 启用运行时编译 (关键步骤!):
    Ctrl + Shift + A 搜索 Registry → 勾选:

    代码

    compiler.automake.allow.when.app.running
    
3. 修改配置(可选)

yaml代码

# application.yml
spring:
  devtools:
    restart:
      enabled: true  # 默认true,可关闭
      trigger-file: .trigger # 用此文件触发重启(避免频繁保存触发)
      exclude: static/**      # 排除无需监控的目录

三、使用技巧

▶ 静态资源热更新(无需重启)
  • 前端文件位置src/main/resources/static 或 public
  • 浏览器安装插件LiveReload
  • 修改 CSS/JS/HTML 后 → 自动刷新页面
▶ 跳过指定文件重启

java代码

// 在代码中排除触发重启
@SpringBootApplication
public class App {
    public static void main(String[] args) {
        System.setProperty("spring.devtools.restart.exclude", "templates/**");
        SpringApplication.run(App.class, args);
    }
}
▶ 手动触发重启

在项目中创建 src/main/resources/.trigger 文件(文件名与配置一致),修改该文件触发重启。


四、常见问题解决

❌ 修改 Java 代码后未重启
  • 检查是否关闭了 IDEA 的 Build project automatically
  • 确认 Registry 中的 compiler.automake.allow.when.app.running 已启用
  • 尝试手动 Build:Build > Build Project (Ctrl+F9)
❌ 静态资源修改未刷新
  • 检查是否使用了 src/main/webapp 目录(不推荐) → 改用 static 或 public
  • 浏览器禁用缓存:开发者工具 → Network → ✅ Disable cache
❌ 热部署失效(多模块项目)

在子模块的 pom.xml 中添加:

xml代码

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <excludeDevtools>false</excludeDevtools>
            </configuration>
        </plugin>
    </plugins>
</build>

五、高级方案:JRebel(付费)

若需 无重启热更新(直接替换内存中的类),推荐 JRebel

  1. 安装 IDEA 插件:JRebel and XRebel
  2. 激活(可试用14天)
  3. 启动项目时选择 ▶ Debug with JRebel

优势:修改 Java 代码后无需重启应用,实时生效(对大型项目提速显著)。


六、热启动原理图

mermaid代码导出svg

⚠️ 生产环境警告:务必移除 spring-boot-devtools 依赖(通过 <scope>provided</scope> 或 developmentOnly),避免安全风险!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值