填坑:Spring RestTemplate请求,并返回Page
RestTemplate指定返回泛型
RestTemplate.exchange()方法可以指定返回数据时,用泛型去包装
public <T> ResponseEntity<T> exchange(URI,HttpMethod, HttpEntity<?>,ParameterizedTypeReference<T>)
使用方法:
ParameterizedTypeReference<MyPageImpl<User>> typeRef = new ParameterizedTypeReference<MyPageImpl<User>>(){};
MyPageImpl<User> page = RestTemplate.exchange(uri,method,entity,typeRef);
这里面有个坑,因为org.springframework.data.domain.PageImpl,缺少默认的构造器及一些setter方法,所以Jackson不知道怎么去包装。
我的解决方法是新建一个继续自PageImpl的类
public class MyPageImpl<T> extends PageImpl {
private boolean first;
private boolean last;
private long numberOfElements;
private Object sort;
private long totalPages;
@JsonCreator
public MyPageImpl(@JsonProperty("content") List<T> content,
@JsonProperty("number") int page,
@JsonProperty("size") int size,
@JsonProperty("totalElements") long total) {
super(content, new PageRequest(page, size), total);
}
}
主是使用@JsonCreator及@JsonProperty告诉Jackson如何把数据注入自定义的构造器