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; } }
原文地址:https://www.cnblogs.com/CR1me/p/9875012.html
时间: 2024-11-04 10:49:05