6. 客户端支持

本节描述了 Spring HATEOAS 对 Client 端的支持。spring-doc.cadn.net.cn

6.1. 遍历

Spring HATEOAS 提供了一个用于客户端服务遍历的 API。它的灵感来自 Traverson JavaScript 库。 以下示例演示如何使用它:spring-doc.cadn.net.cn

Map<String, Object> parameters = new HashMap<>();
parameters.put("user", 27);

Traverson traverson = new Traverson(URI.create("http://localhost:8080/api/"), MediaTypes.HAL_JSON);
String name = traverson
    .follow("movies", "movie", "actor").withTemplateParameters(parameters)
    .toObject("$.name");

您可以设置Traverson实例,方法是将其指向 REST 服务器并配置要设置为Accept头。然后,您可以定义要发现和关注的关系名称。关系名称可以是简单名称或 JSONPath 表达式(以 an 开头)。$spring-doc.cadn.net.cn

然后,样本将参数映射传递到Traverson实例。这些参数用于扩展遍历期间找到的 URI(模板化)。遍历通过访问最终遍历的表示来结束。在前面的示例中,我们评估 JSONPath 表达式以访问参与者的名称。spring-doc.cadn.net.cn

前面的示例是遍历的最简单版本,其中rel值是字符串,在每个跃点中,将应用相同的模板参数。spring-doc.cadn.net.cn

每个级别都有更多选项可用于自定义模板参数。 以下示例显示了这些选项。spring-doc.cadn.net.cn

ParameterizedTypeReference<EntityModel<Item>> resourceParameterizedTypeReference = new ParameterizedTypeReference<EntityModel<Item>>() {};

EntityModel<Item> itemResource = traverson.//
    follow(rel("items").withParameter("projection", "noImages")).//
    follow("$._embedded.items[0]._links.self.href").//
    toObject(resourceParameterizedTypeReference);

静电rel(…​)function 是定义单个Hop.用.withParameter(key, value)使指定 URI 模板变量变得简单。spring-doc.cadn.net.cn

.withParameter()返回一个新的Hopobject 的您可以将任意数量的.withParameter随你所欲。结果是单个Hop定义。 以下示例显示了一种执行此作的方法:
ParameterizedTypeReference<EntityModel<Item>> resourceParameterizedTypeReference = new ParameterizedTypeReference<EntityModel<Item>>() {};

Map<String, Object> params = Collections.singletonMap("projection", "noImages");

EntityModel<Item> itemResource = traverson.//
    follow(rel("items").withParameters(params)).//
    follow("$._embedded.items[0]._links.self.href").//
    toObject(resourceParameterizedTypeReference);

您还可以加载整个Mapof 参数.withParameters(Map).spring-doc.cadn.net.cn

follow()是可链接的,这意味着您可以将多个跃点串在一起,如前面的示例所示。你可以将多个基于字符串的rel值 (follow("items", "item")) 或具有特定参数的单个跃点。

6.1.1.EntityModel<T>与。CollectionModel<T>

到目前为止显示的示例演示了如何避开 Java 的类型擦除并将单个 JSON 格式的资源转换为EntityModel<Item>对象。但是,如果您获得像\_embeddedHAL 系列? 您只需稍作调整即可执行此作,如下例所示:spring-doc.cadn.net.cn

CollectionModelType<Item> collectionModelType =
    TypeReferences.CollectionModelType<Item>() {};

CollectionModel<Item> itemResource = traverson.//
    follow(rel("items")).//
    toObject(collectionModelType);

这个 API 不是获取单个资源,而是将集合反序列化为CollectionModel.spring-doc.cadn.net.cn

当使用支持超媒体的表示时,一个常见的任务是找到一个具有特定关系类型的链接。Spring HATEOAS 提供了基于 JSONPathLinkDiscoverer接口,用于默认表示渲染或开箱即用的 HAL。使用@EnableHypermediaSupport中,我们会自动将支持配置的超媒体类型的实例公开为 Spring Bean。spring-doc.cadn.net.cn

或者,您可以按如下方式设置和使用实例:spring-doc.cadn.net.cn

String content = "{'_links' :  { 'foo' : { 'href' : '/foo/bar' }}}";
LinkDiscoverer discoverer = new HalLinkDiscoverer();
Link link = discoverer.findLinkWithRel("foo", content);

assertThat(link.getRel(), is("foo"));
assertThat(link.getHref(), is("/foo/bar"));

6.3. 配置 WebClient 实例

如果您需要配置WebClient要说超媒体,这很容易。获取HypermediaWebClientConfigurer如下所示:spring-doc.cadn.net.cn

例 43.配置WebClient你自己
@Bean
WebClient.Builder hypermediaWebClient(HypermediaWebClientConfigurer configurer) { (1)
 return configurer.registerHypermediaTypes(WebClient.builder()); (2)
}
1 在您的@Configuration类中,获取HypermediaWebClientConfigurerbean Spring HATEOAS 注册。
2 创建WebClient.Builder中,使用 Configurer 注册超媒体类型。
什么HypermediaWebClientConfigurer它是否使用WebClient.Builder.要利用它, 您需要将构建器注入到应用程序中的某个位置,然后运行build()方法生成WebClient.

如果您使用的是 Spring Boot,还有另一种方法:WebClientCustomizer.spring-doc.cadn.net.cn

例 44.让 Spring Boot 配置内容
@Bean (4)
WebClientCustomizer hypermediaWebClientCustomizer(HypermediaWebClientConfigurer configurer) { (1)
    return webClientBuilder -> { (2)
        configurer.registerHypermediaTypes(webClientBuilder); (3)
    };
}
1 创建 Spring bean 时,请求 Spring HATEOAS 的HypermediaWebClientConfigurer豆。
2 使用 Java 8 lambda 表达式定义WebClientCustomizer.
3 在函数调用中,应用registerHypermediaTypes方法。
4 将整个内容作为 Spring bean 返回,以便 Spring Boot 可以获取它并将其应用于其自动配置WebClient.Builder豆。

在这个阶段,每当你需要混凝土时WebClient,只需注入WebClient.Builder添加到您的代码中,并使用build().这WebClient实例 将能够使用超媒体进行交互。spring-doc.cadn.net.cn

6.4. 配置WebTestClient实例

当使用支持超媒体的表示时,一个常见的任务是通过使用WebTestClient.spring-doc.cadn.net.cn

要配置WebTestClient在测试用例中,请查看以下示例:spring-doc.cadn.net.cn

例 45.配置WebTestClient使用 Spring HATEOAS 时
@Test // #1225
void webTestClientShouldSupportHypermediaDeserialization() {

  // Configure an application context programmatically.
  AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
  context.register(HalConfig.class); (1)
  context.refresh();

  // Create an instance of a controller for testing
  WebFluxEmployeeController controller = context.getBean(WebFluxEmployeeController.class);
  controller.reset();

  // Extract the WebTestClientConfigurer from the app context.
  HypermediaWebTestClientConfigurer configurer = context.getBean(HypermediaWebTestClientConfigurer.class);

  // Create a WebTestClient by binding to the controller and applying the hypermedia configurer.
  WebTestClient client = WebTestClient.bindToApplicationContext(context).build().mutateWith(configurer); (2)

  // Exercise the controller.
  client.get().uri("http://localhost/employees").accept(HAL_JSON) //
      .exchange() //
      .expectStatus().isOk() //
      .expectBody(new TypeReferences.CollectionModelType<EntityModel<Employee>>() {}) (3)
      .consumeWith(result -> {
        CollectionModel<EntityModel<Employee>> model = result.getResponseBody(); (4)

        // Assert against the hypermedia model.
        assertThat(model.getRequiredLink(IanaLinkRelations.SELF)).isEqualTo(Link.of("http://localhost/employees"));
        assertThat(model.getContent()).hasSize(2);
      });
}
1 注册使用@EnableHypermediaSupport以启用 HAL 支持。
2 HypermediaWebTestClientConfigurer以应用超媒体支持。
3 要求回复CollectionModel<EntityModel<Employee>>使用 Spring HATEOAS 的TypeReferences.CollectionModelType助手。
4 在获得 Spring HATEOAS 格式的 “body” 后,断言反对它!
WebTestClient是不可变的值类型,因此您无法就地更改它。HypermediaWebClientConfigurer返回一个 mutated 变体,然后必须捕获该变体才能使用它。

如果您使用的是 Spring Boot,则还有其他选项,如下所示:spring-doc.cadn.net.cn

例 46.配置WebTestClient使用 Spring Boot 时
@SpringBootTest
@AutoConfigureWebTestClient (1)
class WebClientBasedTests {

    @Test
    void exampleTest(@Autowired WebTestClient.Builder builder, @Autowired HypermediaWebTestClientConfigurer configurer) { (2)
        client = builder.apply(configurer).build(); (3)

        client.get().uri("/") //
                .exchange() //
                .expectBody(new TypeReferences.EntityModelType<Employee>() {}) (4)
                .consumeWith(result -> {
                    // assert against this EntityModel<Employee>!
                });
    }
}
1 这是 Spring Boot 的 test 注解,它将配置一个WebTestClient.Builder对于此测试类。
2 Autowire Spring Boot 的WebTestClient.Builderbuilder和 Spring HATEOAS 的 configurer 作为方法参数。
3 HypermediaWebTestClientConfigurer注册对超媒体的支持。
4 Signal 您希望EntityModel<Employee>返回TypeReferences.

同样,您可以使用与前面的示例类似的断言。spring-doc.cadn.net.cn

还有许多其他方法可以设计测试用例。WebTestClient可以绑定到控制器、函数和 URL。本节并不是要展示所有这些。相反,这为您提供了一些入门示例。重要的是,通过应用HypermediaWebTestClientConfigurer、任何WebTestClient可以更改以处理超媒体。spring-doc.cadn.net.cn

6.5. 配置 RestTemplate 实例

如果您想创建自己的RestTemplate,配置为使用超媒体,您可以使用HypermediaRestTemplateConfigurer:spring-doc.cadn.net.cn

例 47.配置RestTemplate你自己
/**
 * Use the {@link HypermediaRestTemplateConfigurer} to configure a {@link RestTemplate}.
 */
@Bean
RestTemplate hypermediaRestTemplate(HypermediaRestTemplateConfigurer configurer) { (1)
	return configurer.registerHypermediaTypes(new RestTemplate()); (2)
}
1 在您的@Configuration类中,获取HypermediaRestTemplateConfigurerbean Spring HATEOAS 注册。
2 创建RestTemplate中,使用 Configurer 应用超媒体类型。

您可以自由地将此模式应用于RestTemplate,无论是创建已注册的 bean,还是在您定义的服务中。spring-doc.cadn.net.cn

如果您使用的是 Spring Boot,还有另一种方法。spring-doc.cadn.net.cn

总的来说,Spring Boot 已经摆脱了注册RestTemplatebean 中。spring-doc.cadn.net.cn

为了补偿这一点, Spring Boot 提供了一个RestTemplateBuilder.这个自动配置的 bean 允许你定义用于时尚的各种 bean 一个RestTemplate实例。您要求RestTemplateBuilderbean 中,请将其build()方法,然后应用最终设置(例如凭据和其他详细信息)。spring-doc.cadn.net.cn

要注册基于超媒体的消息转换器,请将以下内容添加到您的代码中:spring-doc.cadn.net.cn

例 48.让 Spring Boot 配置内容
@Bean (4)
RestTemplateCustomizer hypermediaRestTemplateCustomizer(HypermediaRestTemplateConfigurer configurer) { (1)
    return restTemplate -> { (2)
        configurer.registerHypermediaTypes(restTemplate); (3)
    };
}
1 创建 Spring bean 时,请求 Spring HATEOAS 的HypermediaRestTemplateConfigurer豆。
2 使用 Java 8 lambda 表达式定义RestTemplateCustomizer.
3 在函数调用中,应用registerHypermediaTypes方法。
4 将整个内容作为 Spring bean 返回,以便 Spring Boot 可以获取它并将其应用于其自动配置RestTemplateBuilder.

在这个阶段,每当你需要混凝土时RestTemplate,只需注入RestTemplateBuilder添加到您的代码中,并使用build().这RestTemplate实例 将能够使用超媒体进行交互。spring-doc.cadn.net.cn


APP信息