1. Spring Boot自动配置原理
核心机制:
Spring Boot通过@EnableAutoConfiguration注解触发自动配置,结合spring.factories文件中的EnableAutoConfiguration列表加载组件。其核心逻辑如下:
-
条件化配置 :使用
@Conditional系列注解(如@ConditionalOnClass、@ConditionalOnMissingBean)判断是否启用配置。 -
默认配置覆盖 :用户可通过
application.properties覆盖默认属性(如数据库连接、端口号)。 -
扩展性 :通过自定义
@Configuration类或扩展WebMvcConfigurer实现个性化配置。
示例:
# 修改Tomcat端口
server.port=8081
# 关闭Thymeleaf缓存(开发环境建议关闭)
spring.thymeleaf.cache=false
2. 静态资源映射规则
默认资源路径:
Spring Boot默认从以下路径加载静态资源(按优先级排序):
-
classpath:/META-INF/resources/ -
classpath:/resources/ -
classpath:/static/ -
classpath:/public/ -
项目根路径
/**(如localhost:8080/abc)。
配置类解析:
@ConfigurationProperties(prefix = "spring.resources")
public class ResourceProperties {
private List<String> staticLocations; // 静态资源路径
private int cachePeriod; // 缓存时间(秒)
}
扩展方法:
通过实现WebMvcConfigurer自定义资源映射:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/custom/**")
.addResourceLocations("file:D:/uploads/");
}
}
3. Thymeleaf模板引擎
核心优势:
-
自然语法,无需编译,直接在浏览器中打开HTML调试。
-
支持HTML5、XML、JavaScript等格式,与Spring Security深度集成。
基本语法:
| 标签 | 功能 | 示例 |
|---|---|---|
th:text |
文本替换(自动转义) | <p th:text="${msg}"></p> |
th:utext |
不转义输出 | <div th:utext="${html}"></div> |
th:each |
循环遍历 | <tr th:each="user : ${users}"> |
th:href |
动态生成URL | <a th:href="@{/user/{id}(id=${user.id})}"> |
th:if/th:unless |
条件判断 | <div th:if="${user.age > 18}"> |
国际化支持:
-
在
src/main/resources下创建messages_xx.properties文件(如messages_en_US.properties)。 -
使用
#{key}引用国际化文本:<button th:text="#{button.submit}"></button> <div th:text="#{welcome(${name})}"></div>
4. 配置扩展与最佳实践
静态资源优化:
-
WebJars :通过
webjars引入前端库(如jQuery),访问路径为/webjars/jquery/3.3.1/jquery.js。 -
欢迎页 :静态资源文件夹下的
index.html自动映射到根路径/。
Thymeleaf配置:
# 自定义模板路径和缓存
spring.thymeleaf.prefix=classpath:/custom-templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
Tymeleaf语法整理
1. 变量表达式与文本输出
HTML示例:
<!-- 变量表达式 -->
<div th:text="${msg}"></div>
<!-- 不转义输出 -->
<div th:utext="${htmlContent}"></div>
Controller代码:
@GetMapping("/test")
public String test(Model model) {
model.addAttribute("msg", "<h1>Hello Thymeleaf</h1>");
model.addAttribute("htmlContent", "<p>支持HTML标签</p>");
return "test";
}
说明:
-
th:text:自动转义HTML标签,防止XSS攻击。 -
th:utext:直接输出原始HTML内容。 -
数据通过
Model对象传递,键名需与模板中表达式一致。
2. 循环与迭代
HTML示例:
<!-- 集合遍历 -->
<h3 th:each="user : ${users}" th:text="${user}"></h3>
<!-- 列表索引 -->
<h3 th:each="user, iterStat : ${users}">索引:${iterStat.index}</h3>
Controller代码:
@GetMapping("/list")
public String list(Model model) {
model.addAttribute("users", Arrays.asList("Alice", "Bob", "Charlie"));
return "list";
}
说明:
-
th:each支持遍历List、Map、数组。 -
iterStat提供循环状态(索引、是否首尾等)。
3. 表单绑定与对象属性
HTML示例:
<form th:object="${user}">
<input th:value="*{name}" placeholder="用户名">
<input th:value="*{age}" type="number">
</form>
Controller代码:
@GetMapping("/form")
public String form(Model model) {
model.addAttribute("user", new User("张三", 25));
return "form";
}
说明:
-
th:object绑定表单对象,*{}访问对象属性。 -
表单提交时,Thymeleaf自动将输入值映射到Java对象。
4. 链接与URL生成
HTML示例:
<a th:href="@{/user/{id}(id=${user.id})}">用户详情</a>
<!-- 外部链接 -->
<a th:href="@{https://www.baidu.com}">百度</a>
Controller代码:
@GetMapping("/user/{id}")
public String getUser(@PathVariable Long id, Model model) {
model.addAttribute("id", id);
return "detail";
}
说明:
-
@{}生成动态URL,支持路径参数和查询参数。 -
自动拼接上下文路径(如
/app/user/1)。
5. 日期与数值格式化
HTML示例:
<!-- 日期格式化 -->
<span th:text="${#temporals.format(createTime, 'yyyy-MM-dd')}"></span>
<!-- 数值格式化 -->
<span th:text="${#numbers.formatDecimal(price, 1, 2)}"></span>
Controller代码:
@GetMapping("/date")
public String dateDemo(Model model) {
model.addAttribute("createTime", LocalDateTime.now());
model.addAttribute("price", 99.99);
return "date-demo";
}
说明:
-
#temporals处理日期,#numbers处理数值。 -
支持自定义格式(如
yyyy年MM月dd日)。
6. 国际化(i18n)
HTML示例:
<!-- 语言切换 -->
<a th:href="@{/i18n?lang=en_US}">English</a>
<a th:href="@{/i18n?lang=zh_CN}">中文</a>
<!-- 国际化文本 -->
<button th:text="#{button.submit}"></button>
资源文件 (messages_en_US.properties):
button.submit=Submit
welcome=Welcome, {0}!
Controller代码:
@GetMapping("/i18n")
public String i18n(Model model, Locale locale) {
model.addAttribute("lang", locale.getLanguage());
return "i18n";
}
说明:
-
通过
LocaleResolver解析语言环境。 -
{0}为参数占位符,支持动态替换。
7. 条件判断与逻辑运算
HTML示例:
<!-- 条件判断 -->
<div th:if="${user.age >= 18}">成年人</div>
<div th:unless="${user.vip}">非VIP用户</div>
<!-- 逻辑运算 -->
<div th:if="${user.score > 90 and user.status == 'active'}">优秀用户</div>
Controller代码:
@GetMapping("/condition")
public String condition(Model model) {
model.addAttribute("user", new User("李四", 22, true, 95.5));
return "condition";
}
说明:
-
支持
and、or、not逻辑运算符。 -
支持比较运算符(
>,<,==等)。
8. 片段复用与布局
HTML示例:
<!-- 定义片段 -->
<footer th:fragment="footer">
<p>版权所有 © 2023</p>
</footer>
<!-- 引用片段 -->
<div th:replace="~{common :: footer}"></div>
Controller代码:
@GetMapping("/layout")
public String layout() {
return "layout-demo";
}
说明:
-
th:fragment定义可复用代码块。 -
th:replace替换当前内容,th:insert插入内容。
9. 内联表达式与JavaScript
HTML示例:
<!-- 内联文本 -->
<span>[[${message}]]</span>
<!-- 内联脚本 -->
<script th:inline="javascript">
var user = [[${user}]];
console.log(user.name);
</script>
Controller代码:
@GetMapping("/inline")
public String inline(Model model) {
model.addAttribute("message", "内联表达式示例");
model.addAttribute("user", new User("王五", 30));
return "inline-demo";
}
说明:
-
[[...]]用于内联文本,避免转义。 -
th:inline="javascript"传递数据到JS。
总结
Thymeleaf通过声明式语法与Spring Boot无缝集成,核心优势包括:
-
自然模板:HTML直接可读,无需预编译。
-
动态绑定:支持对象属性、集合遍历、条件判断。
-
国际化:通过资源文件实现多语言支持。
-
扩展性:自定义格式化器、拦截器等。
最佳实践:
-
使用
th:object简化表单绑定。 -
优先使用
th:utext输出富文本内容。 -
通过
#temporals和#numbers规范日期/数值格式。 -
利用片段复用提升模板可维护性。