spring-tutorial/docs/01.Java/13.框架/01.Spring/01.Spring核心/26.Spring国际化.md

3.6 KiB
Raw Permalink Blame History

title date order categories tags permalink
Spring 国际化 2022-12-22 11:44:54 26
Java
框架
Spring
Spring核心
Java
框架
Spring
/pages/b5b8ad/

Spring 国际化

Spring 国际化使用场景

  • 普通国际化文案
  • Bean Validation 校验国际化文案
  • Web 站点页面渲染
  • Web MVC 错误消息提示

Spring 国际化接口

  • 核心接口:org.springframework.context.MessageSource
  • 主要概念
    • 文案模板编码code
    • 文案模板参数args
    • 区域Locale

层次性 MessageSource

  • Spring 层次性接口回顾
    • org.springframework.beans.factory.HierarchicalBeanFactory
    • org.springframework.context.ApplicationContext
    • org.springframework.beans.factory.config.BeanDefinition
  • Spring 层次性国际化接口
    • org.springframework.context.HierarchicalMessageSource

Java 国际化标准实现

核心接口:

  • 抽象实现 - java.util.ResourceBundle
  • Properties 资源实现 - java.util.PropertyResourceBundle
  • 例举实现 - java.util.ListResourceBundle

ResourceBundle 核心特性

  • Key-Value 设计
  • 层次性设计
  • 缓存设计
  • 字符编码控制 - java.util.ResourceBundle.Control@since 1.6
  • Control SPI 扩展 - java.util.spi.ResourceBundleControlProvider@since 1.8

Java 文本格式化

  • 核心接口
    • java.text.MessageFormat
  • 基本用法
    • 设置消息格式模式- new MessageFormat(...)
    • 格式化 - format(new Object[]{...})
  • 消息格式模式
    • 格式元素:{ArgumentIndex (,FormatType,(FormatStyle))}
    • FormatType消息格式类型可选项每种类型在 number、date、time 和 choice 类型选其一
    • FormatStyle消息格式风格可选项包括short、medium、long、full、integer、currency、 percent
  • 高级特性
    • 重置消息格式模式
    • 重置 java.util.Locale
    • 重置 java.text.Format

MessageSource 开箱即用实现

  • 基于 ResourceBundle + MessageFormat 组合 MessageSource 实现
  • org.springframework.context.support.ResourceBundleMessageSource
  • 可重载 Properties + MessageFormat 组合 MessageSource 实现
  • org.springframework.context.support.ReloadableResourceBundleMessageSource

MessageSource 內建依赖

  • MessageSource 內建 Bean 可能来源
  • 预注册 Bean 名称为“messageSource”类型为MessageSource Bean
  • 默认內建实现 - DelegatingMessageSource
  • 层次性查找 MessageSource 对象

问题

Spring Boot 为什么要新建 MessageSource Bean

  • AbstractApplicationContext 的实现决定了 MessageSource 內建实现
  • Spring Boot 通过外部化配置简化 MessageSource Bean 构建
  • Spring Boot 基于 Bean Validation 校验非常普遍

Spring 国际化接口有哪些

  • 核心接口 - MessageSource
  • 层次性接口 - org.springframework.context.HierarchicalMessageSource

Spring 有哪些 MessageSource 內建实现

  • org.springframework.context.support.ResourceBundleMessageSource
  • org.springframework.context.support.ReloadableResourceBundleMessageSource
  • org.springframework.context.support.StaticMessageSource
  • org.springframework.context.support.DelegatingMessageSource

如何实现配置自动更新 MessageSource

主要技术

  • Java NIO 2java.nio.file.WatchService
  • Java Concurrency : java.util.concurrent.ExecutorService
  • Springorg.springframework.context.support.AbstractMessageSource

参考资料