package com.poyee.i18n; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.context.i18n.LocaleContextHolder; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 国际化工具类,用于获取国际化信息 */ @Configuration public class I18nUtils { // 定义占位符的正则表达式模式 private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\{(\\d+)\\}"); private MessageProperties messageProperties; // 存储消息的Map,键是消息键,值是包含语言和消息的Map private static Map> messages; /** * 初始化国际化工具类,并加载消息属性 * * @return I18nUtils实例 */ @Autowired public I18nUtils(MessageProperties messageProperties) { this.messageProperties = messageProperties; messages = messageProperties.init(); } /** * 根据枚举和参数获取国际化消息 * * @param i18n 国际化消息枚举 * @param args 消息中的参数 * @return 国际化后的消息 */ public static String get(I18nMessageEnums i18n, Object... args) { String key = i18n.getCode(); Map translations = messages.get(key); String message; if (Objects.isNull(translations)) { // 如果没有找到对应的翻译,使用枚举中的默认消息 message = i18n.getMessage(); } else { // 根据当前的locale获取对应的翻译 Locale locale = LocaleContextHolder.getLocale(); message = translations.getOrDefault(locale.getLanguage(), translations.get(I18nLanguage.EN.getCode())); } // 替换消息中的占位符 return replacePlaceholders(message, args); } /** * 替换消息中的占位符 * * @param message 原始消息 * @param args 消息中的参数 * @return 替换占位符后的消息 */ private static String replacePlaceholders(String message, Object[] args) { if (!message.contains("{")) { // 如果消息中不包含占位符,直接返回原始消息 return message; } // 替换已提供的参数 Matcher matcher = PLACEHOLDER_PATTERN.matcher(message); StringBuffer sb = new StringBuffer(); while (matcher.find()) { String indexStr = matcher.group(1); int index = Integer.parseInt(indexStr); if (index < args.length) { // 如果索引在参数数组范围内,替换占位符 Object arg = args[index]; matcher.appendReplacement(sb, arg == null ? "" : arg.toString()); } else { // 如果索引超出参数数组范围,保留占位符 matcher.appendReplacement(sb, ""); } } matcher.appendTail(sb); return sb.toString(); } }