나는 아주 간단한 컨트롤러를 가지고 HTTP 요청을 만들고 HATEOAS 형식의 리소스를 받는다.Spring HATEOAS를 적절한 객체로 변환하는 방법
package com.provider.spring.controller;
import java.util.List;
import org.springframework.hateoas.Link;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.provider.employee.EmployeeDTO;
import com.provider.http.HttpComponentsClientHttpRequestFactoryBasicAuth;
import com.provider.spring.rest.Resource;
@Controller
public class EmployeeController {
private static final String REL_SELF = "self";
private static final String REL_SEARCH = "search";
private static final String REL_EMPLOYEE = "employee";
private static final String RESOURCE_URI = "http://localhost:8080/employees";
private RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactoryBasicAuth("user", "password"));
private List<EmployeeDTO> employees;
@RequestMapping("/employees")
public String getAllEmployees() {
String result = null;
try {
String resultBody = restTemplate.getForObject(RESOURCE_URI, String.class);
ObjectMapper objectMapper = new ObjectMapper();
Resource<EmployeeDTO> resource = objectMapper.readValue(resultBody, Resource.class);
// Get objects with relation "employee"
for(Link l : resource.getLinks()) {
if(l.getRel().equals(REL_EMPLOYEE)) {
// TODO: Construct EmployeeDTO from Link.
// TODO: Add EmployeeDTO to list.
}
}
}
catch(Exception e) {
e.printStackTrace();
result = "error";
return result;
}
return result;
}
}
개체를 개체로 변환하는 기존의 기본 방법이 있습니까?
는 EmployeeDTO에 대한 자세한 내용은 여기를 참조하십시오 : 당신은 RestTemplate의 생성자의 일부 MessageConverters를 등록하거나 setMessageConverters을 사용할 수 있습니다 https://gist.github.com/Xerosigma/64469a30355f5de0228a
EmployeeDTO 클래스를 볼 수 있습니까? 우리가 인스턴스화하려고하는 대상 클래스를 보는 것이 도움이 될 것입니다. –
예! 여기에는 요점이 있으며, 불행히도 실패한 시도가 포함 된 최신 컨트롤러를 포함 시켰습니다. https://gist.github.com/Xerosigma/64469a30355f5de0228a –