DSL Customization

此部分仅对 Groovy DSL 有效

This section is valid only for the Groovy DSL

正如本节后面部分中所示,您可以通过扩展 DSL 来定制 Spring Cloud 合约验证程序。

You can customize the Spring Cloud Contract Verifier by extending the DSL, as shown in the remainder of this section.

Extending the DSL

您可以为 DSL 提供您自己的功能。此功能的关键需求是维持静态兼容性。在本章的后面部分,您可以看到示例:

You can provide your own functions to the DSL. The key requirement for this feature is to maintain the static compatibility. Later in this chapter, you can see examples of:

  • Creating a JAR with reusable classes.

  • Referencing of these classes in the DSLs.

您可以在 here找到完整的示例。

You can find the full example here.

Common JAR

以下示例显示了可以在 DSL 中重复使用的三个类。

The following examples show three classes that can be reused in the DSLs.

{samples_url}/common/src/main/java/com/example/PatternUtils.java[PatternUtils] 包含消费者和生产者都使用的函数。

{samples_url}/common/src/main/java/com/example/PatternUtils.java[PatternUtils] contains functions used by both the consumer and the producer.

{samples_url}/common/src/main/java/com/example/ConsumerUtils.java[ConsumerUtils] 包含消费者使用的函数。

{samples_url}/common/src/main/java/com/example/ConsumerUtils.java[ConsumerUtils] contains functions used by the consumer.

{samples_url}/common/src/main/java/com/example/ProducerUtils.java[ProducerUtils] 包含生产者使用的函数。

{samples_url}/common/src/main/java/com/example/ProducerUtils.java[ProducerUtils] contains functions used by the producer.

Adding a Test Dependency in the Project’s Dependencies

如需在项目的依赖项中添加测试依赖项,您必须先将 common jar 依赖项添加为测试依赖项。由于您的合同文件在测试资源路径上可用,因此 common jar 类会自动在您的 Groovy 文件中可见。以下 {samples_url}/producer/[example] 展示了如何测试依赖项。

To add a test dependency in the project’s dependencies, you must first add the common jar dependency as a test dependency. Because your contracts files are available on the test resources path, the common jar classes automatically become visible in your Groovy files. The following {samples_url}/producer/[example] show how to test the dependency.

Adding a Test Dependency in the Plugin’s Dependencies

现在,您必须添加插件的依赖关系,以便在运行时可以重复使用。

Now, you must add the dependency for the plugin to reuse at runtime.

Referencing Classes in DSLs

您现在可以在您的 DSL 中引用您的类,如 {samples_url}/producer/src/test/resources/contracts/beer/rest/shouldGrantABeerIfOldEnough.groovy[以下示例所示]。

You can now reference your classes in your DSL, as the {samples_url}/producer/src/test/resources/contracts/beer/rest/shouldGrantABeerIfOldEnough.groovy[following example shows].

您可以通过设置 convertToYamltrue 来设置 Spring Cloud Contract 插件。这样,您不需要向使用 YAML 契约而非 Groovy 契约的使用者端添加带扩展功能的依赖项。

You can set the Spring Cloud Contract plugin up by setting convertToYaml to true. That way, you do NOT have to add the dependency with the extended functionality to the consumer side, since the consumer side uses YAML contracts instead of Groovy contracts.