如何使用 #messages.format(...) 对数字和日期进行本地化格式化?是否依赖 java.time 包?

解读

面试官抛出此题,通常想验证三件事:

  1. 你是否真的用过 Thymeleaf 的国际化工具,而不是只会写 th:text="#{...}";
  2. 你是否知道 #messages.format(...) 底层就是 JDK 的 MessageFormat,因此可以插数字、日期、货币;
  3. 你是否清楚 Java 8 以后 java.time 与旧 Date 在格式化器上的差异,以及 Spring Boot 2.x+ 默认已经帮你把 java.time 的支持加进来了。

国内项目 90% 直接上 Spring Boot,默认就带 spring-boot-starter-thymeleaf,所以回答时要把“Spring 上下文里已经给你配好了 MessageSource”这一点讲出来,才能体现工程落地经验。

知识点

  1. #messages 是 Thymeleaf 在上下文中自动暴露的 Messages 对象,对应接口 org.thymeleaf.context.IMessages,其实现又委托给 Spring 的 MessageSource。
  2. #messages.format(key, arg0, arg1...) 等价于 Spring 的 MessageSource#getMessage(key, args, locale),底层用 java.text.MessageFormat 做占位替换。
  3. MessageFormat 支持 {0,number,currency}、{0,date,short}、{0,date,yyyy-MM-dd HH:mm:ss} 等模式;因此模板里只要把数字/日期对象当参数传进去即可,无需手写 DecimalFormat 或 DateTimeFormatter。
  4. 如果参数类型是 java.time 系列(LocalDateTime、LocalDate、Instant 等),Spring Boot 2.x 默认会注册 FormattingConversionService,并自动装配 DateTimeFormatterRegistrar,所以 MessageFormat 仍然能识别;换言之“不强制依赖,但已经内置好”。
  5. 若项目降到 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

结论:

  1. 数字、日期本地化完全靠 #messages.format(...) 就能完成;
  2. 参数可以是 BigDecimal、LocalDateTime 等,Spring Boot 已内置 java.time 的转换器,因此“不额外依赖,但默认已支持”。

拓展思考

  1. 性能角度:
    高并发场景下,#messages.format(...) 每次都会新建 MessageFormat 实例,可配合 th:cache="messages" 或自己在 Service 层缓存 MessageFormat 对象,减少 GC 压力。

  2. 多语言货币切换:
    国内电商出海,要求同一套模板支持 “人民币/美元/欧元” 动态切换,可在 MessageSource 外层再包一层 CurrencySymbolMessageSource,根据当前 Locale 把 {1,number,currency} 的货币符号动态替换成对应币种的符号,模板层无感。

  3. 前后端分离趋势:
    如果公司采用 “Thymeleaf 只做首屏渲染 + 后续走接口” 的混合架构,可以把 #messages.format(...) 封装成工具方法,在构建静态 HTML 片段时一次性渲染好,避免前端再写一套 Intl.NumberFormat,实现真正的“SEO 友好 + 无 JS 也能看”。