spring boot集成thymeleaf国际化需完成三步:准备i18n多语言.properties资源文件并设utf-8编码;配置spring.messages.basename指定资源路径;选用sessionlocaleresolver配合localechangeinterceptor支持手动切换语言;模板中用#{key}语法自动渲染对应语言文案。

Spring Boot 集成 Thymeleaf 国际化,核心是三件事:资源文件准备、语言环境解析、模板中调用。只要把这三块串起来,就能让页面自动按用户语言显示对应文案,后端提示信息也能同步切换。
准备多语言资源文件
在 src/main/resources 下新建目录(如 i18n),放入标准命名的 .properties 文件:
-
i18n/messages.properties(默认语言,比如中文) -
i18n/messages_en_US.properties(美式英语) -
i18n/messages_zh_CN.properties(显式中文,可选,与默认一致时可省略) - 支持更多语言就继续加,例如
messages_ja_JP.properties
每个文件内容格式统一,例如:
welcome.title=欢迎使用系统<br>login.button=登录<br>error.required=此项为必填
确保 IDE 将 .properties 文件编码设为 UTF-8,避免中文乱码。
配置 MessageSource 和资源路径
Spring Boot 默认已自动配置 ResourceBundleMessageSource,只需在 application.yml 中指定资源位置:
spring:<br> messages:<br> basename: i18n.messages<br> encoding: UTF-8
这告诉 Spring 去加载 i18n/messages_*.properties 系列文件。不需要额外写 @Bean,除非你要自定义缓存策略或 fallback 行为。
选择并配置 LocaleResolver
LocaleResolver 决定“当前用哪种语言”。Spring Boot 默认用 AcceptHeaderLocaleResolver(读浏览器 Accept-Language 头),开箱即用但不可变。若需手动切换(比如点“中文/English”按钮),推荐 SessionLocaleResolver:
- 在配置类中声明 Bean:
@Configuration<br>public class WebConfig {<br> @Bean<br> public LocaleResolver localeResolver() {<br> SessionLocaleResolver slr = new SessionLocaleResolver();<br> slr.setDefaultLocale(Locale.CHINA); // 默认中文<br> return slr;<br> }<br>}
- 再配一个拦截器,让它能识别 URL 参数(如
?lang=zh_CN):
@Bean<br>public LocaleChangeInterceptor localeChangeInterceptor() {<br> LocaleChangeInterceptor lci = new LocaleChangeInterceptor();<br> lci.setParamName("lang"); // 对应请求参数名<br> return lci;<br>}
- 记得把拦截器注册进 MVC 链路(实现
WebMvcConfigurer的addInterceptors方法)
在 Thymeleaf 模板里使用国际化
直接用 #{...} 语法引用 key,Thymeleaf 会自动从当前 Locale 对应的资源文件中取值:
<h2 th:text="#{welcome.title}"></h2><br><button th:text="#{login.button}"></button>
支持带参数的 message,例如 hello.user=你好,{0}!,模板中写:<span th:text="#{hello.user(${user.name})}"></span>
IDEA 通常会提供 key 的自动补全和预览,前提是资源文件结构和配置正确。











