是否有任何库允许我使用与我们在BeanUtils中使用相同的已知符号来提取POJO参数,但是为了轻松替换字符串中的占位符?
我知道可以使用BeanUtils本身或具有类似功能的其他库来自己滚动,但我不想重新发明轮子。
我想采用如下字符串:
String s = "User ${user.name} just placed an order. Deliver is to be
made to ${user.address.street}, ${user.address.number} - ${user.address.city} /
${user.address.state}";
并传递以下User类的一个实例:
public class User {
private String name;
private Address address;
// (...)
public String getName() { return name; }
public Address getAddress() { return address; }
}
public class Address {
private String street;
private int number;
private String city;
private String state;
public String getStreet() { return street; }
public int getNumber() { return number; }
// other getters...
}
类似于:
System.out.println(BeanUtilsReplacer.replaceString(s, user));
将每个占位符替换为实际值。
有什么想法吗?
答案 0 :(得分:2)
使用BeanUtils滚动自己不需要太多的轮子改造(假设你希望它像所要求的那样基本)。此实现采用Map替换上下文,其中map键应对应于为替换而给出的变量查找路径的第一部分。
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.beanutils.BeanUtils;
public class BeanUtilsReplacer
{
private static Pattern lookupPattern = Pattern.compile("\\$\\{([^\\}]+)\\}");
public static String replaceString(String input, Map<String, Object> context)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
{
int position = 0;
StringBuffer result = new StringBuffer();
Matcher m = lookupPattern.matcher(input);
while (m.find())
{
result.append(input.substring(position, m.start()));
result.append(BeanUtils.getNestedProperty(context, m.group(1)));
position = m.end();
}
if (position == 0)
{
return input;
}
else
{
result.append(input.substring(position));
return result.toString();
}
}
}
考虑到你问题中提供的变量:
Map<String, Object> context = new HashMap<String, Object>();
context.put("user", user);
System.out.println(BeanUtilsReplacer.replaceString(s, context));
答案 1 :(得分:1)
请参阅有关using Expression Language in a standalone context的类似问题的答案。
答案 2 :(得分:1)
Spring Framework应该具有执行此操作的功能(请参阅下面的Spring JDBC示例)。如果你可以使用groovy(只需添加groovy.jar文件),你可以使用Groovy的GString功能来完成这项工作。
Groovy示例
foxtype = 'quick'
foxcolor = ['b', 'r', 'o', 'w', 'n']
println "The $foxtype ${foxcolor.join()} fox"
Spring JDBC有一个功能,我用它来支持来自bean的命名和嵌套命名绑定变量:
public int countOfActors(Actor exampleActor) {
// notice how the named parameters match the properties of the above 'Actor' class
String sql = "select count(0) from T_ACTOR where first_name = :firstName and last_name = :lastName";
SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(exampleActor);
return this.namedParameterJdbcTemplate.queryForInt(sql, namedParameters);
}
答案 3 :(得分:1)
您的字符串示例是至少一些模板引擎中的有效模板,如Velocity或Freemarker。这些库提供了一种将模板与包含某些对象的上下文(例如示例中的“user”)合并的方法。
请参阅http://velocity.apache.org/或http://www.freemarker.org/
一些示例代码(来自Freemarker网站):
/* ------------------------------------------------------------------- */
/* You usually do it only once in the whole application life-cycle: */
/* Create and adjust the configuration */
Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(
new File("/where/you/store/templates"));
cfg.setObjectWrapper(new DefaultObjectWrapper());
/* ------------------------------------------------------------------- */
/* You usually do these for many times in the application life-cycle: */
/* Get or create a template */
Template temp = cfg.getTemplate("test.ftl");
/* Create a data-model */
Map root = new HashMap();
root.put("user", "Big Joe");
Map latest = new HashMap();
root.put("latestProduct", latest);
latest.put("url", "products/greenmouse.html");
latest.put("name", "green mouse");
/* Merge data-model with template */
Writer out = new OutputStreamWriter(System.out);
temp.process(root, out);
out.flush();