spring国际化: 从数据库中读取国际化资源
Posted Mr风清
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring国际化: 从数据库中读取国际化资源相关的知识,希望对你有一定的参考价值。
public class MessageResource extends AbstractMessageSource implements ResourceLoaderAware, InitializingBean { @SuppressWarnings("unused") private ResourceLoader resourceLoader = null; @Autowired private Sys_resourcesService sys_resourcesService = null; private final String MAP_SPLIT_CODE = "|"; private final Map<String, String> properties = new HashMap<String, String>(); public MessageResource(){ } @Override public void afterPropertiesSet() throws Exception { System.out.println("中国大陆:语言:" + Locale.SIMPLIFIED_CHINESE.getLanguage() +", 国家"); System.out.println("台湾:语言:" + Locale.TAIWAN.getLanguage()); properties.clear(); properties.putAll(loadTexts()); } /** * 读取资源信息 * @return */ private List<Resource> getResource(){ return sys_resourcesService.findAll(); } /** * 加载数据 * @return */ protected Map<String, String> loadTexts(){ Map<String, String> mapResource = new HashMap<String, String>(); List<Resource> resources = this.getResource(); for (Resource item : resources) { String code = item.getRskey() + MAP_SPLIT_CODE + item.getLanguage(); mapResource.put(code, item.getText()); } System.out.println("国际化资源加载完毕.共"+resources.size()+"条."); return mapResource; } /** * 获取文本 * @param code * @param locale 本地化语言 * @return */ private String getText(String code, Locale locale){ String localeCode = locale.getLanguage(); if(localeCode != null && localeCode.toUpperCase().equals(R.lan.ZH)){ if(locale.getCountry().toUpperCase().equals(R.lan.CN)){ localeCode = R.lan.CN.toLowerCase(); }else{ localeCode = R.lan.TW.toLowerCase(); } } String key = code + MAP_SPLIT_CODE + localeCode; String localeText = properties.get(key); String resourceText = code; if(localeText != null && !"".equals(localeText)) { resourceText = localeText; }else{ localeCode = Locale.ENGLISH.getLanguage(); key = code + MAP_SPLIT_CODE + localeCode; localeText = properties.get(key); if(localeText != null && !"".equals(localeText)) { resourceText = localeText; }else{ try{ if(getParentMessageSource() != null) { resourceText = getParentMessageSource().getMessage(code, null, locale); } }catch(Exception e) { logger.error("找不到对应的消息, code: " + code); } } } return resourceText; } @Override public void setResourceLoader(ResourceLoader resourceLoader){ this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader()); } @Override protected MessageFormat resolveCode(String code, Locale locale){ String msg = getText(code, locale); MessageFormat result = createMessageFormat(msg, locale); return result; } @Override protected String resolveCodeWithoutArguments(String code, Locale locale){ String result = getText(code, locale); return result; } }
以上是关于spring国际化: 从数据库中读取国际化资源的主要内容,如果未能解决你的问题,请参考以下文章
Java IO流 之 ResourceBundle 读取国际化资源文件