使用Spring Boot DevTools快速重启功能
背景
在Spring Boot项目中,修改一些简单的代码后,每次手动终止并启动整个项目比较繁琐且消耗时间。Spring Boot DevTools 提供了开发时的热重启功能,使得在开发过程中修改代码后可以快速生效,而无需手动重启整个应用,可以大幅减少重启时间。
Spring Boot DevTools:这是Spring Boot提供的开发工具,它能够监控类路径上的变化,并自动重启应用。但请注意,它并不是真正的热部署(即不需要任何重启),而是通过快速重启(Restart)来加载更改。它使用两个类加载器来实现快速重启,对于静态资源和模板文件的更改,只需要刷新浏览器即可看到变化。
配置步骤:
- 添加依赖到 pom.xml:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional>
</dependency>
- 在 IDEA 中开启自动编译:
- 打开设置 → Build, Execution, Deployment → Compiler
- 勾选 “Build project automatically”
- 开启 IDEA 的自动编译支持:
- 按 Ctrl+Shift+Alt+/ (Windows) 或 Cmd+Shift+Option+/ (Mac)
- 选择 “Registry”
- 勾选 “compiler.automake.allow.when.app.running”
注意:
新版 IntelliJ IDEA(2021.2 以后)里把compiler.automake.allow.when.app.running 这个选项从 Registry 移到了 Advanced Settings,所以当 Ctrl + Shift + Alt + / 打开 Registry 时搜不到就按一下做法:
(1)打开 Settings / Preferences
- Windows:File → Settings
- macOS:IntelliJ IDEA → Preferences
(2)左侧菜单选择 Advanced Settings(在最下面)
(3)在右侧找到Allow auto-make to start even if developed application is currently running,把它勾上即可
- 应用配置
在 application.yml 或 application.properties 中:
spring:devtools:restart:enabled: true # 启用热重启additional-exclude: static/** # 静态资源更改不触发重启thymeleaf:cache: false # 禁用模板缓存
启动一次应用
以后在 IDE 里 Ctrl+S 保存代码,Devtools 会监听 classpath 变化 → 自动重启(Restart 是秒级,比冷启动快很多)。
注意
• 静态资源(html、css、js)默认不会触发重启,而是直接刷新浏览器。
• 如果改的是 application.yml 或 pom.xml,需要手动重启。