Spring Boot DevTools 是開發階段的利器,提供類文件、配置文件、靜態資源的熱加載與應用快速重啟。本文詳細講解其原理、配置要點、Thymeleaf 頁面熱更新以及常見問題解決方案。
當檢測到 classpath 下文件變更,DevTools 丟棄舊的 Restart ClassLoader,創建新實例加載修改後的類,基礎類加載器保持不變,從而實現毫秒級重啟。
<dependencies>
<!-- Thymeleaf 模板引擎 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- DevTools 熱部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork> <!-- 關鍵:必須開啟 fork 才能觸發重啟 -->
</configuration>
</plugin>
</plugins>
</build>
optional=true 表示依賴不傳遞,避免影響依賴本項目的其他模塊。
src/main
├── java
│ └── com.xxx.firstboot.web
│ └── ThymeleafController.java
└── resources
├── static # 靜態資源(css、js、圖片)
└── templates # Thymeleaf 頁面(.html)
└── greet.html
@Controller
@RequestMapping("/thymeleaf")
@Api("測試Thymeleaf和devtools")
public class ThymeleafController {
@GetMapping("/greeting")
@ApiOperation("第一個thymeleaf程序")
public String greeting(@RequestParam(name = "name", defaultValue = "world") String name, Model model) {
model.addAttribute("xname", name);
return "greet"; // 解析為 templates/greet.html
}
}
<!DOCTYPE HTML>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<title>第一個thymeleaf程序</title>
<meta charset="UTF-8"/>
</head>
<body>
<p th:text="'Hello, ' + ${xname} + '!'"></p>
<div>1234567890!!!xx</div>
</body>
</html>
| 修改類型 | 應用行為 | 說明 |
|---|---|---|
| Java 類文件 | 應用重啟 | 保存觸發 Restart ClassLoader 重建 |
| 配置文件 | 應用重啟 | 同類文件 |
| Thymeleaf 頁面 | 不重啟,自動刷新 | DevTools 內嵌 LiveReload Server,瀏覽器自動刷新 |
# 默認排除目錄不觸發重啟(但會 LiveReload) # 可自定義排除: spring.devtools.restart.exclude=static/**,public/** # 在保留默認排除基礎上追加: spring.devtools.restart.additional-exclude=myfolder/** # 監聽非 classpath 目錄(如外部配置文件): spring.devtools.restart.additional-paths=/opt/config/
Build Automatically 開啟,且 spring-boot-maven-plugin 配置了 <fork>true</fork>。spring.thymeleaf.cache=false(DevTools 已自動設置),或手動添加。devtools 依賴的模塊才會被監聽,其他模塊需各自引入。掌握 DevTools 可顯著提升開發效率,配合 Thymeleaf 的 LiveReload 體驗接近前端熱更新,是 Spring Boot 開發的必備技能。