|
@@ -0,0 +1,60 @@
|
|
|
+package com.hb.proj.allconfig;
|
|
|
+
|
|
|
+import java.util.Locale;
|
|
|
+
|
|
|
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
|
|
+import org.springframework.context.MessageSource;
|
|
|
+import org.springframework.context.annotation.Bean;
|
|
|
+import org.springframework.context.annotation.Configuration;
|
|
|
+import org.springframework.context.i18n.LocaleContextHolder;
|
|
|
+import org.springframework.web.servlet.LocaleResolver;
|
|
|
+import org.springframework.web.servlet.i18n.SessionLocaleResolver;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 多语言配置
|
|
|
+ * @author cwen
|
|
|
+ *
|
|
|
+ */
|
|
|
+
|
|
|
+@Configuration
|
|
|
+@ConditionalOnProperty(prefix = "spring.messages",name = "active")
|
|
|
+public class LocalConfig {
|
|
|
+
|
|
|
+ //spring.messages.basename 配置国际化文件的名称,比如默认值是messages,多个值逗号分隔
|
|
|
+ private static MessageSource messageSource;
|
|
|
+
|
|
|
+ public LocalConfig(MessageSource messageSource) {
|
|
|
+ LocalConfig.messageSource=messageSource;
|
|
|
+ }
|
|
|
+
|
|
|
+ public static String get(String msgKey,String defaultMsg) {
|
|
|
+ return get(msgKey,defaultMsg,LocaleContextHolder.getLocale());
|
|
|
+ }
|
|
|
+
|
|
|
+ public static String get(String msgKey) {
|
|
|
+ return get(msgKey,msgKey,LocaleContextHolder.getLocale());
|
|
|
+ }
|
|
|
+
|
|
|
+ public static String get(String msgKey,String defaultMessage,Locale locale)
|
|
|
+ {
|
|
|
+ try
|
|
|
+ {
|
|
|
+ return messageSource==null?defaultMessage:messageSource.getMessage(msgKey, null, defaultMessage,locale);
|
|
|
+ }
|
|
|
+ catch (Exception e)
|
|
|
+ {
|
|
|
+ return msgKey;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 默认解析器 其中locale表示默认语言 bean name必须是localeResolver,
|
|
|
+ * 这样DispatcherServlet才能自动侦测到它,每DispatcherServlet只能注册一个区域解析器
|
|
|
+ */
|
|
|
+ @Bean
|
|
|
+ public LocaleResolver localeResolver() {
|
|
|
+ SessionLocaleResolver localeResolver = new SessionLocaleResolver();
|
|
|
+ localeResolver.setDefaultLocale(Locale.CHINA);
|
|
|
+ return localeResolver;
|
|
|
+ }
|
|
|
+}
|