Spring中从ResourceBundleMessageSource按模式获取属性键

2024-05-12

我有近百个这样的房产

    NotEmpty.order.languageFrom=Field Language can't be empty
    NotEmpty.order.languageTo=Field Language can't be empty
    NotEmpty.order.description=Description field can't be empty
    NotEmpty.order.formType=FormType field can't be empty
    NotEmpty.cart.formType=FormType field can't be empty
    NotEmpty.cart.formType=FormType field can't be empty

我希望能够在不事先了解键的情况下获得这些属性(键/值)...类似getPropertyPair(regexp .*.order.[a-z]*=)

有谁知道 spring 或 JDK 是否为此提供了一些东西?我想我必须获取 ResourceBundle 并获取所有密钥并对其进行正则表达式...


我认为你不能在 Spring 中做到这一点,但这里有一些代码可能会有所帮助:

public class Main {
  public static void main(String[] args) {
    ResourceBundle labels = ResourceBundle.getBundle("spring-regex/regex-resources", Locale.UK);
    Enumeration<String> labelKeys = labels.getKeys();

    // Build up a buffer of label keys
    StringBuffer sb = new StringBuffer();
    while (labelKeys.hasMoreElements()) {
      String key = labelKeys.nextElement();
      sb.append(key + "|");
    }

    // Choose the pattern for matching
    Pattern pattern = Pattern.compile(".*.order.[a-z]*\\|");
    Matcher matcher = pattern.matcher(sb);

    // Attempt to find all matching keys
    List<String> matchingLabelKeys = new ArrayList<String>();
    while (matcher.find()) {
      String key=matcher.group();
      matchingLabelKeys.add(key.substring(0,key.length()-1));
    }

    // Show results
    for (String value: matchingLabelKeys) {
      System.out.format("Key=%s Resource=%s",value,labels.getString(value));
    }

  }

}

这有点老套,但我相信你可以将其整理成更有用的东西。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring中从ResourceBundleMessageSource按模式获取属性键 的相关文章

随机推荐