over 8 years ago
在Spring設定檔中
<!-- 多國語言支持 -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:i18n/messages</value>
</list>
</property>
<property name="defaultEncoding" value="UTF-8" />
<property name="cacheSeconds" value="1800" />
</bean>
<!-- 輔助類別,幫助在非spring管理下的物件取得spring管理的物件 -->
<bean id="SpringApplicationContext" class="com.secom.mobile.common.ApplicationContextHelper"></bean>
在src或是resources下面再新增一個資料夾i18n裡面放參數檔,像下面這樣
另外是ApplicationContextHelper,有的時候並不是透過spring管理物件例如說throw new MitakeExecption(ICommonCode.UNKNOWN_RUNTIME_EXCEPTION);,但是在新產生的物件並沒有spring幫你注入的messageSource,這時候就要透過實作ApplicationContextAware來取得Spring中的資源了
package com.secom.mobile.common;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class ApplicationContextHelper implements ApplicationContextAware{
private static ApplicationContext applicationContext = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext)throws BeansException {
this.applicationContext = applicationContext;
}
public static Object getBean( String beanName ) {
return applicationContext.getBean( beanName );
}
}
都弄好了候你就可以方便的變換輸出的語言
String message = null;
MessageSource messageSource = (MessageSource)ApplicationContextHelper.getBean("messageSource");
message = messageSource.getMessage("V1020", new Object[]{}, Locale.US);
Locale.US、Locale.TAIWAN、Locale.CHINA分別對應底下的參數檔
messages_en_US.properties、messages_zh_TW.properties、messages_zh_CN.properties
V1020=加密公鑰驗證失敗
V1030=欄位驗證錯誤 ex:某欄位不可超過多少碼
V1040=JSON格式無法解析
V1050=含有非法字元