有没有办法让 Spring 从 DTO 自动填充 RestTemplate
查询参数,类似于它自动实例化响应 DTO 的方式?
我想写这样的东西:
RequestDto request = new RequestDto();
request.setFoo("foo");
request.setBar("bar");
ResponseDto response = restTemplate.getForObject(
"http://example.com/api",
ResponseDto.class,
request
);
而不是:
ResponseDto response = restTemplate.getForObject(
"http://example.com/api?foo={foo}&bar={bar}",
ResponseDto.class,
"foo",
"bar"
);
因为有许多大型 DTO,需要大量的样板代码,这些代码必须与任何 DTO 更改保持同步。
Spring 4.3.25
最佳答案
我认为这不可能直接实现。以下内容并不完全使用 DTO,但它确实允许您构建请求,而无需手动形成 URL 字符串。您可以使用Spring的UriComponentsBuilder类。
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://example.com/api")
.queryParam("foo", "bar")
// etc. ...
.queryParam("bar", "foo");
String result = restTemplate.getForObject(builder.toString(), String.class);
您可以循环 DTO 并按照上面的方式构建查询。或者如果没有 DTO,您可以使用 Map<String, String>
并循环它。
Map<String, String> params = new HashMap<>();
params.put("foo", "bar");
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://example.com/api");
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.queryParam(entry.getKey(), entry.getValue());
}
String result = restTemplate.getForObject(builder.toString(), String.class);
编辑:
正如下面crizzis建议的那样,您可以使用Spring Cloud OpenFeign的 REST 客户端(来自 Feign @QueryMap support ):
The OpenFeign @QueryMap annotation provides support for POJOs to be used as GET parameter maps. Unfortunately, the default OpenFeign QueryMap annotation is incompatible with Spring because it lacks a value property.
和
Spring Cloud OpenFeign provides an equivalent @SpringQueryMap annotation, which is used to annotate a POJO or Map parameter as a query parameter map.
根据您的问题的示例:
public class RequestDto {
private string foo;
private string bar;
}
@FeignClient(name = "client", url = "http://example.com")
public interface FooTemplate {
@GetMapping(path = "/api")
String endpoint(@SpringQueryMap RequestDto requestDto);
}
关于spring - 从 DTO 填充查询参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63631972/