java - 类似于 spring 的 NamedParameterUtils 的工具用于常规字符串处理?

标签 java spring string velocity

我想用值替换字符串中的命名参数,就像使用 Python 的 % 运算符时一样。 Spring 支持与我需要的 NamedParameterUtils 功能非常相似的功能,但由于某种原因,它与 Jdbc 紧密耦合,并用问号替换了那些命名参数。

那么,如果我想做 ":a is :b"% {"a":"Java", "b":"Beautiful"} 我必须诉诸使用像 Velocity 这样的重炮吗?或者我错过了一些简单的事情?

更新:使用 Dmitry 的代码编写我自己的简单版本:

public static String formatSqlWithNamedParams(String sqlTemplate, Map<String, Object> params){
    StringWriter writer = new StringWriter();
    Pattern var = Pattern.compile("\\$\\{\\s*([\\w\\[\\]\\(\\)\\.]+)\\s*\\}");
    Matcher match = var.matcher(sqlTemplate);
    int offset = 0;
    while (match.find()) {
        writer.write(sqlTemplate.substring(offset, match.start()));
        String key = match.group(1);
        Object val = params.get(key);
        writer.write(val.toString());
        offset = match.end();
    }
    writer.write(sqlTemplate.substring(offset));
    return writer.toString();
}

最佳答案

大约需要 50 行代码才能编写您想要的内容。

这是我不久前写的“TrivialTemplate”的摘录,它的作用非常相似:

private final Pattern var = Pattern
        .compile("\\{\\s*([\\w\\[\\]\\(\\)\\.]+)\\s*\\}");
private final PropertyUtilsBean bean = new PropertyUtilsBean();
private final Object data;

public TrivialTemplate(Object data) {
    this.data = data;
}

public void process(BufferedReader reader, PrintWriter writer) {
    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            Matcher match = var.matcher(line);
            int offset = 0;
            while (match.find()) {
                writer.write(line.substring(offset, match.start()));
                String key = match.group(1);
                if (!isBlank(key)) {
                    Object val = bean.getNestedProperty(data, key
                            .toLowerCase());
                    writer.write(val != null ? val.toString() : "{null}");
                } else {
                    writer.write("{null}");
                }
                offset = match.end();
            }
            writer.write(line.substring(offset));
            writer.println();
        }
    } catch (Throwable t) {
        throw new RuntimeException("template error", t);
    }
}

我使用 BeanUtils 来支持任意数据对象,但您也可以轻松地将其限制为 map 。

关于java - 类似于 spring 的 NamedParameterUtils 的工具用于常规字符串处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6251083/

相关文章:

spring - 微服务之间的原子操作

Python:在多列中查找字符串并将其返回到新列中

c++ - 给定 1000 个长度为 100 的字符串,找出最小的唯一子字符串的长度

java - WinXP 和 Mac OS X 中的 MySql

java - JFrame 很小

java - Spring JSON序列化、Gson反序列化

java - 错误由: java. lang.ClassNotFoundException : org. springframework.security.context.DelegatingApplicationListener引起

java - Eclipse 说选择不包含主要类型?

java - Hibernate:集合的投影返回 ArrayIndexOutOfBoundsException

Java: getSelectedItem() 对于字符串类型未定义