I18n.java
2.91 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package com.bsth.util;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
/**
* @Author hill
*/
@Component
public class I18n implements InitializingBean {
private ThreadLocal<Locale> locales = new ThreadLocal<>();
@Autowired
private MessageSource messageSource;
@Value("${i18n.locale}")
private String locale;
private static I18n i18n;
public static I18n getInstance() {
if (i18n == null) {
throw new RuntimeException("I18n not initialized");
}
return i18n;
}
public void setLocale(Locale locale) {
locales.set(locale);
}
/**
* 获取properties文件中所有的键值
* @param basename
* @return
*/
public Map<String, String> getAllMessage(String basename) {
Map<String, String> map = new HashMap<>();
ResourceBundle resourceBundle = ResourceBundle.getBundle(basename, locales.get() == null ? Locale.getDefault() : locales.get());
for (String key : resourceBundle.keySet()) {
try {
map.put(key, new String(resourceBundle.getString(key).getBytes("ISO-8859-1"), "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
return map;
}
/**
*
* @param expression
* @param args
* @return
*/
public String getMessage(String expression, String ... args) {
String message = messageSource.getMessage(expression, null, locales.get() == null ? Locale.getDefault() : locales.get());
return StringUtils.isEmpty(message) ? "" : format(message, args);
}
private String format(String format, String args[]) {
String result = format;
int start = format.indexOf("######{"), end = -1;
String idx = "";
while (start > -1) {
end = result.indexOf("}", start);
if (end == -1) {
throw new RuntimeException(String.format("[%s] 格式异常", format));
}
idx = result.substring(start + 7, end);
result = result.replace(result.substring(start, end + 1), args[Integer.parseInt(idx)]);
start = result.indexOf("######{");
}
return result;
}
@Override
public void afterPropertiesSet() throws Exception {
i18n = this;
String [] arr = locale.split("_");
Locale.setDefault(new Locale(arr[0], arr[1]));
}
}