Spring Boot集成Thymeleaf只需三步:添加spring-boot-starter-thymeleaf依赖、将HTML模板置于src/main/resources/templates目录并声明th命名空间、用@Controller返回视图名;自动配置已默认启用,开发时建议关闭缓存。

Spring Boot 集成 Thymeleaf 很简单,核心就三步:加依赖、放模板、写控制器。官方自动配置已覆盖大部分场景,不需要手动注册视图解析器。
添加 starter 依赖
在 pom.xml 中加入:
org.springframework.boot spring-boot-starter-thymeleaf
同时确保已有 spring-boot-starter-web(Web 功能必需)。Maven 会自动拉取 Thymeleaf 核心库 + Spring Boot 的自动配置类 ThymeleafAutoConfiguration。
按约定放好模板文件
Thymeleaf 默认从 src/main/resources/templates 目录加载 HTML 模板:
- 新建目录
resources/templates(若不存在) - 放入纯 HTML 文件,例如
index.html - 文件必须声明命名空间:
- 模板名(不含后缀)就是控制器返回的视图名,如
return "index";→ 渲染templates/index.html
控制器返回视图名
用 @Controller(非 @RestController),通过 Model 传数据,返回字符串视图名:
-
@Controllerpublic class HelloController { - @GetMapping("/")
- public String home(Model model) {
- model.addAttribute("msg", "欢迎使用 Thymeleaf");
- return "index"; // 自动匹配 templates/index.html
- }
- }
模板中用 th:text="${msg}" 即可显示内容。
开发阶段推荐配置
在 application.yml 中关闭缓存,让修改实时生效:
spring:thymeleaf:cache: falseencoding: UTF-8mode: HTML
注意:prefix 和 suffix 默认已是 classpath:/templates/ 和 .html,无需显式配置,除非你要改路径或后缀。











