我正在从文件中读取数据,我需要用Java Bean值替换占位符。
我尝试过StrSubstitutor
来映射值,但是没有用,也许我的方法不正确,占位符的声明正确,请建议我正确的方法
Class Test{
String firstName;
Request request;
}
class Request {
String requestNumber;
}
setValues(){
String template ="Dear ${test.firstname},Your Request number is ${test.request.requestNumber}.";
Test test= test;
Map<String, String> valuesMap = new HashMap<>();
valuesMap.put("test.firstname",test.getFirstName());
valuesMap.put("test.request.requestNumber",test.getRequest().getRequestNumber());
StrSubstitutor StrSubstitutor = new StrSubstitutor(valuesMap);
String mailContent = StrSubstitutor.replace(template );
}
输出应为
尊敬的名字,您的请求号是1234567。
答案 0 :(得分:0)
您基本上可以将每个键替换为值
String template ="Dear ${test.firstname},Your Request number is ${test.request.requestNumber}.";
Test test = ...;
Map<String, String> valuesMap = new HashMap<>();
valuesMap.put("test.firstname",test.getFirstName());
valuesMap.put("test.request.requestNumber",test.getRequest().getRequestNumber());
for (Map.Entry<String, String> entry : map.entrySet()) {
template = template.replace("${" + entry.getKey() + "}", entry.getValue());
}
选中此post以获得更多答案