How to use a simple string template in java
Using Apache Commons Lang for simple string templates
The simpliest way to have a string template in java is by using the Apache Commons Lang library which you already have as a dependency already.
Get library
Resolve the dependency through maven by defining it in your pom.xml
.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
String template usage
To use the string template approach from Apache Commons Lang library, you first define your data with a Map
. Then, you develop your template via a simple string or load it from a file. The template format is very similar to Kotlin String Templates, Velocity or Freemarker. The values are defined with the syntax ${map_key}
.
Example:
Map<String, String> valuesMap = new HashMap<String, String>();
valuesMap.put("name", "John Doe");
String templateString = "Welcome ${name}.";
StrSubstitutor sub = new StringSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);
This is a great way for setting up a string template for testing or one off templates within your application.