组件
Locale
Locale对象代表具体的地理,政治或文化地区。设置语言区域如zh,CN,对语言敏感操作定制特定的信息。
public final class Locale implements Cloneable, Serializable {
// 语言、国家
public Locale(String language, String country) {
this(language, country, "");
}
public static Locale getDefault() {
// 默认语言、区域、国家,通过jvm变量user.language、user.region、user.country获取
return defaultLocale;
}
}
MessageSource
用于支持信息的国际化和包含参数的信息的替换
public interface MessageSource {
/**
*code表示资源文件中的属性
*args表示替换参数
*未找到资源的默认值
*当前语言区域
*/
String getMessage(String code, @Nullable Object[] args, @Nullable String defaultMessage, Locale locale);
String getMessage(String code, @Nullable Object[] args, Locale locale) throws NoSuchMessageException;
}
工具类
NumberFormat
根据locale格式化数字
public abstract class NumberFormat extends Format {
// 数字类型
private static final int NUMBERSTYLE = 0;
// 货币类型
private static final int CURRENCYSTYLE = 1;
// 百分类型
private static final int PERCENTSTYLE = 2;
// 科学计数类型
private static final int SCIENTIFICSTYLE = 3;
// 整数类型
private static final int INTEGERSTYLE = 4;
// 构造方法,默认NUMBERSTYLE
public static NumberFormat getInstance(Locale inLocale) {
return getInstance(inLocale, NUMBERSTYLE);
}
}
DateFormat
根据locale格式化日期
public abstract class DateFormat extends Format {
// 构造方法
public final static DateFormat getDateInstance()
{
return get(0, DEFAULT, 2, Locale.getDefault(Locale.Category.FORMAT));
}
}
MessageFormat
提供了占位符{ArgumentIndex ,FormatType,FormatStyle }来显示消息
public abstract class NumberFormat extends Format {
// 默认构造,传入模式
public MessageFormat(String pattern) {
this.locale = Locale.getDefault(Locale.Category.FORMAT);
applyPattern(pattern);
}
}
ResourceBundle
资源束包含区域特定的对象。用来加载区域敏感资源
public void test() {
Locale locale = Locale.getDefault();
// 调用类加载器在classpath中搜索获得资源
ResourceBundle bundle = ResourceBundle.getBundle("i18n/list", locale);
System.out.println(bundle.getString("login.name"));
}
使用
配置文件
<!--id必须为messageSource-->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<!--文件编码-->
<property name="fileEncodings" value="UTF-8"/>
<!--资源路径-->
<property name="basename" value="i18n/list"/>
<!--找不到key则返回key,不抛异常-->
<property name="useCodeAsDefaultMessage" value="true" />
<!--动态加载资源文件-->
<property name="cacheMillis" value="5000"/>
</bean>
获得资源
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:bean.xml");
MessageSource source = context.getBean("messageSource", MessageSource.class);
String message1 = source.getMessage("login.name", new String[]{"占位"}, Locale.CHINA);
String message = source.getMessage("login.name", new String[]{"占位"}, Locale.US);
System.out.println("中文:" + message1);
System.out.println("英文:" + message);
}