如何使用 #messages.format(...) 对数字和日期进行本地化格式化?是否依赖 java.time 包?
解读
面试官抛出此题,通常想验证三件事:
- 你是否真的用过 Thymeleaf 的国际化工具,而不是只会写
th:text="#{...}"; - 你是否知道
#messages.format(...)底层就是 JDK 的MessageFormat,因此可以插数字、日期、货币; - 你是否清楚 Java 8 以后
java.time与旧Date在格式化器上的差异,以及 Spring Boot 2.x+ 默认已经帮你把java.time的支持加进来了。
国内项目 90% 直接上 Spring Boot,默认就带 spring-boot-starter-thymeleaf,所以回答时要把“Spring 上下文里已经给你配好了 MessageSource”这一点讲出来,才能体现工程落地经验。
知识点
#messages是 Thymeleaf 在上下文中自动暴露的Messages对象,对应接口org.thymeleaf.context.IMessages,其实现又委托给 Spring 的MessageSource。#messages.format(key, arg0, arg1...)等价于 Spring 的MessageSource#getMessage(key, args, locale),底层用java.text.MessageFormat做占位替换。MessageFormat支持{0,number,currency}、{0,date,short}、{0,date,yyyy-MM-dd HH:mm:ss}等模式;因此模板里只要把数字/日期对象当参数传进去即可,无需手写DecimalFormat或DateTimeFormatter。- 如果参数类型是
java.time系列(LocalDateTime、LocalDate、Instant等),Spring Boot 2.x 默认会注册FormattingConversionService,并自动装配DateTimeFormatterRegistrar,所以MessageFormat仍然能识别;换言之“不强制依赖,但已经内置好”。 - 若项目降到 Spring Boot 1.x 或纯 Servlet 项目,需要手动注册
java.time的格式化器,否则只能传java.util.Date。
答案
步骤一:在 messages.properties 里写带占位符的模板
order.info=订单编号:{0},金额:{1,number,currency},下单时间:{2,date,yyyy-MM-dd HH:mm:ss}
步骤二:在 Controller 把数据放进 Model
model.addAttribute("orderSn", "JD20240518001");
model.addAttribute("amount", new BigDecimal("128.88"));
model.addAttribute("orderTime", LocalDateTime.now()); // java.time 类型
步骤三:在 HTML 里用 #messages.format(...) 输出
<p th:text="${#messages.format('order.info', orderSn, amount, orderTime)}"></p>
浏览器里中文环境显示:
订单编号:JD20240518001,金额:¥128.88,下单时间:2024-05-18 14:32:15
结论:
- 数字、日期本地化完全靠
#messages.format(...)就能完成; - 参数可以是
BigDecimal、LocalDateTime等,Spring Boot 已内置java.time的转换器,因此“不额外依赖,但默认已支持”。
拓展思考
-
性能角度:
高并发场景下,#messages.format(...)每次都会新建MessageFormat实例,可配合th:cache="messages"或自己在 Service 层缓存MessageFormat对象,减少 GC 压力。 -
多语言货币切换:
国内电商出海,要求同一套模板支持 “人民币/美元/欧元” 动态切换,可在MessageSource外层再包一层CurrencySymbolMessageSource,根据当前Locale把{1,number,currency}的货币符号动态替换成对应币种的符号,模板层无感。 -
前后端分离趋势:
如果公司采用 “Thymeleaf 只做首屏渲染 + 后续走接口” 的混合架构,可以把#messages.format(...)封装成工具方法,在构建静态 HTML 片段时一次性渲染好,避免前端再写一套Intl.NumberFormat,实现真正的“SEO 友好 + 无 JS 也能看”。