I18nResources.java
1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.huaheng.gateway.config;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.i18n.LocaleContextHolder;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
/**
* 国际化
*/
@PropertySource(value = { "classpath:i18n/messages*.properties" })
public class I18nResources {
/** 将国际化信息存放在一个map中 */
private static final Map<String, ResourceBundle> MESSAGES = new HashMap<String, ResourceBundle>();
/** 获取国际化信息 */
public static String getMessage(String key, Object... params) {
//获取语言,这个语言是从header中的Accept-Language中获取的,
//会根据Accept-Language的值生成符合规则的locale,如zh、pt、en等
Locale locale = LocaleContextHolder.getLocale();
ResourceBundle message = MESSAGES.get(locale.getLanguage());
if (message == null) {
synchronized (MESSAGES) {
//在这里读取配置信息
message = MESSAGES.get(locale.getLanguage());
if (message == null) {
//注1
message = ResourceBundle.getBundle("i18n/messages", locale);
MESSAGES.put(locale.getLanguage(), message);
}
}
}
//此处获取并返回message
try {
if (params != null) {
return new String(message.getString(key).getBytes("ISO-8859-1"), "UTF8");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return key;
}
/** 清除国际化信息 */
public static void flushMessage() {
MESSAGES.clear();
}
}