java的locale仅标识语言和地区,不提供翻译功能;多语言需配合resourcebundle、messageformat及规范命名的属性文件实现,且必须显式传入locale对象才能生效。

Java 的 Locale 类本身不提供翻译或资源加载能力,它只是标识“当前想用哪种语言+地区”的标签;真正实现多语言靠的是配合 ResourceBundle、MessageFormat 和符合命名规范的属性文件。
为什么 new Locale("zh", "CN") 有时不生效?
常见错误是只创建 Locale 对象却不把它传给实际读取资源的组件。比如:
-
ResourceBundle.getBundle("messages", locale)必须显式传入locale,否则默认用Locale.getDefault() - JVM 启动参数(如
-Duser.language=zh -Duser.country=CN)会影响Locale.getDefault(),但运行时改系统属性不会自动刷新已有ResourceBundle实例 - Web 应用中,HTTP 请求头里的
Accept-Language需要手动解析成Locale,框架(如 Spring)才可能据此切换资源束
ResourceBundle 查找路径和命名规则怎么配?
假设基名为 messages,ResourceBundle.getBundle("messages", locale) 会按优先级尝试加载以下类路径下的文件(.properties 或 .class):
-
messages_zh_CN.properties(最精确匹配) -
messages_zh.properties(仅语言匹配) -
messages.properties(默认兜底,必须存在)
注意:zh-CN 是 HTTP 标准写法,但 Java 要求用下划线 zh_CN;大小写敏感,Messages_zh_CN.properties 不会被识别。
立即学习“Java免费学习笔记(深入)”;
日期/数字格式化为何没随 Locale 改变?
Locale 只是输入参数,SimpleDateFormat 和 NumberFormat 必须显式构造时传入:
Locale zhCN = new Locale("zh", "CN");
DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, zhCN); // ✅
NumberFormat nf = NumberFormat.getCurrencyInstance(zhCN); // ✅
// 错误写法:new SimpleDateFormat("yyyy-MM-dd") 默认用系统 locale
另外,DateTimeFormatter(Java 8+)需用 DateTimeFormatter.ofPattern("yyyy年MM月dd日").withLocale(zhCN),漏掉 withLocale 就无效。
Spring Boot 里 @Value("${xxx}") 能自动国际化吗?
不能。@Value 解析的是 application.properties,它不走 ResourceBundle 机制。多语言文案必须放在单独的 messages.properties 系列文件中,并通过 MessageSource 接口获取:
- 配置
MessageSourcebean(Spring Boot 默认已配好ResourceBundleMessageSource) - 注入
MessageSource,调用getMessage("key", args, locale) - Thymeleaf 模板中用
#{key},JSP 用<message code="key"></message>
最容易被忽略的一点:所有带参数的占位符(如 hello={0}, age={1})必须用 MessageFormat 兼容语法,且传参类型要匹配——传 int 却在模板里写 {0,date} 会抛 IllegalArgumentException。










