|
@@ -0,0 +1,70 @@
|
|
|
+package com.txz.project.util;
|
|
|
+
|
|
|
+import org.springframework.context.MessageSource;
|
|
|
+import org.springframework.context.i18n.LocaleContextHolder;
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
+import org.springframework.util.ObjectUtils;
|
|
|
+
|
|
|
+import javax.annotation.PostConstruct;
|
|
|
+import javax.annotation.Resource;
|
|
|
+import java.util.Locale;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 描述: 3、国际化工具类
|
|
|
+ * 版权: Copyright (c) 2020
|
|
|
+ * 公司: XXXX
|
|
|
+ * 作者: yanghj
|
|
|
+ * 版本: 4.0
|
|
|
+ * 创建日期: 2020/9/18 10:31
|
|
|
+ */
|
|
|
+
|
|
|
+@Component
|
|
|
+public class I18nUtil
|
|
|
+{
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private MessageSource messageSource;
|
|
|
+
|
|
|
+ private static MessageSource staticMessageSource;
|
|
|
+
|
|
|
+ public static String acceptLanguage;
|
|
|
+
|
|
|
+ // 用 @PostConstruct 替代 InitializingBean 接口
|
|
|
+ @PostConstruct
|
|
|
+ public void init() {
|
|
|
+ if (staticMessageSource == null) {
|
|
|
+ I18nUtil.staticMessageSource = this.messageSource;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // 静态 get 方法(同上)
|
|
|
+ public static String get(String msgKey) {
|
|
|
+ try {
|
|
|
+// ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
|
|
+// String header = sra.getRequest().getHeader("accept-language");
|
|
|
+ String header = LanguageContextHolder.getLanguage();
|
|
|
+ // String header = acceptLanguage;
|
|
|
+ LocaleContextHolder.setLocale(Locale.US);
|
|
|
+ if(!ObjectUtils.isEmpty(header)) {
|
|
|
+ if ("en".equals(header)) {
|
|
|
+ LocaleContextHolder.setLocale(Locale.US);
|
|
|
+ } else if ("zh".equals(header)) {
|
|
|
+ LocaleContextHolder.setLocale(Locale.SIMPLIFIED_CHINESE);
|
|
|
+ } else if ("bd".equals(header)) {
|
|
|
+ Locale bengaliLocale = new Locale("bn", "BD"); //孟加拉文
|
|
|
+ LocaleContextHolder.setLocale(bengaliLocale);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ return staticMessageSource.getMessage(msgKey, null, LocaleContextHolder.getLocale());
|
|
|
+ } catch (Exception e) {
|
|
|
+ return msgKey;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+}
|