在JAVA中,很多时候,我们后台要对数据进行变量配置,希望可以在运行时再进行变量替换.我们今天给大空提供的是org.apache.commons.text方案.
1.首先,引用org.apache.commons.text包
maven:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-text</artifactId> <version>1.6</version> </dependency>
gradle:
// https://mvnrepository.com/artifact/org.apache.commons/commons-text
implementation group: 'org.apache.commons', name: 'commons-text', version: '1.6'
2.上demo
public static void main(String[] args) { Map<String, String> valuesMap = Maps.newHashMap(); valuesMap.put("title", "负氧离子环境监测"); valuesMap.put("anion", "436"); valuesMap.put("temperature", "20.5"); valuesMap.put("humidity", "95.0"); valuesMap.put("pm25", "25"); valuesMap.put("pm10", "21"); String text = "负离子:${anion}个/cm3" + "\n" + "温度:${temperature}℃" + " " + "湿度:${humidity}%" + "\n" + "PM2.5:${pm25}ug/m3" + "\n" + "PM10:${pm10}ug/m3"; StringSubstitutor sub = new StringSubstitutor(valuesMap); String resolvedString = sub.replace(text); System.out.println(resolvedString); }
实际效果: