若你的web app需要针对当前用户选择的语言进行语言切换, 则例如, 如果语言资源以message带头的, 需要做如下定制:
1/在application.yml里面指定语言资源位置:
2/由于第1点中我将语言资源文件指定为messages/message开关,则需要在resource下的messages文件夹下建立如下语言资源文件,如果只支持英文和简体中文,则需要定义如下资源文件(message.properties必须有,可以为空) :
3/建立语言资源访问工具类:
package com.freestyle.common.spring.utils;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ResourceBundleMessageSource;
/**
* 多国语言资源工具
* Created by rocklee on 2019/9/12 14:46
*/
public class MessageUtil extends ResourceBundleMessageSource {
private static MessageSource messageSource;
public static void setMessageSource(MessageSource source){
messageSource=source;
}
public MessageUtil() {
super();
//this.messageSource = messageSource;
}
/**
* 获取单个国际化翻译值
*/
public static String get(String pvsKey) {
try {
return messageSource.getMessage(pvsKey, null, LocaleContextHolder.getLocale());
} catch (Exception e) {
return pvsKey;
}
}
/**
* 获取单个国际化翻译值
*/
public static String get(String pvsKey,Object ... pvParams) {
try {
return messageSource.getMessage(pvsKey, pvParams, LocaleContextHolder.getLocale());
} catch (Exception e) {
return pvsKey;
}
}
}
4/在sb运行加载完毕后为其指定messagesource对象:
@Component
public class ApplicationEvent implements ApplicationListener<ContextRefreshedEvent> {
@Resource
protected MessageSource messageSource;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
MessageUtil.setMessageSource(messageSource);
}
}
5/建立本地化配置类
/**
* 本地化配置
* Created by rocklee on 2019/9/12 14:33
*/
@Configuration
public class LocaleConfig {
/**
* 默认解析器 其中locale表示默认语言
*/
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver localeResolver = new SessionLocaleResolver();
localeResolver.setDefaultLocale(Locale.US);
return localeResolver;
}
/**
* 默认拦截器 其中lang表示切换语言的参数名
*/
@Bean
public WebMvcConfigurer localeInterceptor() {
return new WebMvcConfigurer() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeInterceptor = new LocaleChangeInterceptor();
localeInterceptor.setParamName("lang");
registry.addInterceptor(localeInterceptor);
}
};
}
}
客户端切换语言用:
http://192.168.1.2:8889/...?lang=en_US
http://192.168.1.2:8889/...?lang=zh_CN
取message:
throw new RuntimeException(MessageUtil.get("FGS004",LotStatus.fromValue(lvExists.getF9yStatus()).toString()));