I18n.java
1.38 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
package com.bsth.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.Locale;
/**
* @Author hill
*/
@Component
public class I18n {
private ThreadLocal<Locale> locales = new ThreadLocal<>();
@Autowired
private MessageSource messageSource;
public void setLocale(Locale locale) {
locales.set(locale);
}
public String getMessage(String expression, String ... args) {
String message = messageSource.getMessage(expression, null, locales.get() == null ? Locale.SIMPLIFIED_CHINESE : 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;
}
}