I18nUtils.java 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package com.poyee.i18n;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.context.i18n.LocaleContextHolder;
  5. import java.util.Locale;
  6. import java.util.Map;
  7. import java.util.Objects;
  8. import java.util.regex.Matcher;
  9. import java.util.regex.Pattern;
  10. /**
  11. * 国际化工具类,用于获取国际化信息
  12. */
  13. @Configuration
  14. public class I18nUtils {
  15. // 定义占位符的正则表达式模式
  16. private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\{(\\d+)\\}");
  17. private MessageProperties messageProperties;
  18. // 存储消息的Map,键是消息键,值是包含语言和消息的Map
  19. private static Map<String, Map<String, String>> messages;
  20. /**
  21. * 初始化国际化工具类,并加载消息属性
  22. *
  23. * @return I18nUtils实例
  24. */
  25. @Autowired
  26. public I18nUtils(MessageProperties messageProperties) {
  27. this.messageProperties = messageProperties;
  28. messages = messageProperties.init();
  29. }
  30. /**
  31. * 根据枚举和参数获取国际化消息
  32. *
  33. * @param i18n 国际化消息枚举
  34. * @param args 消息中的参数
  35. * @return 国际化后的消息
  36. */
  37. public static String get(I18nMessageEnums i18n, Object... args) {
  38. String key = i18n.getCode();
  39. Map<String, String> translations = messages.get(key);
  40. String message;
  41. if (Objects.isNull(translations)) {
  42. // 如果没有找到对应的翻译,使用枚举中的默认消息
  43. message = i18n.getMessage();
  44. } else {
  45. // 根据当前的locale获取对应的翻译
  46. Locale locale = LocaleContextHolder.getLocale();
  47. message = translations.getOrDefault(locale.getLanguage(), translations.get(I18nLanguage.EN.getCode()));
  48. }
  49. // 替换消息中的占位符
  50. return replacePlaceholders(message, args);
  51. }
  52. /**
  53. * 替换消息中的占位符
  54. *
  55. * @param message 原始消息
  56. * @param args 消息中的参数
  57. * @return 替换占位符后的消息
  58. */
  59. private static String replacePlaceholders(String message, Object[] args) {
  60. if (!message.contains("{")) {
  61. // 如果消息中不包含占位符,直接返回原始消息
  62. return message;
  63. }
  64. // 替换已提供的参数
  65. Matcher matcher = PLACEHOLDER_PATTERN.matcher(message);
  66. StringBuffer sb = new StringBuffer();
  67. while (matcher.find()) {
  68. String indexStr = matcher.group(1);
  69. int index = Integer.parseInt(indexStr);
  70. if (index < args.length) {
  71. // 如果索引在参数数组范围内,替换占位符
  72. Object arg = args[index];
  73. matcher.appendReplacement(sb, arg == null ? "" : arg.toString());
  74. } else {
  75. // 如果索引超出参数数组范围,保留占位符
  76. matcher.appendReplacement(sb, "");
  77. }
  78. }
  79. matcher.appendTail(sb);
  80. return sb.toString();
  81. }
  82. }