Spring boot and java 8:有没有动态构建字符串的方法?

Spring boot and java 8: Is there a way to build a string dynamically?

有没有办法在 java 8 and/or spring 引导中动态构建字符串?我正在尝试使用从 REST 服务调用接收到的参数构建一个 URL,此服务有多个可选过滤器,我可以使用伪 AI 方法,在该方法中我使用多个 if-else 验证所有内容,但我没有认为这是最好的方法。 URL 是对 Jira REST Api 的调用,因此语法是独一无二的。

我要避免的是这个

and = "\"%20AND%20\"";    
if (param1 != null) url += param1;
if (param1 != null && param2 != null) url += param1 + and + param2;
if (param1 != null && param2 != null && param3 != null) url += param1 + and + param2 + and + param3;
if (param1 != null && param2 == null && param3 != null) url += param1 + and + param3;

我认为一定有比验证每个参数 10 次更好的方法。

有多种解决方案可用:

  • 只需使用 StringBuilder 或简单的字符串连接来构建您的查询字符串
  • Springs UriComponentsBuilder JavaDoc 提供了一种更加结构化的查询字符串构建方式,您可能更熟悉基于 JPA 的解决方案
  • 使用 RestTemplates 允许传递代表您的请求参数的有条件填充的 Map
  • Springs 较新 WebClient class 还支持使用这样的 uri 构建器在 get 上设置参数:
WebClient c = WebClient.create();
c.get().uri(uriBuilder -> uriBuilder
    .queryParam("param1", "value")
    .queryParam("param2", "value2")
    .build()
).retrieve();