SpringBoot配置国际化

项目使用的springboot版本2.4.10

首先:

在项目resources目录下创建 i18n 文件夹,并创建 messages.properties、messages_zh_CN.properties、messages_en_US.properties

messages.properties留空

messages_zh_CN.properties对应中文

index.title=首页

messages_en_US.properties对应英文

index.title=Index Page

方式一、通过application,yml配置(此方式不支持动态切换语言,系统启动时根据配置的spring.web.locale进行解析)

1、application,yml文件

spring:
  #国际化
  messages:
    basename: i18n/messages
  #设置区域(语言)
  #国际化Locale有两种设置方式:
  #1、通过配置LocaleChangeInterceptor拦截请求(需要配置@Bean LocaleChangeInterceptor注册到WebMvcConfigurer InterceptorRegistry),动态切换语言方式:请求URL?language=zh_CN
  #2、通过配置文件spring.web.locale=zh_CN,spring.web.locale-resolver=fixed设置,不可动态切换语言
  web:
    locale: zh_CN
    locale-resolver: fixed
  #模板
  thymeleaf:
    enabled: true #开启thymeleaf视图解析
    encoding: UTF-8 #编码
    prefix: classpath:/templates/  #前缀
    cache: false #是否使用缓存
    mode: HTML #严格的HTML语法模式
    suffix: .html #后缀名

 2、访问页面会根据配置的语言自动解析

方式二、配置LocaleChangeInterceptor实现动态切换语言

1、创建WebMvcConfig类

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        
        registry.addInterceptor(localeChangeInterceptor());
    }



    /**
     * Cookie方式
     *
     * @return
     */
    @Bean
    public LocaleResolver localeResolver() {
        return new CookieLocaleResolver();
    }

    /**
     * 切换语言按钮URL?language=zh_CN,切换后将语言信息存入cookie;
     *
     * @return
     */
    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("language");
        return lci;
    }
}

2、application,yml文件

spring:
  #国际化
  messages:
    basename: i18n/messages
  #模板
  thymeleaf:
    enabled: true #开启thymeleaf视图解析
    encoding: UTF-8 #编码
    prefix: classpath:/templates/  #前缀
    cache: false #是否使用缓存
    mode: HTML #严格的HTML语法模式
    suffix: .html #后缀名

3、切换语言 http://localhost:8080/?language=zh_CN

最后,因为使用Thymeleaf模板,html界面采用#{}取值,例如:<title th:text="#{index.title}"></title>

原文地址:https://www.cnblogs.com/lyxy/p/15334421.html