Spring-boot国际化

912 阅读1分钟

1.配置博客

    国际化自动配置
        basename:默认的扫描的国际化文件名为messages,即在resources建立messages_xx.properties文件,可以通过逗号指定多个,如果不指定包名默认从classpath下寻找。

        encoding:默认的编码为UTF-8。
        
        cacheSeconds:加载国际化文件的缓存时间,单位为秒,默认为永久缓存。
        
        fallbackToSystemLocale:当找不到当前语言的资源文件时,如果为true默认找当前系统的语言对应的资源文件如messages_zh_CN.properties,如果为false即加载系统默认的如messages.properties文件。

2、在resources下创建i18n(目录名自定义)目录下创建以下几个文件

    如index.properties,index_zh_CN.properties,index.properties作为找不到定义语言的资源文件时的默认配置文件。

3、添加语言解析器,并设置默认语言为US英文博客

import java.util.Locale;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

@Configuration
public class I18nConfig extends WebMvcConfigurerAdapter {
     @Bean  
        public LocaleResolver localeResolver() {  
            SessionLocaleResolver slr = new SessionLocaleResolver();  
            slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);  
            return slr;  
        }  

        @Bean  
        public LocaleChangeInterceptor localeChangeInterceptor() {  
            LocaleChangeInterceptor lci = new LocaleChangeInterceptor();  
            lci.setParamName("lang");  
            return lci;  
        }  

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

}

4.controller层中语言属性

    LocaleContextHolder.getLocale()

5.修改语言