In Java, it's hard to use a formatted string, whether it's String.Format or Messageformat. Velocity is good, but it's too heavy. Today, we recommend Apache Commons-lang in Strsubstitutor.
Document Address: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/StrSubstitutor.html
Strsubstitutor in Apache Commons-lang3 package, to use, please add the following dependencies in the Pom.xml:
1 <dependency>2 <groupId>org.apache.commons</groupId>3 <artifactId>commons-lang3</artifactId>4 <version>3.4</version>5 </dependency>
1, directly replace the system property values
strsubstitutor.replacesystemproperties ( "You is running with java.version = ${java.version} and Os.name = ${os.name}. ");
2. Replace placeholders in strings with map
Map Valuesmap = HashMap ();
Valuesmap.put ("Animal", "Quick brown fox");
Valuesmap.put ("target", "lazy dog"= "The ${animal} jumped over the ${target}." ;
New= Sub.replace (templatestring);
Resolvedstring Result: The quick brown fox jumped over the lazy dog.
3. Strsubstitutor will replace variables recursively, such as:
map<string, object> params = maps.newhashmap (); params.put ("name", "${x}");p arams.put ("x", "Y");
New Strsubstitutor (params);
String Hello2 = "${name}";
System.out.println (Strsubstitutor.replace (Hello2));
The final output is: Y
4, sometimes the variable is also nested other variables, this strsubstitutor is also supported, but to call the next setenablesubstitutioninvariables can be.
map<string, object> params = maps.newhashmap ();p arams.put ("jre-1.8", "java-version-1.8"); Params.put ("java.specification.version", "1.8"new strsubstitutor (params); Strsubstitutor.setenablesubstitutioninvariables (true); System.out.println (Strsubstitutor.replace ("${jre-${java.specification.version}}");
Output: java-version-1.8
How to use Apache strsubstitutor