Java placeholder tool class, use the PropertyPlaceholderHelper class in the Spring framework or use the StringSubstitutor class in Apache Commons to parse property placeholders in strings

1. PropertyPlaceholderHelper placeholder tool class in Spring framework

The PropertyPlaceholderHelper class is a utility class that provides a simple way to parse property placeholders in strings. An attribute placeholder is a sequence of characters usually enclosed in curly braces with prefix and suffix symbols. Placeholders can be replaced using the PropertyPlaceholderHelper class.

The PropertyPlaceholderHelper class has two constructors (constructor method one):

public PropertyPlaceholderHelper(String placeholderPrefix, String placeholderSuffix) {
   this(placeholderPrefix, placeholderSuffix, (String)null, true);
}
  • String placeholderPrefix --placeholder prefix
  • String placeholderSuffix --placeholder suffix

For example:

The PropertyPlaceholderHelper class has two constructors (constructor method two):

    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 --placeholder prefix
  • String placeholderSuffix --placeholder suffix
  • String valueSeparator --Default value separator
  • boolean ignoreUnresolvablePlaceholders -- Whether to throw an exception when parsing fails

For example:

2. Core method replacePlaceholders

These two methods in the PropertyPlaceholderHelper class implement the replacement function of property placeholders. Their method names are the same, but their parameter types are different.

Method information (String value, final Properties properties) and usage examples:

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);
    }

Method information (String value, PlaceholderResolver placeholderResolver) and usage examples:

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);
    }

Output information:

3. Use lambda expressions and function parameters

The implementation results are as follows:

Specific methods to achieve:

    /**
     * 使用 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);
    }

4. Use the StringSubstitutor class to parse placeholders

Add pom.xml dependency:

		<!-- 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>

Instructions:

    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);

    }

Output information:

Extensions: Apache Commons Text is a module for handling strings and blocks of text. It provides some utility classes for common tasks with strings, such as escaping and escaping. The following is its usage API:

Overview (Apache Commons Text 1.9 API)

In the above, what is ImmutableMap<String, String> used? What is the difference between HashMap and HashMap?

ImmutableMap and HashMap are two different Map implementations in Java. They have the following differences, characteristics and usage scenarios:

Variability:

ImmutableMap is immutable and once created, its contents cannot be modified. Any modification operation to ImmutableMap will return a new ImmutableMap instance.

HashMap is mutable, and key-value pairs can be added, deleted, or modified at any time.


Thread safety:

ImmutableMap is thread-safe, and multiple threads can read the contents of ImmutableMap at the same time without additional synchronization measures.
HashMap is not thread-safe. If multiple threads access and modify the same HashMap instance at the same time, data inconsistency or concurrent modification exceptions may occur.


performance:

Since ImmutableMap is immutable, it does not require additional synchronization operations after creation, so it has better performance in a multi-threaded environment.
HashMap usually has better performance in a single-threaded environment, but synchronization operations are required in a multi-threaded environment, which may introduce additional overhead.


scenes to be used:

      When you need to create an immutable mapping relationship and want to ensure thread safety, you can use ImmutableMap. For example, ImmutableMap is a good choice when sharing configuration information or constant mapping in a multi-threaded environment.
       HashMap can be used when you need a variable mapping relationship that does not involve multi-threaded access. For example, HashMap is a common choice when performing operations such as dynamic addition, deletion, and modification of data in a single-threaded environment.


In short, ImmutableMap is suitable for scenarios that require immutability and thread safety, while HashMap is suitable for scenarios that require variability and better performance. According to the specific needs and usage environment, select the appropriate implementation class to meet the needs.
 

Guess you like

Origin blog.csdn.net/amosjob/article/details/135159603