Java占位符工具类,使用Spring框架中PropertyPlaceholderHelper类或使用Apache Commons中StringSubstitutor类解析字符串中的属性占位符

一、Spring框架中PropertyPlaceholderHelper占位符工具类

PropertyPlaceholderHelper 类是一个实用程序类,它提供了一种简单的方法来解析字符串中的属性占位符。属性占位符是通常是用花括号 前缀符号和后缀符号 括起来的字符序列。可以使用 PropertyPlaceholderHelper 类替换占位符。

PropertyPlaceholderHelper 类有两个构造函数(构造方法一):

public PropertyPlaceholderHelper(String placeholderPrefix, String placeholderSuffix) {
   this(placeholderPrefix, placeholderSuffix, (String)null, true);
}
  • String placeholderPrefix        --占位符前缀
  • String placeholderSuffix        --占位符后缀

例如:

PropertyPlaceholderHelper 类有两个构造函数(构造方法二):

    public PropertyPlaceholderHelper(String placeholderPrefix, String placeholderSuffix, @Nullable String valueSeparator, boolean ignoreUnresolvablePlaceholders) {
        Assert.notNull(placeholderPrefix, "'placeholderPrefix' must not be null");
        Assert.notNull(placeholderSuffix, "'placeholderSuffix' must not be null");
        this.placeholderPrefix = placeholderPrefix;
        this.placeholderSuffix = placeholderSuffix;
        String simplePrefixForSuffix = (String)wellKnownSimplePrefixes.get(this.placeholderSuffix);
        if (simplePrefixForSuffix != null && this.placeholderPrefix.endsWith(simplePrefixForSuffix)) {
            this.simplePrefix = simplePrefixForSuffix;
        } else {
            this.simplePrefix = this.placeholderPrefix;
        }

        this.valueSeparator = valueSeparator;
        this.ignoreUnresolvablePlaceholders = ignoreUnresolvablePlaceholders;
    }
  • String placeholderPrefix    --占位符前缀
  • String placeholderSuffix    --占位符后缀
  • String valueSeparator        --默认值分割符
  • boolean ignoreUnresolvablePlaceholders    --解析失败时是否抛出异常

例如:

二、核心方法 replacePlaceholders

PropertyPlaceholderHelper类中的这两个方法实现了属性占位符的替换功能。它们方法名称相同,参数类型不同。

方法信息(String value, final Properties properties)及使用样例:

public String replacePlaceholders(String value, final Properties properties)
    /**
     * 使用样例
     * 
     * String replacePlaceholders(String value, final Properties properties)
     */
    public static void testProperties(){
        Properties properties = new Properties();
        properties.setProperty("name", "lisi");
        properties.setProperty("age", "29");

        PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper("${","}");
        String value = "My name is ${name} and I am ${age} years old.";
        String result = helper.replacePlaceholders(value, properties);

        System.out.println(result);
    }

方法信息(String value, PlaceholderResolver placeholderResolver)及使用样例:

public String replacePlaceholders(String value, PlaceholderResolver placeholderResolver)
    /**
     * 使用样例
     *
     * String replacePlaceholders(String value, PlaceholderResolver placeholderResolver)
     */
    public static void testProperties(){
        PlaceholderResolver resolver = new PlaceholderResolver() {
            @Override
            public String resolvePlaceholder(String placeholderName) {
                if (placeholderName.equals("name")) {
                    return "lisi";
                } else if (placeholderName.equals("age")) {
                    return "29";
                }
                return null;
            }
        };

        PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper("${","}");
        String value = "My name is ${name} and I am ${age} years old.";
        String result = helper.replacePlaceholders(value, resolver);

        System.out.println(result);
    }

输出信息:

三、使用lambda表达式,函数传参

实现结果如下:

具体方法实现:

    /**
     * 使用 PropertyPlaceholderHelper 解析模板中属性占位符
     */
    public static void methodPropertyPlaceholderHelper(){

        PropertyPlaceholderHelper propertyPlaceholderHelper =
                new PropertyPlaceholderHelper("#{","}");

        // 定义模版信息
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name","#{name}");
        jsonObject.put("age","#{age}");

        String strJson = JSON.toJSONString(jsonObject);
        System.out.println("JSON 模版: " + strJson + "\n");

        // 定义数据信息
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("age", "29");
        hashMap.put("name", "zhangSan");

        String strHelper = propertyPlaceholderHelper.replacePlaceholders(strJson, item ->hashMap.get(item));
        System.out.println("解析方式一: replacePlaceholders: " + strHelper);


        /**
         *  解析方式二:
         *  前缀、后缀、分隔符、是否忽略解析失败
         *
         *  使用参数 ignoreUnresolvablePlaceholders 布尔类型,解析失败则抛出异常
         */
        PropertyPlaceholderHelper valueSeparator = new PropertyPlaceholderHelper(
                "#{", "}", ":", false);

        String strValueSeparator = valueSeparator.replacePlaceholders(strJson, item -> hashMap.get(item));
        System.out.println("解析方式二: replacePlaceholders strValueSeparator: " + strValueSeparator);
    }

四、使用StringSubstitutor类解析占位符

添加pom.xml依赖:

		<!-- StringSubstitutor 依赖-->
        <dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-text</artifactId>
			<version>1.10.0</version>
		</dependency>

        <!-- google 工具类-->
		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>32.0.1-jre</version>
		</dependency>

使用方法:

    public static void methodGooglePlaceholderHelper(){

        String originalString = "Hello, ${name}! Today is ${date}.";

        ImmutableMap<String, String> valueMap = ImmutableMap.of(
                "name", "zhangSan",
                "date", "2023-12-22"
        );

        StringSubstitutor substitutor = new StringSubstitutor(valueMap);
        String replacedString = substitutor.replace(originalString);
        System.out.println(replacedString);

    }

输出信息:

扩展:Apache Commons Text 是一款处理字符串和文本块的模块。它提供了一些实用的工具类,用于处理字符串的常见任务,如转义和反转义。如下是它的使用API:

Overview (Apache Commons Text 1.9 API)

上文中,使用的ImmutableMap<String, String> 是什么?和HashMap有什么区别?

ImmutableMap和HashMap是Java中两种不同的Map实现,它们有以下区别、特征和使用场景:

可变性:

ImmutableMap是不可变的,一旦创建后,不能修改其内容。任何对ImmutableMap的修改操作都会返回一个新的ImmutableMap实例。

HashMap是可变的,可以随时添加、删除或修改其中的键值对。


线程安全性:

ImmutableMap是线程安全的,多个线程可以同时读取ImmutableMap的内容而无需额外的同步措施。
HashMap是非线程安全的,如果多个线程同时访问和修改同一个HashMap实例,可能会导致数据不一致或并发修改异常。


性能:

由于ImmutableMap是不可变的,它在创建后就不需要进行额外的同步操作,因此在多线程环境下具有更好的性能。
HashMap在单线程环境下通常具有较好的性能,但在多线程环境下需要进行同步操作,可能会引入额外的开销。


使用场景:

      当你需要创建一个不可变的映射关系,并且希望保证线程安全性时,可以使用ImmutableMap。例如,在多线程环境下共享配置信息或常量映射等情况下,ImmutableMap是一个不错的选择。
       当你需要一个可变的映射关系,并且不涉及多线程访问时,可以使用HashMap。例如,在单线程环境下进行数据的动态添加、删除和修改等操作时,HashMap是常用的选择。


总之,ImmutableMap适用于需要不可变性和线程安全性的场景,而HashMap适用于需要可变性和较好性能的场景。根据具体需求和使用环境,选择合适的实现类来满足需求。
 

  • 20
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值