Spring云FeignClient解码application/hal+json资源<Object>return类型

Spring Cloud FeignClient decoding application/hal+json Resource<Object> return type

我正在使用 Spring Cloud、Spring Data JPA、Spring Data Rest 和 Spring Boot 开发 REST API。服务器实现根据 HAL 规范等正确生成各种数据项。它生成 HAL+JSON 如下:

{
  "lastModifiedBy" : "unknown",
  "lastModifiedOn" : "2015-06-04T12:19:45.249688",
  "id" : 2,
  "name" : "Item 2",
  "description" : null,
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/pltm/accounts/2"
    },
    "customers" : {
      "href" : "http://localhost:8080/pltm/accounts/2/customers"
    },
    "users" : {
      "href" : "http://localhost:8080/pltm/accounts/2/users"
    },
    "groups" : {
      "href" : "http://localhost:8080/pltm/accounts/2/groups"
    }
  }
}

现在我正在尝试使用 FeignClient Spring 云库来实现客户端实现。我定义了我的客户端界面如下。

@FeignClient("serviceId")
@RequestMapping(value = "/api", consumes = MediaType.APPLICATION_JSON_VALUE)
public interface PltmClient
{
  // Account Requests
  @RequestMapping(method = RequestMethod.GET, value = "/accounts")
  PagedResources<Resource<Account>> getAccounts();

  @RequestMapping(method = RequestMethod.GET, value = "/accounts/{id}")
  Resource<Account> getAccountAsResource(@PathVariable("id") Long id);

  @RequestMapping(method = RequestMethod.GET, value = "/accounts/{id}")
  Account getAccount(@PathVariable("id") Long id);
}

当我调用 getAccout() 方法时,我返回了我的域对象 Account,其中包含 JSON 文档中的详细信息。该对象是一个简单的 POJO。所有字段都已正确填写。

public class Account
{
   private Long id;
   private String name;
   private String description;

   /** Setters/Getters left out for brevity **/
 }

但是当我调用 getAccountAsResource() 时,它起作用了,我得到了一个包含数据的 Resource 对象。但是,对 Resource.getContent() return 的调用是一个未完全填充的 Account 对象。在这种情况下,Account.getId() 为 NULL,这会导致问题。

知道为什么会这样吗?我的一个想法是 Resource class 定义了一个 getId() 方法,这在某种程度上混淆了 Jackson ObjectMapper。

更大的问题是整个方法是否可行或者是否有更好的方法?显然,我可以只使用普通的 POJO 作为我的 return 类型,但这会丢失客户端的 HAL 信息。

是否有人为 Spring 数据 REST 服务器端点成功实施了基于 Java 的客户端实施?

Account 没有 id 是 spring-data-rest 的一个特性。您需要在服务器端启用填充 id。

我还向 return ID(在帐户中)添加了不同的方法

@JsonProperty("accountId")
public String getId() {
    return id;
}

启用 ID

@Configuration
public class MyConfig extends RepositoryRestMvcConfiguration {

    @Override
    protected void configureRepositoryRestConfiguration( RepositoryRestConfiguration config) {
        config.exposeIdsFor(Account.class);
    }
}

我在这里使用过它:https://github.com/spencergibb/myfeed,虽然我相信我使用资源的地方,我正在使用 RestTemplate