From 554d59bf917dc2d0ba7ffd11e1f4df3d954a4b8b Mon Sep 17 00:00:00 2001 From: Marcin Grzejszczak Date: Thu, 11 Jul 2019 17:00:25 +0200 Subject: [PATCH 01/18] WIP --- README.adoc | 420 ++++++---------- docs/src/main/asciidoc/README.adoc | 28 +- .../{building.adoc => _building.adoc} | 0 docs/src/main/asciidoc/_contract_flows.adoc | 8 + .../main/asciidoc/{links.adoc => _links.adoc} | 0 ...c => _spring-cloud-contract-verifier.adoc} | 17 +- ...emock.adoc => _spring-cloud-wiremock.adoc} | 25 +- ..._contract.adoc => _verifier_contract.adoc} | 124 +++-- .../{verifier_faq.adoc => _verifier_faq.adoc} | 2 +- ...ction.adoc => _verifier_how_it_works.adoc} | 204 ++------ .../main/asciidoc/_verifier_introduction.adoc | 120 +++++ ...essaging.adoc => _verifier_messaging.adoc} | 0 docs/src/main/asciidoc/_verifier_setup.adoc | 7 + ...brunner.adoc => _verifier_stubrunner.adoc} | 0 ...msg.adoc => _verifier_stubrunner_msg.adoc} | 0 docs/src/main/asciidoc/docker-project.adoc | 180 +++++++ docs/src/main/asciidoc/gradle-project.adoc | 420 ++++++++++++++++ ...verifier_setup.adoc => maven-project.adoc} | 475 ++---------------- docs/src/main/asciidoc/migrations.adoc | 180 ------- .../main/asciidoc/spring-cloud-contract.adoc | 11 +- 20 files changed, 1104 insertions(+), 1117 deletions(-) rename docs/src/main/asciidoc/{building.adoc => _building.adoc} (100%) create mode 100644 docs/src/main/asciidoc/_contract_flows.adoc rename docs/src/main/asciidoc/{links.adoc => _links.adoc} (100%) rename docs/src/main/asciidoc/{spring-cloud-contract-verifier.adoc => _spring-cloud-contract-verifier.adoc} (76%) rename docs/src/main/asciidoc/{spring-cloud-wiremock.adoc => _spring-cloud-wiremock.adoc} (92%) rename docs/src/main/asciidoc/{verifier_contract.adoc => _verifier_contract.adoc} (98%) rename docs/src/main/asciidoc/{verifier_faq.adoc => _verifier_faq.adoc} (99%) rename docs/src/main/asciidoc/{verifier_introduction.adoc => _verifier_how_it_works.adoc} (85%) create mode 100644 docs/src/main/asciidoc/_verifier_introduction.adoc rename docs/src/main/asciidoc/{verifier_messaging.adoc => _verifier_messaging.adoc} (100%) create mode 100644 docs/src/main/asciidoc/_verifier_setup.adoc rename docs/src/main/asciidoc/{verifier_stubrunner.adoc => _verifier_stubrunner.adoc} (100%) rename docs/src/main/asciidoc/{verifier_stubrunner_msg.adoc => _verifier_stubrunner_msg.adoc} (100%) create mode 100644 docs/src/main/asciidoc/docker-project.adoc create mode 100644 docs/src/main/asciidoc/gradle-project.adoc rename docs/src/main/asciidoc/{verifier_setup.adoc => maven-project.adoc} (66%) delete mode 100644 docs/src/main/asciidoc/migrations.adoc diff --git a/README.adoc b/README.adoc index 43c5b4f045..78c55fab50 100644 --- a/README.adoc +++ b/README.adoc @@ -8,8 +8,24 @@ Edit the files in the src/main/asciidoc/ directory instead. image::https://badges.gitter.im/Join%20Chat.svg[Gitter, link="https://gitter.im/spring-cloud/spring-cloud-contract?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge"] image::https://codecov.io/gh/spring-cloud/spring-cloud-contract/branch/{branch}/graph/badge.svg["codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-contract"] image::https://circleci.com/gh/spring-cloud/spring-cloud-contract.svg?style=svg["CircleCI", link="https://circleci.com/gh/spring-cloud/spring-cloud-contract"] -:introduction_url: ../../../.. -:verifier_core_path: {introduction_url}/spring-cloud-contract-verifier +:branch: master +:core_path: ../../.. +:plugins_path: ../../../spring-cloud-contract-tools +:converters_path: {plugins_path}/spring-cloud-contract-converters +:verifier_root_path: {core_path}/spring-cloud-contract-verifier +:contract_spec_path: {core_path}/specs/spring-cloud-contract-spec-java +:contract_spec_tests_path: {core_path}/specs/spring-cloud-contract-spec +:samples_path: {core_path}/samples +:verifier_core_path: {verifier_root_path} +:stubrunner_core_path: {core_path}/spring-cloud-contract-stub-runner +:standalone_samples_path: {samples_path}/standalone/dsl +:standalone_messaging_samples_path: {samples_path}/standalone/messaging +:standalone_pact_path: {samples_path}/standalone/pact +:standalone_restdocs_path: {samples_path}/standalone/restdocs +:tests_path: {core_path}/tests +:samples_branch: 2.2.x +:samples_url: https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/{samples_branch} +:introduction_url: ${core_path}/../../ == Spring Cloud Contract @@ -27,23 +43,9 @@ https://cloud-samples.spring.io/spring-cloud-contract-samples/workshops.html[thi === Spring Cloud Contract Verifier -== Spring Cloud Contract Verifier Introduction +== Spring Cloud Contract Introduction -Spring Cloud Contract Verifier enables Consumer Driven Contract (CDC) development of -JVM-based applications. It moves TDD to the level of software architecture. - -Spring Cloud Contract Verifier ships with _Contract Definition Language_ (CDL). Contract -definitions are used to produce the following resources: - -* JSON stub definitions to be used by WireMock when doing integration testing on the -client code (_client tests_). Test code must still be written by hand, and test data is -produced by Spring Cloud Contract Verifier. -* Messaging routes, if you're using a messaging service. We integrate with Spring -Integration, Spring Cloud Stream, Spring AMQP, and Apache Camel. You can also set your -own integrations. -* Acceptance tests (in JUnit 4, JUnit 5 or Spock) are used to verify if server-side implementation -of the API is compliant with the contract (__server tests__). A full test is generated by -Spring Cloud Contract Verifier. +Spring Cloud Contract moves TDD to the level of software architecture. It allows to perform consumer, consumer-driven and producer-driven contract testing. === History @@ -71,6 +73,7 @@ Both have their advantages but also a lot of disadvantages. *Deploy all microservices and perform end to end tests* + Advantages: - Simulates production. @@ -99,29 +102,30 @@ Disadvantages: reality. - You can go to production with passing tests and failing production. -To solve the aforementioned issues, Spring Cloud Contract Verifier with Stub Runner was -created. The main idea is to give you very fast feedback, without the need to set up the +To solve the aforementioned issues, Spring Cloud Contract was created. The main idea is to give you very fast feedback, without the need to set up the whole world of microservices. If you work on stubs, then the only applications you need are those that your application directly uses. image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/docs/src/main/asciidoc/images/Stubs2.png[Stubbed Services] -Spring Cloud Contract Verifier gives you the certainty that the stubs that you use were +Spring Cloud Contract gives you the certainty that the stubs that you use were created by the service that you're calling. Also, if you can use them, it means that they were tested against the producer's side. In short, you can trust those stubs. === Purposes -The main purposes of Spring Cloud Contract Verifier with Stub Runner are: +The main purposes of Spring Cloud Contract are: -- To ensure that WireMock/Messaging stubs (used when developing the client) do exactly +- To ensure that Http / Messaging stubs (used when developing the client) do exactly what the actual server-side implementation does. -- To promote ATDD method and Microservices architectural style. +- To promote ATDD (acceptance test driven developement) method and Microservices architectural style. - To provide a way to publish changes in contracts that are immediately visible on both sides. - To generate boilerplate test code to be used on the server side. -IMPORTANT: Spring Cloud Contract Verifier's purpose is NOT to start writing business +By default Spring Cloud Contract integrates with http://wiremock.org[Wiremock] as the HTTP server stub. + +IMPORTANT: Spring Cloud Contract's purpose is NOT to start writing business features in the contracts. Assume that we have a business use case of fraud check. If a user can be a fraud for 100 different reasons, we would assume that you would create 2 contracts, one for the positive case and one for the negative case. Contract tests are @@ -129,7 +133,7 @@ used to test contracts between applications and not to simulate full behavior. === How It Works -This section explores how Spring Cloud Contract Verifier with Stub Runner works. +This section explores how Spring Cloud Contract. [[spring-cloud-contract-verifier-intro-three-second-tour]] ==== A Three-second Tour @@ -142,10 +146,28 @@ This very brief tour walks through using Spring Cloud Contract: You can find a somewhat longer tour <>. +[plantuml, three-second, png] +---- +"API Producer"->"API Producer": add Spring Cloud \nContract (SCC) plugin +"API Producer"->"API Producer": add SCC Verifier dependency +"API Producer"->"API Producer": define contracts +"API Producer"->"Build": run build +"Build"->"SCC Plugin": generate \ntests, stubs and stubs \nartifact (e.g. stubs-jar) +"Build"->"Nexus / Artifactory": upload contracts \nand stubs and the project arifact +"Build"->"API Producer": Build successful +"API Consumer"->"API Consumer": add SCC Stub Runner \ndependency +"API Consumer"->"API Consumer": write a SCC Stub Runner \nbased contract test +"SCC Stub Runner"->"Nexus / Artifactory": test asks for [API Producer] stubs +"Nexus / Artifactory"->"SCC Stub Runner": fetch the [API Producer] stubs +"SCC Stub Runner"->"SCC Stub Runner": run in memory\n HTTP server stubs +"API Consumer"->"SCC Stub Runner": send a request \nto the HTTP server stub +"SCC Stub Runner"->"API Consumer": communication is correct +---- + [[spring-cloud-contract-verifier-intro-three-second-tour-producer]] ===== On the Producer Side -To start working with Spring Cloud Contract, add files with `REST/` messaging contracts +To start working with Spring Cloud Contract, add files with `REST`/messaging contracts expressed in either Groovy DSL or YAML to the contracts directory, which is set by the `contractsDslDir` property. By default, it is `$rootDir/src/test/resources/contracts`. @@ -154,7 +176,7 @@ shown in the following example: [source,xml,indent=0] ---- -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] ---- The following listing shows how to add the plugin, which should go in the build/plugins @@ -199,7 +221,7 @@ following example: [source,xml,indent=0] ---- -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] ---- You can get the Producer-side stubs installed in your Maven repository in either of two @@ -221,9 +243,7 @@ Stub Runner` properties, as shown in the following example: + [source,yaml,indent=0] ---- -stubrunner: - ids: 'com.example:http-server-dsl:+:stubs:8080' - repositoryRoot: https://repo.spring.io/libs-snapshot +Unresolved directive in _verifier_how_it_works.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ---- Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, @@ -265,9 +285,11 @@ expressed in either Groovy DSL or YAML to the contracts directory, which is set For the HTTP stubs, a contract defines what kind of response should be returned for a given request (taking into account the HTTP methods, URLs, headers, status codes, and so -on). The following example shows how an HTTP stub contract in Groovy DSL: +on). The following example shows how an HTTP stub contract: -[source,groovy,indent=0] +==== +[source,groovy,indent=0,role="primary"] +.groovy ---- package contracts @@ -296,9 +318,8 @@ org.springframework.cloud.contract.spec.Contract.make { } ---- -The same contract expressed in YAML would look like the following example: - -[source,yaml,indent=0] +[source,yaml,indent=0,role="secondary"] +.yaml ---- request: method: PUT @@ -321,6 +342,7 @@ response: headers: Content-Type: application/json;charset=UTF-8 ---- +==== In the case of messaging, you can define: @@ -329,26 +351,29 @@ was sent, the message body, and the header). * The methods that should be called after the message is received. * The methods that, when called, should trigger a message. -The following example shows a Camel messaging contract expressed in Groovy DSL: +The following example shows a Camel messaging contract: -[source,groovy] +==== +[source,groovy,indent=0,role="primary"] +.groovy ---- -Unresolved directive in verifier_introduction.adoc - include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_no_output_dsl] +Unresolved directive in _verifier_how_it_works.adoc - include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_no_output_dsl] ---- -The following example shows the same contract expressed in YAML: +[source,yaml,indent=0,role="secondary"] +.yaml +---- +Unresolved directive in _verifier_how_it_works.adoc - include::{verifier_core_path}/src/test/resources/yml/contract_message_scenario3.yml[indent=0] +---- +==== -[source,yml,indent=0] ----- -Unresolved directive in verifier_introduction.adoc - include::{verifier_core_path}/src/test/resources/yml/contract_message_scenario3.yml[indent=0] ----- Then you can add Spring Cloud Contract Verifier dependency and plugin to your build file, as shown in the following example: [source,xml,indent=0] ---- -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] ---- The following listing shows how to add the plugin, which should go in the build/plugins @@ -404,7 +429,7 @@ In order to use `WebTestClient` set `testMode` to `WEBTESTCLIENT`. Here is an example of a test generated in `WEBTESTCLIENT` test mode: - [source,java,indent=0] +[source,java,indent=0] ---- @Test public void validate_shouldRejectABeerIfTooYoung() throws Exception { @@ -434,7 +459,7 @@ order number followed by an underscore at the beginning of the contract file nam The following example shows an auto-generated test in Spock for a messaging stub contract: - [source,groovy,indent=0] +[source,groovy,indent=0] ---- given: ContractVerifierMessage inputMessage = contractVerifierMessaging.create( @@ -503,7 +528,7 @@ To get started, add the dependency to `Spring Cloud Contract Stub Runner`: [source,xml,indent=0] ---- -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] ---- You can get the Producer-side stubs installed in your Maven repository in either of two @@ -525,9 +550,7 @@ Runner` properties, as shown in the following example: + [source,yaml,indent=0] ---- -stubrunner: - ids: 'com.example:http-server-dsl:+:stubs:8080' - repositoryRoot: https://repo.spring.io/libs-snapshot +Unresolved directive in _verifier_how_it_works.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ---- Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, @@ -570,17 +593,19 @@ Assume that you want to send a request containing the ID of a client company and amount it wants to borrow from us. You also want to send it to the /fraudcheck url via the PUT method. -.Groovy DSL -[source,groovy,indent=0] +==== +[source,groovy,indent=0,role="primary"] +.groovy ---- -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[] ---- -.YAML -[source,yml,indent=0] +[source,yaml,indent=0,role="secondary"] +.yaml ---- -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/yml/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.yml[] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/yml/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.yml[] ---- +==== ==== Client Side @@ -592,14 +617,14 @@ At some point in time, you need to send a request to the Fraud Detection service [source,groovy,indent=0] ---- -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/src/main/java/com/example/loan/LoanApplicationService.java[tags=client_call_server,indent=0] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/src/main/java/com/example/loan/LoanApplicationService.java[tags=client_call_server,indent=0] ---- Annotate your test class with `@AutoConfigureStubRunner`. In the annotation provide the group id and artifact id for the Stub Runner to download stubs of your collaborators. [source,groovy,indent=0] ---- -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=autoconfigure_stubrunner,indent=0] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=autoconfigure_stubrunner,indent=0] ---- After that, during the tests, Spring Cloud Contract automatically finds the stubs @@ -671,13 +696,13 @@ following section to your build: [source,xml,indent=0,subs="verbatim,attributes",role="primary"] .Maven ---- -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=repos,indent=0] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=repos,indent=0] ---- [source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] .Gradle ---- -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/build.gradle[tags=deps_repos,indent=0] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/build.gradle[tags=deps_repos,indent=0] ---- ==== Consumer side (Loan Issuance) @@ -701,7 +726,7 @@ As a developer of the Loan Issuance service (a consumer of the Fraud Detection s [source,groovy,indent=0] ---- -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=client_tdd,indent=0] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=client_tdd,indent=0] ---- Assume that you have written a test of your new feature. If a loan application for a big @@ -715,7 +740,7 @@ client wants to borrow. You want to send it to the `/fraudcheck` url via the `PU [source,groovy,indent=0] ---- -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/src/main/java/com/example/loan/LoanApplicationService.java[tags=client_call_server,indent=0] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/src/main/java/com/example/loan/LoanApplicationService.java[tags=client_call_server,indent=0] ---- For simplicity, the port of the Fraud Detection service is set to `8080`, and the @@ -742,17 +767,19 @@ your expectations. To do so, write the following contract: IMPORTANT: Place the contract under `src/test/resources/contracts/fraud` folder. The `fraud` folder is important because the producer's test base class name references that folder. -.Groovy DSL -[source,groovy,indent=0] +==== +[source,groovy,indent=0,role="primary"] +.groovy ---- -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[] ---- -.YAML -[source,yml,indent=0] +[source,yaml,indent=0,role="secondary"] +.yaml ---- -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/yml/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.yml[] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/yml/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.yml[] ---- +==== The YML contract is quite straight-forward. However when you take a look at the Contract written using a statically typed Groovy DSL - you might wonder what the @@ -790,14 +817,14 @@ First, add the `Spring Cloud Contract` BOM. [source,xml,indent=0] ---- -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_bom,indent=0] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_bom,indent=0] ---- Next, add the `Spring Cloud Contract Verifier` Maven plugin [source,xml,indent=0] ---- -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0] ---- Since the plugin was added, you get the `Spring Cloud Contract Verifier` features which, @@ -853,14 +880,14 @@ Add the `Spring Cloud Contract` BOM: [source,xml,indent=0] ---- -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=contract_bom,indent=0] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=contract_bom,indent=0] ---- Add the dependency to `Spring Cloud Contract Stub Runner`: [source,xml,indent=0] ---- -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] ---- Annotate your test class with `@AutoConfigureStubRunner`. In the annotation, provide the @@ -870,7 +897,7 @@ can also provide the offline work switch (`StubRunnerProperties.StubsMode.LOCAL` [source,groovy,indent=0] ---- -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=autoconfigure_stubrunner,indent=0] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=autoconfigure_stubrunner,indent=0] ---- Now, when you run your tests, you see something like this: @@ -909,8 +936,8 @@ As a reminder, you can see the initial implementation here: [source,java,indent=0] ---- -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=server_api,indent=0] -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=initial_impl,indent=0] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=server_api,indent=0] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=initial_impl,indent=0] } ---- @@ -926,14 +953,14 @@ You must add the dependencies needed by the autogenerated tests: [source,xml,indent=0] ---- -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] ---- In the configuration of the Maven plugin, pass the `packageWithBaseClasses` property [source,xml,indent=0] ---- -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0] ---- IMPORTANT: This example uses "convention based" naming by setting the @@ -949,7 +976,7 @@ start the server side `FraudDetectionController`. [source,java,indent=0] ---- -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/src/test/java/com/example/fraud/FraudBase.java[] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/src/test/java/com/example/fraud/FraudBase.java[] ---- Now, if you run the `./mvnw clean install`, you get something like this: @@ -1006,9 +1033,9 @@ implementation: [source,java,indent=0] ---- -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=server_api,indent=0] -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=new_impl,indent=0] -Unresolved directive in verifier_introduction.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=initial_impl,indent=0] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=server_api,indent=0] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=new_impl,indent=0] +Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=initial_impl,indent=0] } ---- @@ -1052,9 +1079,7 @@ achieving the same thing by changing the properties. [source,yaml,indent=0] ---- -stubrunner: - ids: 'com.example:http-server-dsl:+:stubs:8080' - repositoryRoot: https://repo.spring.io/libs-snapshot +Unresolved directive in _verifier_how_it_works.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ---- That's it! @@ -1124,8 +1149,8 @@ your test. The following code shows an example: [source,java,indent=0] ---- -Unresolved directive in spring-cloud-wiremock.adoc - include::{doc_samples}/src/test/java/com/example/WiremockForDocsTests.java[tags=wiremock_test1] -Unresolved directive in spring-cloud-wiremock.adoc - include::{doc_samples}/src/test/java/com/example/WiremockForDocsTests.java[tags=wiremock_test2] +Unresolved directive in _spring-cloud-wiremock.adoc - include::{doc_samples}/src/test/java/com/example/WiremockForDocsTests.java[tags=wiremock_test1] +Unresolved directive in _spring-cloud-wiremock.adoc - include::{doc_samples}/src/test/java/com/example/WiremockForDocsTests.java[tags=wiremock_test2] ---- To start the stub server on a different port use (for example), @@ -1169,7 +1194,7 @@ stubs are stored under `/META-INF/group-id/artifact-id/versions/mappings/` folde [source,java,indent=0] ---- -Unresolved directive in spring-cloud-wiremock.adoc - include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockFilesApplicationWithUrlResourceTests.java[tags=load_all_stubs] +Unresolved directive in _spring-cloud-wiremock.adoc - include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockFilesApplicationWithUrlResourceTests.java[tags=load_all_stubs] ---- === Using Files to Specify the Stub Bodies @@ -1197,8 +1222,8 @@ instance, as shown in the following example: [source,java,indent=0] ---- -Unresolved directive in spring-cloud-wiremock.adoc - include::{doc_samples}/src/test/java/com/example/WiremockForDocsClassRuleTests.java[tags=wiremock_test1] -Unresolved directive in spring-cloud-wiremock.adoc - include::{doc_samples}/src/test/java/com/example/WiremockForDocsClassRuleTests.java[tags=wiremock_test2] +Unresolved directive in _spring-cloud-wiremock.adoc - include::{doc_samples}/src/test/java/com/example/WiremockForDocsClassRuleTests.java[tags=wiremock_test1] +Unresolved directive in _spring-cloud-wiremock.adoc - include::{doc_samples}/src/test/java/com/example/WiremockForDocsClassRuleTests.java[tags=wiremock_test2] ---- The `@ClassRule` means that the server shuts down after all the methods in this class @@ -1260,7 +1285,7 @@ a Spring `MockRestServiceServer`. The following code shows an example: [source,java,indent=0] ---- -Unresolved directive in spring-cloud-wiremock.adoc - include::{doc_samples}/src/test/java/com/example/WiremockForDocsMockServerApplicationTests.java[tags=wiremock_test] +Unresolved directive in _spring-cloud-wiremock.adoc - include::{doc_samples}/src/test/java/com/example/WiremockForDocsMockServerApplicationTests.java[tags=wiremock_test] ---- The `baseUrl` value is prepended to all mock calls, and the `stubs()` method takes a stub @@ -1285,9 +1310,9 @@ Example: [source,java,indent=0] ---- -Unresolved directive in spring-cloud-wiremock.adoc - include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockConfigurationCustomizerTests.java[tags=customizer_1] +Unresolved directive in _spring-cloud-wiremock.adoc - include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockConfigurationCustomizerTests.java[tags=customizer_1] // perform your customization here -Unresolved directive in spring-cloud-wiremock.adoc - include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockConfigurationCustomizerTests.java[tags=customizer_2] +Unresolved directive in _spring-cloud-wiremock.adoc - include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockConfigurationCustomizerTests.java[tags=customizer_2] ---- === Generating Stubs using REST Docs @@ -1297,7 +1322,30 @@ documentation (for example in Asciidoctor format) for an HTTP API with Spring Mo or `WebTestClient` or Rest Assured. At the same time that you generate documentation for your API, you can also generate WireMock stubs by using Spring Cloud Contract WireMock. To do so, write your normal REST Docs test cases and use `@AutoConfigureRestDocs` to have stubs be -automatically generated in the REST Docs output directory. The following code shows an +automatically generated in the REST Docs output directory. + +[plantuml, rest-docs, png] +---- +"API Producer"->"API Producer": add Spring Cloud Contract (SCC) \nStub Runner dependency +"API Producer"->"API Producer": setup stub jar assembly +"API Producer"->"API Producer": write and setup REST Docs tests +"API Producer"->"Build": run build +"Build"->"REST Docs": generate API \ndocumentation +"REST Docs"->"SCC": generate stubs from the \nREST Docs tests +"REST Docs"->"SCC": generate contracts from the \nREST Docs tests +"Build"->"Build": assemble stubs jar with \nstubs and contracts +"Build"->"Nexus / Artifactory": upload contracts \nand stubs and the project arifact +"Build"->"API Producer": Build successful +"API Consumer"->"API Consumer": add SCC Stub Runner \ndependency +"API Consumer"->"API Consumer": write a SCC Stub Runner \nbased contract test +"SCC Stub Runner"->"Nexus / Artifactory": test asks for [API Producer] stubs +"Nexus / Artifactory"->"SCC Stub Runner": fetch the [API Producer] stubs +"SCC Stub Runner"->"SCC Stub Runner": run in memory\n HTTP server stubs +"API Consumer"->"SCC Stub Runner": send a request \nto the HTTP server stub +"SCC Stub Runner"->"API Consumer": communication is correct +---- + +The following code shows an example using `MockMvc`: [source,java,indent=0] @@ -1461,7 +1509,7 @@ Consider the following test: [source,java] ---- -Unresolved directive in spring-cloud-wiremock.adoc - include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/restdocs/ContractDslSnippetTests.java[tags=contract_snippet] +Unresolved directive in _spring-cloud-wiremock.adoc - include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/restdocs/ContractDslSnippetTests.java[tags=contract_snippet] ---- The preceding test creates the stub presented in the previous section, generating both @@ -1511,185 +1559,7 @@ You can read more about Spring Cloud Contract Verifier by reading the == Contributing -:spring-cloud-build-branch: master - -Spring Cloud is released under the non-restrictive Apache 2.0 license, -and follows a very standard Github development process, using Github -tracker for issues and merging pull requests into master. If you want -to contribute even something trivial please do not hesitate, but -follow the guidelines below. - -=== Sign the Contributor License Agreement -Before we accept a non-trivial patch or pull request we will need you to sign the -https://cla.pivotal.io/sign/spring[Contributor License Agreement]. -Signing the contributor's agreement does not grant anyone commit rights to the main -repository, but it does mean that we can accept your contributions, and you will get an -author credit if we do. Active contributors might be asked to join the core team, and -given the ability to merge pull requests. - -=== Code of Conduct -This project adheres to the Contributor Covenant https://github.com/spring-cloud/spring-cloud-build/blob/master/docs/src/main/asciidoc/code-of-conduct.adoc[code of -conduct]. By participating, you are expected to uphold this code. Please report -unacceptable behavior to spring-code-of-conduct@pivotal.io. - -=== Code Conventions and Housekeeping -None of these is essential for a pull request, but they will all help. They can also be -added after the original pull request but before a merge. - -* Use the Spring Framework code format conventions. If you use Eclipse - you can import formatter settings using the - `eclipse-code-formatter.xml` file from the - https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-dependencies-parent/eclipse-code-formatter.xml[Spring - Cloud Build] project. If using IntelliJ, you can use the - https://plugins.jetbrains.com/plugin/6546[Eclipse Code Formatter - Plugin] to import the same file. -* Make sure all new `.java` files to have a simple Javadoc class comment with at least an - `@author` tag identifying you, and preferably at least a paragraph on what the class is - for. -* Add the ASF license header comment to all new `.java` files (copy from existing files - in the project) -* Add yourself as an `@author` to the .java files that you modify substantially (more - than cosmetic changes). -* Add some Javadocs and, if you change the namespace, some XSD doc elements. -* A few unit tests would help a lot as well -- someone has to do it. -* If no-one else is using your branch, please rebase it against the current master (or - other target branch in the main project). -* When writing a commit message please follow https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html[these conventions], - if you are fixing an existing issue please add `Fixes gh-XXXX` at the end of the commit - message (where XXXX is the issue number). - -=== Checkstyle - -Spring Cloud Build comes with a set of checkstyle rules. You can find them in the `spring-cloud-build-tools` module. The most notable files under the module are: - -.spring-cloud-build-tools/ ----- -└── src -    ├── checkstyle -    │   └── checkstyle-suppressions.xml <3> -    └── main -    └── resources -    ├── checkstyle-header.txt <2> -    └── checkstyle.xml <1> ----- -<1> Default Checkstyle rules -<2> File header setup -<3> Default suppression rules - -==== Checkstyle configuration - -Checkstyle rules are *disabled by default*. To add checkstyle to your project just define the following properties and plugins. - -.pom.xml ----- - -true <1> - true - <2> - true - <3> - - - - - <4> - io.spring.javaformat - spring-javaformat-maven-plugin - - <5> - org.apache.maven.plugins - maven-checkstyle-plugin - - - - - - <5> - org.apache.maven.plugins - maven-checkstyle-plugin - - - - ----- -<1> Fails the build upon Checkstyle errors -<2> Fails the build upon Checkstyle violations -<3> Checkstyle analyzes also the test sources -<4> Add the Spring Java Format plugin that will reformat your code to pass most of the Checkstyle formatting rules -<5> Add checkstyle plugin to your build and reporting phases - -If you need to suppress some rules (e.g. line length needs to be longer), then it's enough for you to define a file under `${project.root}/src/checkstyle/checkstyle-suppressions.xml` with your suppressions. Example: - -.projectRoot/src/checkstyle/checkstyle-suppresions.xml ----- - - - - - - ----- - -It's advisable to copy the `${spring-cloud-build.rootFolder}/.editorconfig` and `${spring-cloud-build.rootFolder}/.springformat` to your project. That way, some default formatting rules will be applied. You can do so by running this script: - -```bash -$ curl https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/.editorconfig -o .editorconfig -$ touch .springformat -``` - -=== IDE setup - -==== Intellij IDEA - -In order to setup Intellij you should import our coding conventions, inspection profiles and set up the checkstyle plugin. -The following files can be found in the https://github.com/spring-cloud/spring-cloud-build/tree/master/spring-cloud-build-tools[Spring Cloud Build] project. - -.spring-cloud-build-tools/ ----- -└── src -    ├── checkstyle -    │   └── checkstyle-suppressions.xml <3> -    └── main -    └── resources -    ├── checkstyle-header.txt <2> -    ├── checkstyle.xml <1> -    └── intellij -       ├── Intellij_Project_Defaults.xml <4> -       └── Intellij_Spring_Boot_Java_Conventions.xml <5> ----- -<1> Default Checkstyle rules -<2> File header setup -<3> Default suppression rules -<4> Project defaults for Intellij that apply most of Checkstyle rules -<5> Project style conventions for Intellij that apply most of Checkstyle rules - -.Code style - -image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-code-style.png[Code style] - -Go to `File` -> `Settings` -> `Editor` -> `Code style`. There click on the icon next to the `Scheme` section. There, click on the `Import Scheme` value and pick the `Intellij IDEA code style XML` option. Import the `spring-cloud-build-tools/src/main/resources/intellij/Intellij_Spring_Boot_Java_Conventions.xml` file. - -.Inspection profiles - -image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-inspections.png[Code style] - -Go to `File` -> `Settings` -> `Editor` -> `Inspections`. There click on the icon next to the `Profile` section. There, click on the `Import Profile` and import the `spring-cloud-build-tools/src/main/resources/intellij/Intellij_Project_Defaults.xml` file. - -.Checkstyle - -To have Intellij work with Checkstyle, you have to install the `Checkstyle` plugin. It's advisable to also install the `Assertions2Assertj` to automatically convert the JUnit assertions - -image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-checkstyle.png[Checkstyle] - -Go to `File` -> `Settings` -> `Other settings` -> `Checkstyle`. There click on the `+` icon in the `Configuration file` section. There, you'll have to define where the checkstyle rules should be picked from. In the image above, we've picked the rules from the cloned Spring Cloud Build repository. However, you can point to the Spring Cloud Build's GitHub repository (e.g. for the `checkstyle.xml` : `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle.xml`). We need to provide the following variables: - -- `checkstyle.header.file` - please point it to the Spring Cloud Build's, `spring-cloud-build-tools/src/main/resources/checkstyle/checkstyle-header.txt` file either in your cloned repo or via the `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle-header.txt` URL. -- `checkstyle.suppressions.file` - default suppressions. Please point it to the Spring Cloud Build's, `spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` file either in your cloned repo or via the `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` URL. -- `checkstyle.additional.suppressions.file` - this variable corresponds to suppressions in your local project. E.g. you're working on `spring-cloud-contract`. Then point to the `project-root/src/checkstyle/checkstyle-suppressions.xml` folder. Example for `spring-cloud-contract` would be: `/home/username/spring-cloud-contract/src/checkstyle/checkstyle-suppressions.xml`. - -IMPORTANT: Remember to set the `Scan Scope` to `All sources` since we apply checkstyle rules for production and test sources. +Unresolved directive in README.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/contributing.adoc[] == How to build it diff --git a/docs/src/main/asciidoc/README.adoc b/docs/src/main/asciidoc/README.adoc index cf91eb0f74..2c6fded0b4 100644 --- a/docs/src/main/asciidoc/README.adoc +++ b/docs/src/main/asciidoc/README.adoc @@ -2,8 +2,24 @@ image::https://badges.gitter.im/Join%20Chat.svg[Gitter, link="https://gitter.im/spring-cloud/spring-cloud-contract?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge"] image::https://codecov.io/gh/spring-cloud/spring-cloud-contract/branch/{branch}/graph/badge.svg["codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-contract"] image::https://circleci.com/gh/spring-cloud/spring-cloud-contract.svg?style=svg["CircleCI", link="https://circleci.com/gh/spring-cloud/spring-cloud-contract"] -:introduction_url: ../../../.. -:verifier_core_path: {introduction_url}/spring-cloud-contract-verifier +:branch: master +:core_path: ../../.. +:plugins_path: ../../../spring-cloud-contract-tools +:converters_path: {plugins_path}/spring-cloud-contract-converters +:verifier_root_path: {core_path}/spring-cloud-contract-verifier +:contract_spec_path: {core_path}/specs/spring-cloud-contract-spec-java +:contract_spec_tests_path: {core_path}/specs/spring-cloud-contract-spec +:samples_path: {core_path}/samples +:verifier_core_path: {verifier_root_path} +:stubrunner_core_path: {core_path}/spring-cloud-contract-stub-runner +:standalone_samples_path: {samples_path}/standalone/dsl +:standalone_messaging_samples_path: {samples_path}/standalone/messaging +:standalone_pact_path: {samples_path}/standalone/pact +:standalone_restdocs_path: {samples_path}/standalone/restdocs +:tests_path: {core_path}/tests +:samples_branch: 2.2.x +:samples_url: https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/{samples_branch} +:introduction_url: ${core_path}/../../ == Spring Cloud Contract @@ -21,13 +37,13 @@ https://cloud-samples.spring.io/spring-cloud-contract-samples/workshops.html[thi === Spring Cloud Contract Verifier -include::verifier_introduction.adoc[] +include::_verifier_introduction.adoc[] -include::links.adoc[] +include::_links.adoc[] === Spring Cloud Contract WireMock -include::spring-cloud-wiremock.adoc[] +include::_spring-cloud-wiremock.adoc[] == Documentation @@ -38,4 +54,4 @@ You can read more about Spring Cloud Contract Verifier by reading the include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/contributing.adoc[] -include::building.adoc[] +include::_building.adoc[] diff --git a/docs/src/main/asciidoc/building.adoc b/docs/src/main/asciidoc/_building.adoc similarity index 100% rename from docs/src/main/asciidoc/building.adoc rename to docs/src/main/asciidoc/_building.adoc diff --git a/docs/src/main/asciidoc/_contract_flows.adoc b/docs/src/main/asciidoc/_contract_flows.adoc new file mode 100644 index 0000000000..72ec8a01e5 --- /dev/null +++ b/docs/src/main/asciidoc/_contract_flows.adoc @@ -0,0 +1,8 @@ +- Provider contract testing with Maven / Gradle, stubs in artifactory +- Provider contract testing with Maven / Gradle, stubs in git +- Consumer Driven Contracts with contracts on the producer side +- Consumer Driven Contracts with contracts in external repo +- Consumer Driven Contracts with contracts and stubs in git +- Provider contract testing with Maven / Gradle, stubs in artifactory in non Spring world +- Provider contract testing with Maven / Gradle, stubs in artifactory in non JVM world +- Provider contract testing with REST Docs and with Maven / Gradle stubs in Artifactory \ No newline at end of file diff --git a/docs/src/main/asciidoc/links.adoc b/docs/src/main/asciidoc/_links.adoc similarity index 100% rename from docs/src/main/asciidoc/links.adoc rename to docs/src/main/asciidoc/_links.adoc diff --git a/docs/src/main/asciidoc/spring-cloud-contract-verifier.adoc b/docs/src/main/asciidoc/_spring-cloud-contract-verifier.adoc similarity index 76% rename from docs/src/main/asciidoc/spring-cloud-contract-verifier.adoc rename to docs/src/main/asciidoc/_spring-cloud-contract-verifier.adoc index 1dd900ca53..d8d9b6f29f 100644 --- a/docs/src/main/asciidoc/spring-cloud-contract-verifier.adoc +++ b/docs/src/main/asciidoc/_spring-cloud-contract-verifier.adoc @@ -1,3 +1,4 @@ +:branch: master :core_path: ../../.. :plugins_path: ../../../spring-cloud-contract-tools :converters_path: {plugins_path}/spring-cloud-contract-converters @@ -12,20 +13,20 @@ :standalone_pact_path: {samples_path}/standalone/pact :standalone_restdocs_path: {samples_path}/standalone/restdocs :tests_path: {core_path}/tests -:samples_branch: 2.1.x +:samples_branch: 2.2.x :samples_url: https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/{samples_branch} :introduction_url: ${core_path}/../../ -include::verifier_introduction.adoc[] +include::_verifier_introduction.adoc[] -include::verifier_faq.adoc[] +include::_verifier_faq.adoc[] -include::verifier_setup.adoc[] +include::_verifier_setup.adoc[] -include::verifier_messaging.adoc[] +include::_verifier_messaging.adoc[] -include::verifier_stubrunner.adoc[] +include::_verifier_stubrunner.adoc[] -include::verifier_stubrunner_msg.adoc[] +include::_verifier_stubrunner_msg.adoc[] -include::verifier_contract.adoc[] \ No newline at end of file +include::_verifier_contract.adoc[] \ No newline at end of file diff --git a/docs/src/main/asciidoc/spring-cloud-wiremock.adoc b/docs/src/main/asciidoc/_spring-cloud-wiremock.adoc similarity index 92% rename from docs/src/main/asciidoc/spring-cloud-wiremock.adoc rename to docs/src/main/asciidoc/_spring-cloud-wiremock.adoc index 9ad7e9b200..e4203362c6 100644 --- a/docs/src/main/asciidoc/spring-cloud-wiremock.adoc +++ b/docs/src/main/asciidoc/_spring-cloud-wiremock.adoc @@ -191,7 +191,30 @@ documentation (for example in Asciidoctor format) for an HTTP API with Spring Mo or `WebTestClient` or Rest Assured. At the same time that you generate documentation for your API, you can also generate WireMock stubs by using Spring Cloud Contract WireMock. To do so, write your normal REST Docs test cases and use `@AutoConfigureRestDocs` to have stubs be -automatically generated in the REST Docs output directory. The following code shows an +automatically generated in the REST Docs output directory. + +[plantuml, rest-docs, png] +---- +"API Producer"->"API Producer": add Spring Cloud Contract (SCC) \nStub Runner dependency +"API Producer"->"API Producer": setup stub jar assembly +"API Producer"->"API Producer": write and setup REST Docs tests +"API Producer"->"Build": run build +"Build"->"REST Docs": generate API \ndocumentation +"REST Docs"->"SCC": generate stubs from the \nREST Docs tests +"REST Docs"->"SCC": generate contracts from the \nREST Docs tests +"Build"->"Build": assemble stubs jar with \nstubs and contracts +"Build"->"Nexus / Artifactory": upload contracts \nand stubs and the project arifact +"Build"->"API Producer": Build successful +"API Consumer"->"API Consumer": add SCC Stub Runner \ndependency +"API Consumer"->"API Consumer": write a SCC Stub Runner \nbased contract test +"SCC Stub Runner"->"Nexus / Artifactory": test asks for [API Producer] stubs +"Nexus / Artifactory"->"SCC Stub Runner": fetch the [API Producer] stubs +"SCC Stub Runner"->"SCC Stub Runner": run in memory\n HTTP server stubs +"API Consumer"->"SCC Stub Runner": send a request \nto the HTTP server stub +"SCC Stub Runner"->"API Consumer": communication is correct +---- + +The following code shows an example using `MockMvc`: [source,java,indent=0] diff --git a/docs/src/main/asciidoc/verifier_contract.adoc b/docs/src/main/asciidoc/_verifier_contract.adoc similarity index 98% rename from docs/src/main/asciidoc/verifier_contract.adoc rename to docs/src/main/asciidoc/_verifier_contract.adoc index ee2eaa7fb2..2ca22db220 100644 --- a/docs/src/main/asciidoc/verifier_contract.adoc +++ b/docs/src/main/asciidoc/_verifier_contract.adoc @@ -64,17 +64,19 @@ The following sections describe the most common top-level elements: You can add a `description` to your contract. The description is arbitrary text. The following code shows an example: -.Groovy DSL -[source,groovy,indent=0] +==== +[source,groovy,indent=0,role="primary"] +.groovy ---- include::{contract_spec_tests_path}/src/test/groovy/org/springframework/cloud/contract/spec/internal/ContractSpec.groovy[tags=description,indent=0] ---- -.YAML -[source,yml,indent=0] +[source,yaml,indent=0,role="secondary"] +.yaml ---- include::{verifier_core_path}/src/test/resources/yml/contract_rest.yml[indent=0] ---- +==== [[contract-dsl-name]] ==== Name @@ -89,17 +91,19 @@ generated test not compile. Also, remember that, if you provide the same name fo multiple contracts, your autogenerated tests fail to compile and your generated stubs override each other. -.Groovy DSL -[source,groovy,indent=0] +==== +[source,groovy,indent=0,role="primary"] +.groovy ---- include::{contract_spec_tests_path}/src/test/groovy/org/springframework/cloud/contract/spec/internal/ContractSpec.groovy[tags=name,indent=0] ---- -.YAML -[source,yml,indent=0] +[source,yaml,indent=0,role="secondary"] +.yaml ---- include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=name,indent=0] ---- +==== [[contract-dsl-ignoring-contracts]] ==== Ignoring Contracts @@ -107,17 +111,19 @@ include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=name,inde If you want to ignore a contract, you can either set a value of ignored contracts in the plugin configuration or set the `ignored` property on the contract itself: -.Groovy DSL -[source,groovy,indent=0] +==== +[source,groovy,indent=0,role="primary"] +.groovy ---- include::{contract_spec_tests_path}/src/test/groovy/org/springframework/cloud/contract/spec/internal/ContractSpec.groovy[tags=ignored,indent=0] ---- -.YAML -[source,yml,indent=0] +[source,yaml,indent=0,role="secondary"] +.yaml ---- include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=ignored,indent=0] ---- +==== [[contract-dsl-passing-values-from-files]] ==== Passing Values from Files @@ -138,17 +144,19 @@ following resources in our project. Further assume that your contract is as follows: -.Groovy DSL -[source,groovy,indent=0] +==== +[source,groovy,indent=0,role="primary"] +.groovy ---- include::{verifier_core_path}/src/test/resources/classpath/readFromFile.groovy[indent=0] ---- -.YAML -[source,yml,indent=0] +[source,yaml,indent=0,role="secondary"] +.yaml ---- include::{verifier_core_path}/src/test/resources/yml/contract_from_file.yml[indent=0] ---- +==== Further assume that the JSON files is as follows: @@ -171,17 +179,19 @@ relative to the folder in which the contract lays. If you need to pass the contents of a file in a binary form it's enough for you to use the `fileAsBytes` method in Groovy DSL or `bodyFromFileAsBytes` field in YAML. -.Groovy DSL -[source,groovy,indent=0] +==== +[source,groovy,indent=0,role="primary"] +.groovy ---- include::{verifier_core_path}/src/test/resources/body_builder/worksWithPdf.groovy[indent=0] ---- -.YAML -[source,yml,indent=0] +[source,yaml,indent=0,role="secondary"] +.yaml ---- include::{verifier_core_path}/src/test/resources/yml/contract_pdf.yml[indent=0] ---- +==== IMPORTANT: You should use this approach whenever you want to work with binary payloads both for HTTP and messaging. @@ -216,32 +226,36 @@ value `5` has **higher** priority than `priority` with value `10`. The HTTP protocol requires only **method and url** to be specified in a request. The same information is mandatory in request definition of the Contract. -.Groovy DSL -[source,groovy,indent=0] +==== +[source,groovy,indent=0,role="primary"] +.groovy ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=request,indent=0] ---- -.YAML -[source,yml,indent=0] +[source,yaml,indent=0,role="secondary"] +.yaml ---- include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=request_obligatory,indent=0] ---- +==== It is possible to specify an absolute rather than relative `url`, but using `urlPath` is the recommended way, as doing so makes the tests **host-independent**. -.Groovy DSL -[source,groovy,indent=0] +==== +[source,groovy,indent=0,role="primary"] +.groovy ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=url,indent=0] ---- -.YAML -[source,yml,indent=0] +[source,yaml,indent=0,role="secondary"] +.yaml ---- include::{verifier_core_path}/src/test/resources/yml/contract_rest_with_path.yml[tags=url_path,indent=0] ---- +==== `request` may contain **query parameters**. @@ -310,17 +324,19 @@ include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=body,inde `request` may contain **multipart** elements. To include multipart elements, use the `multipart` method/section, as shown in the following examples -.Groovy DSL -[source,groovy,indent=0] +==== +[source,groovy,indent=0,role="primary"] +.groovy ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MethodBodyBuilderSpec.groovy[tags=multipartdsl,indent=0] ---- -.YAML -[source,yml,indent=0] +[source,yaml,indent=0,role="secondary"] +.yaml ---- include::{verifier_core_path}/src/test/resources/yml/contract_multipart.yml[indent=0] ---- +==== In the preceding example, we define parameters in either of two ways: @@ -657,17 +673,19 @@ matches the JSON Path. E.g. for json path `$.foo` - `{{{ jsonpath this '$.foo' } Consider the following contract: -.Groovy DSL -[source,groovy,indent=0] +==== +[source,groovy,indent=0,role="primary"] +.groovy ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MethodBodyBuilderSpec.groovy[tags=template_contract,indent=0] ---- -.YAML -[source,yml,indent=0] +[source,yaml,indent=0,role="secondary"] +.yaml ---- include::{verifier_core_path}/src/test/resources/yml/contract_reference_request.yml[indent=0] ---- +==== Running a JUnit test generation leads to a test that resembles the following example: @@ -911,17 +929,19 @@ You can also define which type the regular expression corresponds to via the `re Consider the following example: -.Groovy DSL -[source,groovy,indent=0] +==== +[source,groovy,indent=0,role="primary"] +.groovy ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MockMvcMethodBodyBuilderWithMatchersSpec.groovy[tags=matchers,indent=0] ---- -.YAML -[source,yml,indent=0] +[source,yaml,indent=0,role="secondary"] +.yaml ---- include::{verifier_core_path}/src/test/resources/yml/contract_matchers.yml[indent=0] ---- +==== In the preceding example, you can see the dynamic portions of the contract in the `matchers` sections. For the request part, you can see that, for all fields but @@ -1419,17 +1439,19 @@ in the generated test. You can define multiple contracts in one file. Such a contract might resemble the following example: -.Groovy DSL -[source,groovy,indent=0] +==== +[source,groovy,indent=0,role="primary"] +.groovy ---- include::{plugins_path}/spring-cloud-contract-maven-plugin/src/test/projects/multiple-contracts/src/test/resources/contracts/com/hello/v1/WithList.groovy[lines=18..-1,indent=0] ---- -.YAML -[source,yml,indent=0] +[source,yaml,indent=0,role="secondary"] +.yaml ---- include::{verifier_core_path}/src/test/resources/yml/multiple_contracts.yml[indent=0] ---- +==== In the preceding example, one contract has the `name` field and the other does not. This leads to generation of two tests that look more or less like this: @@ -1534,14 +1556,14 @@ include::{standalone_restdocs_path}/http-server/src/test/java/com/example/fraud/ TIP: You don't need to specify the output directory for the generated snippets since version 1.2.0.RELEASE of Spring REST Docs. -== Customization +=== DSL Customization IMPORTANT: This section is valid only for Groovy DSL You can customize the Spring Cloud Contract Verifier by extending the DSL, as shown in the remainder of this section. -=== Extending the DSL +==== Extending the 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 document, you can see examples of: @@ -1552,7 +1574,7 @@ maintain the static compatibility. Later in this document, you can see examples You can find the full example https://github.com/spring-cloud-samples/spring-cloud-contract-samples[here]. -==== Common JAR +===== Common JAR The following examples show three classes that can be reused in the DSLs. @@ -1577,14 +1599,14 @@ include::{samples_url}/common/src/main/java/com/example/ConsumerUtils.java[] include::{samples_url}/common/src/main/java/com/example/ProducerUtils.java[] ---- -==== Adding the Dependency to the Project +===== Adding the Dependency to the Project In order for the plugins and IDE to be able to reference the common JAR classes, you need to pass the dependency to your project. // TODO missing code block here - we should show an example adding a dependency -==== Test the Dependency in the Project's Dependencies +===== Test the Dependency in the Project's Dependencies 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 @@ -1602,7 +1624,7 @@ include::{samples_url}/producer/pom.xml[tags=test_dep,indent=0] include::{samples_url}/producer/build.gradle[tags=test_dep,indent=0] ---- -==== Test a Dependency in the Plugin's Dependencies +===== Test a Dependency in the Plugin's Dependencies Now, you must add the dependency for the plugin to reuse at runtime, as shown in the following example: @@ -1619,7 +1641,7 @@ include::{samples_url}/producer/pom.xml[tags=test_dep_in_plugin,indent=0] include::{samples_url}/producer/build.gradle[tags=test_dep_in_plugin,indent=0] ---- -==== Referencing classes in DSLs +===== Referencing classes in DSLs You can now reference your classes in your DSL, as shown in the following example: diff --git a/docs/src/main/asciidoc/verifier_faq.adoc b/docs/src/main/asciidoc/_verifier_faq.adoc similarity index 99% rename from docs/src/main/asciidoc/verifier_faq.adoc rename to docs/src/main/asciidoc/_verifier_faq.adoc index 2c17140c21..97ac27ecee 100644 --- a/docs/src/main/asciidoc/verifier_faq.adoc +++ b/docs/src/main/asciidoc/_verifier_faq.adoc @@ -1,5 +1,5 @@ :introduction_url: https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch} -:samples_branch: 2.1.x +:samples_branch: 2.2.x == Spring Cloud Contract FAQ diff --git a/docs/src/main/asciidoc/verifier_introduction.adoc b/docs/src/main/asciidoc/_verifier_how_it_works.adoc similarity index 85% rename from docs/src/main/asciidoc/verifier_introduction.adoc rename to docs/src/main/asciidoc/_verifier_how_it_works.adoc index f2342dd43f..eeff07d9c6 100644 --- a/docs/src/main/asciidoc/verifier_introduction.adoc +++ b/docs/src/main/asciidoc/_verifier_how_it_works.adoc @@ -1,106 +1,6 @@ -== Spring Cloud Contract Verifier Introduction - -Spring Cloud Contract Verifier enables Consumer Driven Contract (CDC) development of -JVM-based applications. It moves TDD to the level of software architecture. - -Spring Cloud Contract Verifier ships with _Contract Definition Language_ (CDL). Contract -definitions are used to produce the following resources: - -* JSON stub definitions to be used by WireMock when doing integration testing on the -client code (_client tests_). Test code must still be written by hand, and test data is -produced by Spring Cloud Contract Verifier. -* Messaging routes, if you're using a messaging service. We integrate with Spring -Integration, Spring Cloud Stream, Spring AMQP, and Apache Camel. You can also set your -own integrations. -* Acceptance tests (in JUnit 4, JUnit 5 or Spock) are used to verify if server-side implementation -of the API is compliant with the contract (__server tests__). A full test is generated by -Spring Cloud Contract Verifier. - -=== History - -Before becoming Spring Cloud Contract, this project was called https://github.com/Codearte/accurest[Accurest]. -It was created by https://twitter.com/mgrzejszczak[Marcin Grzejszczak] and https://twitter.com/jkubrynski[Jakub Kubrynski] -from (https://github.com/Codearte[Codearte]. - -The `0.1.0` release took place on 26 Jan 2015 and it became stable with `1.0.0` release on 29 Feb 2016. - -=== Why a Contract Verifier? - -Assume that we have a system consisting of multiple microservices: - -image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/docs/src/main/asciidoc/images/Deps.png[Microservices Architecture] - -==== Testing issues - -If we wanted to test the application in top left corner to determine whether it can -communicate with other services, we could do one of two things: - -- Deploy all microservices and perform end-to-end tests. -- Mock other microservices in unit/integration tests. - -Both have their advantages but also a lot of disadvantages. - -*Deploy all microservices and perform end to end tests* - -Advantages: - -- Simulates production. -- Tests real communication between services. - -Disadvantages: - -- To test one microservice, we have to deploy 6 microservices, a couple of databases, -etc. -- The environment where the tests run is locked for a single suite of tests (nobody else -would be able to run the tests in the meantime). -- They take a long time to run. -- The feedback comes very late in the process. -- They are extremely hard to debug. - -*Mock other microservices in unit/integration tests* - -Advantages: - -- They provide very fast feedback. -- They have no infrastructure requirements. - -Disadvantages: - -- The implementor of the service creates stubs that might have nothing to do with -reality. -- You can go to production with passing tests and failing production. - -To solve the aforementioned issues, Spring Cloud Contract Verifier with Stub Runner was -created. The main idea is to give you very fast feedback, without the need to set up the -whole world of microservices. If you work on stubs, then the only applications you need -are those that your application directly uses. - -image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/docs/src/main/asciidoc/images/Stubs2.png[Stubbed Services] - -Spring Cloud Contract Verifier gives you the certainty that the stubs that you use were -created by the service that you're calling. Also, if you can use them, it means that they -were tested against the producer's side. In short, you can trust those stubs. - -=== Purposes - -The main purposes of Spring Cloud Contract Verifier with Stub Runner are: - -- To ensure that WireMock/Messaging stubs (used when developing the client) do exactly -what the actual server-side implementation does. -- To promote ATDD method and Microservices architectural style. -- To provide a way to publish changes in contracts that are immediately visible on both -sides. -- To generate boilerplate test code to be used on the server side. - -IMPORTANT: Spring Cloud Contract Verifier's purpose is NOT to start writing business -features in the contracts. Assume that we have a business use case of fraud check. If a -user can be a fraud for 100 different reasons, we would assume that you would create 2 -contracts, one for the positive case and one for the negative case. Contract tests are -used to test contracts between applications and not to simulate full behavior. - === How It Works -This section explores how Spring Cloud Contract Verifier with Stub Runner works. +This section explores how Spring Cloud Contract. [[spring-cloud-contract-verifier-intro-three-second-tour]] ==== A Three-second Tour @@ -113,10 +13,28 @@ This very brief tour walks through using Spring Cloud Contract: You can find a somewhat longer tour <>. +[plantuml, three-second, png] +---- +"API Producer"->"API Producer": add Spring Cloud \nContract (SCC) plugin +"API Producer"->"API Producer": add SCC Verifier dependency +"API Producer"->"API Producer": define contracts +"API Producer"->"Build": run build +"Build"->"SCC Plugin": generate \ntests, stubs and stubs \nartifact (e.g. stubs-jar) +"Build"->"Nexus / Artifactory": upload contracts \nand stubs and the project arifact +"Build"->"API Producer": Build successful +"API Consumer"->"API Consumer": add SCC Stub Runner \ndependency +"API Consumer"->"API Consumer": write a SCC Stub Runner \nbased contract test +"SCC Stub Runner"->"Nexus / Artifactory": test asks for [API Producer] stubs +"Nexus / Artifactory"->"SCC Stub Runner": fetch the [API Producer] stubs +"SCC Stub Runner"->"SCC Stub Runner": run in memory\n HTTP server stubs +"API Consumer"->"SCC Stub Runner": send a request \nto the HTTP server stub +"SCC Stub Runner"->"API Consumer": communication is correct +---- + [[spring-cloud-contract-verifier-intro-three-second-tour-producer]] ===== On the Producer Side -To start working with Spring Cloud Contract, add files with `REST/` messaging contracts +To start working with Spring Cloud Contract, add files with `REST`/messaging contracts expressed in either Groovy DSL or YAML to the contracts directory, which is set by the `contractsDslDir` property. By default, it is `$rootDir/src/test/resources/contracts`. @@ -234,9 +152,11 @@ expressed in either Groovy DSL or YAML to the contracts directory, which is set For the HTTP stubs, a contract defines what kind of response should be returned for a given request (taking into account the HTTP methods, URLs, headers, status codes, and so -on). The following example shows how an HTTP stub contract in Groovy DSL: +on). The following example shows how an HTTP stub contract: -[source,groovy,indent=0] +==== +[source,groovy,indent=0,role="primary"] +.groovy ---- package contracts @@ -265,9 +185,8 @@ org.springframework.cloud.contract.spec.Contract.make { } ---- -The same contract expressed in YAML would look like the following example: - -[source,yaml,indent=0] +[source,yaml,indent=0,role="secondary"] +.yaml ---- request: method: PUT @@ -290,6 +209,7 @@ response: headers: Content-Type: application/json;charset=UTF-8 ---- +==== In the case of messaging, you can define: @@ -298,19 +218,22 @@ was sent, the message body, and the header). * The methods that should be called after the message is received. * The methods that, when called, should trigger a message. -The following example shows a Camel messaging contract expressed in Groovy DSL: +The following example shows a Camel messaging contract: -[source,groovy] +==== +[source,groovy,indent=0,role="primary"] +.groovy ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_no_output_dsl] ---- -The following example shows the same contract expressed in YAML: - -[source,yml,indent=0] +[source,yaml,indent=0,role="secondary"] +.yaml ---- include::{verifier_core_path}/src/test/resources/yml/contract_message_scenario3.yml[indent=0] ---- +==== + Then you can add Spring Cloud Contract Verifier dependency and plugin to your build file, as shown in the following example: @@ -373,7 +296,7 @@ In order to use `WebTestClient` set `testMode` to `WEBTESTCLIENT`. Here is an example of a test generated in `WEBTESTCLIENT` test mode: - [source,java,indent=0] +[source,java,indent=0] ---- @Test public void validate_shouldRejectABeerIfTooYoung() throws Exception { @@ -403,7 +326,7 @@ order number followed by an underscore at the beginning of the contract file nam The following example shows an auto-generated test in Spock for a messaging stub contract: - [source,groovy,indent=0] +[source,groovy,indent=0] ---- given: ContractVerifierMessage inputMessage = contractVerifierMessaging.create( @@ -537,17 +460,19 @@ Assume that you want to send a request containing the ID of a client company and amount it wants to borrow from us. You also want to send it to the /fraudcheck url via the PUT method. -.Groovy DSL -[source,groovy,indent=0] +==== +[source,groovy,indent=0,role="primary"] +.groovy ---- include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[] ---- -.YAML -[source,yml,indent=0] +[source,yaml,indent=0,role="secondary"] +.yaml ---- include::{introduction_url}/samples/standalone/yml/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.yml[] ---- +==== ==== Client Side @@ -709,17 +634,19 @@ your expectations. To do so, write the following contract: IMPORTANT: Place the contract under `src/test/resources/contracts/fraud` folder. The `fraud` folder is important because the producer's test base class name references that folder. -.Groovy DSL -[source,groovy,indent=0] +==== +[source,groovy,indent=0,role="primary"] +.groovy ---- include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[] ---- -.YAML -[source,yml,indent=0] +[source,yaml,indent=0,role="secondary"] +.yaml ---- include::{introduction_url}/samples/standalone/yml/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.yml[] ---- +==== The YML contract is quite straight-forward. However when you take a look at the Contract written using a statically typed Groovy DSL - you might wonder what the @@ -1022,35 +949,4 @@ achieving the same thing by changing the properties. include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ---- -That's it! - -=== Dependencies - -The best way to add dependencies is to use the proper `starter` dependency. - -For `stub-runner`, use `spring-cloud-starter-stub-runner`. When you use a plugin, add -`spring-cloud-starter-contract-verifier`. - -=== Additional Links - -Here are some resources related to Spring Cloud Contract Verifier and Stub Runner. Note -that some may be outdated, because the Spring Cloud Contract Verifier project is under -constant development. - -==== Spring Cloud Contract video - -You can check out the video from the Warsaw JUG about Spring Cloud Contract: - -video::sAAklvxmPmk[youtube,start=538,width=640,height=480] - -==== Readings - -- https://www.slideshare.net/MarcinGrzejszczak/stick-to-the-rules-consumer-driven-contracts-201507-confitura[Slides from Marcin Grzejszczak's talk about Accurest] -- https://toomuchcoding.com/blog/categories/accurest/[Accurest related articles from Marcin Grzejszczak's blog] -- https://toomuchcoding.com/blog/categories/spring-cloud-contract/[Spring Cloud Contract related articles from Marcin Grzejszczak's blog] -- https://groovy-lang.org/json.html[Groovy docs regarding JSON] - -=== Samples - -You can find some samples at -https://github.com/spring-cloud-samples/spring-cloud-contract-samples[samples]. +That's it! \ No newline at end of file diff --git a/docs/src/main/asciidoc/_verifier_introduction.adoc b/docs/src/main/asciidoc/_verifier_introduction.adoc new file mode 100644 index 0000000000..466d8ad150 --- /dev/null +++ b/docs/src/main/asciidoc/_verifier_introduction.adoc @@ -0,0 +1,120 @@ +== Spring Cloud Contract Introduction + +Spring Cloud Contract moves TDD to the level of software architecture. It allows to perform consumer, consumer-driven and producer-driven contract testing. + +=== History + +Before becoming Spring Cloud Contract, this project was called https://github.com/Codearte/accurest[Accurest]. +It was created by https://twitter.com/mgrzejszczak[Marcin Grzejszczak] and https://twitter.com/jkubrynski[Jakub Kubrynski] +from (https://github.com/Codearte[Codearte]. + +The `0.1.0` release took place on 26 Jan 2015 and it became stable with `1.0.0` release on 29 Feb 2016. + +=== Why a Contract Verifier? + +Assume that we have a system consisting of multiple microservices: + +image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/docs/src/main/asciidoc/images/Deps.png[Microservices Architecture] + +==== Testing issues + +If we wanted to test the application in top left corner to determine whether it can +communicate with other services, we could do one of two things: + +- Deploy all microservices and perform end-to-end tests. +- Mock other microservices in unit/integration tests. + +Both have their advantages but also a lot of disadvantages. + +*Deploy all microservices and perform end to end tests* + + +Advantages: + +- Simulates production. +- Tests real communication between services. + +Disadvantages: + +- To test one microservice, we have to deploy 6 microservices, a couple of databases, +etc. +- The environment where the tests run is locked for a single suite of tests (nobody else +would be able to run the tests in the meantime). +- They take a long time to run. +- The feedback comes very late in the process. +- They are extremely hard to debug. + +*Mock other microservices in unit/integration tests* + +Advantages: + +- They provide very fast feedback. +- They have no infrastructure requirements. + +Disadvantages: + +- The implementor of the service creates stubs that might have nothing to do with +reality. +- You can go to production with passing tests and failing production. + +To solve the aforementioned issues, Spring Cloud Contract was created. The main idea is to give you very fast feedback, without the need to set up the +whole world of microservices. If you work on stubs, then the only applications you need +are those that your application directly uses. + +image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/docs/src/main/asciidoc/images/Stubs2.png[Stubbed Services] + +Spring Cloud Contract gives you the certainty that the stubs that you use were +created by the service that you're calling. Also, if you can use them, it means that they +were tested against the producer's side. In short, you can trust those stubs. + +=== Purposes + +The main purposes of Spring Cloud Contract are: + +- To ensure that Http / Messaging stubs (used when developing the client) do exactly +what the actual server-side implementation does. +- To promote ATDD (acceptance test driven developement) method and Microservices architectural style. +- To provide a way to publish changes in contracts that are immediately visible on both +sides. +- To generate boilerplate test code to be used on the server side. + +By default Spring Cloud Contract integrates with http://wiremock.org[Wiremock] as the HTTP server stub. + +IMPORTANT: Spring Cloud Contract's purpose is NOT to start writing business +features in the contracts. Assume that we have a business use case of fraud check. If a +user can be a fraud for 100 different reasons, we would assume that you would create 2 +contracts, one for the positive case and one for the negative case. Contract tests are +used to test contracts between applications and not to simulate full behavior. + +include::_verifier_how_it_works.adoc[] + +=== Dependencies + +The best way to add dependencies is to use the proper `starter` dependency. + +For `stub-runner`, use `spring-cloud-starter-stub-runner`. When you use a plugin, add +`spring-cloud-starter-contract-verifier`. + +=== Additional Links + +Here are some resources related to Spring Cloud Contract Verifier and Stub Runner. Note +that some may be outdated, because the Spring Cloud Contract Verifier project is under +constant development. + +==== Spring Cloud Contract video + +You can check out the video from the Warsaw JUG about Spring Cloud Contract: + +video::sAAklvxmPmk[youtube,start=538,width=640,height=480] + +==== Readings + +- https://www.slideshare.net/MarcinGrzejszczak/stick-to-the-rules-consumer-driven-contracts-201507-confitura[Slides from Marcin Grzejszczak's talk about Accurest] +- https://toomuchcoding.com/blog/categories/accurest/[Accurest related articles from Marcin Grzejszczak's blog] +- https://toomuchcoding.com/blog/categories/spring-cloud-contract/[Spring Cloud Contract related articles from Marcin Grzejszczak's blog] +- https://groovy-lang.org/json.html[Groovy docs regarding JSON] + +=== Samples + +You can find some samples at +https://github.com/spring-cloud-samples/spring-cloud-contract-samples[samples]. diff --git a/docs/src/main/asciidoc/verifier_messaging.adoc b/docs/src/main/asciidoc/_verifier_messaging.adoc similarity index 100% rename from docs/src/main/asciidoc/verifier_messaging.adoc rename to docs/src/main/asciidoc/_verifier_messaging.adoc diff --git a/docs/src/main/asciidoc/_verifier_setup.adoc b/docs/src/main/asciidoc/_verifier_setup.adoc new file mode 100644 index 0000000000..e805a2d1c7 --- /dev/null +++ b/docs/src/main/asciidoc/_verifier_setup.adoc @@ -0,0 +1,7 @@ +== Spring Cloud Contract Verifier Setup + +You can set up Spring Cloud Contract Verifier in the following ways: + +* link:gradle-project.html[As a Gradle project] +* link:maven-project.html[As a Maven project] +* link:docker-project.html[As a Docker project] \ No newline at end of file diff --git a/docs/src/main/asciidoc/verifier_stubrunner.adoc b/docs/src/main/asciidoc/_verifier_stubrunner.adoc similarity index 100% rename from docs/src/main/asciidoc/verifier_stubrunner.adoc rename to docs/src/main/asciidoc/_verifier_stubrunner.adoc diff --git a/docs/src/main/asciidoc/verifier_stubrunner_msg.adoc b/docs/src/main/asciidoc/_verifier_stubrunner_msg.adoc similarity index 100% rename from docs/src/main/asciidoc/verifier_stubrunner_msg.adoc rename to docs/src/main/asciidoc/_verifier_stubrunner_msg.adoc diff --git a/docs/src/main/asciidoc/docker-project.adoc b/docs/src/main/asciidoc/docker-project.adoc new file mode 100644 index 0000000000..4eca6a5220 --- /dev/null +++ b/docs/src/main/asciidoc/docker-project.adoc @@ -0,0 +1,180 @@ += Docker Project + +We're publishing a `springcloud/spring-cloud-contract` Docker image +that contains a project that will generate tests and execute them in `EXPLICIT` mode +against a running application. + +TIP: The `EXPLICIT` mode means that the tests generated from contracts will send +real requests and not the mocked ones. + +== Short intro to Maven, JARs and Binary storage + +Since the Docker image can be used by non JVM projects, it's good to +explain the basic terms behind Spring Cloud Contract packaging defaults. + +Part of the following definitions were taken from the https://maven.apache.org/glossary.html[Maven Glossary] + +- `Project`: Maven thinks in terms of projects. Everything that you +will build are projects. Those projects follow a well defined +“Project Object Model”. Projects can depend on other projects, +in which case the latter are called “dependencies”. A project may +consistent of several subprojects, however these subprojects are still +treated equally as projects. +- `Artifact`: An artifact is something that is either produced or used +by a project. Examples of artifacts produced by Maven for a project +include: JARs, source and binary distributions. Each artifact +is uniquely identified by a group id and an artifact ID which is +unique within a group. +- `JAR`: JAR stands for Java ARchive. It's a format based on +the ZIP file format. Spring Cloud Contract packages the contracts and generated +stubs in a JAR file. +- `GroupId`: A group ID is a universally unique identifier for a project. +While this is often just the project name (eg. commons-collections), +it is helpful to use a fully-qualified package name to distinguish it +from other projects with a similar name (eg. org.apache.maven). +Typically, when published to the Artifact Manager, the `GroupId` will get +slash separated and form part of the URL. E.g. for group id `com.example` +and artifact id `application` would be `/com/example/application/`. +- `Classifier`: The Maven dependency notation looks as follows: +`groupId:artifactId:version:classifier`. The classifier is additional suffix +passed to the dependency. E.g. `stubs`, `sources`. The same dependency +e.g. `com.example:application` can produce multiple artifacts that +differ from each other with the classifier. +- `Artifact manager`: When you generate binaries / sources / packages, you would +like them to be available for others to download / reference or reuse. In case +of the JVM world those artifacts would be JARs, for Ruby these are gems +and for Docker those would be Docker images. You can store those artifacts +in a manager. Examples of such managers can be https://jfrog.com/artifactory/[Artifactory] +or https://www.sonatype.org/nexus/[Nexus]. + +== How it works + +The image searches for contracts under the `/contracts` folder. +The output from running the tests will be available under +`/spring-cloud-contract/build` folder (it's useful for debugging +purposes). + +It's enough for you to mount your contracts, pass the environment variables + and the image will: + +- generate the contract tests +- execute the tests against the provided URL +- generate the https://github.com/tomakehurst/wiremock[WireMock] stubs +- (optional - turned on by default) publish the stubs to a Artifact Manager + +=== Environment Variables + +The Docker image requires some environment variables to point to +your running application, to the Artifact manager instance etc. + +- `PROJECT_GROUP` - your project's group id. Defaults to `com.example` +- `PROJECT_VERSION` - your project's version. Defaults to `0.0.1-SNAPSHOT` +- `PROJECT_NAME` - artifact id. Defaults to `example` +- `PRODUCER_STUBS_CLASSIFIER` - archive classifier used for generated producer stubs, defaults to `stubs`. +- `REPO_WITH_BINARIES_URL` - URL of your Artifact Manager. Defaults to `http://localhost:8081/artifactory/libs-release-local` +which is the default URL of https://jfrog.com/artifactory/[Artifactory] running locally +- `REPO_WITH_BINARIES_USERNAME` - (optional) username when the Artifact Manager is secured, defaults to `admin`. +- `REPO_WITH_BINARIES_PASSWORD` - (optional) password when the Artifact Manager is secured, defaults to `password`. +- `PUBLISH_ARTIFACTS` - if set to `true` then will publish artifact to binary storage. Defaults to `true`. + +These environment variables are used when contracts lay in an external repository. To enable +this feature you must set the `EXTERNAL_CONTRACTS_ARTIFACT_ID` environment variable. + +- `EXTERNAL_CONTRACTS_GROUP_ID` - group id of the project with contracts. Defaults to `com.example` +- `EXTERNAL_CONTRACTS_ARTIFACT_ID`- artifact id of the project with contracts. +- `EXTERNAL_CONTRACTS_CLASSIFIER`- classifier of the project with contracts. Empty by default +- `EXTERNAL_CONTRACTS_VERSION` - version of the project with contracts. Defaults to `+`, equivalent to picking the latest +- `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL` - URL of your Artifact Manager. Defaults to value of `REPO_WITH_BINARIES_URL` env var. +If that's not set, defaults to `http://localhost:8081/artifactory/libs-release-local` +which is the default URL of https://jfrog.com/artifactory/[Artifactory] running locally +- `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_USERNAME` - (optional) username if the `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL` +requires authentication, defaults to `REPO_WITH_BINARIES_USERNAME`. If that's not set defaults to `admin`. +- `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_PASSWORD` - (optional) password if the `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL` +requires authentication, defaults to `REPO_WITH_BINARIES_PASSWORD`. If that's not set defaults to `password`. +- `EXTERNAL_CONTRACTS_PATH` - path to contracts for the given project, inside the project with contracts. +Defaults to slash separated `EXTERNAL_CONTRACTS_GROUP_ID` concatenated with `/` and `EXTERNAL_CONTRACTS_ARTIFACT_ID`. E.g. +for group id `foo.bar` and artifact id `baz`, would result in `foo/bar/baz` contracts path. +- `EXTERNAL_CONTRACTS_WORK_OFFLINE` - if set to `true` then will retrieve artifact with contracts +from the container's `.m2`. Mount your local `.m2` as a volume available at the container's `/root/.m2` path. +You must not set both `EXTERNAL_CONTRACTS_WORK_OFFLINE` and `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL`. + + +These environment variables are used when tests are executed: + +- `APPLICATION_BASE_URL` - url against which tests should be executed. +Remember that it has to be accessible from the Docker container (e.g. `localhost` +will not work) +- `APPLICATION_USERNAME` - (optional) username for basic authentication to your application +- `APPLICATION_PASSWORD` - (optional) password for basic authentication to your application + +== Example of usage + +Let's take a look at a simple MVC application + +```bash +$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs +$ cd bookstore +``` + +The contracts are available under `/contracts` folder. + +[[docker-server-side]] +== Server side (nodejs) + +Since we want to run tests, we could just execute: + +```bash +$ npm test +``` + +however, for learning purposes, let's split it into pieces: + +```bash +# Stop docker infra (nodejs, artifactory) +$ ./stop_infra.sh +# Start docker infra (nodejs, artifactory) +$ ./setup_infra.sh + +# Kill & Run app +$ pkill -f "node app" +$ nohup node app & + +# Prepare environment variables +$ SC_CONTRACT_DOCKER_VERSION="..." +$ APP_IP="192.168.0.100" +$ APP_PORT="3000" +$ ARTIFACTORY_PORT="8081" +$ APPLICATION_BASE_URL="http://${APP_IP}:${APP_PORT}" +$ ARTIFACTORY_URL="http://${APP_IP}:${ARTIFACTORY_PORT}/artifactory/libs-release-local" +$ CURRENT_DIR="$( pwd )" +$ CURRENT_FOLDER_NAME=${PWD##*/} +$ PROJECT_VERSION="0.0.1.RELEASE" + +# Execute contract tests +$ docker run --rm -e "APPLICATION_BASE_URL=${APPLICATION_BASE_URL}" -e "PUBLISH_ARTIFACTS=true" -e "PROJECT_NAME=${CURRENT_FOLDER_NAME}" -e "REPO_WITH_BINARIES_URL=${ARTIFACTORY_URL}" -e "PROJECT_VERSION=${PROJECT_VERSION}" -v "${CURRENT_DIR}/contracts/:/contracts:ro" -v "${CURRENT_DIR}/node_modules/spring-cloud-contract/output:/spring-cloud-contract-output/" springcloud/spring-cloud-contract:"${SC_CONTRACT_DOCKER_VERSION}" + +# Kill app +$ pkill -f "node app" +``` + +What will happen is that via bash scripts: + +- infrastructure will be set up (MongoDb, Artifactory). +In real life scenario you would just run the NodeJS application +with mocked database. In this example we want to show how we can +benefit from Spring Cloud Contract in no time. +- due to those constraints the contracts also represent the +stateful situation +** first request is a `POST` that causes data to get inserted to the database +** second request is a `GET` that returns a list of data with 1 previously inserted element +- the NodeJS application will be started (on port `3000`) +- contract tests will be generated via Docker and tests +will be executed against the running application +** the contracts will be taken from `/contracts` folder. +** the output of the test execution is available under +`node_modules/spring-cloud-contract/output`. +- the stubs will be uploaded to Artifactory. You can check them out +under http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/ . +The stubs will be here http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar. + +To see how the client side looks like check out the <> section. diff --git a/docs/src/main/asciidoc/gradle-project.adoc b/docs/src/main/asciidoc/gradle-project.adoc new file mode 100644 index 0000000000..8d03c5b3e8 --- /dev/null +++ b/docs/src/main/asciidoc/gradle-project.adoc @@ -0,0 +1,420 @@ +:branch: master +:core_path: ../../.. +:plugins_path: ../../../spring-cloud-contract-tools +:converters_path: {plugins_path}/spring-cloud-contract-converters +:verifier_root_path: {core_path}/spring-cloud-contract-verifier +:contract_spec_path: {core_path}/specs/spring-cloud-contract-spec-java +:contract_spec_tests_path: {core_path}/specs/spring-cloud-contract-spec +:samples_path: {core_path}/samples +:verifier_core_path: {verifier_root_path} +:stubrunner_core_path: {core_path}/spring-cloud-contract-stub-runner +:standalone_samples_path: {samples_path}/standalone/dsl +:standalone_messaging_samples_path: {samples_path}/standalone/messaging +:standalone_pact_path: {samples_path}/standalone/pact +:standalone_restdocs_path: {samples_path}/standalone/restdocs +:tests_path: {core_path}/tests +:samples_branch: 2.2.x +:samples_url: https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/{samples_branch} +:introduction_url: ${core_path}/../../ + += Gradle Project + +To learn how to set up the Gradle project for Spring Cloud Contract Verifier, read the +following sections: + +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> + +[[gradle-prerequisites]] +== Prerequisites + +In order to use Spring Cloud Contract Verifier with WireMock, you muse use either a +Gradle or a Maven plugin. + +WARNING: If you want to use Spock in your projects, you must add separately the +`spock-core` and `spock-spring` modules. Check https://spockframework.github.io/[Spock +docs for more information] + +[[gradle-add-gradle-plugin]] +== Add Gradle Plugin with Dependencies + +To add a Gradle plugin with dependencies, use code similar to this: + +[source,groovy,indent=0] +---- +buildscript { + repositories { + mavenCentral() + } + dependencies { + classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}" + classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}" + } +} + +apply plugin: 'groovy' +apply plugin: 'spring-cloud-contract' + +dependencyManagement { + imports { + mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${verifier_version}" + } +} + +dependencies { + testCompile 'org.codehaus.groovy:groovy-all:2.4.6' + // example with adding Spock core and Spock Spring + testCompile 'org.spockframework:spock-core:1.0-groovy-2.4' + testCompile 'org.spockframework:spock-spring:1.0-groovy-2.4' + testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier' +} +---- + +[[gradle-and-rest-assured]] +== Gradle and Rest Assured 2.0 + +By default, Rest Assured 3.x is added to the classpath. However, to use Rest Assured 2.x +you can add it to the plugins classpath, as shown here: + +[source,groovy,indent=0] +---- +buildscript { + repositories { + mavenCentral() + } + dependencies { + classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}" + classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}" + classpath "com.jayway.restassured:rest-assured:2.5.0" + classpath "com.jayway.restassured:spring-mock-mvc:2.5.0" + } +} + +depenendencies { + // all dependencies + // you can exclude rest-assured from spring-cloud-contract-verifier + testCompile "com.jayway.restassured:rest-assured:2.5.0" + testCompile "com.jayway.restassured:spring-mock-mvc:2.5.0" +} +---- + +That way, the plugin automatically sees that Rest Assured 2.x is present on the classpath +and modifies the imports accordingly. + +[[gradle-snapshot-versions]] +== Snapshot Versions for Gradle + +Add the additional snapshot repository to your build.gradle to use snapshot versions, +which are automatically uploaded after every successful build, as shown here: + +[source,groovy,indent=0] +---- +include::{standalone_samples_path}/http-server/build.gradle[tags=repos,indent=0] +} +---- +[[gradle-add-stubs]] +== Add stubs + +By default, Spring Cloud Contract Verifier is looking for stubs in the +`src/test/resources/contracts` directory. + +The directory containing stub definitions is treated as a class name, and each stub +definition is treated as a single test. Spring Cloud Contract Verifier assumes that it +contains at least one level of directories that are to be used as the test class name. +If more than one level of nested directories is present, all except the last one is used +as the package name. For example, with following structure: + +[source,groovy,indent=0] +---- +src/test/resources/contracts/myservice/shouldCreateUser.groovy +src/test/resources/contracts/myservice/shouldReturnUser.groovy +---- + +Spring Cloud Contract Verifier creates a test class named `defaultBasePackage.MyService` +with two methods: + + - `shouldCreateUser()` + - `shouldReturnUser()` + +[[gradle-run-plugin]] +== Run the Plugin + +The plugin registers itself to be invoked before a `check` task. If you want it to be +part of your build process, you need to do nothing more. If you just want to generate +tests, invoke the `generateContractTests` task. + +[[gradle-default-setup]] +== Default Setup + +The default Gradle Plugin setup creates the following Gradle part of the build (in +pseudocode): + +[source,groovy,indent=0] +---- +contracts { + testFramework ='JUNIT' + testMode = 'MockMvc' + generatedTestSourcesDir = project.file("${project.buildDir}/generated-test-sources/contracts") + generatedTestResourcesDir = project.file("${project.buildDir}/generated-test-resources/contracts") + contractsDslDir = "${project.rootDir}/src/test/resources/contracts" + basePackageForTests = 'org.springframework.cloud.verifier.tests' + stubsOutputDir = project.file("${project.buildDir}/stubs") + + // the following properties are used when you want to provide where the JAR with contract lays + contractDependency { + stringNotation = '' + } + contractsPath = '' + contractsWorkOffline = false + contractRepository { + cacheDownloadedContracts(true) + } +} + +tasks.create(type: Jar, name: 'verifierStubsJar', dependsOn: 'generateClientStubs') { + baseName = project.name + classifier = contracts.stubsSuffix + from contractVerifier.stubsOutputDir +} + +project.artifacts { + archives task +} + +tasks.create(type: Copy, name: 'copyContracts') { + from contracts.contractsDslDir + into contracts.stubsOutputDir +} + +verifierStubsJar.dependsOn 'copyContracts' + +publishing { + publications { + stubs(MavenPublication) { + artifactId project.name + artifact verifierStubsJar + } + } +} +---- + +[[gradle-configure-plugin]] +== Configure Plugin + +To change the default configuration, add a `contracts` snippet to your Gradle config, as +shown here: + +[source,groovy,indent=0] +---- +contracts { + testMode = 'MockMvc' + baseClassForTests = 'org.mycompany.tests' + generatedTestSourcesDir = project.file('src/generatedContract') +} +---- + +[[gradle-configuration-options]] +== Configuration Options + +* *testMode*: Defines the mode for acceptance tests. By default, the mode is MockMvc, +which is based on Spring's MockMvc. It can also be changed to *WebTestClient*, *JaxRsClient* or to +*Explicit* for real HTTP calls. +* *imports*: Creates an array with imports that should be included in generated tests +(for example ['org.myorg.Matchers']). By default, it creates an empty array. +* *staticImports*: Creates an array with static imports that should be included in +generated tests(for example ['org.myorg.Matchers.*']). By default, it creates an empty +array. +* *basePackageForTests*: Specifies the base package for all generated tests. If not set, +the value is picked from `baseClassForTests`'s package and from `packageWithBaseClasses`. +If neither of these values are set, then the value is set to +`org.springframework.cloud.contract.verifier.tests`. +* *baseClassForTests*: Creates a base class for all generated tests. By default, if you +use Spock classes, the class is `spock.lang.Specification`. +* *packageWithBaseClasses*: Defines a package where all the base classes reside. This +setting takes precedence over *baseClassForTests*. +* *baseClassMappings*: Explicitly maps a contract package to a FQN of a base class. This +setting takes precedence over *packageWithBaseClasses* and *baseClassForTests*. +* *ruleClassForTests*: Specifies a rule that should be added to the generated test +classes. +* *ignoredFiles*: Uses an `Antmatcher` to allow defining stub files for which processing +should be skipped. By default, it is an empty array. +* *contractsDslDir*: Specifies the directory containing contracts written using the +GroovyDSL. By default, its value is `$rootDir/src/test/resources/contracts`. +* *generatedTestSourcesDir*: Specifies the test source directory where tests generated +from the Groovy DSL should be placed. By default its value is +`$buildDir/generated-test-sources/contracts`. +* *generatedTestResourcesDir*: Specifies the test resource directory where resources used by the tests generated +from the Groovy DSL should be placed. By default its value is +`$buildDir/generated-test-resources/contracts`. +* *stubsOutputDir*: Specifies the directory where the generated WireMock stubs from +the Groovy DSL should be placed. +* *testFramework*: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (`TestFramework.JUNIT`) and +JUnit 5 are supported with JUnit 4 being the default framework. +* *contractsProperties*: a map containing properties to be passed to Spring Cloud Contract +components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders. + +The following properties are used when you want to specify the location of the JAR +containing the contracts: + +* *contractDependency*: Specifies the Dependency that provides +`groupid:artifactid:version:classifier` coordinates. You can use the `contractDependency` +closure to set it up. +* *contractsPath*: Specifies the path to the jar. If contract dependencies are + downloaded, the path defaults to `groupid/artifactid` where `groupid` is slash + separated. Otherwise, it scans contracts under the provided directory. +* *contractsMode*: Specifies the mode of downloading contracts (whether the +JAR is available offline, remotely etc.) +* *deleteStubsAfterTest*: If set to `false` will not remove any downloaded +contracts from temporary directories + +Below you can find a list of experimental features you can turn on via the plugin: + +* *convertToYaml*: converts all DSLs to the declarative, YAML format. This can be extremely useful when you're using external libraries in your Groovy DSLs. By turning this feature on (by setting it to `true`) you will not need to add the library dependency on the consumer side. +* *assertJsonSize*: You can check the size of JSON arrays in the generated tests. This feature is disabled by default. + +[[gradle-single-base-class]] +== Single Base Class for All Tests + +When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base +specification for all generated acceptance tests. In this class, you need to point to an +endpoint, which should be verified. + +[source,groovy,indent=0] +---- +include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/resources/functionalTest/bootSimple/src/test/groovy/org/springframework/cloud/contract/verifier/twitter/places/BaseMockMvcSpec.groovy[tags=base_class,indent=0] +---- + +If you use `Explicit` mode, you can use a base class to initialize the whole tested app +as you might see in regular integration tests. If you use the `JAXRSCLIENT` mode, this +base class should also contain a `protected WebTarget webTarget` field. Right now, the +only option to test the JAX-RS API is to start a web server. + +[[gradle-different-base-classes]] +== Different Base Classes for Contracts + +If your base classes differ between contracts, you can tell the Spring Cloud Contract +plugin which class should get extended by the autogenerated tests. You have two options: + +* Follow a convention by providing the `packageWithBaseClasses` +* Provide explicit mapping via `baseClassMappings` + +*By Convention* + +The convention is such that if you have a contract under (for example) +`src/test/resources/contract/foo/bar/baz/` and set the value of the +`packageWithBaseClasses` property to `com.example.base`, then Spring Cloud Contract +Verifier assumes that there is a `BarBazBase` class under the `com.example.base` package. +In other words, the system takes the last two parts of the package, if they exist, and +forms a class with a `Base` suffix. This rule takes precedence over *baseClassForTests*. +Here is an example of how it works in the `contracts` closure: + +[source,groovy,indent=0] +---- +include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/groovy/org/springframework/cloud/contract/verifier/plugin/ContractVerifierSpec.groovy[tags=package_with_base_classes,indent=0] +---- + +*By Mapping* + +You can manually map a regular expression of the contract's package to fully qualified +name of the base class for the matched contract. You have to provide a list called +`baseClassMappings` that consists `baseClassMapping` objects that takes a +`contractPackageRegex` to `baseClassFQN` mapping. Consider the following example: + +[source,groovy,indent=0] +---- +include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/groovy/org/springframework/cloud/contract/verifier/plugin/ContractVerifierSpec.groovy[tags=base_class_mappings,indent=0] +---- + +Let's assume that you have contracts under + - `src/test/resources/contract/com/` + - `src/test/resources/contract/foo/` + +By providing the `baseClassForTests`, we have a fallback in case mapping did not succeed. +(You could also provide the `packageWithBaseClasses` as a fallback.) That way, the tests +generated from `src/test/resources/contract/com/` contracts extend the +`com.example.ComBase`, whereas the rest of the tests extend `com.example.FooBase`. + +[[gradle-invoking-generated-tests]] +== Invoking Generated Tests + +To ensure that the provider side is compliant with defined contracts, you need to invoke: + +[source,bash,indent=0] +---- +./gradlew generateContractTests test +---- + +[[gradle-pushing-stubs-to-scm]] +== Pushing stubs to SCM + +If you're using the SCM repository to keep the contracts and +stubs, you might want to automate the step of pushing stubs to +the repository. To do that, it's enough to call the `pushStubsToScm` +task. Example: + +[source,bash,indent=0] +---- +$ ./gradlew pushStubsToScm +---- + +Under <> you can find all possible +configuration options that you can pass either via +the `contractsProperties` field e.g. `contracts { contractsProperties = [foo:"bar"] }`, +via `contractsProperties` method e.g. `contracts { contractsProperties([foo:"bar"]) }`, +a system property or an environment variable. + +[[gradle-consumer]] +== Spring Cloud Contract Verifier on the Consumer Side + +In a consuming service, you need to configure the Spring Cloud Contract Verifier plugin +in exactly the same way as in case of provider. If you do not want to use Stub Runner +then you need to copy contracts stored in `src/test/resources/contracts` and generate +WireMock JSON stubs using: + +[source,bash,indent=0] +---- +./gradlew generateClientStubs +---- + +NOTE: The `stubsOutputDir` option has to be set for stub generation to work. + +When present, JSON stubs can be used in automated tests of consuming a service. + +[source,groovy,indent=0] +---- +@ContextConfiguration(loader == SpringApplicationContextLoader, classes == Application) +class LoanApplicationServiceSpec extends Specification { + + @ClassRule + @Shared + WireMockClassRule wireMockRule == new WireMockClassRule() + + @Autowired + LoanApplicationService sut + + def 'should successfully apply for loan'() { + given: + LoanApplication application = + new LoanApplication(client: new Client(clientPesel: '12345678901'), amount: 123.123) + when: + LoanApplicationResult loanApplication == sut.loanApplication(application) + then: + loanApplication.loanApplicationStatus == LoanApplicationStatus.LOAN_APPLIED + loanApplication.rejectionReason == null + } +} +---- + +`LoanApplication` makes a call to `FraudDetection` service. This request is handled by a +WireMock server configured with stubs generated by Spring Cloud Contract Verifier. \ No newline at end of file diff --git a/docs/src/main/asciidoc/verifier_setup.adoc b/docs/src/main/asciidoc/maven-project.adoc similarity index 66% rename from docs/src/main/asciidoc/verifier_setup.adoc rename to docs/src/main/asciidoc/maven-project.adoc index 24c4a7a32e..2cb981a6e9 100644 --- a/docs/src/main/asciidoc/verifier_setup.adoc +++ b/docs/src/main/asciidoc/maven-project.adoc @@ -1,416 +1,23 @@ -== Spring Cloud Contract Verifier Setup - -You can set up Spring Cloud Contract Verifier in the following ways: - -* <> -* <> -* <> - -[[gradle-project]] -=== Gradle Project - -To learn how to set up the Gradle project for Spring Cloud Contract Verifier, read the -following sections: - -* <> -* <> -* <> -* <> -* <> -* <> -* <> -* <> -* <> -* <> -* <> -* <> -* <> - -[[gradle-prerequisites]] -==== Prerequisites - -In order to use Spring Cloud Contract Verifier with WireMock, you muse use either a -Gradle or a Maven plugin. - -WARNING: If you want to use Spock in your projects, you must add separately the -`spock-core` and `spock-spring` modules. Check https://spockframework.github.io/[Spock -docs for more information] - -[[gradle-add-gradle-plugin]] -==== Add Gradle Plugin with Dependencies - -To add a Gradle plugin with dependencies, use code similar to this: - -[source,groovy,indent=0] ----- -buildscript { - repositories { - mavenCentral() - } - dependencies { - classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}" - classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}" - } -} - -apply plugin: 'groovy' -apply plugin: 'spring-cloud-contract' - -dependencyManagement { - imports { - mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${verifier_version}" - } -} - -dependencies { - testCompile 'org.codehaus.groovy:groovy-all:2.4.6' - // example with adding Spock core and Spock Spring - testCompile 'org.spockframework:spock-core:1.0-groovy-2.4' - testCompile 'org.spockframework:spock-spring:1.0-groovy-2.4' - testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier' -} ----- - -[[gradle-and-rest-assured]] -==== Gradle and Rest Assured 2.0 - -By default, Rest Assured 3.x is added to the classpath. However, to use Rest Assured 2.x -you can add it to the plugins classpath, as shown here: - -[source,groovy,indent=0] ----- -buildscript { - repositories { - mavenCentral() - } - dependencies { - classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}" - classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}" - classpath "com.jayway.restassured:rest-assured:2.5.0" - classpath "com.jayway.restassured:spring-mock-mvc:2.5.0" - } -} - -depenendencies { - // all dependencies - // you can exclude rest-assured from spring-cloud-contract-verifier - testCompile "com.jayway.restassured:rest-assured:2.5.0" - testCompile "com.jayway.restassured:spring-mock-mvc:2.5.0" -} ----- - -That way, the plugin automatically sees that Rest Assured 2.x is present on the classpath -and modifies the imports accordingly. - -[[gradle-snapshot-versions]] -==== Snapshot Versions for Gradle - -Add the additional snapshot repository to your build.gradle to use snapshot versions, -which are automatically uploaded after every successful build, as shown here: - -[source,groovy,indent=0] ----- -include::{standalone_samples_path}/http-server/build.gradle[tags=repos,indent=0] -} ----- -[[gradle-add-stubs]] -==== Add stubs - -By default, Spring Cloud Contract Verifier is looking for stubs in the -`src/test/resources/contracts` directory. - -The directory containing stub definitions is treated as a class name, and each stub -definition is treated as a single test. Spring Cloud Contract Verifier assumes that it -contains at least one level of directories that are to be used as the test class name. -If more than one level of nested directories is present, all except the last one is used -as the package name. For example, with following structure: - -[source,groovy,indent=0] ----- -src/test/resources/contracts/myservice/shouldCreateUser.groovy -src/test/resources/contracts/myservice/shouldReturnUser.groovy ----- - -Spring Cloud Contract Verifier creates a test class named `defaultBasePackage.MyService` -with two methods: - - - `shouldCreateUser()` - - `shouldReturnUser()` - -[[gradle-run-plugin]] -==== Run the Plugin - -The plugin registers itself to be invoked before a `check` task. If you want it to be -part of your build process, you need to do nothing more. If you just want to generate -tests, invoke the `generateContractTests` task. - -[[gradle-default-setup]] -==== Default Setup - -The default Gradle Plugin setup creates the following Gradle part of the build (in -pseudocode): - -[source,groovy,indent=0] ----- -contracts { - testFramework ='JUNIT' - testMode = 'MockMvc' - generatedTestSourcesDir = project.file("${project.buildDir}/generated-test-sources/contracts") - generatedTestResourcesDir = project.file("${project.buildDir}/generated-test-resources/contracts") - contractsDslDir = "${project.rootDir}/src/test/resources/contracts" - basePackageForTests = 'org.springframework.cloud.verifier.tests' - stubsOutputDir = project.file("${project.buildDir}/stubs") - - // the following properties are used when you want to provide where the JAR with contract lays - contractDependency { - stringNotation = '' - } - contractsPath = '' - contractsWorkOffline = false - contractRepository { - cacheDownloadedContracts(true) - } -} - -tasks.create(type: Jar, name: 'verifierStubsJar', dependsOn: 'generateClientStubs') { - baseName = project.name - classifier = contracts.stubsSuffix - from contractVerifier.stubsOutputDir -} - -project.artifacts { - archives task -} - -tasks.create(type: Copy, name: 'copyContracts') { - from contracts.contractsDslDir - into contracts.stubsOutputDir -} - -verifierStubsJar.dependsOn 'copyContracts' - -publishing { - publications { - stubs(MavenPublication) { - artifactId project.name - artifact verifierStubsJar - } - } -} ----- - -[[gradle-configure-plugin]] -==== Configure Plugin - -To change the default configuration, add a `contracts` snippet to your Gradle config, as -shown here: - -[source,groovy,indent=0] ----- -contracts { - testMode = 'MockMvc' - baseClassForTests = 'org.mycompany.tests' - generatedTestSourcesDir = project.file('src/generatedContract') -} ----- - -[[gradle-configuration-options]] -==== Configuration Options - -* *testMode*: Defines the mode for acceptance tests. By default, the mode is MockMvc, -which is based on Spring's MockMvc. It can also be changed to *WebTestClient*, *JaxRsClient* or to -*Explicit* for real HTTP calls. -* *imports*: Creates an array with imports that should be included in generated tests -(for example ['org.myorg.Matchers']). By default, it creates an empty array. -* *staticImports*: Creates an array with static imports that should be included in -generated tests(for example ['org.myorg.Matchers.*']). By default, it creates an empty -array. -* *basePackageForTests*: Specifies the base package for all generated tests. If not set, -the value is picked from `baseClassForTests`'s package and from `packageWithBaseClasses`. -If neither of these values are set, then the value is set to -`org.springframework.cloud.contract.verifier.tests`. -* *baseClassForTests*: Creates a base class for all generated tests. By default, if you -use Spock classes, the class is `spock.lang.Specification`. -* *packageWithBaseClasses*: Defines a package where all the base classes reside. This -setting takes precedence over *baseClassForTests*. -* *baseClassMappings*: Explicitly maps a contract package to a FQN of a base class. This -setting takes precedence over *packageWithBaseClasses* and *baseClassForTests*. -* *ruleClassForTests*: Specifies a rule that should be added to the generated test -classes. -* *ignoredFiles*: Uses an `Antmatcher` to allow defining stub files for which processing -should be skipped. By default, it is an empty array. -* *contractsDslDir*: Specifies the directory containing contracts written using the -GroovyDSL. By default, its value is `$rootDir/src/test/resources/contracts`. -* *generatedTestSourcesDir*: Specifies the test source directory where tests generated -from the Groovy DSL should be placed. By default its value is -`$buildDir/generated-test-sources/contracts`. -* *generatedTestResourcesDir*: Specifies the test resource directory where resources used by the tests generated -from the Groovy DSL should be placed. By default its value is -`$buildDir/generated-test-resources/contracts`. -* *stubsOutputDir*: Specifies the directory where the generated WireMock stubs from -the Groovy DSL should be placed. -* *testFramework*: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (`TestFramework.JUNIT`) and -JUnit 5 are supported with JUnit 4 being the default framework. -* *contractsProperties*: a map containing properties to be passed to Spring Cloud Contract -components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders. - -The following properties are used when you want to specify the location of the JAR -containing the contracts: - -* *contractDependency*: Specifies the Dependency that provides -`groupid:artifactid:version:classifier` coordinates. You can use the `contractDependency` -closure to set it up. -* *contractsPath*: Specifies the path to the jar. If contract dependencies are - downloaded, the path defaults to `groupid/artifactid` where `groupid` is slash - separated. Otherwise, it scans contracts under the provided directory. -* *contractsMode*: Specifies the mode of downloading contracts (whether the -JAR is available offline, remotely etc.) -* *deleteStubsAfterTest*: If set to `false` will not remove any downloaded -contracts from temporary directories - -Below you can find a list of experimental features you can turn on via the plugin: - -* *convertToYaml*: converts all DSLs to the declarative, YAML format. This can be extremely useful when you're using external libraries in your Groovy DSLs. By turning this feature on (by setting it to `true`) you will not need to add the library dependency on the consumer side. -* *assertJsonSize*: You can check the size of JSON arrays in the generated tests. This feature is disabled by default. - -[[gradle-single-base-class]] -==== Single Base Class for All Tests - -When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base -specification for all generated acceptance tests. In this class, you need to point to an -endpoint, which should be verified. - -[source,groovy,indent=0] ----- -include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/resources/functionalTest/bootSimple/src/test/groovy/org/springframework/cloud/contract/verifier/twitter/places/BaseMockMvcSpec.groovy[tags=base_class,indent=0] ----- - -If you use `Explicit` mode, you can use a base class to initialize the whole tested app -as you might see in regular integration tests. If you use the `JAXRSCLIENT` mode, this -base class should also contain a `protected WebTarget webTarget` field. Right now, the -only option to test the JAX-RS API is to start a web server. - -[[gradle-different-base-classes]] -==== Different Base Classes for Contracts - -If your base classes differ between contracts, you can tell the Spring Cloud Contract -plugin which class should get extended by the autogenerated tests. You have two options: - -* Follow a convention by providing the `packageWithBaseClasses` -* Provide explicit mapping via `baseClassMappings` - -*By Convention* - -The convention is such that if you have a contract under (for example) -`src/test/resources/contract/foo/bar/baz/` and set the value of the -`packageWithBaseClasses` property to `com.example.base`, then Spring Cloud Contract -Verifier assumes that there is a `BarBazBase` class under the `com.example.base` package. -In other words, the system takes the last two parts of the package, if they exist, and -forms a class with a `Base` suffix. This rule takes precedence over *baseClassForTests*. -Here is an example of how it works in the `contracts` closure: - -[source,groovy,indent=0] ----- -include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/groovy/org/springframework/cloud/contract/verifier/plugin/ContractVerifierSpec.groovy[tags=package_with_base_classes,indent=0] ----- - -*By Mapping* - -You can manually map a regular expression of the contract's package to fully qualified -name of the base class for the matched contract. You have to provide a list called -`baseClassMappings` that consists `baseClassMapping` objects that takes a -`contractPackageRegex` to `baseClassFQN` mapping. Consider the following example: - -[source,groovy,indent=0] ----- -include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/groovy/org/springframework/cloud/contract/verifier/plugin/ContractVerifierSpec.groovy[tags=base_class_mappings,indent=0] ----- - -Let's assume that you have contracts under - - `src/test/resources/contract/com/` - - `src/test/resources/contract/foo/` - -By providing the `baseClassForTests`, we have a fallback in case mapping did not succeed. -(You could also provide the `packageWithBaseClasses` as a fallback.) That way, the tests -generated from `src/test/resources/contract/com/` contracts extend the -`com.example.ComBase`, whereas the rest of the tests extend `com.example.FooBase`. - -[[gradle-invoking-generated-tests]] -==== Invoking Generated Tests - -To ensure that the provider side is compliant with defined contracts, you need to invoke: - -[source,bash,indent=0] ----- -./gradlew generateContractTests test ----- - -[[gradle-pushing-stubs-to-scm]] -==== Pushing stubs to SCM - -If you're using the SCM repository to keep the contracts and -stubs, you might want to automate the step of pushing stubs to -the repository. To do that, it's enough to call the `pushStubsToScm` -task. Example: - -[source,bash,indent=0] ----- -$ ./gradlew pushStubsToScm ----- - -Under <> you can find all possible -configuration options that you can pass either via -the `contractsProperties` field e.g. `contracts { contractsProperties = [foo:"bar"] }`, -via `contractsProperties` method e.g. `contracts { contractsProperties([foo:"bar"]) }`, -a system property or an environment variable. - -[[gradle-consumer]] -==== Spring Cloud Contract Verifier on the Consumer Side - -In a consuming service, you need to configure the Spring Cloud Contract Verifier plugin -in exactly the same way as in case of provider. If you do not want to use Stub Runner -then you need to copy contracts stored in `src/test/resources/contracts` and generate -WireMock JSON stubs using: - -[source,bash,indent=0] ----- -./gradlew generateClientStubs ----- - -NOTE: The `stubsOutputDir` option has to be set for stub generation to work. - -When present, JSON stubs can be used in automated tests of consuming a service. - -[source,groovy,indent=0] ----- -@ContextConfiguration(loader == SpringApplicationContextLoader, classes == Application) -class LoanApplicationServiceSpec extends Specification { - - @ClassRule - @Shared - WireMockClassRule wireMockRule == new WireMockClassRule() - - @Autowired - LoanApplicationService sut - - def 'should successfully apply for loan'() { - given: - LoanApplication application = - new LoanApplication(client: new Client(clientPesel: '12345678901'), amount: 123.123) - when: - LoanApplicationResult loanApplication == sut.loanApplication(application) - then: - loanApplication.loanApplicationStatus == LoanApplicationStatus.LOAN_APPLIED - loanApplication.rejectionReason == null - } -} ----- - -`LoanApplication` makes a call to `FraudDetection` service. This request is handled by a -WireMock server configured with stubs generated by Spring Cloud Contract Verifier. - -[[maven-project]] -=== Maven Project +:branch: master +:core_path: ../../.. +:plugins_path: ../../../spring-cloud-contract-tools +:converters_path: {plugins_path}/spring-cloud-contract-converters +:verifier_root_path: {core_path}/spring-cloud-contract-verifier +:contract_spec_path: {core_path}/specs/spring-cloud-contract-spec-java +:contract_spec_tests_path: {core_path}/specs/spring-cloud-contract-spec +:samples_path: {core_path}/samples +:verifier_core_path: {verifier_root_path} +:stubrunner_core_path: {core_path}/spring-cloud-contract-stub-runner +:standalone_samples_path: {samples_path}/standalone/dsl +:standalone_messaging_samples_path: {samples_path}/standalone/messaging +:standalone_pact_path: {samples_path}/standalone/pact +:standalone_restdocs_path: {samples_path}/standalone/restdocs +:tests_path: {core_path}/tests +:samples_branch: 2.2.x +:samples_url: https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/{samples_branch} +:introduction_url: ${core_path}/../../ + += Maven Project To learn how to set up the Maven project for Spring Cloud Contract Verifier, read the following sections: @@ -429,7 +36,7 @@ following sections: * <> [[maven-add-plugin]] -==== Add maven plugin +== Add maven plugin Add the Spring Cloud Contract BOM in a fashion similar to this: @@ -450,7 +57,7 @@ https://cloud.spring.io/spring-cloud-static/spring-cloud-contract/2.0.0.RELEASE/ Cloud Contract Maven Plugin Documentation (example for `2.0.0.RELEASE` version)]. [[maven-rest-assured]] -==== Maven and Rest Assured 2.0 +== Maven and Rest Assured 2.0 By default, Rest Assured 3.x is added to the classpath. However, you can use Rest Assured 2.x by adding it to the plugins classpath, as shown here: @@ -508,7 +115,7 @@ That way, the plugin automatically sees that Rest Assured 3.x is present on the and modifies the imports accordingly. [[maven-snapshot-versions]] -==== Snapshot versions for Maven +== Snapshot versions for Maven For Snapshot and Milestone versions, you have to add the following section to your `pom.xml`, as shown here: @@ -519,7 +126,7 @@ include::{standalone_samples_path}/http-server/pom.xml[tags=repos,indent=0] ---- [[maven-add-stubs]] -==== Add stubs +== Add stubs By default, Spring Cloud Contract Verifier is looking for stubs in the `src/test/resources/contracts` directory. The directory containing stub definitions is @@ -541,14 +148,14 @@ with two methods * `shouldReturnUser()` [[maven-run-plugin]] -==== Run plugin +== Run plugin The plugin goal `generateTests` is assigned to be invoked in the phase called `generate-test-sources`. If you want it to be part of your build process, you need not do anything. If you just want to generate tests, invoke the `generateTests` goal. [[maven-configure-plugin]] -==== Configure plugin +== Configure plugin To change the default configuration, just add a `configuration` section to the plugin definition or the `execution` definition, as shown here: @@ -575,7 +182,7 @@ definition or the `execution` definition, as shown here: ---- [[maven-configuration-options]] -==== Configuration Options +== Configuration Options * *testMode*: Defines the mode for acceptance tests. By default, the mode is MockMvc, which is based on Spring's MockMvc. It can also be changed to *WebTestClient*, *JaxRsClient* or to @@ -639,7 +246,7 @@ Below you can find a list of experimental features you can turn on via the plugi * *assertJsonSize*: You can check the size of JSON arrays in the generated tests. This feature is disabled by default. [[maven-single-base]] -==== Single Base Class for All Tests +== Single Base Class for All Tests When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base specification for all generated acceptance tests. In this class, you need to point to an @@ -718,7 +325,7 @@ If you use the `JAXRSCLIENT` mode, this base class should also contain a `protec now, the only option to test the JAX-RS API is to start a web server. [[maven-different-base]] -==== Different base classes for contracts +== Different base classes for contracts If your base classes differ between contracts, you can tell the Spring Cloud Contract plugin which class should get extended by the autogenerated tests. You have two options: @@ -763,7 +370,7 @@ generated from `src/test/resources/contract/com/` contracts extend the `com.example.ComBase`, whereas the rest of the tests extend `com.example.FooBase`. [[maven-invoking-generated-tests]] -==== Invoking generated tests +== Invoking generated tests The Spring Cloud Contract Maven Plugin generates verification code in a directory called `/generated-test-sources/contractVerifier` and attaches this directory to `testCompile` @@ -807,7 +414,7 @@ To ensure that provider side is compliant with defined contracts, you need to in `mvn generateTest test`. [[maven-pushing-stubs-to-scm]] -==== Pushing stubs to SCM +== Pushing stubs to SCM If you're using the SCM repository to keep the contracts and stubs, you might want to automate the step of pushing stubs to @@ -858,7 +465,7 @@ the `` map, a system property or an environment variable. [[maven-sts]] -==== Maven Plugin and STS +== Maven Plugin and STS If you see the following exception while using STS: @@ -915,7 +522,7 @@ In order to fix this issue, provide the following section in your `pom.xml`: ---- -==== Maven Plugin with Spock Tests +== Maven Plugin with Spock Tests You can select the http://spockframework.org/[Spock Framework] for creating and executing the auto-generated contract verification tests with both Maven and Gradle plugin. However, whereas with Gradle its really straightforward, @@ -939,7 +546,7 @@ Surefire plugin setup, like in the following example: include::{samples_url}/producer_with_spock/pom.xml[tags=pock-surefire-setup,indent=0] ---- -=== Stubs and Transitive Dependencies += Stubs and Transitive Dependencies The Maven and Gradle plugin that add the tasks that create the stubs jar for you. One problem that arises is that, when reusing the stubs, you can mistakenly import all of @@ -983,7 +590,7 @@ For example, you might decide to have no dependencies at all. As a consumer, if you add the stub dependency to your classpath, you can explicitly exclude the unwanted dependencies. -=== Scenarios += Scenarios You can handle scenarios with Spring Cloud Contract Verifier. All you need to do is to stick to the proper naming convention while creating your contracts. The convention @@ -1012,7 +619,7 @@ https://wiremock.org/docs/stateful-behaviour/[https://wiremock.org/docs/stateful Spring Cloud Contract Verifier also generates tests with a guaranteed order of execution. [[docker-project]] -=== Docker Project += Docker Project We're publishing a `springcloud/spring-cloud-contract` Docker image that contains a project that will generate tests and execute them in `EXPLICIT` mode @@ -1021,7 +628,7 @@ against a running application. TIP: The `EXPLICIT` mode means that the tests generated from contracts will send real requests and not the mocked ones. -==== Short intro to Maven, JARs and Binary storage +== Short intro to Maven, JARs and Binary storage Since the Docker image can be used by non JVM projects, it's good to explain the basic terms behind Spring Cloud Contract packaging defaults. @@ -1061,7 +668,7 @@ and for Docker those would be Docker images. You can store those artifacts in a manager. Examples of such managers can be https://jfrog.com/artifactory/[Artifactory] or https://www.sonatype.org/nexus/[Nexus]. -==== How it works +== How it works The image searches for contracts under the `/contracts` folder. The output from running the tests will be available under @@ -1076,7 +683,7 @@ It's enough for you to mount your contracts, pass the environment variables - generate the https://github.com/tomakehurst/wiremock[WireMock] stubs - (optional - turned on by default) publish the stubs to a Artifact Manager -===== Environment Variables +=== Environment Variables The Docker image requires some environment variables to point to your running application, to the Artifact manager instance etc. @@ -1121,7 +728,7 @@ will not work) - `APPLICATION_USERNAME` - (optional) username for basic authentication to your application - `APPLICATION_PASSWORD` - (optional) password for basic authentication to your application -==== Example of usage +== Example of usage Let's take a look at a simple MVC application @@ -1133,7 +740,7 @@ $ cd bookstore The contracts are available under `/contracts` folder. [[docker-server-side]] -==== Server side (nodejs) +== Server side (nodejs) Since we want to run tests, we could just execute: diff --git a/docs/src/main/asciidoc/migrations.adoc b/docs/src/main/asciidoc/migrations.adoc deleted file mode 100644 index b4c8954058..0000000000 --- a/docs/src/main/asciidoc/migrations.adoc +++ /dev/null @@ -1,180 +0,0 @@ -:core_path: ../../../.. -:doc_samples: {core_path}/samples/wiremock-jetty -:wiremock_tests: {core_path}/spring-cloud-contract-wiremock - -== Migrations - -TIP: For up to date migration guides please visit -the project's https://github.com/spring-cloud/spring-cloud-contract/wiki/[wiki page]. - -This section covers migrating from one version of Spring Cloud Contract Verifier to the -next version. It covers the following versions upgrade paths: - -[[cloud-verifier-1.0-1.1]] -=== 1.0.x -> 1.1.x - -This section covers upgrading from version 1.0 to version 1.1. - -==== New structure of generated stubs - -In `1.1.x` we have introduced a change to the structure of generated stubs. If you have -been using the `@AutoConfigureWireMock` notation to use the stubs from the classpath, -it no longer works. The following example shows how the `@AutoConfigureWireMock` notation -used to work: - -[source,java] ----- -@AutoConfigureWireMock(stubs = "classpath:/customer-stubs/mappings", port = 8084) ----- - -You must either change the location of the stubs to: -`classpath:.../META-INF/groupId/artifactId/version/mappings` or use the new -classpath-based `@AutoConfigureStubRunner`, as shown in the following example: - -[source,java] ----- -@AutoConfigureWireMock(stubs = "classpath:customer-stubs/META-INF/travel.components/customer-contract/1.0.2-SNAPSHOT/mappings/", port = 8084) ----- - -If you do not want to use `@AutoConfigureStubRunner` and you want to remain with the old -structure, set your plugin tasks accordingly. The following example would work for the -structure presented in the previous snippet. - -[source,xml,indent=0,subs="verbatim,attributes",role="primary"] -.Maven ----- - - - - - true - - - - - - - - - org.apache.maven.plugins - maven-assembly-plugin - - - stub - prepare-package - - single - - false - - true - ${basedir}/src/assembly/stub.xml - - - - - - - - - - - - stubs - - jar - - false - - - ${project.build.directory}/snippets/stubs - customer-stubs/mappings - - **/* - - - - ${basedir}/src/test/resources/contracts - customer-stubs/contracts - - **/*.groovy - - - - - - ----- - -[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] -.Gradle ----- -task copyStubs(type: Copy, dependsOn: 'generateWireMockClientStubs') { -// Preserve directory structure from 1.0.X of spring-cloud-contract - from "${project.buildDir}/resources/main/customer-stubs/META-INF/${project.group}/${project.name}/${project.version}" - into "${project.buildDir}/resources/main/customer-stubs" -} ----- - -[[cloud-verifier-1.1-1.2]] -=== 1.1.x -> 1.2.x - -This section covers upgrading from version 1.1 to version 1.2. - -==== Custom `HttpServerStub` - -`HttpServerStub` includes a method that was not in version 1.1. The method is -`String registeredMappings()` If you have classes that implement `HttpServerStub`, you -now have to implement the `registeredMappings()` method. It should return a `String` -representing all mappings available in a single `HttpServerStub`. - -See https://github.com/spring-cloud/spring-cloud-contract/issues/355[issue 355] for more -detail. - -==== New packages for generated tests - -The flow for setting the generated tests package name will look like this: - -* Set `basePackageForTests` -* If `basePackageForTests` was not set, pick the package from `baseClassForTests` -* If `baseClassForTests` was not set, pick `packageWithBaseClasses` -* If nothing got set, pick the default value: -`org.springframework.cloud.contract.verifier.tests` - -See https://github.com/spring-cloud/spring-cloud-contract/issues/260[issue 260] for more -detail. - -==== New Methods in TemplateProcessor - -In order to add support for `fromRequest.path`, the following methods had to be added to the -`TemplateProcessor` interface: - -* `path()` -* `path(int index)` - -See https://github.com/spring-cloud/spring-cloud-contract/issues/388[issue 388] for more -detail. - -==== RestAssured 3.0 - -Rest Assured, used in the generated test classes, got bumped to `3.0`. If -you manually set versions of Spring Cloud Contract and the release train -you might see the following exception: - -[source,bash] ----- -Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:testCompile (default-testCompile) on project some-project: Compilation failure: Compilation failure: -[ERROR] /some/path/SomeClass.java:[4,39] package com.jayway.restassured.response does not exist ----- - -This exception will occur due to the fact that the tests got generated with -an old version of plugin and at test execution time you have an incompatible -version of the release train (and vice versa). - -Done via https://github.com/spring-cloud/spring-cloud-contract/issues/267[issue 267] - -[[cloud-verifier-1.2-2.0]] -=== 1.2.x -> 2.0.x \ No newline at end of file diff --git a/docs/src/main/asciidoc/spring-cloud-contract.adoc b/docs/src/main/asciidoc/spring-cloud-contract.adoc index a0b79b8813..5b78422ed6 100644 --- a/docs/src/main/asciidoc/spring-cloud-contract.adoc +++ b/docs/src/main/asciidoc/spring-cloud-contract.adoc @@ -17,15 +17,12 @@ Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer, Jay Bryant_ == Spring Cloud Contract You need confidence when pushing new features to a new application or service in a -distributed system. This project provides support for Consumer Driven Contracts and -service schemas in Spring applications (for both HTTP and message-based interactions), +distributed system. This project provides contract tests support for both HTTP and message-based interactions, covering a range of options for writing tests, publishing them as assets, and asserting that a contract is kept by producers and consumers. -include::spring-cloud-contract-verifier.adoc[] +include::_spring-cloud-contract-verifier.adoc[] -include::spring-cloud-wiremock.adoc[] +include::_spring-cloud-wiremock.adoc[] -include::migrations.adoc[] - -include::links.adoc[] +include::_links.adoc[] From 52c3e5d89dfdb259504900f6a905023811ffadd1 Mon Sep 17 00:00:00 2001 From: Marcin Grzejszczak Date: Tue, 16 Jul 2019 17:05:50 +0200 Subject: [PATCH 02/18] WIP --- README.adoc | 192 +++- docs/src/main/asciidoc/attributes.adoc | 25 + .../main/asciidoc/documentation-overview.adoc | 149 ++++ docs/src/main/asciidoc/getting-started.adoc | 821 ++++++++++++++++++ docs/src/main/asciidoc/index.htmladoc | 17 + docs/src/main/asciidoc/index.htmlpdfadoc | 14 + docs/src/main/asciidoc/index.htmlsingleadoc | 14 + docs/src/main/asciidoc/legal.adoc | 11 + docs/src/main/asciidoc/maven-project.adoc | 2 +- .../main/asciidoc/spring-cloud-contract.adoc | 29 +- 10 files changed, 1241 insertions(+), 33 deletions(-) create mode 100644 docs/src/main/asciidoc/attributes.adoc create mode 100644 docs/src/main/asciidoc/documentation-overview.adoc create mode 100644 docs/src/main/asciidoc/getting-started.adoc create mode 100644 docs/src/main/asciidoc/index.htmladoc create mode 100644 docs/src/main/asciidoc/index.htmlpdfadoc create mode 100644 docs/src/main/asciidoc/index.htmlsingleadoc create mode 100644 docs/src/main/asciidoc/legal.adoc mode change 100644 => 120000 docs/src/main/asciidoc/spring-cloud-contract.adoc diff --git a/README.adoc b/README.adoc index 78c55fab50..3bc6dfc1bc 100644 --- a/README.adoc +++ b/README.adoc @@ -243,7 +243,9 @@ Stub Runner` properties, as shown in the following example: + [source,yaml,indent=0] ---- -Unresolved directive in _verifier_how_it_works.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] +stubrunner: + ids: 'com.example:http-server-dsl:+:stubs:8080' + repositoryRoot: https://repo.spring.io/libs-snapshot ---- Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, @@ -550,7 +552,9 @@ Runner` properties, as shown in the following example: + [source,yaml,indent=0] ---- -Unresolved directive in _verifier_how_it_works.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] +stubrunner: + ids: 'com.example:http-server-dsl:+:stubs:8080' + repositoryRoot: https://repo.spring.io/libs-snapshot ---- Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, @@ -1079,7 +1083,9 @@ achieving the same thing by changing the properties. [source,yaml,indent=0] ---- -Unresolved directive in _verifier_how_it_works.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] +stubrunner: + ids: 'com.example:http-server-dsl:+:stubs:8080' + repositoryRoot: https://repo.spring.io/libs-snapshot ---- That's it! @@ -1559,7 +1565,185 @@ You can read more about Spring Cloud Contract Verifier by reading the == Contributing -Unresolved directive in README.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/contributing.adoc[] +:spring-cloud-build-branch: master + +Spring Cloud is released under the non-restrictive Apache 2.0 license, +and follows a very standard Github development process, using Github +tracker for issues and merging pull requests into master. If you want +to contribute even something trivial please do not hesitate, but +follow the guidelines below. + +=== Sign the Contributor License Agreement +Before we accept a non-trivial patch or pull request we will need you to sign the +https://cla.pivotal.io/sign/spring[Contributor License Agreement]. +Signing the contributor's agreement does not grant anyone commit rights to the main +repository, but it does mean that we can accept your contributions, and you will get an +author credit if we do. Active contributors might be asked to join the core team, and +given the ability to merge pull requests. + +=== Code of Conduct +This project adheres to the Contributor Covenant https://github.com/spring-cloud/spring-cloud-build/blob/master/docs/src/main/asciidoc/code-of-conduct.adoc[code of +conduct]. By participating, you are expected to uphold this code. Please report +unacceptable behavior to spring-code-of-conduct@pivotal.io. + +=== Code Conventions and Housekeeping +None of these is essential for a pull request, but they will all help. They can also be +added after the original pull request but before a merge. + +* Use the Spring Framework code format conventions. If you use Eclipse + you can import formatter settings using the + `eclipse-code-formatter.xml` file from the + https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-dependencies-parent/eclipse-code-formatter.xml[Spring + Cloud Build] project. If using IntelliJ, you can use the + https://plugins.jetbrains.com/plugin/6546[Eclipse Code Formatter + Plugin] to import the same file. +* Make sure all new `.java` files to have a simple Javadoc class comment with at least an + `@author` tag identifying you, and preferably at least a paragraph on what the class is + for. +* Add the ASF license header comment to all new `.java` files (copy from existing files + in the project) +* Add yourself as an `@author` to the .java files that you modify substantially (more + than cosmetic changes). +* Add some Javadocs and, if you change the namespace, some XSD doc elements. +* A few unit tests would help a lot as well -- someone has to do it. +* If no-one else is using your branch, please rebase it against the current master (or + other target branch in the main project). +* When writing a commit message please follow https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html[these conventions], + if you are fixing an existing issue please add `Fixes gh-XXXX` at the end of the commit + message (where XXXX is the issue number). + +=== Checkstyle + +Spring Cloud Build comes with a set of checkstyle rules. You can find them in the `spring-cloud-build-tools` module. The most notable files under the module are: + +.spring-cloud-build-tools/ +---- +└── src +    ├── checkstyle +    │   └── checkstyle-suppressions.xml <3> +    └── main +    └── resources +    ├── checkstyle-header.txt <2> +    └── checkstyle.xml <1> +---- +<1> Default Checkstyle rules +<2> File header setup +<3> Default suppression rules + +==== Checkstyle configuration + +Checkstyle rules are *disabled by default*. To add checkstyle to your project just define the following properties and plugins. + +.pom.xml +---- + +true <1> + true + <2> + true + <3> + + + + + <4> + io.spring.javaformat + spring-javaformat-maven-plugin + + <5> + org.apache.maven.plugins + maven-checkstyle-plugin + + + + + + <5> + org.apache.maven.plugins + maven-checkstyle-plugin + + + + +---- +<1> Fails the build upon Checkstyle errors +<2> Fails the build upon Checkstyle violations +<3> Checkstyle analyzes also the test sources +<4> Add the Spring Java Format plugin that will reformat your code to pass most of the Checkstyle formatting rules +<5> Add checkstyle plugin to your build and reporting phases + +If you need to suppress some rules (e.g. line length needs to be longer), then it's enough for you to define a file under `${project.root}/src/checkstyle/checkstyle-suppressions.xml` with your suppressions. Example: + +.projectRoot/src/checkstyle/checkstyle-suppresions.xml +---- + + + + + + +---- + +It's advisable to copy the `${spring-cloud-build.rootFolder}/.editorconfig` and `${spring-cloud-build.rootFolder}/.springformat` to your project. That way, some default formatting rules will be applied. You can do so by running this script: + +```bash +$ curl https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/.editorconfig -o .editorconfig +$ touch .springformat +``` + +=== IDE setup + +==== Intellij IDEA + +In order to setup Intellij you should import our coding conventions, inspection profiles and set up the checkstyle plugin. +The following files can be found in the https://github.com/spring-cloud/spring-cloud-build/tree/master/spring-cloud-build-tools[Spring Cloud Build] project. + +.spring-cloud-build-tools/ +---- +└── src +    ├── checkstyle +    │   └── checkstyle-suppressions.xml <3> +    └── main +    └── resources +    ├── checkstyle-header.txt <2> +    ├── checkstyle.xml <1> +    └── intellij +       ├── Intellij_Project_Defaults.xml <4> +       └── Intellij_Spring_Boot_Java_Conventions.xml <5> +---- +<1> Default Checkstyle rules +<2> File header setup +<3> Default suppression rules +<4> Project defaults for Intellij that apply most of Checkstyle rules +<5> Project style conventions for Intellij that apply most of Checkstyle rules + +.Code style + +image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-code-style.png[Code style] + +Go to `File` -> `Settings` -> `Editor` -> `Code style`. There click on the icon next to the `Scheme` section. There, click on the `Import Scheme` value and pick the `Intellij IDEA code style XML` option. Import the `spring-cloud-build-tools/src/main/resources/intellij/Intellij_Spring_Boot_Java_Conventions.xml` file. + +.Inspection profiles + +image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-inspections.png[Code style] + +Go to `File` -> `Settings` -> `Editor` -> `Inspections`. There click on the icon next to the `Profile` section. There, click on the `Import Profile` and import the `spring-cloud-build-tools/src/main/resources/intellij/Intellij_Project_Defaults.xml` file. + +.Checkstyle + +To have Intellij work with Checkstyle, you have to install the `Checkstyle` plugin. It's advisable to also install the `Assertions2Assertj` to automatically convert the JUnit assertions + +image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-checkstyle.png[Checkstyle] + +Go to `File` -> `Settings` -> `Other settings` -> `Checkstyle`. There click on the `+` icon in the `Configuration file` section. There, you'll have to define where the checkstyle rules should be picked from. In the image above, we've picked the rules from the cloned Spring Cloud Build repository. However, you can point to the Spring Cloud Build's GitHub repository (e.g. for the `checkstyle.xml` : `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle.xml`). We need to provide the following variables: + +- `checkstyle.header.file` - please point it to the Spring Cloud Build's, `spring-cloud-build-tools/src/main/resources/checkstyle/checkstyle-header.txt` file either in your cloned repo or via the `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle-header.txt` URL. +- `checkstyle.suppressions.file` - default suppressions. Please point it to the Spring Cloud Build's, `spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` file either in your cloned repo or via the `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` URL. +- `checkstyle.additional.suppressions.file` - this variable corresponds to suppressions in your local project. E.g. you're working on `spring-cloud-contract`. Then point to the `project-root/src/checkstyle/checkstyle-suppressions.xml` folder. Example for `spring-cloud-contract` would be: `/home/username/spring-cloud-contract/src/checkstyle/checkstyle-suppressions.xml`. + +IMPORTANT: Remember to set the `Scan Scope` to `All sources` since we apply checkstyle rules for production and test sources. == How to build it diff --git a/docs/src/main/asciidoc/attributes.adoc b/docs/src/main/asciidoc/attributes.adoc new file mode 100644 index 0000000000..06f822c0e8 --- /dev/null +++ b/docs/src/main/asciidoc/attributes.adoc @@ -0,0 +1,25 @@ +:doctype: book +:idprefix: +:idseparator: - +:toc: left +:toclevels: 4 +:tabsize: 4 +:numbered: +:sectanchors: +:sectnums: +:icons: font +:hide-uri-scheme: +:docinfo: shared,private + +:spring-cloud-contract-repo: snapshot +:github-tag: master +:spring-cloud-contract-docs-version: current +:spring-cloud-contract-docs: https://docs.spring.io/spring-cloud-contract/docs/{spring-cloud-contract-docs-version}/reference +:spring-cloud-contract-docs-current: https://docs.spring.io/spring-cloud-contract/docs/current/reference +:github-repo: spring-cloud/spring-cloud-contract +:github-raw: https://raw.github.com/{github-repo}/{github-tag} +:github-code: https://github.com/{github-repo}/tree/{github-tag} +:github-issues: https://github.com/{github-repo}/issues/ +:github-wiki: https://github.com/{github-repo}/wiki +:github-master-code: https://github.com/{github-repo}/tree/master +:sc-ext: java \ No newline at end of file diff --git a/docs/src/main/asciidoc/documentation-overview.adoc b/docs/src/main/asciidoc/documentation-overview.adoc new file mode 100644 index 0000000000..3540dc502f --- /dev/null +++ b/docs/src/main/asciidoc/documentation-overview.adoc @@ -0,0 +1,149 @@ +[[contract-documentation]] += Spring Cloud Contract Documentation +include::attributes.adoc[] + +This section provides a brief overview of Spring Cloud Contract reference documentation. It serves +as a map for the rest of the document. + + + +[[contract-documentation-about]] +== About the Documentation +The Spring Cloud Contract reference guide is available as + +* {spring-cloud-contract-docs}/html[Multi-page HTML] +* {spring-cloud-contract-docs}/htmlsingle[Single page HTML] +* {spring-cloud-contract-docs}/pdf/spring-cloud-contract-reference.pdf[PDF] + +The latest copy is available at {spring-cloud-contract-docs-current}. + +Copies of this document may be made for your own use and for distribution to others, +provided that you do not charge any fee for such copies and further provided that each +copy contains this Copyright Notice, whether distributed in print or electronically. + + + +[[contract-documentation-getting-help]] +== Getting Help +If you have trouble with Spring Cloud Contract, we would like to help. + +* Try the <>. They provide solutions to the most +common questions. +* Learn the Spring Cloud Contract basics. If you are +starting out with Spring Cloud Contract, try one of the https://spring.io/guides[guides]. +* Ask a question. We monitor https://stackoverflow.com[stackoverflow.com] for questions +tagged with https://stackoverflow.com/tags/spring-cloud-contract[`spring-cloud-contract`]. +* Report bugs with Spring Cloud Contract at https://github.com/spring-cloud/spring-cloud-contract/issues. + +NOTE: All of Spring Cloud Contract is open source, including the documentation. If you find +problems with the docs or if you want to improve them, please {github-code}[get +involved]. + + + +[[contract-documentation-first-steps]] +== First Steps +If you are getting started with Spring Cloud Contract or 'Spring' in general, start with +<>: + +* *From scratch:* +<> | +<> | +<> +* *Tutorial:* +<> | +<> +* *Running your example:* +<> | +<> + + + +== Working with Spring Cloud Contract +Ready to actually start using Spring Cloud Contract? <>: + +* *Build systems:* +<> | +<> | +<> | +<> +* *Best practices:* +<> | +<> | +<> | +<> +* *Running your code:* +<> | +<> | +<> | +<> +* *Packaging your app:* +<> +* *Spring Cloud Contract CLI:* +<> + + + +== Learning about Spring Cloud Contract Features +Need more details about Spring Cloud Contract's core features? +<>: + +* *Core Features:* +<> | +<> | +<> | +<> +* *Web Applications:* +<> | +<> +* *Working with data:* +<> | +<> +* *Messaging:* +<> | +<> +* *Testing:* +<> | +<> | +<> +* *Extending:* +<> | +<> + + + +== Moving to Production +When you are ready to push your Spring Cloud Contract application to production, we have +<> that you might like: + +* *Management endpoints:* +<> | +<> +* *Connection options:* +<> | +<> +* *Monitoring:* +<> | +<> | +<> | +<> + + + +== Advanced Topics +Finally, we have a few topics for more advanced users: + +* *Spring Cloud Contract Applications Deployment:* +<> | +<> +* *Build tool plugins:* +<> | +<> +* *Appendix:* +<> | +<> | +<> + diff --git a/docs/src/main/asciidoc/getting-started.adoc b/docs/src/main/asciidoc/getting-started.adoc new file mode 100644 index 0000000000..48c6d2fe56 --- /dev/null +++ b/docs/src/main/asciidoc/getting-started.adoc @@ -0,0 +1,821 @@ +[[getting-started]] += Getting Started +include::attributes.adoc[] + +If you are getting started with Spring Boot, or "`Spring`" in general, start by reading +this section. It answers the basic "`what?`", "`how?`" and "`why?`" questions. It +includes an introduction to Spring Boot, along with installation instructions. We then +walk you through building your first Spring Boot application, discussing some core +principles as we go. + + + +[[getting-started-introducing-spring-boot]] +== Introducing Spring Boot +Spring Boot makes it easy to create stand-alone, production-grade Spring-based +Applications that you can run. We take an opinionated view of the Spring platform and +third-party libraries, so that you can get started with minimum fuss. Most Spring Boot +applications need very little Spring configuration. + +You can use Spring Boot to create Java applications that can be started by using +`java -jar` or more traditional war deployments. We also provide a command line tool that +runs "`spring scripts`". + +Our primary goals are: + +* Provide a radically faster and widely accessible getting-started experience for all +Spring development. +* Be opinionated out of the box but get out of the way quickly as requirements start to +diverge from the defaults. +* Provide a range of non-functional features that are common to large classes of projects +(such as embedded servers, security, metrics, health checks, and externalized +configuration). +* Absolutely no code generation and no requirement for XML configuration. + + + +[[getting-started-system-requirements]] +== System Requirements +Spring Boot {spring-boot-version} requires https://www.java.com[Java 8] and is compatible +up to Java 12 (included). {spring-reference}[Spring Framework {spring-framework-version}] +or above is also required. + +Explicit build support is provided for the following build tools: + +|=== +|Build Tool |Version + +|Maven +|3.3+ + +|Gradle +|5.x (4.10 is also supported but in a deprecated form) +|=== + + + +[[getting-started-system-requirements-servlet-containers]] +=== Servlet Containers +Spring Boot supports the following embedded servlet containers: + +|=== +|Name |Servlet Version + +|Tomcat 9.0 +|4.0 + +|Jetty 9.4 +|3.1 + +|Undertow 2.0 +|4.0 +|=== + +You can also deploy Spring Boot applications to any Servlet 3.1+ compatible container. + + + +[[getting-started-installing-spring-boot]] +== Installing Spring Boot +Spring Boot can be used with "`classic`" Java development tools or installed as a command +line tool. Either way, you need https://www.java.com[Java SDK v1.8] or higher. Before you +begin, you should check your current Java installation by using the following command: + +[indent=0] +---- + $ java -version +---- + +If you are new to Java development or if you want to experiment with Spring Boot, you +might want to try the <> (Command +Line Interface) first. Otherwise, read on for "`classic`" installation instructions. + + + +[[getting-started-installation-instructions-for-java]] +=== Installation Instructions for the Java Developer +You can use Spring Boot in the same way as any standard Java library. To do so, include +the appropriate `+spring-boot-*.jar+` files on your classpath. Spring Boot does not +require any special tools integration, so you can use any IDE or text editor. Also, there +is nothing special about a Spring Boot application, so you can run and debug a Spring +Boot application as you would any other Java program. + +Although you _could_ copy Spring Boot jars, we generally recommend that you use a build +tool that supports dependency management (such as Maven or Gradle). + + + +[[getting-started-maven-installation]] +==== Maven Installation +Spring Boot is compatible with Apache Maven 3.3 or above. If you do not already have +Maven installed, you can follow the instructions at https://maven.apache.org. + +TIP: On many operating systems, Maven can be installed with a package manager. If you use +OSX Homebrew, try `brew install maven`. Ubuntu users can run +`sudo apt-get install maven`. Windows users with https://chocolatey.org/[Chocolatey] can +run `choco install maven` from an elevated (administrator) prompt. + +Spring Boot dependencies use the `org.springframework.boot` `groupId`. Typically, your +Maven POM file inherits from the `spring-boot-starter-parent` project and declares +dependencies to one or more <>. +Spring Boot also provides an optional +<> to create +executable jars. + +The following listing shows a typical `pom.xml` file: + +[source,xml,indent=0,subs="verbatim,quotes,attributes"] +---- + + + 4.0.0 + + com.example + myproject + 0.0.1-SNAPSHOT + + + + org.springframework.boot + spring-boot-starter-parent + {spring-boot-version} + + + + + + org.springframework.boot + spring-boot-starter-web + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + +ifeval::["{spring-boot-repo}" != "release"] + + + + + spring-snapshots + https://repo.spring.io/snapshot + true + + + spring-milestones + https://repo.spring.io/milestone + + + + + spring-snapshots + https://repo.spring.io/snapshot + + + spring-milestones + https://repo.spring.io/milestone + + +endif::[] + +---- + +TIP: The `spring-boot-starter-parent` is a great way to use Spring Boot, but it might not +be suitable all of the time. Sometimes you may need to inherit from a different parent +POM, or you might not like our default settings. In those cases, see +<> for an alternative solution that uses an `import` +scope. + + + +[[getting-started-gradle-installation]] +==== Gradle Installation +Spring Boot is compatible with 5.x. 4.10 is also supported but this support is deprecated +and will be removed in a future release. If you do not already have Gradle installed, you +can follow the instructions at https://gradle.org. + +Spring Boot dependencies can be declared by using the `org.springframework.boot` `group`. +Typically, your project declares dependencies to one or more +<>. Spring Boot +provides a useful <> that can be used to simplify dependency declarations and to create executable +jars. + +.Gradle Wrapper +**** +The Gradle Wrapper provides a nice way of "`obtaining`" Gradle when you need to build a +project. It is a small script and library that you commit alongside your code to +bootstrap the build process. See {gradle-user-guide}/gradle_wrapper.html for details. +**** + +More details on getting started with Spring Boot and Gradle can be found in the +{spring-boot-gradle-plugin-reference}/#getting-started[Getting Started section] of the +Gradle plugin's reference guide. + + + +[[getting-started-installing-the-cli]] +=== Installing the Spring Boot CLI +The Spring Boot CLI (Command Line Interface) is a command line tool that you can use to +quickly prototype with Spring. It lets you run http://groovy-lang.org/[Groovy] scripts, +which means that you have a familiar Java-like syntax without so much boilerplate code. + +You do not need to use the CLI to work with Spring Boot, but it is definitely the +quickest way to get a Spring application off the ground. + + + +[[getting-started-manual-cli-installation]] +==== Manual Installation +You can download the Spring CLI distribution from the Spring software repository: + +* https://repo.spring.io/{spring-boot-repo}/org/springframework/boot/spring-boot-cli/{spring-boot-version}/spring-boot-cli-{spring-boot-version}-bin.zip[spring-boot-cli-{spring-boot-version}-bin.zip] +* https://repo.spring.io/{spring-boot-repo}/org/springframework/boot/spring-boot-cli/{spring-boot-version}/spring-boot-cli-{spring-boot-version}-bin.tar.gz[spring-boot-cli-{spring-boot-version}-bin.tar.gz] + +Cutting edge +https://repo.spring.io/snapshot/org/springframework/boot/spring-boot-cli/[snapshot +distributions] are also available. + +Once downloaded, follow the +{github-raw}/spring-boot-project/spring-boot-cli/src/main/content/INSTALL.txt[INSTALL.txt] +instructions from the unpacked archive. In summary, there is a `spring` script +(`spring.bat` for Windows) in a `bin/` directory in the `.zip` file. Alternatively, you +can use `java -jar` with the `.jar` file (the script helps you to be sure that the +classpath is set correctly). + + + +[[getting-started-sdkman-cli-installation]] +==== Installation with SDKMAN! +SDKMAN! (The Software Development Kit Manager) can be used for managing multiple versions +of various binary SDKs, including Groovy and the Spring Boot CLI. +Get SDKMAN! from https://sdkman.io and install Spring Boot by using the following +commands: + +[indent=0,subs="verbatim,quotes,attributes"] +---- + $ sdk install springboot + $ spring --version + Spring Boot v{spring-boot-version} +---- + +If you develop features for the CLI and want easy access to the version you built, +use the following commands: + +[indent=0,subs="verbatim,quotes,attributes"] +---- + $ sdk install springboot dev /path/to/spring-boot/spring-boot-cli/target/spring-boot-cli-{spring-boot-version}-bin/spring-{spring-boot-version}/ + $ sdk default springboot dev + $ spring --version + Spring CLI v{spring-boot-version} +---- + +The preceding instructions install a local instance of `spring` called the `dev` +instance. It points at your target build location, so every time you rebuild Spring Boot, +`spring` is up-to-date. + +You can see it by running the following command: + +[indent=0,subs="verbatim,quotes,attributes"] +---- + $ sdk ls springboot + + ================================================================================ + Available Springboot Versions + ================================================================================ + > + dev + * {spring-boot-version} + + ================================================================================ + + - local version + * - installed + > - currently in use + ================================================================================ +---- + + + +[[getting-started-homebrew-cli-installation]] +==== OSX Homebrew Installation +If you are on a Mac and use https://brew.sh/[Homebrew], you can install the Spring Boot +CLI by using the following commands: + +[indent=0] +---- + $ brew tap pivotal/tap + $ brew install springboot +---- + +Homebrew installs `spring` to `/usr/local/bin`. + +NOTE: If you do not see the formula, your installation of brew might be out-of-date. In +that case, run `brew update` and try again. + + + +[[getting-started-macports-cli-installation]] +==== MacPorts Installation +If you are on a Mac and use https://www.macports.org/[MacPorts], you can install the +Spring Boot CLI by using the following command: + +[indent=0] +---- + $ sudo port install spring-boot-cli +---- + + + +[[getting-started-cli-command-line-completion]] +==== Command-line Completion +The Spring Boot CLI includes scripts that provide command completion for the +https://en.wikipedia.org/wiki/Bash_%28Unix_shell%29[BASH] and +https://en.wikipedia.org/wiki/Z_shell[zsh] shells. You can `source` the script (also named +`spring`) in any shell or put it in your personal or system-wide bash completion +initialization. On a Debian system, the system-wide scripts are in +`/shell-completion/bash` and all scripts in that directory are executed when a new shell +starts. For example, to run the script manually if you have installed by using SDKMAN!, +use the following commands: + +[indent=0] +---- + $ . ~/.sdkman/candidates/springboot/current/shell-completion/bash/spring + $ spring + grab help jar run test version +---- + +NOTE: If you install the Spring Boot CLI by using Homebrew or MacPorts, the command-line +completion scripts are automatically registered with your shell. + + + +[[getting-started-scoop-cli-installation]] +==== Windows Scoop Installation +If you are on a Windows and use https://scoop.sh/[Scoop], you can install the Spring Boot +CLI by using the following commands: + +[indent=0] +---- + > scoop bucket add extras + > scoop install springboot +---- + +Scoop installs `spring` to `~/scoop/apps/springboot/current/bin`. + +NOTE: If you do not see the app manifest, your installation of scoop might be out-of-date. +In that case, run `scoop update` and try again. + + + +[[getting-started-cli-example]] +==== Quick-start Spring CLI Example +You can use the following web application to test your installation. To start, create a +file called `app.groovy`, as follows: + +[source,groovy,indent=0,subs="verbatim,quotes,attributes"] +---- + @RestController + class ThisWillActuallyRun { + + @RequestMapping("/") + String home() { + "Hello World!" + } + + } +---- + +Then run it from a shell, as follows: + +[indent=0] +---- + $ spring run app.groovy +---- + +NOTE: The first run of your application is slow, as dependencies are downloaded. +Subsequent runs are much quicker. + +Open `http://localhost:8080` in your favorite web browser. You should see the following +output: + +[indent=0] +---- + Hello World! +---- + + + +[[getting-started-upgrading-from-an-earlier-version]] +=== Upgrading from an Earlier Version of Spring Boot +If you are upgrading from an earlier release of Spring Boot, check the +{github-wiki}/Spring-Boot-2.0-Migration-Guide["`migration guide`" on the project wiki] +that provides detailed upgrade instructions. Check also the +{github-wiki}["`release notes`"] for a list of "`new and noteworthy`" features for each +release. + +When upgrading to a new feature release, some properties may have been renamed or removed. +Spring Boot provides a way to analyze your application's environment and print diagnostics +at startup, but also temporarily migrate properties at runtime for you. To enable that +feature, add the following dependency to your project: + +[source,xml,indent=0] +---- + + org.springframework.boot + spring-boot-properties-migrator + runtime + +---- + +WARNING: Properties that are added late to the environment, such as when using +`@PropertySource`, will not be taken into account. + +NOTE: Once you're done with the migration, please make sure to remove this module from +your project's dependencies. + +To upgrade an existing CLI installation, use the appropriate package manager command (for +example, `brew upgrade`) or, if you manually installed the CLI, follow the +<>, remembering to update +your `PATH` environment variable to remove any older references. + + + +[[getting-started-first-application]] +== Developing Your First Spring Boot Application +This section describes how to develop a simple "`Hello World!`" web application that +highlights some of Spring Boot's key features. We use Maven to build this project, since +most IDEs support it. + +[TIP] +==== +The https://spring.io[spring.io] web site contains many "`Getting Started`" +https://spring.io/guides[guides] that use Spring Boot. If you need to solve a specific +problem, check there first. + +You can shortcut the steps below by going to https://start.spring.io and choosing the +"Web" starter from the dependencies searcher. Doing so generates a new project structure +so that you can <>. Check +the {spring-initializr-reference}/#user-guide[Spring Initializr documentation] for more +details. +==== + +Before we begin, open a terminal and run the following commands to ensure that you have +valid versions of Java and Maven installed: + +[indent=0] +---- + $ java -version + java version "1.8.0_102" + Java(TM) SE Runtime Environment (build 1.8.0_102-b14) + Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode) +---- + +[indent=0] +---- + $ mvn -v + Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-17T14:33:14-04:00) + Maven home: /usr/local/Cellar/maven/3.3.9/libexec + Java version: 1.8.0_102, vendor: Oracle Corporation +---- + +NOTE: This sample needs to be created in its own folder. Subsequent instructions assume +that you have created a suitable folder and that it is your current directory. + + + +[[getting-started-first-application-pom]] +=== Creating the POM +We need to start by creating a Maven `pom.xml` file. The `pom.xml` is the recipe that is +used to build your project. Open your favorite text editor and add the following: + +[source,xml,indent=0,subs="verbatim,quotes,attributes"] +---- + + + 4.0.0 + + com.example + myproject + 0.0.1-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + {spring-boot-version} + + + + +ifeval::["{spring-boot-repo}" != "release"] + + + + spring-snapshots + https://repo.spring.io/snapshot + true + + + spring-milestones + https://repo.spring.io/milestone + + + + + spring-snapshots + https://repo.spring.io/snapshot + + + spring-milestones + https://repo.spring.io/milestone + + +endif::[] + +---- + +The preceding listing should give you a working build. You can test it by running `mvn +package` (for now, you can ignore the "`jar will be empty - no content was marked for +inclusion!`" warning). + +NOTE: At this point, you could import the project into an IDE (most modern Java IDEs +include built-in support for Maven). For simplicity, we continue to use a plain text +editor for this example. + + + +[[getting-started-first-application-dependencies]] +=== Adding Classpath Dependencies +Spring Boot provides a number of "`Starters`" that let you add jars to your classpath. +Our applications for smoke tests use the `spring-boot-starter-parent` in the `parent` +section of the POM. The `spring-boot-starter-parent` is a special starter that provides +useful Maven defaults. It also provides a +<> +section so that you can omit `version` tags for "`blessed`" dependencies. + +Other "`Starters`" provide dependencies that you are likely to need when developing a +specific type of application. Since we are developing a web application, we add a +`spring-boot-starter-web` dependency. Before that, we can look at what we currently have +by running the following command: + +[indent=0] +---- + $ mvn dependency:tree + + [INFO] com.example:myproject:jar:0.0.1-SNAPSHOT +---- + +The `mvn dependency:tree` command prints a tree representation of your project +dependencies. You can see that `spring-boot-starter-parent` provides no dependencies by +itself. To add the necessary dependencies, edit your `pom.xml` and add the +`spring-boot-starter-web` dependency immediately below the `parent` section: + +[source,xml,indent=0,subs="verbatim,quotes,attributes"] +---- + + + org.springframework.boot + spring-boot-starter-web + + +---- + +If you run `mvn dependency:tree` again, you see that there are now a number of additional +dependencies, including the Tomcat web server and Spring Boot itself. + + + +[[getting-started-first-application-code]] +=== Writing the Code +To finish our application, we need to create a single Java file. By default, Maven +compiles sources from `src/main/java`, so you need to create that folder structure and +then add a file named `src/main/java/Example.java` to contain the following code: + +[source,java,indent=0] +---- + import org.springframework.boot.*; + import org.springframework.boot.autoconfigure.*; + import org.springframework.web.bind.annotation.*; + + @RestController + @EnableAutoConfiguration + public class Example { + + @RequestMapping("/") + String home() { + return "Hello World!"; + } + + public static void main(String[] args) { + SpringApplication.run(Example.class, args); + } + + } +---- + +Although there is not much code here, quite a lot is going on. We step through the +important parts in the next few sections. + + + +[[getting-started-first-application-annotations]] +==== The `@RestController` and `@RequestMapping` Annotations +The first annotation on our `Example` class is `@RestController`. This is known as a +_stereotype_ annotation. It provides hints for people reading the code and for Spring +that the class plays a specific role. In this case, our class is a web `@Controller`, so +Spring considers it when handling incoming web requests. + +The `@RequestMapping` annotation provides "`routing`" information. It tells Spring that +any HTTP request with the `/` path should be mapped to the `home` method. The +`@RestController` annotation tells Spring to render the resulting string directly back to +the caller. + +TIP: The `@RestController` and `@RequestMapping` annotations are Spring MVC annotations. +(They are not specific to Spring Boot.) See the {spring-reference}web.html#mvc[MVC +section] in the Spring Reference Documentation for more details. + + + +[[getting-started-first-application-auto-configuration]] +==== The @EnableAutoConfiguration Annotation +The second class-level annotation is `@EnableAutoConfiguration`. This annotation tells +Spring Boot to "`guess`" how you want to configure Spring, based on the jar dependencies +that you have added. Since `spring-boot-starter-web` added Tomcat and Spring MVC, the +auto-configuration assumes that you are developing a web application and sets up Spring +accordingly. + +.Starters and Auto-configuration +**** +Auto-configuration is designed to work well with "`Starters`", but the two concepts are +not directly tied. You are free to pick and choose jar dependencies outside of the +starters. Spring Boot still does its best to auto-configure your application. +**** + + + +[[getting-started-first-application-main-method]] +==== The "`main`" Method +The final part of our application is the `main` method. This is just a standard method +that follows the Java convention for an application entry point. Our main method +delegates to Spring Boot's `SpringApplication` class by calling `run`. +`SpringApplication` bootstraps our application, starting Spring, which, in turn, starts +the auto-configured Tomcat web server. We need to pass `Example.class` as an argument to +the `run` method to tell `SpringApplication` which is the primary Spring component. The +`args` array is also passed through to expose any command-line arguments. + + + +[[getting-started-first-application-run]] +=== Running the Example +At this point, your application should work. Since you used the +`spring-boot-starter-parent` POM, you have a useful `run` goal that you can use to start +the application. Type `mvn spring-boot:run` from the root project directory to start the +application. You should see output similar to the following: + +[indent=0,subs="attributes"] +---- + $ mvn spring-boot:run + + . ____ _ __ _ _ + /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ + ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ + \\/ ___)| |_)| | | | | || (_| | ) ) ) ) + ' |____| .__|_| |_|_| |_\__, | / / / / + =========|_|==============|___/=/_/_/_/ + :: Spring Boot :: (v{spring-boot-version}) + ....... . . . + ....... . . . (log output here) + ....... . . . + ........ Started Example in 2.222 seconds (JVM running for 6.514) +---- + +If you open a web browser to `http://localhost:8080`, you should see the following output: + +[indent=0] +---- + Hello World! +---- + +To gracefully exit the application, press `ctrl-c`. + + + +[[getting-started-first-application-executable-jar]] +=== Creating an Executable Jar +We finish our example by creating a completely self-contained executable jar file that +we could run in production. Executable jars (sometimes called "`fat jars`") are archives +containing your compiled classes along with all of the jar dependencies that your code +needs to run. + +.Executable jars and Java +**** +Java does not provide a standard way to load nested jar files (jar files that are +themselves contained within a jar). This can be problematic if you are looking to +distribute a self-contained application. + +To solve this problem, many developers use "`uber`" jars. An uber jar packages all the +classes from all the application's dependencies into a single archive. The problem with +this approach is that it becomes hard to see which libraries are in your application. It +can also be problematic if the same filename is used (but with different content) in +multiple jars. + +Spring Boot takes a <> and lets you +actually nest jars directly. +**** + +To create an executable jar, we need to add the `spring-boot-maven-plugin` to our +`pom.xml`. To do so, insert the following lines just below the `dependencies` section: + +[source,xml,indent=0,subs="verbatim,quotes,attributes"] +---- + + + + org.springframework.boot + spring-boot-maven-plugin + + + +---- + +NOTE: The `spring-boot-starter-parent` POM includes `` configuration to bind +the `repackage` goal. If you do not use the parent POM, you need to declare this +configuration yourself. See the {spring-boot-maven-plugin-site}/usage.html[plugin +documentation] for details. + +Save your `pom.xml` and run `mvn package` from the command line, as follows: + +[indent=0,subs="attributes"] +---- + $ mvn package + + [INFO] Scanning for projects... + [INFO] + [INFO] ------------------------------------------------------------------------ + [INFO] Building myproject 0.0.1-SNAPSHOT + [INFO] ------------------------------------------------------------------------ + [INFO] .... .. + [INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ myproject --- + [INFO] Building jar: /Users/developer/example/spring-boot-example/target/myproject-0.0.1-SNAPSHOT.jar + [INFO] + [INFO] --- spring-boot-maven-plugin:{spring-boot-version}:repackage (default) @ myproject --- + [INFO] ------------------------------------------------------------------------ + [INFO] BUILD SUCCESS + [INFO] ------------------------------------------------------------------------ +---- + +If you look in the `target` directory, you should see `myproject-0.0.1-SNAPSHOT.jar`. The +file should be around 10 MB in size. If you want to peek inside, you can use `jar tvf`, +as follows: + +[indent=0] +---- + $ jar tvf target/myproject-0.0.1-SNAPSHOT.jar +---- + +You should also see a much smaller file named `myproject-0.0.1-SNAPSHOT.jar.original` in +the `target` directory. This is the original jar file that Maven created before it was +repackaged by Spring Boot. + +To run that application, use the `java -jar` command, as follows: + +[indent=0,subs="attributes"] +---- + $ java -jar target/myproject-0.0.1-SNAPSHOT.jar + + . ____ _ __ _ _ + /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ + ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ + \\/ ___)| |_)| | | | | || (_| | ) ) ) ) + ' |____| .__|_| |_|_| |_\__, | / / / / + =========|_|==============|___/=/_/_/_/ + :: Spring Boot :: (v{spring-boot-version}) + ....... . . . + ....... . . . (log output here) + ....... . . . + ........ Started Example in 2.536 seconds (JVM running for 2.864) +---- + +As before, to exit the application, press `ctrl-c`. + + + +[[getting-started-whats-next]] +== What to Read Next +Hopefully, this section provided some of the Spring Boot basics and got you on your way +to writing your own applications. If you are a task-oriented type of developer, you might +want to jump over to https://spring.io and check out some of the +https://spring.io/guides/[getting started] guides that solve specific "`How do I do that +with Spring?`" problems. We also have Spring Boot-specific +"`<>`" reference documentation. + +Otherwise, the next logical step is to read _<>_. If +you are really impatient, you could also jump ahead and read about +_<>_. diff --git a/docs/src/main/asciidoc/index.htmladoc b/docs/src/main/asciidoc/index.htmladoc new file mode 100644 index 0000000000..795c5a05af --- /dev/null +++ b/docs/src/main/asciidoc/index.htmladoc @@ -0,0 +1,17 @@ +[[spring-cloud-contract-reference-documentation]] += Spring Cloud Contract Reference Documentation +Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak, Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer, Jay Bryant +:docinfo: shared + +The reference documentation consists of the following sections: + +[horizontal] +<> :: Legal information. +<> :: About the Documentation, Getting Help, First Steps, and more. +<> :: Introducing Spring Cloud Contract, System Requirements, Developing Your First Spring Cloud Contract based Application +<> :: Build Systems, Structuring Your Code, Configuration, Spring Beans and Dependency Injection, and more. +<> :: Profiles, Logging, Security, Caching, Spring Integration, Testing, and more. +<> :: Monitoring, Metrics, Auditing, and more. +<> :: Maven Plugin, Gradle Plugin. +<> :: Application Development, Configuration, Embedded Servers, Data Access, and many more. +<> :: Properties, Metadata, Configuration, Dependencies, and more. diff --git a/docs/src/main/asciidoc/index.htmlpdfadoc b/docs/src/main/asciidoc/index.htmlpdfadoc new file mode 100644 index 0000000000..aaf35c5e0e --- /dev/null +++ b/docs/src/main/asciidoc/index.htmlpdfadoc @@ -0,0 +1,14 @@ +[[spring-cloud-contract-reference-documentation]] += Spring Cloud Contract Reference Documentation +Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak, Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer, Jay Bryant +:docinfo: shared +include::attributes.adoc[] + +include::legal.adoc[leveloffset=+1] +include::documentation-overview.adoc[leveloffset=+1] +include::getting-started.adoc[leveloffset=+1] +include::using-spring-cloud-contract.adoc[leveloffset=+1] +include::spring-cloud-contract-features.adoc[leveloffset=+1] +include::build-tool-plugins.adoc[leveloffset=+1] +include::howto.adoc[leveloffset=+1] +include::appendix.adoc[leveloffset=+1] \ No newline at end of file diff --git a/docs/src/main/asciidoc/index.htmlsingleadoc b/docs/src/main/asciidoc/index.htmlsingleadoc new file mode 100644 index 0000000000..aaf35c5e0e --- /dev/null +++ b/docs/src/main/asciidoc/index.htmlsingleadoc @@ -0,0 +1,14 @@ +[[spring-cloud-contract-reference-documentation]] += Spring Cloud Contract Reference Documentation +Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak, Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer, Jay Bryant +:docinfo: shared +include::attributes.adoc[] + +include::legal.adoc[leveloffset=+1] +include::documentation-overview.adoc[leveloffset=+1] +include::getting-started.adoc[leveloffset=+1] +include::using-spring-cloud-contract.adoc[leveloffset=+1] +include::spring-cloud-contract-features.adoc[leveloffset=+1] +include::build-tool-plugins.adoc[leveloffset=+1] +include::howto.adoc[leveloffset=+1] +include::appendix.adoc[leveloffset=+1] \ No newline at end of file diff --git a/docs/src/main/asciidoc/legal.adoc b/docs/src/main/asciidoc/legal.adoc new file mode 100644 index 0000000000..0f27c2bf5a --- /dev/null +++ b/docs/src/main/asciidoc/legal.adoc @@ -0,0 +1,11 @@ +[legal] += Legal + +{spring-cloud-contract-version} + +Copyright © 2012-2019 + +Copies of this document may be made for your own use and for distribution to +others, provided that you do not charge any fee for such copies and further +provided that each copy contains this Copyright Notice, whether distributed in +print or electronically. \ No newline at end of file diff --git a/docs/src/main/asciidoc/maven-project.adoc b/docs/src/main/asciidoc/maven-project.adoc index 2cb981a6e9..5b21e7c4ad 100644 --- a/docs/src/main/asciidoc/maven-project.adoc +++ b/docs/src/main/asciidoc/maven-project.adoc @@ -543,7 +543,7 @@ Surefire plugin setup, like in the following example: [source,xml,indent=0] ---- -include::{samples_url}/producer_with_spock/pom.xml[tags=pock-surefire-setup,indent=0] +include::{samples_url}/producer_with_spock/pom.xml[tags=spock-surefire-setup,indent=0] ---- = Stubs and Transitive Dependencies diff --git a/docs/src/main/asciidoc/spring-cloud-contract.adoc b/docs/src/main/asciidoc/spring-cloud-contract.adoc deleted file mode 100644 index 5b78422ed6..0000000000 --- a/docs/src/main/asciidoc/spring-cloud-contract.adoc +++ /dev/null @@ -1,28 +0,0 @@ -:toc: left -:toclevels: 3 -:nofooter: -:source-highlighter: prettify -:numbered: -:icons: font -:sectlinks: true -:branch: master - -= Spring Cloud Contract - -_Documentation Authors: Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak, -Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer, Jay Bryant_ - -{spring-cloud-version} - -== Spring Cloud Contract - -You need confidence when pushing new features to a new application or service in a -distributed system. This project provides contract tests support for both HTTP and message-based interactions, -covering a range of options for writing tests, publishing them as assets, and asserting -that a contract is kept by producers and consumers. - -include::_spring-cloud-contract-verifier.adoc[] - -include::_spring-cloud-wiremock.adoc[] - -include::_links.adoc[] diff --git a/docs/src/main/asciidoc/spring-cloud-contract.adoc b/docs/src/main/asciidoc/spring-cloud-contract.adoc new file mode 120000 index 0000000000..1abdb4fda5 --- /dev/null +++ b/docs/src/main/asciidoc/spring-cloud-contract.adoc @@ -0,0 +1 @@ +index.htmladoc \ No newline at end of file From a68ae38c89b6e91bc7f94b3fe23a711782a6e98a Mon Sep 17 00:00:00 2001 From: Marcin Grzejszczak Date: Thu, 18 Jul 2019 14:38:43 +0200 Subject: [PATCH 03/18] WIP --- docs/pom.xml | 4 + docs/src/main/asciidoc/_attributes.adoc | 15 + docs/src/main/asciidoc/attributes.adoc | 25 - .../main/asciidoc/documentation-overview.adoc | 110 +- docs/src/main/asciidoc/getting-started.adoc | 2 +- docs/src/main/asciidoc/index.htmlpdfadoc | 2 +- docs/src/main/asciidoc/index.htmlsingleadoc | 2 +- docs/src/main/asciidoc/legal.adoc | 2 +- docs/src/main/asciidoc/using.adoc | 1152 +++++++++++++++++ 9 files changed, 1229 insertions(+), 85 deletions(-) create mode 100644 docs/src/main/asciidoc/_attributes.adoc delete mode 100644 docs/src/main/asciidoc/attributes.adoc create mode 100644 docs/src/main/asciidoc/using.adoc diff --git a/docs/pom.xml b/docs/pom.xml index 99972b5f3f..5eeb1fc5bb 100644 --- a/docs/pom.xml +++ b/docs/pom.xml @@ -35,6 +35,10 @@ docs + + pl.project13.maven + git-commit-id-plugin + org.apache.maven.plugins maven-dependency-plugin diff --git a/docs/src/main/asciidoc/_attributes.adoc b/docs/src/main/asciidoc/_attributes.adoc new file mode 100644 index 0000000000..13bbf150e5 --- /dev/null +++ b/docs/src/main/asciidoc/_attributes.adoc @@ -0,0 +1,15 @@ +:doctype: book +:idprefix: +:idseparator: - +:toc: left +:toclevels: 4 +:tabsize: 4 +:numbered: +:sectanchors: +:sectnums: +:icons: font +:hide-uri-scheme: +:docinfo: shared,private + +:sc-ext: java +:project-full-name: Spring Cloud Contract \ No newline at end of file diff --git a/docs/src/main/asciidoc/attributes.adoc b/docs/src/main/asciidoc/attributes.adoc deleted file mode 100644 index 06f822c0e8..0000000000 --- a/docs/src/main/asciidoc/attributes.adoc +++ /dev/null @@ -1,25 +0,0 @@ -:doctype: book -:idprefix: -:idseparator: - -:toc: left -:toclevels: 4 -:tabsize: 4 -:numbered: -:sectanchors: -:sectnums: -:icons: font -:hide-uri-scheme: -:docinfo: shared,private - -:spring-cloud-contract-repo: snapshot -:github-tag: master -:spring-cloud-contract-docs-version: current -:spring-cloud-contract-docs: https://docs.spring.io/spring-cloud-contract/docs/{spring-cloud-contract-docs-version}/reference -:spring-cloud-contract-docs-current: https://docs.spring.io/spring-cloud-contract/docs/current/reference -:github-repo: spring-cloud/spring-cloud-contract -:github-raw: https://raw.github.com/{github-repo}/{github-tag} -:github-code: https://github.com/{github-repo}/tree/{github-tag} -:github-issues: https://github.com/{github-repo}/issues/ -:github-wiki: https://github.com/{github-repo}/wiki -:github-master-code: https://github.com/{github-repo}/tree/master -:sc-ext: java \ No newline at end of file diff --git a/docs/src/main/asciidoc/documentation-overview.adoc b/docs/src/main/asciidoc/documentation-overview.adoc index 3540dc502f..5457895431 100644 --- a/docs/src/main/asciidoc/documentation-overview.adoc +++ b/docs/src/main/asciidoc/documentation-overview.adoc @@ -1,21 +1,19 @@ -[[contract-documentation]] +[[documentation]] = Spring Cloud Contract Documentation -include::attributes.adoc[] +include::_attributes.adoc[] -This section provides a brief overview of Spring Cloud Contract reference documentation. It serves +This section provides a brief overview of {project-full-name} reference documentation. It serves as a map for the rest of the document. [[contract-documentation-about]] == About the Documentation -The Spring Cloud Contract reference guide is available as +The {project-full-name} reference guide is available as -* {spring-cloud-contract-docs}/html[Multi-page HTML] -* {spring-cloud-contract-docs}/htmlsingle[Single page HTML] -* {spring-cloud-contract-docs}/pdf/spring-cloud-contract-reference.pdf[PDF] - -The latest copy is available at {spring-cloud-contract-docs-current}. +* {docs-url}/html[Multi-page HTML] +* {docs-url}/htmlsingle[Single page HTML] +* {docs-url}/pdf/{project-name}.pdf[PDF] Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each @@ -23,19 +21,19 @@ copy contains this Copyright Notice, whether distributed in print or electronica -[[contract-documentation-getting-help]] +[[documentation-getting-help]] == Getting Help -If you have trouble with Spring Cloud Contract, we would like to help. +If you have trouble with {project-full-name}, we would like to help. * Try the <>. They provide solutions to the most common questions. -* Learn the Spring Cloud Contract basics. If you are -starting out with Spring Cloud Contract, try one of the https://spring.io/guides[guides]. +* Learn the {project-full-name} basics. If you are +starting out with {project-full-name}, try one of the https://spring.io/guides[guides]. * Ask a question. We monitor https://stackoverflow.com[stackoverflow.com] for questions -tagged with https://stackoverflow.com/tags/spring-cloud-contract[`spring-cloud-contract`]. -* Report bugs with Spring Cloud Contract at https://github.com/spring-cloud/spring-cloud-contract/issues. +tagged with https://stackoverflow.com/tags/{project-name}[`{project-name}`]. +* Report bugs with {project-full-name} at https://github.com/spring-cloud/{project-name}/issues. -NOTE: All of Spring Cloud Contract is open source, including the documentation. If you find +NOTE: All of {project-full-name} is open source, including the documentation. If you find problems with the docs or if you want to improve them, please {github-code}[get involved]. @@ -43,13 +41,13 @@ involved]. [[contract-documentation-first-steps]] == First Steps -If you are getting started with Spring Cloud Contract or 'Spring' in general, start with +If you are getting started with {project-full-name} or 'Spring' in general, start with <>: * *From scratch:* -<> | +<> | <> | -<> +<> * *Tutorial:* <> | <> @@ -59,64 +57,64 @@ If you are getting started with Spring Cloud Contract or 'Spring' in general, st -== Working with Spring Cloud Contract -Ready to actually start using Spring Cloud Contract? <>: * *Build systems:* -<> | -<> | -<> | -<> +<> | +<> | +<> | +<> * *Best practices:* -<> | -<> | -<> | -<> | +<> | +<> | +<> * *Running your code:* -<> | -<> | -<> | -<> +<> | +<> | +<> | +<> * *Packaging your app:* -<> -* *Spring Cloud Contract CLI:* -<> +<> +* *{project-full-name} CLI:* +<<{project-name}-cli.adoc#cli, Using the CLI>> -== Learning about Spring Cloud Contract Features -Need more details about Spring Cloud Contract's core features? -<>: +== Learning about {project-full-name} Features +Need more details about {project-full-name}'s core features? +<<{project-name}-features.adoc#contract-features, The following content is for you>>: * *Core Features:* -<> | -<> | -<> | -<> +<<{project-name}-features.adoc#contract-features-spring-application, SpringApplication>> | +<<{project-name}-features.adoc#contract-features-external-config, External Configuration>> | +<<{project-name}-features.adoc#contract-features-profiles, Profiles>> | +<<{project-name}-features.adoc#contract-features-logging, Logging>> * *Web Applications:* -<> | -<> +<<{project-name}-features.adoc#contract-features-spring-mvc, MVC>> | +<<{project-name}-features.adoc#contract-features-embedded-container, Embedded Containers>> * *Working with data:* -<> | -<> +<<{project-name}-features.adoc#contract-features-sql, SQL>> | +<<{project-name}-features.adoc#contract-features-nosql, NO-SQL>> * *Messaging:* -<> | -<> +<<{project-name}-features.adoc#contract-features-messaging, Overview>> | +<<{project-name}-features.adoc#contract-features-jms, JMS>> * *Testing:* -<> | -<> | +<<{project-name}-features.adoc#contract-features-testing-{project-name}-applications, Boot Applications>> | -<> +<<{project-name}-features.adoc#contract-features-test-utilities, Utils>> * *Extending:* -<> | -<> +<<{project-name}-features.adoc#contract-features-developing-auto-configuration, Auto-configuration>> | +<<{project-name}-features.adoc#contract-features-condition-annotations, @Conditions>> == Moving to Production -When you are ready to push your Spring Cloud Contract application to production, we have +When you are ready to push your {project-full-name} application to production, we have <> that you might like: * *Management endpoints:* @@ -136,7 +134,7 @@ When you are ready to push your Spring Cloud Contract application to production, == Advanced Topics Finally, we have a few topics for more advanced users: -* *Spring Cloud Contract Applications Deployment:* +* *{project-full-name} Applications Deployment:* <> | <> * *Build tool plugins:* diff --git a/docs/src/main/asciidoc/getting-started.adoc b/docs/src/main/asciidoc/getting-started.adoc index 48c6d2fe56..4dc56a7fc6 100644 --- a/docs/src/main/asciidoc/getting-started.adoc +++ b/docs/src/main/asciidoc/getting-started.adoc @@ -1,6 +1,6 @@ [[getting-started]] = Getting Started -include::attributes.adoc[] +include::_attributes.adoc[] If you are getting started with Spring Boot, or "`Spring`" in general, start by reading this section. It answers the basic "`what?`", "`how?`" and "`why?`" questions. It diff --git a/docs/src/main/asciidoc/index.htmlpdfadoc b/docs/src/main/asciidoc/index.htmlpdfadoc index aaf35c5e0e..7f92b081e8 100644 --- a/docs/src/main/asciidoc/index.htmlpdfadoc +++ b/docs/src/main/asciidoc/index.htmlpdfadoc @@ -2,7 +2,7 @@ = Spring Cloud Contract Reference Documentation Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak, Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer, Jay Bryant :docinfo: shared -include::attributes.adoc[] +include::_attributes.adoc[] include::legal.adoc[leveloffset=+1] include::documentation-overview.adoc[leveloffset=+1] diff --git a/docs/src/main/asciidoc/index.htmlsingleadoc b/docs/src/main/asciidoc/index.htmlsingleadoc index aaf35c5e0e..7f92b081e8 100644 --- a/docs/src/main/asciidoc/index.htmlsingleadoc +++ b/docs/src/main/asciidoc/index.htmlsingleadoc @@ -2,7 +2,7 @@ = Spring Cloud Contract Reference Documentation Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak, Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer, Jay Bryant :docinfo: shared -include::attributes.adoc[] +include::_attributes.adoc[] include::legal.adoc[leveloffset=+1] include::documentation-overview.adoc[leveloffset=+1] diff --git a/docs/src/main/asciidoc/legal.adoc b/docs/src/main/asciidoc/legal.adoc index 0f27c2bf5a..27a8a3c7f4 100644 --- a/docs/src/main/asciidoc/legal.adoc +++ b/docs/src/main/asciidoc/legal.adoc @@ -1,7 +1,7 @@ [legal] = Legal -{spring-cloud-contract-version} +{project-version} Copyright © 2012-2019 diff --git a/docs/src/main/asciidoc/using.adoc b/docs/src/main/asciidoc/using.adoc new file mode 100644 index 0000000000..113f1153c6 --- /dev/null +++ b/docs/src/main/asciidoc/using.adoc @@ -0,0 +1,1152 @@ +[[using-boot]] += Using Spring Boot +include::_attributes.adoc[] + +This section goes into more detail about how you should use Spring Boot. It covers topics +such as build systems, auto-configuration, and how to run your applications. We also +cover some Spring Boot best practices. Although there is nothing particularly special +about Spring Boot (it is just another library that you can consume), there are a few +recommendations that, when followed, make your development process a little easier. + +If you are starting out with Spring Boot, you should probably read the +_<>_ guide before diving into this +section. + + + +[[using-boot-build-systems]] +== Build Systems +It is strongly recommended that you choose a build system that supports +<> and that can consume +artifacts published to the "`Maven Central`" repository. We would recommend that you +choose Maven or Gradle. It is possible to get Spring Boot to work with other build +systems (Ant, for example), but they are not particularly well supported. + + + +[[using-boot-dependency-management]] +=== Dependency Management +Each release of Spring Boot provides a curated list of dependencies that it supports. In +practice, you do not need to provide a version for any of these dependencies in your +build configuration, as Spring Boot manages that for you. When you upgrade Spring +Boot itself, these dependencies are upgraded as well in a consistent way. + +NOTE: You can still specify a version and override Spring Boot's recommendations if you +need to do so. + +The curated list contains all the spring modules that you can use with Spring Boot as +well as a refined list of third party libraries. The list is available as a standard +<> +that can be used with both <> and +<>. + +WARNING: Each release of Spring Boot is associated with a base version of the Spring +Framework. We **highly** recommend that you not specify its version. + + + +[[using-boot-maven]] +=== Maven +Maven users can inherit from the `spring-boot-starter-parent` project to obtain sensible +defaults. The parent project provides the following features: + +* Java 1.8 as the default compiler level. +* UTF-8 source encoding. +* A <>, inherited from +the spring-boot-dependencies pom, that manages the versions of common dependencies. This +dependency management lets you omit tags for those dependencies when used in +your own pom. +* An execution of the {spring-boot-maven-plugin-site}/repackage-mojo.html[`repackage` +goal] with a `repackage` execution id. +* Sensible +https://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html[resource +filtering]. +* Sensible plugin configuration (https://www.mojohaus.org/exec-maven-plugin/[exec plugin], +https://github.com/ktoso/maven-git-commit-id-plugin[Git commit ID], and +https://maven.apache.org/plugins/maven-shade-plugin/[shade]). +* Sensible resource filtering for `application.properties` and `application.yml` +including profile-specific files (for example, `application-dev.properties` and +`application-dev.yml`) + +Note that, since the `application.properties` and `application.yml` files accept Spring +style placeholders (`${...}`), the Maven filtering is changed to use `@..@` placeholders. +(You can override that by setting a Maven property called `resource.delimiter`.) + + + +[[using-boot-maven-parent-pom]] +==== Inheriting the Starter Parent +To configure your project to inherit from the `spring-boot-starter-parent`, set the +`parent` as follows: + +[source,xml,indent=0,subs="verbatim,quotes,attributes"] +---- + + + org.springframework.boot + spring-boot-starter-parent + {spring-boot-version} + +---- + +NOTE: You should need to specify only the Spring Boot version number on this dependency. +If you import additional starters, you can safely omit the version number. + +With that setup, you can also override individual dependencies by overriding a property +in your own project. For instance, to upgrade to another Spring Data release train, you +would add the following to your `pom.xml`: + +[source,xml,indent=0,subs="verbatim,quotes,attributes"] +---- + + Fowler-SR2 + +---- + +TIP: Check the +{github-code}/spring-boot-project/spring-boot-dependencies/pom.xml[`spring-boot-dependencies` pom] +for a list of supported properties. + + + +[[using-boot-maven-without-a-parent]] +==== Using Spring Boot without the Parent POM +Not everyone likes inheriting from the `spring-boot-starter-parent` POM. You may have +your own corporate standard parent that you need to use or you may prefer to explicitly +declare all your Maven configuration. + +If you do not want to use the `spring-boot-starter-parent`, you can still keep the +benefit of the dependency management (but not the plugin management) by using a +`scope=import` dependency, as follows: + +[source,xml,indent=0,subs="verbatim,quotes,attributes"] +---- + + + + + org.springframework.boot + spring-boot-dependencies + {spring-boot-version} + pom + import + + + +---- + +The preceding sample setup does not let you override individual dependencies by using a +property, as explained above. To achieve the same result, you need to add an entry in the +`dependencyManagement` of your project **before** the `spring-boot-dependencies` entry. +For instance, to upgrade to another Spring Data release train, you could add the +following element to your `pom.xml`: + +[source,xml,indent=0,subs="verbatim,quotes,attributes"] +---- + + + + + org.springframework.data + spring-data-releasetrain + Fowler-SR2 + pom + import + + + org.springframework.boot + spring-boot-dependencies + {spring-boot-version} + pom + import + + + +---- + +NOTE: In the preceding example, we specify a _BOM_, but any dependency type can be +overridden in the same way. + + + +[[using-boot-maven-plugin]] +==== Using the Spring Boot Maven Plugin +Spring Boot includes a <> that can package the project as an executable jar. Add the plugin to your +`` section if you want to use it, as shown in the following example: + +[source,xml,indent=0,subs="verbatim,quotes,attributes"] +---- + + + + org.springframework.boot + spring-boot-maven-plugin + + + +---- + +NOTE: If you use the Spring Boot starter parent pom, you need to add only the plugin. +There is no need to configure it unless you want to change the settings defined in the +parent. + + + +[[using-boot-gradle]] +=== Gradle +To learn about using Spring Boot with Gradle, please refer to the documentation for +Spring Boot's Gradle plugin: + +* Reference ({spring-boot-gradle-plugin}/reference/html[HTML] and +{spring-boot-gradle-plugin}/reference/pdf/spring-boot-gradle-plugin-reference.pdf[PDF]) +* {spring-boot-gradle-plugin}/api[API] + +[[using-boot-ant]] +=== Ant +It is possible to build a Spring Boot project using Apache Ant+Ivy. The +`spring-boot-antlib` "`AntLib`" module is also available to help Ant create executable +jars. + +To declare dependencies, a typical `ivy.xml` file looks something like the following +example: + +[source,xml,indent=0] +---- + + + + + + + + + + +---- + +A typical `build.xml` looks like the following example: + +[source,xml,indent=0,subs="verbatim,quotes,attributes"] +---- + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +---- + +TIP: If you do not want to use the `spring-boot-antlib` module, see the +_<>_ "`How-to`" . + + + +[[using-boot-starter]] +=== Starters +Starters are a set of convenient dependency descriptors that you can include in your +application. You get a one-stop shop for all the Spring and related technologies that you +need without having to hunt through sample code and copy-paste loads of dependency +descriptors. For example, if you want to get started using Spring and JPA for database +access, include the `spring-boot-starter-data-jpa` dependency in your project. + +The starters contain a lot of the dependencies that you need to get a project up and +running quickly and with a consistent, supported set of managed transitive dependencies. + +.What's in a name +**** +All **official** starters follow a similar naming pattern; `+spring-boot-starter-*+`, +where `+*+` is a particular type of application. This naming structure is intended to +help when you need to find a starter. The Maven integration in many IDEs lets you +search dependencies by name. For example, with the appropriate Eclipse or STS plugin +installed, you can press `ctrl-space` in the POM editor and type +"`spring-boot-starter`" for a complete list. + +As explained in the "`<>`" section, third party starters should not start with `spring-boot`, as it +is reserved for official Spring Boot artifacts. Rather, a third-party starter typically +starts with the name of the project. For example, a third-party starter project called +`thirdpartyproject` would typically be named `thirdpartyproject-spring-boot-starter`. +**** + +The following application starters are provided by Spring Boot under the +`org.springframework.boot` group: + +.Spring Boot application starters +include::{generated-resources-root}/application-starters.adoc[] + +In addition to the application starters, the following starters can be used to add +_<>_ features: + +.Spring Boot production starters +include::{generated-resources-root}/production-starters.adoc[] + +Finally, Spring Boot also includes the following starters that can be used if you want to +exclude or swap specific technical facets: + +.Spring Boot technical starters +include::{generated-resources-root}/technical-starters.adoc[] + +TIP: For a list of additional community contributed starters, see the +{github-master-code}/spring-boot-project/spring-boot-starters/README.adoc[README file] in +the `spring-boot-starters` module on GitHub. + + + +[[using-boot-structuring-your-code]] +== Structuring Your Code +Spring Boot does not require any specific code layout to work. However, there are some +best practices that help. + + + +[[using-boot-using-the-default-package]] +=== Using the "`default`" Package +When a class does not include a `package` declaration, it is considered to be in the +"`default package`". The use of the "`default package`" is generally discouraged and +should be avoided. It can cause particular problems for Spring Boot applications that use +the `@ComponentScan`, `@ConfigurationPropertiesScan`, `@EntityScan`, or `@SpringBootApplication` +annotations, since every class from every jar is read. + +TIP: We recommend that you follow Java's recommended package naming conventions and use a +reversed domain name (for example, `com.example.project`). + + + +[[using-boot-locating-the-main-class]] +=== Locating the Main Application Class +We generally recommend that you locate your main application class in a root package +above other classes. The <> is often placed on your main class, and it +implicitly defines a base "`search package`" for certain items. For example, if you are +writing a JPA application, the package of the `@SpringBootApplication` annotated class +is used to search for `@Entity` items. Using a root package also allows component +scan to apply only on your project. + +TIP: If you don't want to use `@SpringBootApplication`, the `@EnableAutoConfiguration` +`@ComponentScan`, and `@ConfigurationPropertiesScan` annotations that it imports defines +that behaviour so you can also use those instead. + +The following listing shows a typical layout: + +[indent=0] +---- + com + +- example + +- myapplication + +- Application.java + | + +- customer + | +- Customer.java + | +- CustomerController.java + | +- CustomerService.java + | +- CustomerRepository.java + | + +- order + +- Order.java + +- OrderController.java + +- OrderService.java + +- OrderRepository.java +---- + +The `Application.java` file would declare the `main` method, along with the basic +`@SpringBootApplication`, as follows: + +[source,java,indent=0] +---- + package com.example.myapplication; + + import org.springframework.boot.SpringApplication; + import org.springframework.boot.autoconfigure.SpringBootApplication; + + @SpringBootApplication + public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + } +---- + + + +[[using-boot-configuration-classes]] +== Configuration Classes +Spring Boot favors Java-based configuration. Although it is possible to use +`SpringApplication` with XML sources, we generally recommend that your primary source be +a single `@Configuration` class. Usually the class that defines the `main` method is a +good candidate as the primary `@Configuration`. + +TIP: Many Spring configuration examples have been published on the Internet that use XML +configuration. If possible, always try to use the equivalent Java-based configuration. +Searching for `+Enable*+` annotations can be a good starting point. + + + +[[using-boot-importing-configuration]] +=== Importing Additional Configuration Classes +You need not put all your `@Configuration` into a single class. The `@Import` annotation +can be used to import additional configuration classes. Alternatively, you can use +`@ComponentScan` to automatically pick up all Spring components, including +`@Configuration` classes. + + + +[[using-boot-importing-xml-configuration]] +=== Importing XML Configuration +If you absolutely must use XML based configuration, we recommend that you still start +with a `@Configuration` class. You can then use an `@ImportResource` annotation to load +XML configuration files. + + + +[[using-boot-auto-configuration]] +== Auto-configuration +Spring Boot auto-configuration attempts to automatically configure your Spring +application based on the jar dependencies that you have added. For example, if `HSQLDB` +is on your classpath, and you have not manually configured any database connection beans, +then Spring Boot auto-configures an in-memory database. + +You need to opt-in to auto-configuration by adding the `@EnableAutoConfiguration` or +`@SpringBootApplication` annotations to one of your `@Configuration` classes. + +TIP: You should only ever add one `@SpringBootApplication` or `@EnableAutoConfiguration` +annotation. We generally recommend that you add one or the other to your primary +`@Configuration` class only. + + + +[[using-boot-replacing-auto-configuration]] +=== Gradually Replacing Auto-configuration +Auto-configuration is non-invasive. At any point, you can start to define your own +configuration to replace specific parts of the auto-configuration. For example, if you +add your own `DataSource` bean, the default embedded database support backs away. + +If you need to find out what auto-configuration is currently being applied, and why, +start your application with the `--debug` switch. Doing so enables debug logs for a +selection of core loggers and logs a conditions report to the console. + + + +[[using-boot-disabling-specific-auto-configuration]] +=== Disabling Specific Auto-configuration Classes +If you find that specific auto-configuration classes that you do not want are being +applied, you can use the exclude attribute of `@EnableAutoConfiguration` to disable them, +as shown in the following example: + +[source,java,indent=0] +---- + import org.springframework.boot.autoconfigure.*; + import org.springframework.boot.autoconfigure.jdbc.*; + import org.springframework.context.annotation.*; + + @Configuration(proxyBeanMethods = false) + @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) + public class MyConfiguration { + } +---- + +If the class is not on the classpath, you can use the `excludeName` attribute of the +annotation and specify the fully qualified name instead. Finally, you can also control +the list of auto-configuration classes to exclude by using the +`spring.autoconfigure.exclude` property. + +TIP: You can define exclusions both at the annotation level and by using the property. + +[[using-boot-spring-beans-and-dependency-injection]] +== Spring Beans and Dependency Injection +You are free to use any of the standard Spring Framework techniques to define your beans +and their injected dependencies. For simplicity, we often find that using +`@ComponentScan` (to find your beans) and using `@Autowired` (to do constructor +injection) works well. + +If you structure your code as suggested above (locating your application class in a root +package), you can add `@ComponentScan` without any arguments. All of your application +components (`@Component`, `@Service`, `@Repository`, `@Controller` etc.) are +automatically registered as Spring Beans. + +The following example shows a `@Service` Bean that uses constructor injection to obtain a +required `RiskAssessor` bean: + +[source,java,indent=0] +---- + package com.example.service; + + import org.springframework.beans.factory.annotation.Autowired; + import org.springframework.stereotype.Service; + + @Service + public class DatabaseAccountService implements AccountService { + + private final RiskAssessor riskAssessor; + + @Autowired + public DatabaseAccountService(RiskAssessor riskAssessor) { + this.riskAssessor = riskAssessor; + } + + // ... + + } +---- + +If a bean has one constructor, you can omit the `@Autowired`, as shown in the following +example: + +[source,java,indent=0] +---- + @Service + public class DatabaseAccountService implements AccountService { + + private final RiskAssessor riskAssessor; + + public DatabaseAccountService(RiskAssessor riskAssessor) { + this.riskAssessor = riskAssessor; + } + + // ... + + } +---- + +TIP: Notice how using constructor injection lets the `riskAssessor` field be marked as +`final`, indicating that it cannot be subsequently changed. + + + +[[using-boot-using-springbootapplication-annotation]] +== Using the @SpringBootApplication Annotation +Many Spring Boot developers like their apps to use auto-configuration, component scan and +be able to define extra configuration on their "application class". A single +`@SpringBootApplication` annotation can be used to enable those three features, that is: + +* `@EnableAutoConfiguration`: enable <> +* `@ComponentScan`: enable `@Component` scan on the package where the application is +located (see <>) +* `@ConfigurationPropertiesScan`: enable `@ConfigurationProperties` scan on the package +where the application is located (see <>) +* `@Configuration`: allow to register extra beans in the context or import additional +configuration classes + + +[source,java,indent=0] +---- + package com.example.myapplication; + + import org.springframework.boot.SpringApplication; + import org.springframework.boot.autoconfigure.SpringBootApplication; + + @SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan @ConfigurationPropertiesScan + public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + } +---- + +NOTE: `@SpringBootApplication` also provides aliases to customize the attributes of +`@EnableAutoConfiguration` and `@ComponentScan`. + +[NOTE] +==== +None of these features are mandatory and you may choose to replace this single annotation +by any of the features that it enables. For instance, you may not want to use component +scan or configuration properties scan in your application: + +[source,java,indent=0] +---- + package com.example.myapplication; + + import org.springframework.boot.SpringApplication; + import org.springframework.context.annotation.ComponentScan + import org.springframework.context.annotation.Configuration; + import org.springframework.context.annotation.Import; + + @Configuration(proxyBeanMethods = false) + @EnableAutoConfiguration + @Import({ MyConfig.class, MyAnotherConfig.class }) + public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + } +---- + +In this example, `Application` is just like any other Spring Boot application except that +`@Component`-annotated classes and `@ConfigurationProperties`-annotated classes are not detected +automatically and the user-defined beans are imported explicitly (see `@Import`). +==== + + + +[[using-boot-running-your-application]] +== Running Your Application +One of the biggest advantages of packaging your application as a jar and using an +embedded HTTP server is that you can run your application as you would any other. +Debugging Spring Boot applications is also easy. You do not need any special IDE plugins +or extensions. + +NOTE: This section only covers jar based packaging. If you choose to package your +application as a war file, you should refer to your server and IDE documentation. + + + +[[using-boot-running-from-an-ide]] +=== Running from an IDE +You can run a Spring Boot application from your IDE as a simple Java application. +However, you first need to import your project. Import steps vary depending on your IDE +and build system. Most IDEs can import Maven projects directly. For example, Eclipse +users can select `Import...` -> `Existing Maven Projects` from the `File` menu. + +If you cannot directly import your project into your IDE, you may be able to generate IDE +metadata by using a build plugin. Maven includes plugins for +https://maven.apache.org/plugins/maven-eclipse-plugin/[Eclipse] and +https://maven.apache.org/plugins/maven-idea-plugin/[IDEA]. Gradle offers plugins for +{gradle-user-guide}/userguide.html[various IDEs]. + +TIP: If you accidentally run a web application twice, you see a "`Port already in use`" +error. STS users can use the `Relaunch` button rather than the `Run` button to ensure +that any existing instance is closed. + + + +[[using-boot-running-as-a-packaged-application]] +=== Running as a Packaged Application +If you use the Spring Boot Maven or Gradle plugins to create an executable jar, you can +run your application using `java -jar`, as shown in the following example: + +[indent=0,subs="attributes"] +---- + $ java -jar target/myapplication-0.0.1-SNAPSHOT.jar +---- + +It is also possible to run a packaged application with remote debugging support enabled. +Doing so lets you attach a debugger to your packaged application, as shown in the +following example: + +[indent=0,subs="attributes"] +---- + $ java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n \ + -jar target/myapplication-0.0.1-SNAPSHOT.jar +---- + + + +[[using-boot-running-with-the-maven-plugin]] +=== Using the Maven Plugin +The Spring Boot Maven plugin includes a `run` goal that can be used to quickly compile +and run your application. Applications run in an exploded form, as they do in your IDE. +The following example shows a typical Maven command to run a Spring Boot application: + +[indent=0,subs="attributes"] +---- + $ mvn spring-boot:run +---- + +You might also want to use the `MAVEN_OPTS` operating system environment variable, as +shown in the following example: + +[indent=0,subs="attributes"] +---- + $ export MAVEN_OPTS=-Xmx1024m +---- + + + +[[using-boot-running-with-the-gradle-plugin]] +=== Using the Gradle Plugin +The Spring Boot Gradle plugin also includes a `bootRun` task that can be used to run your +application in an exploded form. The `bootRun` task is added whenever you apply the +`org.springframework.boot` and `java` plugins and is shown in the following example: + +[indent=0,subs="attributes"] +---- + $ gradle bootRun +---- + +You might also want to use the `JAVA_OPTS` operating system environment variable, as +shown in the following example: + +[indent=0,subs="attributes"] +---- + $ export JAVA_OPTS=-Xmx1024m +---- + + + +[[using-boot-hot-swapping]] +=== Hot Swapping +Since Spring Boot applications are just plain Java applications, JVM hot-swapping should +work out of the box. JVM hot swapping is somewhat limited with the bytecode that it can +replace. For a more complete solution, +https://zeroturnaround.com/software/jrebel/[JRebel] can be used. + +The +`spring-boot-devtools` module also includes support for quick application restarts. +See the <> section later in this chapter and the +<> for details. + + + +[[using-boot-devtools]] +== Developer Tools +Spring Boot includes an additional set of tools that can make the application +development experience a little more pleasant. The `spring-boot-devtools` module can be +included in any project to provide additional development-time features. To include +devtools support, add the module dependency to your build, as shown in the following +listings for Maven and Gradle: + +.Maven +[source,xml,indent=0,subs="verbatim,quotes,attributes"] +---- + + + org.springframework.boot + spring-boot-devtools + true + + +---- + +.Gradle +[source,groovy,indent=0,subs="attributes"] +---- + configurations { + developmentOnly + runtimeClasspath { + extendsFrom developmentOnly + } + } + dependencies { + developmentOnly("org.springframework.boot:spring-boot-devtools") + } +---- + +NOTE: Developer tools are automatically disabled when running a fully packaged +application. If your application is launched from `java -jar` or if it is started from a +special classloader, then it is considered a "`production application`". If that does not +apply to you (i.e. if you run your application from a container), consider excluding +devtools or set the `-Dspring.devtools.restart.enabled=false` system property. + +TIP: Flagging the dependency as optional in Maven or using a custom `developmentOnly` +configuration in Gradle (as shown above) is a best practice that prevents devtools from +being transitively applied to other modules that use your project. + +TIP: Repackaged archives do not contain devtools by default. If you want to use a +<>, you need to disable the +`excludeDevtools` build property to include it. The property is supported with both the +Maven and Gradle plugins. + + + +[[using-boot-devtools-property-defaults]] +=== Property Defaults +Several of the libraries supported by Spring Boot use caches to improve performance. For +example, <> cache compiled templates to avoid repeatedly parsing template files. Also, +Spring MVC can add HTTP caching headers to responses when serving static resources. + +While caching is very beneficial in production, it can be counter-productive during +development, preventing you from seeing the changes you just made in your application. +For this reason, spring-boot-devtools disables the caching options by default. + +Cache options are usually configured by settings in your `application.properties` file. +For example, Thymeleaf offers the `spring.thymeleaf.cache` property. Rather than needing +to set these properties manually, the `spring-boot-devtools` module automatically applies +sensible development-time configuration. + +Because you need more information about web requests while developing Spring MVC and +Spring WebFlux applications, developer tools will enable `DEBUG` logging for the `web` +logging group. This will give you information about the incoming request, which handler is +processing it, the response outcome, etc. If you wish to log all request details +(including potentially sensitive information), you can turn on the +`spring.http.log-request-details` configuration property. + +NOTE: If you don't want property defaults to be applied you can set +`spring.devtools.add-properties` to `false` in your `application.properties`. + +TIP: For a complete list of the properties that are applied by the devtools, see +{sc-spring-boot-devtools}/env/DevToolsPropertyDefaultsPostProcessor.{sc-ext}[DevToolsPropertyDefaultsPostProcessor]. + + + +[[using-boot-devtools-restart]] +=== Automatic Restart +Applications that use `spring-boot-devtools` automatically restart whenever files on the +classpath change. This can be a useful feature when working in an IDE, as it gives a very +fast feedback loop for code changes. By default, any entry on the classpath that points +to a folder is monitored for changes. Note that certain resources, such as static assets +and view templates, <>. + +.Triggering a restart +**** +As DevTools monitors classpath resources, the only way to trigger a restart is to update +the classpath. The way in which you cause the classpath to be updated depends on the IDE +that you are using. In Eclipse, saving a modified file causes the classpath to be updated +and triggers a restart. In IntelliJ IDEA, building the project +(`Build +->+ Build Project`) has the same effect. +**** + +[NOTE] +==== +As long as forking is enabled, you can also start your application by using the supported +build plugins (Maven and Gradle), since DevTools needs an isolated application +classloader to operate properly. By default, the Gradle and Maven plugins fork the +application process. + +==== + +TIP: Automatic restart works very well when used with LiveReload. +<> for details. If you use +JRebel, automatic restarts are disabled in favor of dynamic class reloading. Other +devtools features (such as LiveReload and property overrides) can still be used. + +NOTE: DevTools relies on the application context's shutdown hook to close it during a +restart. It does not work correctly if you have disabled the shutdown hook +(`SpringApplication.setRegisterShutdownHook(false)`). + +NOTE: When deciding if an entry on the classpath should trigger a restart when it +changes, DevTools automatically ignores projects named `spring-boot`, +`spring-boot-devtools`, `spring-boot-autoconfigure`, `spring-boot-actuator`, and +`spring-boot-starter`. + +NOTE: DevTools needs to customize the `ResourceLoader` used by the `ApplicationContext`. +If your application provides one already, it is going to be wrapped. Direct override of +the `getResource` method on the `ApplicationContext` is not supported. + +[[using-spring-boot-restart-vs-reload]] +.Restart vs Reload +**** +The restart technology provided by Spring Boot works by using two classloaders. Classes +that do not change (for example, those from third-party jars) are loaded into a _base_ +classloader. Classes that you are actively developing are loaded into a _restart_ +classloader. When the application is restarted, the _restart_ classloader is thrown away +and a new one is created. This approach means that application restarts are typically +much faster than "`cold starts`", since the _base_ classloader is already available and +populated. + +If you find that restarts are not quick enough for your applications or you encounter +classloading issues, you could consider reloading technologies such as +https://zeroturnaround.com/software/jrebel/[JRebel] from ZeroTurnaround. These work by +rewriting classes as they are loaded to make them more amenable to reloading. +**** + +[[using-boot-devtools-restart-logging-condition-delta]] +==== Logging changes in condition evaluation +By default, each time your application restarts, a report showing the condition evaluation +delta is logged. The report shows the changes to your application's auto-configuration as +you make changes such as adding or removing beans and setting configuration properties. + +To disable the logging of the report, set the following property: + +[indent=0] +---- + spring.devtools.restart.log-condition-evaluation-delta=false +---- + + +[[using-boot-devtools-restart-exclude]] +==== Excluding Resources +Certain resources do not necessarily need to trigger a restart when they are changed. For +example, Thymeleaf templates can be edited in-place. By default, changing resources +in `/META-INF/maven`, `/META-INF/resources`, `/resources`, `/static`, `/public`, or +`/templates` does not trigger a restart but does trigger a +<>. If you want to customize these +exclusions, you can use the `spring.devtools.restart.exclude` property. For example, to +exclude only `/static` and `/public` you would set the following property: + +[indent=0] +---- + spring.devtools.restart.exclude=static/**,public/** +---- + +TIP: If you want to keep those defaults and _add_ additional exclusions, use the +`spring.devtools.restart.additional-exclude` property instead. + + +[[using-boot-devtools-restart-additional-paths]] +==== Watching Additional Paths +You may want your application to be restarted or reloaded when you make changes to files +that are not on the classpath. To do so, use the +`spring.devtools.restart.additional-paths` property to configure additional paths to +watch for changes. You can use the `spring.devtools.restart.exclude` property +<> to control whether changes +beneath the additional paths trigger a full restart or a +<>. + + + +[[using-boot-devtools-restart-disable]] +==== Disabling Restart +If you do not want to use the restart feature, you can disable it by using the +`spring.devtools.restart.enabled` property. In most cases, you can set this property in +your `application.properties` (doing so still initializes the restart classloader, but it +does not watch for file changes). + +If you need to _completely_ disable restart support (for example, because it does not work +with a specific library), you need to set the `spring.devtools.restart.enabled` `System` +property to `false` before calling `SpringApplication.run(...)`, as shown in the +following example: + +[source,java,indent=0] +---- + public static void main(String[] args) { + System.setProperty("spring.devtools.restart.enabled", "false"); + SpringApplication.run(MyApp.class, args); + } +---- + + + +[[using-boot-devtools-restart-triggerfile]] +==== Using a Trigger File +If you work with an IDE that continuously compiles changed files, you might prefer to +trigger restarts only at specific times. To do so, you can use a "`trigger file`", which +is a special file that must be modified when you want to actually trigger a restart +check. Changing the file only triggers the check and the restart only occurs if +Devtools has detected it has to do something. The trigger file can be updated manually or +with an IDE plugin. + +To use a trigger file, set the `spring.devtools.restart.trigger-file` property to the +path of your trigger file. + +TIP: You might want to set `spring.devtools.restart.trigger-file` as a +<>, so that all your projects behave +in the same way. + + + +[[using-boot-devtools-customizing-classload]] +==== Customizing the Restart Classloader +As described earlier in the <> section, restart +functionality is implemented by using two classloaders. For most applications, this +approach works well. However, it can sometimes cause classloading issues. + +By default, any open project in your IDE is loaded with the "`restart`" classloader, and +any regular `.jar` file is loaded with the "`base`" classloader. If you work on a +multi-module project, and not every module is imported into your IDE, you may need to +customize things. To do so, you can create a `META-INF/spring-devtools.properties` file. + +The `spring-devtools.properties` file can contain properties prefixed with +`restart.exclude` and `restart.include`. The `include` elements are items that should be +pulled up into the "`restart`" classloader, and the `exclude` elements are items that +should be pushed down into the "`base`" classloader. The value of the property is a regex +pattern that is applied to the classpath, as shown in the following example: + +[source,properties,indent=0] +---- + restart.exclude.companycommonlibs=/mycorp-common-[\\w\\d-\.]+\.jar + restart.include.projectcommon=/mycorp-myproj-[\\w\\d-\.]+\.jar +---- + +NOTE: All property keys must be unique. As long as a property starts with +`restart.include.` or `restart.exclude.` it is considered. + +TIP: All `META-INF/spring-devtools.properties` from the classpath are loaded. You can +package files inside your project, or in the libraries that the project consumes. + + + +[[using-boot-devtools-known-restart-limitations]] +==== Known Limitations +Restart functionality does not work well with objects that are deserialized by using a +standard `ObjectInputStream`. If you need to deserialize data, you may need to use +Spring's `ConfigurableObjectInputStream` in combination with +`Thread.currentThread().getContextClassLoader()`. + +Unfortunately, several third-party libraries deserialize without considering the context +classloader. If you find such a problem, you need to request a fix with the original +authors. + + + +[[using-boot-devtools-livereload]] +=== LiveReload +The `spring-boot-devtools` module includes an embedded LiveReload server that can be used +to trigger a browser refresh when a resource is changed. LiveReload browser extensions +are freely available for Chrome, Firefox and Safari from +http://livereload.com/extensions/[livereload.com]. + +If you do not want to start the LiveReload server when your application runs, you can set +the `spring.devtools.livereload.enabled` property to `false`. + +NOTE: You can only run one LiveReload server at a time. Before starting your application, +ensure that no other LiveReload servers are running. If you start multiple applications +from your IDE, only the first has LiveReload support. + + + +[[using-boot-devtools-globalsettings]] +=== Global Settings +You can configure global devtools settings by adding a file named +`.spring-boot-devtools.properties` to your `$HOME` folder (note that the filename starts +with "`.`"). Any properties added to this file apply to _all_ Spring Boot applications on +your machine that use devtools. For example, to configure restart to always use a +<>, you would add the following +property: + +.~/.spring-boot-devtools.properties +[source,properties,indent=0] +---- + spring.devtools.reload.trigger-file=.reloadtrigger +---- + +NOTE: Profiles activated in `.spring-boot-devtools.properties` will not affect the +loading of <>. + + + +[[using-boot-devtools-remote]] +=== Remote Applications +The Spring Boot developer tools are not limited to local development. You can also +use several features when running applications remotely. Remote support is opt-in. To +enable it, you need to make sure that `devtools` is included in the repackaged archive, +as shown in the following listing: + +[source,xml,indent=0,subs="verbatim,quotes,attributes"] +---- + + + + org.springframework.boot + spring-boot-maven-plugin + + false + + + + +---- + +Then you need to set a `spring.devtools.remote.secret` property, as shown in the +following example: + +[source,properties,indent=0] +---- + spring.devtools.remote.secret=mysecret +---- + +WARNING: Enabling `spring-boot-devtools` on a remote application is a security risk. You +should never enable support on a production deployment. + +Remote devtools support is provided in two parts: a server-side endpoint that accepts +connections and a client application that you run in your IDE. The server component is +automatically enabled when the `spring.devtools.remote.secret` property is set. The +client component must be launched manually. + + + +==== Running the Remote Client Application +The remote client application is designed to be run from within your IDE. You need to run +`org.springframework.boot.devtools.RemoteSpringApplication` with the same classpath as +the remote project that you connect to. The application's single required argument is the +remote URL to which it connects. + +For example, if you are using Eclipse or STS and you have a project named `my-app` that +you have deployed to Cloud Foundry, you would do the following: + +* Select `Run Configurations...` from the `Run` menu. +* Create a new `Java Application` "`launch configuration`". +* Browse for the `my-app` project. +* Use `org.springframework.boot.devtools.RemoteSpringApplication` as the main class. +* Add `+++https://myapp.cfapps.io+++` to the `Program arguments` (or whatever your remote +URL is). + +A running remote client might resemble the following listing: + +[indent=0,subs="attributes"] +---- + . ____ _ __ _ _ + /\\ / ___'_ __ _ _(_)_ __ __ _ ___ _ \ \ \ \ + ( ( )\___ | '_ | '_| | '_ \/ _` | | _ \___ _ __ ___| |_ ___ \ \ \ \ + \\/ ___)| |_)| | | | | || (_| []::::::[] / -_) ' \/ _ \ _/ -_) ) ) ) ) + ' |____| .__|_| |_|_| |_\__, | |_|_\___|_|_|_\___/\__\___|/ / / / + =========|_|==============|___/===================================/_/_/_/ + :: Spring Boot Remote :: {spring-boot-version} + + 2015-06-10 18:25:06.632 INFO 14938 --- [ main] o.s.b.devtools.RemoteSpringApplication : Starting RemoteSpringApplication on pwmbp with PID 14938 (/Users/pwebb/projects/spring-boot/code/spring-boot-devtools/target/classes started by pwebb in /Users/pwebb/projects/spring-boot/code/spring-boot-samples/spring-boot-sample-devtools) + 2015-06-10 18:25:06.671 INFO 14938 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2a17b7b6: startup date [Wed Jun 10 18:25:06 PDT 2015]; root of context hierarchy + 2015-06-10 18:25:07.043 WARN 14938 --- [ main] o.s.b.d.r.c.RemoteClientConfiguration : The connection to http://localhost:8080 is insecure. You should use a URL starting with 'https://'. + 2015-06-10 18:25:07.074 INFO 14938 --- [ main] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729 + 2015-06-10 18:25:07.130 INFO 14938 --- [ main] o.s.b.devtools.RemoteSpringApplication : Started RemoteSpringApplication in 0.74 seconds (JVM running for 1.105) +---- + +NOTE: Because the remote client is using the same classpath as the real application it +can directly read application properties. This is how the `spring.devtools.remote.secret` +property is read and passed to the server for authentication. + +TIP: It is always advisable to use `https://` as the connection protocol, so that traffic +is encrypted and passwords cannot be intercepted. + +TIP: If you need to use a proxy to access the remote application, configure the +`spring.devtools.remote.proxy.host` and `spring.devtools.remote.proxy.port` properties. + + + +[[using-boot-devtools-remote-update]] +==== Remote Update +The remote client monitors your application classpath for changes in the same way as the +<>. Any updated resource is pushed to the +remote application and (_if required_) triggers a restart. This can be helpful if you +iterate on a feature that uses a cloud service that you do not have locally. Generally, +remote updates and restarts are much quicker than a full rebuild and deploy cycle. + +NOTE: Files are only monitored when the remote client is running. If you change a file +before starting the remote client, it is not pushed to the remote server. + + + +[[using-boot-packaging-for-production]] +== Packaging Your Application for Production +Executable jars can be used for production deployment. As they are self-contained, they +are also ideally suited for cloud-based deployment. + +For additional "`production ready`" features, such as health, auditing, and metric REST +or JMX end-points, consider adding `spring-boot-actuator`. See +_<>_ for details. + + + +[[using-boot-whats-next]] +== What to Read Next +You should now understand how you can use Spring Boot and some best practices that you +should follow. You can now go on to learn about specific +_<>_ in depth, or you could +skip ahead and read about the "`<>`" aspects of Spring Boot. From cd4ad7b0174568e3dbbc8ba41e0c0dd15e02079f Mon Sep 17 00:00:00 2001 From: Marcin Grzejszczak Date: Fri, 19 Jul 2019 17:39:28 +0200 Subject: [PATCH 04/18] WIP --- README.adoc | 192 +------------- docs/src/main/asciidoc/_attributes.adoc | 21 +- .../_spring-cloud-contract-verifier.adoc | 19 -- .../{_verifier_faq.adoc => howto.adoc} | 250 ++++++++++-------- .../main/asciidoc/spring-cloud-contract.adoc | 1 - 5 files changed, 164 insertions(+), 319 deletions(-) rename docs/src/main/asciidoc/{_verifier_faq.adoc => howto.adoc} (82%) delete mode 120000 docs/src/main/asciidoc/spring-cloud-contract.adoc diff --git a/README.adoc b/README.adoc index 3bc6dfc1bc..78c55fab50 100644 --- a/README.adoc +++ b/README.adoc @@ -243,9 +243,7 @@ Stub Runner` properties, as shown in the following example: + [source,yaml,indent=0] ---- -stubrunner: - ids: 'com.example:http-server-dsl:+:stubs:8080' - repositoryRoot: https://repo.spring.io/libs-snapshot +Unresolved directive in _verifier_how_it_works.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ---- Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, @@ -552,9 +550,7 @@ Runner` properties, as shown in the following example: + [source,yaml,indent=0] ---- -stubrunner: - ids: 'com.example:http-server-dsl:+:stubs:8080' - repositoryRoot: https://repo.spring.io/libs-snapshot +Unresolved directive in _verifier_how_it_works.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ---- Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, @@ -1083,9 +1079,7 @@ achieving the same thing by changing the properties. [source,yaml,indent=0] ---- -stubrunner: - ids: 'com.example:http-server-dsl:+:stubs:8080' - repositoryRoot: https://repo.spring.io/libs-snapshot +Unresolved directive in _verifier_how_it_works.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ---- That's it! @@ -1565,185 +1559,7 @@ You can read more about Spring Cloud Contract Verifier by reading the == Contributing -:spring-cloud-build-branch: master - -Spring Cloud is released under the non-restrictive Apache 2.0 license, -and follows a very standard Github development process, using Github -tracker for issues and merging pull requests into master. If you want -to contribute even something trivial please do not hesitate, but -follow the guidelines below. - -=== Sign the Contributor License Agreement -Before we accept a non-trivial patch or pull request we will need you to sign the -https://cla.pivotal.io/sign/spring[Contributor License Agreement]. -Signing the contributor's agreement does not grant anyone commit rights to the main -repository, but it does mean that we can accept your contributions, and you will get an -author credit if we do. Active contributors might be asked to join the core team, and -given the ability to merge pull requests. - -=== Code of Conduct -This project adheres to the Contributor Covenant https://github.com/spring-cloud/spring-cloud-build/blob/master/docs/src/main/asciidoc/code-of-conduct.adoc[code of -conduct]. By participating, you are expected to uphold this code. Please report -unacceptable behavior to spring-code-of-conduct@pivotal.io. - -=== Code Conventions and Housekeeping -None of these is essential for a pull request, but they will all help. They can also be -added after the original pull request but before a merge. - -* Use the Spring Framework code format conventions. If you use Eclipse - you can import formatter settings using the - `eclipse-code-formatter.xml` file from the - https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-dependencies-parent/eclipse-code-formatter.xml[Spring - Cloud Build] project. If using IntelliJ, you can use the - https://plugins.jetbrains.com/plugin/6546[Eclipse Code Formatter - Plugin] to import the same file. -* Make sure all new `.java` files to have a simple Javadoc class comment with at least an - `@author` tag identifying you, and preferably at least a paragraph on what the class is - for. -* Add the ASF license header comment to all new `.java` files (copy from existing files - in the project) -* Add yourself as an `@author` to the .java files that you modify substantially (more - than cosmetic changes). -* Add some Javadocs and, if you change the namespace, some XSD doc elements. -* A few unit tests would help a lot as well -- someone has to do it. -* If no-one else is using your branch, please rebase it against the current master (or - other target branch in the main project). -* When writing a commit message please follow https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html[these conventions], - if you are fixing an existing issue please add `Fixes gh-XXXX` at the end of the commit - message (where XXXX is the issue number). - -=== Checkstyle - -Spring Cloud Build comes with a set of checkstyle rules. You can find them in the `spring-cloud-build-tools` module. The most notable files under the module are: - -.spring-cloud-build-tools/ ----- -└── src -    ├── checkstyle -    │   └── checkstyle-suppressions.xml <3> -    └── main -    └── resources -    ├── checkstyle-header.txt <2> -    └── checkstyle.xml <1> ----- -<1> Default Checkstyle rules -<2> File header setup -<3> Default suppression rules - -==== Checkstyle configuration - -Checkstyle rules are *disabled by default*. To add checkstyle to your project just define the following properties and plugins. - -.pom.xml ----- - -true <1> - true - <2> - true - <3> - - - - - <4> - io.spring.javaformat - spring-javaformat-maven-plugin - - <5> - org.apache.maven.plugins - maven-checkstyle-plugin - - - - - - <5> - org.apache.maven.plugins - maven-checkstyle-plugin - - - - ----- -<1> Fails the build upon Checkstyle errors -<2> Fails the build upon Checkstyle violations -<3> Checkstyle analyzes also the test sources -<4> Add the Spring Java Format plugin that will reformat your code to pass most of the Checkstyle formatting rules -<5> Add checkstyle plugin to your build and reporting phases - -If you need to suppress some rules (e.g. line length needs to be longer), then it's enough for you to define a file under `${project.root}/src/checkstyle/checkstyle-suppressions.xml` with your suppressions. Example: - -.projectRoot/src/checkstyle/checkstyle-suppresions.xml ----- - - - - - - ----- - -It's advisable to copy the `${spring-cloud-build.rootFolder}/.editorconfig` and `${spring-cloud-build.rootFolder}/.springformat` to your project. That way, some default formatting rules will be applied. You can do so by running this script: - -```bash -$ curl https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/.editorconfig -o .editorconfig -$ touch .springformat -``` - -=== IDE setup - -==== Intellij IDEA - -In order to setup Intellij you should import our coding conventions, inspection profiles and set up the checkstyle plugin. -The following files can be found in the https://github.com/spring-cloud/spring-cloud-build/tree/master/spring-cloud-build-tools[Spring Cloud Build] project. - -.spring-cloud-build-tools/ ----- -└── src -    ├── checkstyle -    │   └── checkstyle-suppressions.xml <3> -    └── main -    └── resources -    ├── checkstyle-header.txt <2> -    ├── checkstyle.xml <1> -    └── intellij -       ├── Intellij_Project_Defaults.xml <4> -       └── Intellij_Spring_Boot_Java_Conventions.xml <5> ----- -<1> Default Checkstyle rules -<2> File header setup -<3> Default suppression rules -<4> Project defaults for Intellij that apply most of Checkstyle rules -<5> Project style conventions for Intellij that apply most of Checkstyle rules - -.Code style - -image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-code-style.png[Code style] - -Go to `File` -> `Settings` -> `Editor` -> `Code style`. There click on the icon next to the `Scheme` section. There, click on the `Import Scheme` value and pick the `Intellij IDEA code style XML` option. Import the `spring-cloud-build-tools/src/main/resources/intellij/Intellij_Spring_Boot_Java_Conventions.xml` file. - -.Inspection profiles - -image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-inspections.png[Code style] - -Go to `File` -> `Settings` -> `Editor` -> `Inspections`. There click on the icon next to the `Profile` section. There, click on the `Import Profile` and import the `spring-cloud-build-tools/src/main/resources/intellij/Intellij_Project_Defaults.xml` file. - -.Checkstyle - -To have Intellij work with Checkstyle, you have to install the `Checkstyle` plugin. It's advisable to also install the `Assertions2Assertj` to automatically convert the JUnit assertions - -image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-checkstyle.png[Checkstyle] - -Go to `File` -> `Settings` -> `Other settings` -> `Checkstyle`. There click on the `+` icon in the `Configuration file` section. There, you'll have to define where the checkstyle rules should be picked from. In the image above, we've picked the rules from the cloned Spring Cloud Build repository. However, you can point to the Spring Cloud Build's GitHub repository (e.g. for the `checkstyle.xml` : `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle.xml`). We need to provide the following variables: - -- `checkstyle.header.file` - please point it to the Spring Cloud Build's, `spring-cloud-build-tools/src/main/resources/checkstyle/checkstyle-header.txt` file either in your cloned repo or via the `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle-header.txt` URL. -- `checkstyle.suppressions.file` - default suppressions. Please point it to the Spring Cloud Build's, `spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` file either in your cloned repo or via the `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` URL. -- `checkstyle.additional.suppressions.file` - this variable corresponds to suppressions in your local project. E.g. you're working on `spring-cloud-contract`. Then point to the `project-root/src/checkstyle/checkstyle-suppressions.xml` folder. Example for `spring-cloud-contract` would be: `/home/username/spring-cloud-contract/src/checkstyle/checkstyle-suppressions.xml`. - -IMPORTANT: Remember to set the `Scan Scope` to `All sources` since we apply checkstyle rules for production and test sources. +Unresolved directive in README.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/contributing.adoc[] == How to build it diff --git a/docs/src/main/asciidoc/_attributes.adoc b/docs/src/main/asciidoc/_attributes.adoc index 13bbf150e5..34e0068487 100644 --- a/docs/src/main/asciidoc/_attributes.adoc +++ b/docs/src/main/asciidoc/_attributes.adoc @@ -12,4 +12,23 @@ :docinfo: shared,private :sc-ext: java -:project-full-name: Spring Cloud Contract \ No newline at end of file +:project-full-name: Spring Cloud Contract + +// project-specific attributes +:core_path: ../../.. +:plugins_path: ../../../spring-cloud-contract-tools +:converters_path: {plugins_path}/spring-cloud-contract-converters +:verifier_root_path: {core_path}/spring-cloud-contract-verifier +:contract_spec_path: {core_path}/specs/spring-cloud-contract-spec-java +:contract_spec_tests_path: {core_path}/specs/spring-cloud-contract-spec +:samples_path: {core_path}/samples +:verifier_core_path: {verifier_root_path} +:stubrunner_core_path: {core_path}/spring-cloud-contract-stub-runner +:standalone_samples_path: {samples_path}/standalone/dsl +:standalone_messaging_samples_path: {samples_path}/standalone/messaging +:standalone_pact_path: {samples_path}/standalone/pact +:standalone_restdocs_path: {samples_path}/standalone/restdocs +:tests_path: {core_path}/tests +:samples_branch: 2.2.x +:samples_url: https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/{samples_branch} +:introduction_url: ${core_path}/../../ \ No newline at end of file diff --git a/docs/src/main/asciidoc/_spring-cloud-contract-verifier.adoc b/docs/src/main/asciidoc/_spring-cloud-contract-verifier.adoc index d8d9b6f29f..484b905565 100644 --- a/docs/src/main/asciidoc/_spring-cloud-contract-verifier.adoc +++ b/docs/src/main/asciidoc/_spring-cloud-contract-verifier.adoc @@ -1,22 +1,3 @@ -:branch: master -:core_path: ../../.. -:plugins_path: ../../../spring-cloud-contract-tools -:converters_path: {plugins_path}/spring-cloud-contract-converters -:verifier_root_path: {core_path}/spring-cloud-contract-verifier -:contract_spec_path: {core_path}/specs/spring-cloud-contract-spec-java -:contract_spec_tests_path: {core_path}/specs/spring-cloud-contract-spec -:samples_path: {core_path}/samples -:verifier_core_path: {verifier_root_path} -:stubrunner_core_path: {core_path}/spring-cloud-contract-stub-runner -:standalone_samples_path: {samples_path}/standalone/dsl -:standalone_messaging_samples_path: {samples_path}/standalone/messaging -:standalone_pact_path: {samples_path}/standalone/pact -:standalone_restdocs_path: {samples_path}/standalone/restdocs -:tests_path: {core_path}/tests -:samples_branch: 2.2.x -:samples_url: https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/{samples_branch} -:introduction_url: ${core_path}/../../ - include::_verifier_introduction.adoc[] include::_verifier_faq.adoc[] diff --git a/docs/src/main/asciidoc/_verifier_faq.adoc b/docs/src/main/asciidoc/howto.adoc similarity index 82% rename from docs/src/main/asciidoc/_verifier_faq.adoc rename to docs/src/main/asciidoc/howto.adoc index 97ac27ecee..5043e5704d 100644 --- a/docs/src/main/asciidoc/_verifier_faq.adoc +++ b/docs/src/main/asciidoc/howto.adoc @@ -1,12 +1,23 @@ -:introduction_url: https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch} -:samples_branch: 2.2.x +[[howto]] += "`How-to`" Guides +include::_attributes.adoc[] -== Spring Cloud Contract FAQ +This section provides answers to some common '`how do I do that...`' questions +that often arise when using {project-full-name}. Its coverage is not exhaustive, but it +does cover quite a lot. -=== Why use Spring Cloud Contract Verifier and not X ? +If you have a specific problem that we do not cover here, you might want to check out +https://stackoverflow.com/tags/{project-name}[stackoverflow.com] to see if someone has +already provided an answer. This is also a great place to ask new questions (please use +the `{project-name}` tag). -For the time being Spring Cloud Contract is a JVM based tool. So it could be your first pick when you're already creating -software for the JVM. This project has a lot of really interesting features but especially quite a few of them definitely make +We are also more than happy to extend this section. If you want to add a '`how-to`', +send us a {github-code}[pull request]. + +[[why-spring-cloud-contract]] +== Why use Spring Cloud Contract and not X ? + +Spring Cloud Contract works great in a polyglot environment. This project has a lot of really interesting features but especially quite a few of them definitely make Spring Cloud Contract Verifier stand out on the "market" of Consumer Driven Contract (CDC) tooling. Out of many the most interesting are: - Possibility to do CDC with messaging @@ -18,11 +29,16 @@ Spring Cloud Contract Verifier stand out on the "market" of Consumer Driven Cont - Spring Cloud Contract integrates with Pact out of the box and provides easy hooks to extend its functionality - Via Docker adds support for any language & framework used -=== I don't want to write a contract in Groovy! +[[how-to-not-write-contracts-in-groovy]] +== I don't want to write a contract in Groovy! -No problem. You can write a contract in YAML! +// TODO: Add a link +No problem. You can write a contract in YAML! Check this section for more information -=== What is this value(consumer(), producer()) ? +We are working on allowing more ways of describing the contracts. You can check the {github-issues}[github-issues] for more information. + +[[how-to-provide-dynamic-values]] +== What is this value(consumer(), producer()) ? One of the biggest challenges related to stubs is their reusability. Only if they can be vastly used, will they serve their purpose. What typically makes that difficult are the hard-coded values of request / response elements. For example dates or ids. @@ -107,69 +123,19 @@ what you might want is the following response: How can you then provide one time a matcher for the consumer and a concrete value for the producer and vice versa? In Spring Cloud Contract we're allowing you to provide a *dynamic value*. That means that it can differ for both -sides of the communication. You can pass the values: - -Either via the `value` method - -[source,groovy,indent=0] ----- -value(consumer(...), producer(...)) -value(stub(...), test(...)) -value(client(...), server(...)) ----- - -or using the `$()` method - -[source,groovy,indent=0] ----- -$(consumer(...), producer(...)) -$(stub(...), test(...)) -$(client(...), server(...)) ----- +sides of the communication. +// TODO: Ensure that the link is correct You can read more about this in the <> section. -Calling `value()` or `$()` tells Spring Cloud Contract that you will be passing a dynamic value. -Inside the `consumer()` method you pass the value that should be used on the consumer side (in the generated stub). -Inside the `producer()` method you pass the value that should be used on the producer side (in the generated test). - -TIP: If on one side you have passed the regular expression and you haven't passed the other, then the -other side will get auto-generated. - -Most often you will use that method together with the `regex` helper method. E.g. `consumer(regex('[0-9]{10}'))`. - -To sum it up the contract for the aforementioned scenario would look more or less like this (the regular expression -for time and UUID are simplified and most likely invalid but we want to keep things very simple in this example): - -[source,groovy,indent=0] ----- -org.springframework.cloud.contract.spec.Contract.make { - request { - method 'GET' - url '/someUrl' - body([ - time : value(consumer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')), - id: value(consumer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}')) - body: "foo" - ]) - } - response { - status OK() - body([ - time : value(producer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')), - id: value([producer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}')) - body: "bar" - ]) - } -} ----- - IMPORTANT: Please read the https://groovy-lang.org/json.html[Groovy docs related to JSON] to understand how to properly structure the request / response bodies. -=== How to do Stubs versioning? +[[how-to-do-stubs-versioning]] +== How to do Stubs versioning? -==== API Versioning +[[how-to-api-versioning]] +=== API Versioning Let's try to answer a question what versioning really means. If you're referring to the API version then there are different approaches. @@ -177,13 +143,14 @@ different approaches. - use Hypermedia, links and do not version your API by any means - pass versions through headers / urls -I will not try to answer a question which approach is better. Whatever suits your needs and allows you to generate +We will not try to answer a question which approach is better. Whatever suits your needs and allows you to generate business value should be picked. Let's assume that you do version your API. In that case you should provide as many contracts as many versions you support. You can create a subfolder for every version or append it to the contract name - whatever suits you more. -==== JAR versioning +[[how-to-jar-versioning]] +=== JAR versioning If by versioning you mean the version of the JAR that contains the stubs then there are essentially two main approaches. @@ -219,7 +186,8 @@ version. Example for 2.1.1. @AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:2.1.1:stubs:8080"}) ---- -==== Dev or prod stubs +[[how-to-dev-or-prod-stubs]] +=== Dev or prod stubs You can manipulate the classifier to run the tests against current development version of the stubs of other services or the ones that were deployed to production. If you alter your build to deploy the stubs with the `prod-stubs` classifier @@ -241,14 +209,16 @@ Example of tests using production version of stubs You can pass those values also via properties from your deployment pipeline. -=== Common repo with contracts +[[how-to-common-repo-with-contracts]] +== Common repo with contracts Another way of storing contracts other than having them with the producer is keeping them in a common place. It can be related to security issues where the consumers can't clone the producer's code. Also if you keep contracts in a single place then you, as a producer, will know how many consumers you have and which consumer you will break with your local changes. -==== Repo structure +[[how-to-repo-structure]] +=== Repo structure Let's assume that we have a producer with coordinates `com.example:server` and 3 consumers: `client1`, `client2`, `client3`. Then in the repository with common contracts you would have the following setup @@ -304,13 +274,47 @@ It's using the assembly plugin in order to build the JAR with all the contracts. include::{introduction_url}/samples/standalone/contracts/src/assembly/contracts.xml[indent=0] ---- -==== Workflow +[[how-to-workflow]] +=== Workflow -The workflow would look similar to the one presented in the `Step by step guide to CDC`. The only difference - is that the producer doesn't own the contracts anymore. So the consumer and the producer have to work on - common contracts in a common repository. +The workflow assumes that Spring Cloud Contract is setup both on the consumer and the producer side. There is also the proper plugin setup in the common repo with contracts. The CI jobs are set for common repo to build an artifact of all contracts and upload it to Nexus / Artifactory. -==== Consumer +[plantuml, three-second, png] +---- +"API Consumer"->"Common repo": create a folder \nfor producer [API Producer] +"API Consumer"->"Common repo": under [API Producer] create a folder \nfor consumer \n[API Consumer] +"API Consumer"->"Common repo": define contracts under \n[API Consumer] folder +"API Consumer"->"Common repo": install stubs of [API Producer]\nin local storage +"Common repo"->"Common Repo\nSCC Plugin": install stubs \nin local storage. \nDon't generate tests. +"Common Repo\nSCC Plugin"->"Local storage": install stubs +"Local storage"->"Common Repo\nSCC Plugin": stubs installed +"API Consumer"->"API Consumer": write a SCC Stub Runner \nbased contract test +"API Consumer"->"API Consumer\nSCC Stub Runner": fetch the stubs\n of [API Producer] \nfrom local storage +"API Consumer\nSCC Stub Runner"->"Local storage": test asks for [API Producer] stubs +"Local storage"->"API Consumer\nSCC Stub Runner": [API Producer] stubs found +"API Consumer\nSCC Stub Runner"->"API Consumer\nSCC Stub Runner": run in memory\n HTTP server stubs +"API Consumer\nSCC Stub Runner"->"API Consumer": HTTP server stubs running,\n ready for tests +"API Consumer"->"API Consumer\nSCC Stub Runner": send a request \nto the HTTP server stub +"API Consumer\nSCC Stub Runner"->"API Consumer": communication is correct. \nTests are passing +"API Consumer"->"Common repo": file pull request \nwith contracts +"API Producer"->"Common repo": take over \nthe pull request +"API Producer"->"Common repo": install the JAR \nwith all contracts\n in local storage +"Common repo"->"Local storage": install the JAR +"Local storage"->"Common repo": contracts JAR installed +"API Producer"->"Producer Build": run the build \nand fetch contracts from \nlocal storage +"Producer Build"->"Producer\nSCC Plugin": generate \ntests, stubs and stubs \nartifact (e.g. stubs-jar) +"Producer\nSCC Plugin"->"Local storage": fetch contract definitions for [API Prodcer] +"Local storage"->"Producer\nSCC Plugin": contracts fetched +"Producer\nSCC Plugin"->"Producer Build": tests and stubs created +"Producer Build"->"Nexus / Artifactory": upload contracts \nand stubs and the project arifact +"Producer Build"->"API Producer": Build successful +"API Producer"->"Common repo": merge the pull request +"Common repo"->"Nexus / Artifactory": upload the fresh JAR \nwith contract definitions +"API Producer"->"API Producer": start fetching contract definitions \nfrom Nexus / Artifactory +---- + +[[how-to-workflow-consumer]] +=== Consumer When the *consumer* wants to work on the contracts offline, instead of cloning the producer code, the consumer team clones the common repository, goes to the required producer's folder (e.g. `com/example/server`) @@ -318,7 +322,8 @@ and runs `mvn clean install -DskipTests` to install locally the stubs converted TIP: You need to have https://maven.apache.org/download.cgi[Maven installed locally] -==== Producer +[[how-to-workflow-producer]] +=== Producer As a *producer* it's enough to alter the Spring Cloud Contract Verifier to provide the URL and the dependency of the JAR containing the contracts: @@ -336,13 +341,15 @@ when some incompatible changes are done. The rest of the flow looks the same. -==== How can I define messaging contracts per topic not per producer? +[[how-to-define-messaging-contracts-per-topic]] +=== How can I define messaging contracts per topic not per producer? To avoid messaging contracts duplication in the common repo, when few producers writing messages to one topic, we could create the structure when the rest contracts would be placed in a folder per producer and messaging contracts in the folder per topic. -===== For Maven Project +[[how-to-define-messaging-contracts-per-topic-maven]] +==== For Maven Project To make it possible to work on the producer side we should specify an inclusion pattern for filtering common repository jar by messaging topics we are interested in. ```includedFiles``` property of ```Maven Spring Cloud Contract plugin``` @@ -383,7 +390,8 @@ allows us to do that. Also ```contractsPath``` need to be specified since the de ---- -===== For Gradle Project +[[how-to-define-messaging-contracts-per-topic-gradle]] +==== For Gradle Project - Add a custom configuration for the common-repo dependency: @@ -467,7 +475,8 @@ contracts { } ---- -=== Do I need a Binary Storage? Can't I use Git? +[[how-to-use-git-as-storage]] +== Do I need a Binary Storage? Can't I use Git? In the polyglot world, there are languages that don't use binary storages like Artifactory or Nexus. Starting from Spring Cloud Contract version 2.0.0 we provide @@ -520,7 +529,8 @@ the stub server mappings. On the consumer side, Stub Runner will scan this folde to start stub servers with stub definitions. The folder structure will be a copy of the one created in the `contracts` subfolder. -==== Protocol convention +[[how-to-protocol-convention]] +=== Protocol convention In order to control the type and location of the source of contracts (whether it's a binary storage or an SCM repository), you can use the protocol in the URL of @@ -538,11 +548,12 @@ git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contr git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git ---- -==== Producer +[[how-to-protocol-convention-producer]] +=== Producer For the producer, to use the SCM approach, we can reuse the same mechanism we use for external contracts. We route Spring Cloud Contract -to use the SCM implementation via the URL that contains +to use the SCM implementation via the URL that starts with the `git://` protocol. IMPORTANT: You have to manually add the `pushStubsToScm` @@ -550,8 +561,9 @@ goal in Maven or execute (bind) the `pushStubsToScm` task in Gradle. We don't push stubs to `origin` of your git repository out of the box. -.Maven -[source,xml,indent=0] +==== +[source,xml,indent=0,role="primary"] +.maven ---- org.springframework.cloud @@ -589,8 +601,8 @@ repository out of the box. ---- -.Gradle -[source,gradle,indent=0] +[source,groovy,indent=0,role="secondary"] +.gradle ---- contracts { // We want to pick contracts from a Git repository @@ -616,6 +628,7 @@ the `publish` task is executed */ publish.dependsOn("publishStubsToScm") ---- +==== With such a setup: @@ -628,21 +641,24 @@ to find contracts. E.g. for `com.example:foo:1.0.0` the path would be * Once the tests pass, the stubs will be committed in the cloned repository * Finally, a push will be done to that repo's `origin` -==== Producer with contracts stored locally +[[how-to-protocol-convention-producer-with-contracts-stored-locally]] +=== Producer with contracts stored locally Another option to use the SCM as the destination for stubs and contracts is to store the contracts locally, with the producer, and only push the contracts and the stubs to SCM. Below, you can find the setup required to achieve this using Maven and Gradle. -.Maven -[source,xml,indent=0] +==== +[source,xml,indent=0,role="primary"] +.maven ---- include::{samples_url}/producer_with_empty_git/pom.xml[tags=plugin,indent=0] ---- -.Gradle -[source,xml,indent=0] +[source,groovy,indent=0,role="secondary"] +.gradle ---- include::{samples_url}/producer_with_empty_git/build.gradle[tags=plugin,indent=0] ---- +==== With such a setup: @@ -654,7 +670,8 @@ With such a setup: ** The stubs and contracts will be committed in the cloned repository * Finally, a push will be done to that repo's `origin` -===== Keeping contracts with the producer and stubs in an external repository +[[how-to-protocol-convention-contracts-producer-stubs-external]] +=== Keeping contracts with the producer and stubs in an external repository It is also possible to keep the contracts in the producer repository, but keep the stubs in an external git repo. This is most useful when you want to use the base consumer-producer collaboration flow, but do not have a possibility to @@ -663,7 +680,8 @@ use an artifact repository for storing the stubs. In order to do that, use the usual producer setup, and then add the `pushStubsToScm` goal and set `contractsRepositoryUrl` to the repository where you want to keep the stubs. -==== Consumer +[[how-to-protocol-convention-contracts-producer-stubs-external-consumer]] +=== Consumer On the consumer side when passing the `repositoryRoot` parameter, either from the `@AutoConfigureStubRunner` annotation, the @@ -688,7 +706,8 @@ to find stub definitions and contracts. E.g. for `com.example:foo:1.0.0` the pat * Stub servers will be started and fed with mappings * Messaging definitions will be read and used in the messaging tests -=== Can I use the Pact Broker? +[[how-to-use-pact-broker]] +== Can I use the Pact Broker? When using https://pact.io/[Pact] you can use the https://github.com/pact-foundation/pact_broker[Pact Broker] to store and share Pact definitions. Starting from Spring Cloud Contract @@ -705,13 +724,15 @@ shares the files with the Producer. Those expectations are generated from the Consumer's code and can break the Producer if the expectations are not met. -==== Pact Consumer +[[how-to-pact-consumer]] +=== Pact Consumer The consumer uses Pact framework to generate Pact files. The Pact files are sent to the Pact Broker. An example of such setup can be found https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/consumer_pact[here]. -==== Producer +[[how-to-pact-producer]] +=== Producer For the producer, to use the Pact files from the Pact Broker, we can reuse the same mechanism we use for external contracts. We route Spring Cloud Contract @@ -719,8 +740,9 @@ to use the Pact implementation via the URL that contains the `pact://` protocol. It's enough to pass the URL to the Pact Broker. An example of such setup can be found https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/producer_pact[here]. -.Maven -[source,xml,indent=0] +==== +[source,xml,indent=0,role="primary"] +.maven ---- org.springframework.cloud @@ -757,8 +779,8 @@ Pact Broker. An example of such setup can be found https://github.com/spring-clo ---- -.Gradle -[source,gradle,indent=0] +[source,groovy,indent=0,role="secondary"] +.gradle ---- buildscript { repositories { @@ -785,6 +807,7 @@ contracts { // Base class mappings etc. } ---- +==== With such a setup: @@ -792,7 +815,8 @@ With such a setup: * Spring Cloud Contract will convert the Pact files into tests and stubs * The JAR with the stubs gets automatically created as usual -==== Pact Consumer (Producer Contract approach) +[[how-to-pact-consumer-producer-contract]] +=== Pact Consumer (Producer Contract approach) In the scenario where you don't want to do Consumer Contract approach (for every single consumer define the expectations) but you'd prefer @@ -803,8 +827,9 @@ Stub Runner option. An example of such setup can be found https://github.com/spr First, remember to add Stub Runner and Spring Cloud Contract Pact module as test dependencies. -.Maven -[source,xml,indent=0] +==== +[source,xml,indent=0,role="primary"] +.maven ---- @@ -834,8 +859,8 @@ as test dependencies. ---- -.Gradle -[source,gradle,indent=0] +[source,groovy,indent=0,role="secondary"] +.gradle ---- dependencyManagement { imports { @@ -850,6 +875,7 @@ dependencies { testCompile("org.springframework.cloud:spring-cloud-contract-pact") } ---- +==== Next, just pass the URL of the Pact Broker to `repositoryRoot`, prefixed with `pact://` protocol. E.g. `pact://http://localhost:8085` @@ -877,7 +903,8 @@ With such a setup: For more information about Pact support you can go to the <> section. -=== How can I debug the request/response being sent by the generated tests client? +[[how-to-debug]] +== How can I debug the request/response being sent by the generated tests client? The generated tests all boil down to RestAssured in some form or fashion which relies on https://hc.apache.org/httpcomponents-client-ga/[Apache HttpClient]. HttpClient has a facility called https://hc.apache.org/httpcomponents-client-ga/logging.html#Wire_Logging[wire logging] which logs the entire request and response to HttpClient. Spring Boot has a logging https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html[common application property] for doing this sort of thing, just add this to your application properties [source,properties,indent=0] @@ -885,7 +912,8 @@ The generated tests all boil down to RestAssured in some form or fashion which r logging.level.org.apache.http.wire=DEBUG ---- -==== How can I debug the mapping/request/response being sent by WireMock? +[[how-to-debug-wiremock]] +== How can I debug the mapping/request/response being sent by WireMock? Starting from version `1.2.0` we turn on WireMock logging to info and the WireMock notifier to being verbose. Now you will @@ -899,13 +927,15 @@ To turn off this feature just bump WireMock logging to `ERROR` logging.level.com.github.tomakehurst.wiremock=ERROR ---- -==== How can I see what got registered in the HTTP server stub? +[[how-to-see-registered-stubs]] +== How can I see what got registered in the HTTP server stub? You can use the `mappingsOutputFolder` property on `@AutoConfigureStubRunner`, `StubRunnerRule` or `StubRunnerExtension`to dump all mappings per artifact id. Also the port at which the given stub server was started will be attached. -==== Can I reference text from file? +[[how-to-reference-text-from-file]] +== Can I reference text from file? Yes! With version 1.2.0 we've added such a possibility. It's enough to call `file(...)` method in the DSL and provide a path relative to where the contract lays. diff --git a/docs/src/main/asciidoc/spring-cloud-contract.adoc b/docs/src/main/asciidoc/spring-cloud-contract.adoc deleted file mode 120000 index 1abdb4fda5..0000000000 --- a/docs/src/main/asciidoc/spring-cloud-contract.adoc +++ /dev/null @@ -1 +0,0 @@ -index.htmladoc \ No newline at end of file From 6a408f9a05e29991e06358aea265fcd2d6ce6755 Mon Sep 17 00:00:00 2001 From: Marcin Grzejszczak Date: Fri, 19 Jul 2019 20:02:36 +0200 Subject: [PATCH 05/18] WIP --- docs/src/main/asciidoc/getting-started.adoc | 1616 ++-- docs/src/main/asciidoc/project-features.adoc | 9041 ++++++++++++++++++ 2 files changed, 9962 insertions(+), 695 deletions(-) create mode 100644 docs/src/main/asciidoc/project-features.adoc diff --git a/docs/src/main/asciidoc/getting-started.adoc b/docs/src/main/asciidoc/getting-started.adoc index 4dc56a7fc6..5585967c82 100644 --- a/docs/src/main/asciidoc/getting-started.adoc +++ b/docs/src/main/asciidoc/getting-started.adoc @@ -2,820 +2,1046 @@ = Getting Started include::_attributes.adoc[] -If you are getting started with Spring Boot, or "`Spring`" in general, start by reading +If you are getting started with {project-full-name}, or "`Spring`" in general, start by reading this section. It answers the basic "`what?`", "`how?`" and "`why?`" questions. It -includes an introduction to Spring Boot, along with installation instructions. We then -walk you through building your first Spring Boot application, discussing some core +includes an introduction to {project-full-name}, along with installation instructions. We then +walk you through building your first {project-full-name} application, discussing some core principles as we go. +[[getting-started-introducing-spring-cloud-contract]] +== Introducing Spring Cloud Contract +Spring Cloud Contract moves TDD to the level of software architecture. It allows to perform consumer, consumer-driven and producer-driven contract testing. -[[getting-started-introducing-spring-boot]] -== Introducing Spring Boot -Spring Boot makes it easy to create stand-alone, production-grade Spring-based -Applications that you can run. We take an opinionated view of the Spring platform and -third-party libraries, so that you can get started with minimum fuss. Most Spring Boot -applications need very little Spring configuration. +[[getting-started-introducing-spring-cloud-contract-history]] +=== History -You can use Spring Boot to create Java applications that can be started by using -`java -jar` or more traditional war deployments. We also provide a command line tool that -runs "`spring scripts`". +Before becoming Spring Cloud Contract, this project was called https://github.com/Codearte/accurest[Accurest]. +It was created by https://twitter.com/mgrzejszczak[Marcin Grzejszczak] and https://twitter.com/jkubrynski[Jakub Kubrynski] +from (https://github.com/Codearte[Codearte]. -Our primary goals are: +The `0.1.0` release took place on 26 Jan 2015 and it became stable with `1.0.0` release on 29 Feb 2016. -* Provide a radically faster and widely accessible getting-started experience for all -Spring development. -* Be opinionated out of the box but get out of the way quickly as requirements start to -diverge from the defaults. -* Provide a range of non-functional features that are common to large classes of projects -(such as embedded servers, security, metrics, health checks, and externalized -configuration). -* Absolutely no code generation and no requirement for XML configuration. +[[getting-started-introducing-spring-cloud-contract-why]] +==== Why would you need it? +Assume that we have a system consisting of multiple microservices: +image::images/Deps.png[Microservices Architecture] -[[getting-started-system-requirements]] -== System Requirements -Spring Boot {spring-boot-version} requires https://www.java.com[Java 8] and is compatible -up to Java 12 (included). {spring-reference}[Spring Framework {spring-framework-version}] -or above is also required. +[[getting-started-introducing-spring-cloud-contract-testing-issues]] +==== Testing issues -Explicit build support is provided for the following build tools: +If we wanted to test the application in top left corner to determine whether it can +communicate with other services, we could do one of two things: -|=== -|Build Tool |Version +- Deploy all microservices and perform end-to-end tests. +- Mock other microservices in unit/integration tests. -|Maven -|3.3+ +Both have their advantages but also a lot of disadvantages. -|Gradle -|5.x (4.10 is also supported but in a deprecated form) -|=== +*Deploy all microservices and perform end to end tests* +Advantages: +- Simulates production. +- Tests real communication between services. -[[getting-started-system-requirements-servlet-containers]] -=== Servlet Containers -Spring Boot supports the following embedded servlet containers: +Disadvantages: -|=== -|Name |Servlet Version +- To test one microservice, we have to deploy 6 microservices, a couple of databases, +etc. +- The environment where the tests run is locked for a single suite of tests (nobody else +would be able to run the tests in the meantime). +- They take a long time to run. +- The feedback comes very late in the process. +- They are extremely hard to debug. -|Tomcat 9.0 -|4.0 +*Mock other microservices in unit/integration tests* -|Jetty 9.4 -|3.1 +Advantages: -|Undertow 2.0 -|4.0 -|=== +- They provide very fast feedback. +- They have no infrastructure requirements. -You can also deploy Spring Boot applications to any Servlet 3.1+ compatible container. +Disadvantages: +- The implementor of the service creates stubs that might have nothing to do with +reality. +- You can go to production with passing tests and failing production. +To solve the aforementioned issues, Spring Cloud Contract was created. The main idea is to give you very fast feedback, without the need to set up the +whole world of microservices. If you work on stubs, then the only applications you need +are those that your application directly uses. -[[getting-started-installing-spring-boot]] -== Installing Spring Boot -Spring Boot can be used with "`classic`" Java development tools or installed as a command -line tool. Either way, you need https://www.java.com[Java SDK v1.8] or higher. Before you -begin, you should check your current Java installation by using the following command: +image::images/Stubs2.png[Stubbed Services] -[indent=0] +Spring Cloud Contract gives you the certainty that the stubs that you use were +created by the service that you're calling. Also, if you can use them, it means that they +were tested against the producer's side. In short, you can trust those stubs. + +[[getting-started-introducing-spring-cloud-contract-purposes]] +=== Purposes + +The main purposes of Spring Cloud Contract are: + +- To ensure that HTTP / Messaging stubs (used when developing the client) do exactly +what the actual server-side implementation does. +- To promote ATDD (acceptance test driven developement) method and Microservices architectural style. +- To provide a way to publish changes in contracts that are immediately visible on both sides. +- To generate boilerplate test code to be used on the server side. + +By default Spring Cloud Contract integrates with http://wiremock.org[Wiremock] as the HTTP server stub. + +IMPORTANT: Spring Cloud Contract's purpose is NOT to start writing business +features in the contracts. Assume that we have a business use case of fraud check. If a +user can be a fraud for 100 different reasons, we would assume that you would create 2 +contracts, one for the positive case and one for the negative case. Contract tests are +used to test contracts between applications and not to simulate full behavior. + +[[getting-started-what-is-a-contract]] +=== What is a contract? + +As consumers of services, we need to define what exactly we want to achieve. We need to +formulate our expectations. That is why we write contracts. In other words a contract is an agreement on how the API / message communication should look like. Let's look at the following example + +Assume that you want to send a request containing the ID of a client company and the +amount it wants to borrow from us. You also want to send it to the /fraudcheck url via +the PUT method. + +==== +[source,groovy,indent=0,role="primary"] +.groovy ---- - $ java -version +include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[] ---- -If you are new to Java development or if you want to experiment with Spring Boot, you -might want to try the <> (Command -Line Interface) first. Otherwise, read on for "`classic`" installation instructions. - - - -[[getting-started-installation-instructions-for-java]] -=== Installation Instructions for the Java Developer -You can use Spring Boot in the same way as any standard Java library. To do so, include -the appropriate `+spring-boot-*.jar+` files on your classpath. Spring Boot does not -require any special tools integration, so you can use any IDE or text editor. Also, there -is nothing special about a Spring Boot application, so you can run and debug a Spring -Boot application as you would any other Java program. - -Although you _could_ copy Spring Boot jars, we generally recommend that you use a build -tool that supports dependency management (such as Maven or Gradle). - - - -[[getting-started-maven-installation]] -==== Maven Installation -Spring Boot is compatible with Apache Maven 3.3 or above. If you do not already have -Maven installed, you can follow the instructions at https://maven.apache.org. - -TIP: On many operating systems, Maven can be installed with a package manager. If you use -OSX Homebrew, try `brew install maven`. Ubuntu users can run -`sudo apt-get install maven`. Windows users with https://chocolatey.org/[Chocolatey] can -run `choco install maven` from an elevated (administrator) prompt. - -Spring Boot dependencies use the `org.springframework.boot` `groupId`. Typically, your -Maven POM file inherits from the `spring-boot-starter-parent` project and declares -dependencies to one or more <>. -Spring Boot also provides an optional -<> to create -executable jars. - -The following listing shows a typical `pom.xml` file: - -[source,xml,indent=0,subs="verbatim,quotes,attributes"] +[source,yaml,indent=0,role="secondary"] +.yaml ---- - - - 4.0.0 +include::{introduction_url}/samples/standalone/yml/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.yml[] +---- +==== - com.example - myproject - 0.0.1-SNAPSHOT +[[getting-started-three-second-tour]] +== A Three-second Tour - - - org.springframework.boot - spring-boot-starter-parent - {spring-boot-version} - +This very brief tour walks through using Spring Cloud Contract: - - - - org.springframework.boot - spring-boot-starter-web - - +* <> +* <> - - - - - org.springframework.boot - spring-boot-maven-plugin - - - +You can find a somewhat longer tour +<>. -ifeval::["{spring-boot-repo}" != "release"] - - - - - spring-snapshots - https://repo.spring.io/snapshot - true - - - spring-milestones - https://repo.spring.io/milestone - - - - - spring-snapshots - https://repo.spring.io/snapshot - - - spring-milestones - https://repo.spring.io/milestone - - -endif::[] - +[plantuml, three-second, png] +---- +"API Producer"->"API Producer": add Spring Cloud \nContract (SCC) plugin +"API Producer"->"API Producer": add SCC Verifier dependency +"API Producer"->"API Producer": define contracts +"API Producer"->"Build": run build +"Build"->"SCC Plugin": generate \ntests, stubs and stubs \nartifact (e.g. stubs-jar) +"Build"->"Nexus / Artifactory": upload contracts \nand stubs and the project arifact +"Build"->"API Producer": Build successful +"API Consumer"->"API Consumer": add SCC Stub Runner \ndependency +"API Consumer"->"API Consumer": write a SCC Stub Runner \nbased contract test +"SCC Stub Runner"->"Nexus / Artifactory": test asks for [API Producer] stubs +"Nexus / Artifactory"->"SCC Stub Runner": fetch the [API Producer] stubs +"SCC Stub Runner"->"SCC Stub Runner": run in memory\n HTTP server stubs +"API Consumer"->"SCC Stub Runner": send a request \nto the HTTP server stub +"SCC Stub Runner"->"API Consumer": communication is correct ---- -TIP: The `spring-boot-starter-parent` is a great way to use Spring Boot, but it might not -be suitable all of the time. Sometimes you may need to inherit from a different parent -POM, or you might not like our default settings. In those cases, see -<> for an alternative solution that uses an `import` -scope. +[[getting-started-three-second-tour-producer]] +=== On the Producer Side +To start working with Spring Cloud Contract, add files with `REST`/messaging contracts +expressed in either Groovy DSL or YAML to the contracts directory, which is set by the +`contractsDslDir` property. By default, it is `$rootDir/src/test/resources/contracts`. - -[[getting-started-gradle-installation]] -==== Gradle Installation -Spring Boot is compatible with 5.x. 4.10 is also supported but this support is deprecated -and will be removed in a future release. If you do not already have Gradle installed, you -can follow the instructions at https://gradle.org. - -Spring Boot dependencies can be declared by using the `org.springframework.boot` `group`. -Typically, your project declares dependencies to one or more -<>. Spring Boot -provides a useful <> that can be used to simplify dependency declarations and to create executable -jars. - -.Gradle Wrapper -**** -The Gradle Wrapper provides a nice way of "`obtaining`" Gradle when you need to build a -project. It is a small script and library that you commit alongside your code to -bootstrap the build process. See {gradle-user-guide}/gradle_wrapper.html for details. -**** - -More details on getting started with Spring Boot and Gradle can be found in the -{spring-boot-gradle-plugin-reference}/#getting-started[Getting Started section] of the -Gradle plugin's reference guide. - - - -[[getting-started-installing-the-cli]] -=== Installing the Spring Boot CLI -The Spring Boot CLI (Command Line Interface) is a command line tool that you can use to -quickly prototype with Spring. It lets you run http://groovy-lang.org/[Groovy] scripts, -which means that you have a familiar Java-like syntax without so much boilerplate code. - -You do not need to use the CLI to work with Spring Boot, but it is definitely the -quickest way to get a Spring application off the ground. - - - -[[getting-started-manual-cli-installation]] -==== Manual Installation -You can download the Spring CLI distribution from the Spring software repository: - -* https://repo.spring.io/{spring-boot-repo}/org/springframework/boot/spring-boot-cli/{spring-boot-version}/spring-boot-cli-{spring-boot-version}-bin.zip[spring-boot-cli-{spring-boot-version}-bin.zip] -* https://repo.spring.io/{spring-boot-repo}/org/springframework/boot/spring-boot-cli/{spring-boot-version}/spring-boot-cli-{spring-boot-version}-bin.tar.gz[spring-boot-cli-{spring-boot-version}-bin.tar.gz] - -Cutting edge -https://repo.spring.io/snapshot/org/springframework/boot/spring-boot-cli/[snapshot -distributions] are also available. - -Once downloaded, follow the -{github-raw}/spring-boot-project/spring-boot-cli/src/main/content/INSTALL.txt[INSTALL.txt] -instructions from the unpacked archive. In summary, there is a `spring` script -(`spring.bat` for Windows) in a `bin/` directory in the `.zip` file. Alternatively, you -can use `java -jar` with the `.jar` file (the script helps you to be sure that the -classpath is set correctly). - - - -[[getting-started-sdkman-cli-installation]] -==== Installation with SDKMAN! -SDKMAN! (The Software Development Kit Manager) can be used for managing multiple versions -of various binary SDKs, including Groovy and the Spring Boot CLI. -Get SDKMAN! from https://sdkman.io and install Spring Boot by using the following -commands: - -[indent=0,subs="verbatim,quotes,attributes"] ----- - $ sdk install springboot - $ spring --version - Spring Boot v{spring-boot-version} ----- - -If you develop features for the CLI and want easy access to the version you built, -use the following commands: - -[indent=0,subs="verbatim,quotes,attributes"] ----- - $ sdk install springboot dev /path/to/spring-boot/spring-boot-cli/target/spring-boot-cli-{spring-boot-version}-bin/spring-{spring-boot-version}/ - $ sdk default springboot dev - $ spring --version - Spring CLI v{spring-boot-version} ----- - -The preceding instructions install a local instance of `spring` called the `dev` -instance. It points at your target build location, so every time you rebuild Spring Boot, -`spring` is up-to-date. - -You can see it by running the following command: - -[indent=0,subs="verbatim,quotes,attributes"] ----- - $ sdk ls springboot - - ================================================================================ - Available Springboot Versions - ================================================================================ - > + dev - * {spring-boot-version} - - ================================================================================ - + - local version - * - installed - > - currently in use - ================================================================================ ----- - - - -[[getting-started-homebrew-cli-installation]] -==== OSX Homebrew Installation -If you are on a Mac and use https://brew.sh/[Homebrew], you can install the Spring Boot -CLI by using the following commands: - -[indent=0] ----- - $ brew tap pivotal/tap - $ brew install springboot ----- - -Homebrew installs `spring` to `/usr/local/bin`. - -NOTE: If you do not see the formula, your installation of brew might be out-of-date. In -that case, run `brew update` and try again. - - - -[[getting-started-macports-cli-installation]] -==== MacPorts Installation -If you are on a Mac and use https://www.macports.org/[MacPorts], you can install the -Spring Boot CLI by using the following command: - -[indent=0] ----- - $ sudo port install spring-boot-cli ----- - - - -[[getting-started-cli-command-line-completion]] -==== Command-line Completion -The Spring Boot CLI includes scripts that provide command completion for the -https://en.wikipedia.org/wiki/Bash_%28Unix_shell%29[BASH] and -https://en.wikipedia.org/wiki/Z_shell[zsh] shells. You can `source` the script (also named -`spring`) in any shell or put it in your personal or system-wide bash completion -initialization. On a Debian system, the system-wide scripts are in -`/shell-completion/bash` and all scripts in that directory are executed when a new shell -starts. For example, to run the script manually if you have installed by using SDKMAN!, -use the following commands: - -[indent=0] ----- - $ . ~/.sdkman/candidates/springboot/current/shell-completion/bash/spring - $ spring - grab help jar run test version ----- - -NOTE: If you install the Spring Boot CLI by using Homebrew or MacPorts, the command-line -completion scripts are automatically registered with your shell. - - - -[[getting-started-scoop-cli-installation]] -==== Windows Scoop Installation -If you are on a Windows and use https://scoop.sh/[Scoop], you can install the Spring Boot -CLI by using the following commands: - -[indent=0] ----- - > scoop bucket add extras - > scoop install springboot ----- - -Scoop installs `spring` to `~/scoop/apps/springboot/current/bin`. - -NOTE: If you do not see the app manifest, your installation of scoop might be out-of-date. -In that case, run `scoop update` and try again. - - - -[[getting-started-cli-example]] -==== Quick-start Spring CLI Example -You can use the following web application to test your installation. To start, create a -file called `app.groovy`, as follows: - -[source,groovy,indent=0,subs="verbatim,quotes,attributes"] ----- - @RestController - class ThisWillActuallyRun { - - @RequestMapping("/") - String home() { - "Hello World!" - } - - } ----- - -Then run it from a shell, as follows: - -[indent=0] ----- - $ spring run app.groovy ----- - -NOTE: The first run of your application is slow, as dependencies are downloaded. -Subsequent runs are much quicker. - -Open `http://localhost:8080` in your favorite web browser. You should see the following -output: - -[indent=0] ----- - Hello World! ----- - - - -[[getting-started-upgrading-from-an-earlier-version]] -=== Upgrading from an Earlier Version of Spring Boot -If you are upgrading from an earlier release of Spring Boot, check the -{github-wiki}/Spring-Boot-2.0-Migration-Guide["`migration guide`" on the project wiki] -that provides detailed upgrade instructions. Check also the -{github-wiki}["`release notes`"] for a list of "`new and noteworthy`" features for each -release. - -When upgrading to a new feature release, some properties may have been renamed or removed. -Spring Boot provides a way to analyze your application's environment and print diagnostics -at startup, but also temporarily migrate properties at runtime for you. To enable that -feature, add the following dependency to your project: +Then add the Spring Cloud Contract Verifier dependency and plugin to your build file, as +shown in the following example: [source,xml,indent=0] ---- - - org.springframework.boot - spring-boot-properties-migrator - runtime - +include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] ---- -WARNING: Properties that are added late to the environment, such as when using -`@PropertySource`, will not be taken into account. +The following listing shows how to add the plugin, which should go in the build/plugins +portion of the file: -NOTE: Once you're done with the migration, please make sure to remove this module from -your project's dependencies. +[source,xml,indent=0] +---- + + org.springframework.cloud + spring-cloud-contract-maven-plugin + ${spring-cloud-contract.version} + true + +---- -To upgrade an existing CLI installation, use the appropriate package manager command (for -example, `brew upgrade`) or, if you manually installed the CLI, follow the -<>, remembering to update -your `PATH` environment variable to remove any older references. +Running `./mvnw clean install` automatically generates tests that verify the application +compliance with the added contracts. By default, the tests get generated under +`org.springframework.cloud.contract.verifier.tests.`. +As the implementation of the functionalities described by the contracts is not yet +present, the tests fail. +To make them pass, you must add the correct implementation of either handling HTTP +requests or messages. Also, you must add a correct base test class for auto-generated +tests to the project. This class is extended by all the auto-generated tests, and it +should contain all the setup necessary to run them (for example `RestAssuredMockMvc` +controller setup or messaging test setup). + +Once the implementation and the test base class are in place, the tests pass, and both the +application and the stub artifacts are built and installed in the local Maven repository. +The changes can now be merged, and both the application and the stub artifacts may be +published in an online repository. + +[[getting-started-three-second-tour-consumer]] +=== On the Consumer Side + +`Spring Cloud Contract Stub Runner` can be used in the integration tests to get a running +WireMock instance or messaging route that simulates the actual service. + +To do so, add the dependency to `Spring Cloud Contract Stub Runner`, as shown in the +following example: + +[source,xml,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] +---- + +You can get the Producer-side stubs installed in your Maven repository in either of two +ways: + +* By checking out the Producer side repository and adding contracts and generating the stubs +by running the following commands: ++ +[source,bash,indent=0] +---- +$ cd local-http-server-repo +$ ./mvnw clean install -DskipTests +---- +TIP: The tests are being skipped because the Producer-side contract implementation is not +in place yet, so the automatically-generated contract tests fail. +* By getting already-existing producer service stubs from a remote repository. To do so, +pass the stub artifact IDs and artifact repository URL as `Spring Cloud Contract +Stub Runner` properties, as shown in the following example: ++ +[source,yaml,indent=0] +---- +include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] +---- + +Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, +provide the `group-id` and `artifact-id` values for `Spring Cloud Contract Stub Runner` to +run the collaborators' stubs for you, as shown in the following example: + +[source,java, indent=0] +---- +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment=WebEnvironment.NONE) +@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"}, + stubsMode = StubRunnerProperties.StubsMode.LOCAL) +public class LoanApplicationServiceTests { +---- + +TIP: Use the `REMOTE` `stubsMode` when downloading stubs from an online repository and +`LOCAL` for offline work. + +Now, in your integration test, you can receive stubbed versions of HTTP responses or +messages that are expected to be emitted by the collaborator service. [[getting-started-first-application]] -== Developing Your First Spring Boot Application -This section describes how to develop a simple "`Hello World!`" web application that -highlights some of Spring Boot's key features. We use Maven to build this project, since -most IDEs support it. +== Developing Your First Spring Cloud Contract based application + +This brief tour walks through using Spring Cloud Contract: + +* <> +* <> + +You can find an even more brief tour +<>. + +[[getting-started-first-application-producer]] +=== On the Producer Side + +To start working with `Spring Cloud Contract`, add files with `REST/` messaging contracts +expressed in either Groovy DSL or YAML to the contracts directory, which is set by the +`contractsDslDir` property. By default, it is `$rootDir/src/test/resources/contracts`. + +For the HTTP stubs, a contract defines what kind of response should be returned for a +given request (taking into account the HTTP methods, URLs, headers, status codes, and so +on). The following example shows how an HTTP stub contract: -[TIP] ==== -The https://spring.io[spring.io] web site contains many "`Getting Started`" -https://spring.io/guides[guides] that use Spring Boot. If you need to solve a specific -problem, check there first. +[source,groovy,indent=0,role="primary"] +.groovy +---- +package contracts -You can shortcut the steps below by going to https://start.spring.io and choosing the -"Web" starter from the dependencies searcher. Doing so generates a new project structure -so that you can <>. Check -the {spring-initializr-reference}/#user-guide[Spring Initializr documentation] for more -details. +org.springframework.cloud.contract.spec.Contract.make { + request { + method 'PUT' + url '/fraudcheck' + body([ + "client.id": $(regex('[0-9]{10}')), + loanAmount: 99999 + ]) + headers { + contentType('application/json') + } + } + response { + status OK() + body([ + fraudCheckStatus: "FRAUD", + "rejection.reason": "Amount too high" + ]) + headers { + contentType('application/json') + } + } +} +---- + +[source,yaml,indent=0,role="secondary"] +.yaml +---- +request: + method: PUT + url: /fraudcheck + body: + "client.id": 1234567890 + loanAmount: 99999 + headers: + Content-Type: application/json + matchers: + body: + - path: $.['client.id'] + type: by_regex + value: "[0-9]{10}" +response: + status: 200 + body: + fraudCheckStatus: "FRAUD" + "rejection.reason": "Amount too high" + headers: + Content-Type: application/json;charset=UTF-8 +---- ==== -Before we begin, open a terminal and run the following commands to ensure that you have -valid versions of Java and Maven installed: +In the case of messaging, you can define: -[indent=0] +* The input and the output messages can be defined (taking into account from and where it +was sent, the message body, and the header). +* The methods that should be called after the message is received. +* The methods that, when called, should trigger a message. + +The following example shows a Camel messaging contract: + +==== +[source,groovy,indent=0,role="primary"] +.groovy ---- - $ java -version - java version "1.8.0_102" - Java(TM) SE Runtime Environment (build 1.8.0_102-b14) - Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode) +include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_no_output_dsl] ---- -[indent=0] +[source,yaml,indent=0,role="secondary"] +.yaml ---- - $ mvn -v - Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-17T14:33:14-04:00) - Maven home: /usr/local/Cellar/maven/3.3.9/libexec - Java version: 1.8.0_102, vendor: Oracle Corporation +include::{verifier_core_path}/src/test/resources/yml/contract_message_scenario3.yml[indent=0] +---- +==== + + +Then you can add Spring Cloud Contract Verifier dependency and plugin to your build file, +as shown in the following example: + +[source,xml,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] ---- -NOTE: This sample needs to be created in its own folder. Subsequent instructions assume -that you have created a suitable folder and that it is your current directory. +The following listing shows how to add the plugin, which should go in the build/plugins +portion of the file: - - -[[getting-started-first-application-pom]] -=== Creating the POM -We need to start by creating a Maven `pom.xml` file. The `pom.xml` is the recipe that is -used to build your project. Open your favorite text editor and add the following: - -[source,xml,indent=0,subs="verbatim,quotes,attributes"] +[source,xml,indent=0] ---- - - - 4.0.0 - - com.example - myproject - 0.0.1-SNAPSHOT - - - org.springframework.boot - spring-boot-starter-parent - {spring-boot-version} - - - - -ifeval::["{spring-boot-repo}" != "release"] - - - - spring-snapshots - https://repo.spring.io/snapshot - true - - - spring-milestones - https://repo.spring.io/milestone - - - - - spring-snapshots - https://repo.spring.io/snapshot - - - spring-milestones - https://repo.spring.io/milestone - - -endif::[] - + + org.springframework.cloud + spring-cloud-contract-maven-plugin + ${spring-cloud-contract.version} + true + ---- -The preceding listing should give you a working build. You can test it by running `mvn -package` (for now, you can ignore the "`jar will be empty - no content was marked for -inclusion!`" warning). +Running `./mvnw clean install` automatically generates tests that verify the application +compliance with the added contracts. By default, the generated tests are under +`org.springframework.cloud.contract.verifier.tests.`. -NOTE: At this point, you could import the project into an IDE (most modern Java IDEs -include built-in support for Maven). For simplicity, we continue to use a plain text -editor for this example. - - - -[[getting-started-first-application-dependencies]] -=== Adding Classpath Dependencies -Spring Boot provides a number of "`Starters`" that let you add jars to your classpath. -Our applications for smoke tests use the `spring-boot-starter-parent` in the `parent` -section of the POM. The `spring-boot-starter-parent` is a special starter that provides -useful Maven defaults. It also provides a -<> -section so that you can omit `version` tags for "`blessed`" dependencies. - -Other "`Starters`" provide dependencies that you are likely to need when developing a -specific type of application. Since we are developing a web application, we add a -`spring-boot-starter-web` dependency. Before that, we can look at what we currently have -by running the following command: - -[indent=0] ----- - $ mvn dependency:tree - - [INFO] com.example:myproject:jar:0.0.1-SNAPSHOT ----- - -The `mvn dependency:tree` command prints a tree representation of your project -dependencies. You can see that `spring-boot-starter-parent` provides no dependencies by -itself. To add the necessary dependencies, edit your `pom.xml` and add the -`spring-boot-starter-web` dependency immediately below the `parent` section: - -[source,xml,indent=0,subs="verbatim,quotes,attributes"] ----- - - - org.springframework.boot - spring-boot-starter-web - - ----- - -If you run `mvn dependency:tree` again, you see that there are now a number of additional -dependencies, including the Tomcat web server and Spring Boot itself. - - - -[[getting-started-first-application-code]] -=== Writing the Code -To finish our application, we need to create a single Java file. By default, Maven -compiles sources from `src/main/java`, so you need to create that folder structure and -then add a file named `src/main/java/Example.java` to contain the following code: +The following example shows a sample auto-generated test for an HTTP contract: [source,java,indent=0] ---- - import org.springframework.boot.*; - import org.springframework.boot.autoconfigure.*; - import org.springframework.web.bind.annotation.*; +@Test +public void validate_shouldMarkClientAsFraud() throws Exception { + // given: + MockMvcRequestSpecification request = given() + .header("Content-Type", "application/vnd.fraud.v1+json") + .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}"); - @RestController - @EnableAutoConfiguration - public class Example { + // when: + ResponseOptions response = given().spec(request) + .put("/fraudcheck"); - @RequestMapping("/") - String home() { - return "Hello World!"; - } + // then: + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*"); + // and: + DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); + assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}"); + assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high"); +} +---- - public static void main(String[] args) { - SpringApplication.run(Example.class, args); - } +The preceding example uses Spring's `MockMvc` to run the tests. This is the default test +mode for HTTP contracts. However, JAX-RS client and explicit HTTP invocations can also be +used. (To do so, change the `testMode` property of the plugin to `JAX-RS` or `EXPLICIT`, +respectively.) +Since 2.1.0, it is also possible to use `RestAssuredWebTestClient`with Spring's reactive `WebTestClient` +run under the hood. This is particularly recommended while working with Reactive, `Web-Flux`-based applications. +In order to use `WebTestClient` set `testMode` to `WEBTESTCLIENT`. + +Here is an example of a test generated in `WEBTESTCLIENT` test mode: + +[source,java,indent=0] +---- +@Test + public void validate_shouldRejectABeerIfTooYoung() throws Exception { + // given: + WebTestClientRequestSpecification request = given() + .header("Content-Type", "application/json") + .body("{\"age\":10}"); + + // when: + WebTestClientResponse response = given().spec(request) + .post("/check"); + + // then: + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.header("Content-Type")).matches("application/json.*"); + // and: + DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); + assertThatJson(parsedJson).field("['status']").isEqualTo("NOT_OK"); } ---- -Although there is not much code here, quite a lot is going on. We step through the -important parts in the next few sections. +Apart from the default JUnit 4, you can instead use JUnit 5 or Spock tests, by setting the plugin +`testFramework` property to either `JUNIT5` or `Spock`. +TIP: You can now also generate WireMock scenarios based on the contracts, by including an +order number followed by an underscore at the beginning of the contract file names. +The following example shows an auto-generated test in Spock for a messaging stub contract: -[[getting-started-first-application-annotations]] -==== The `@RestController` and `@RequestMapping` Annotations -The first annotation on our `Example` class is `@RestController`. This is known as a -_stereotype_ annotation. It provides hints for people reading the code and for Spring -that the class plays a specific role. In this case, our class is a web `@Controller`, so -Spring considers it when handling incoming web requests. - -The `@RequestMapping` annotation provides "`routing`" information. It tells Spring that -any HTTP request with the `/` path should be mapped to the `home` method. The -`@RestController` annotation tells Spring to render the resulting string directly back to -the caller. - -TIP: The `@RestController` and `@RequestMapping` annotations are Spring MVC annotations. -(They are not specific to Spring Boot.) See the {spring-reference}web.html#mvc[MVC -section] in the Spring Reference Documentation for more details. - - - -[[getting-started-first-application-auto-configuration]] -==== The @EnableAutoConfiguration Annotation -The second class-level annotation is `@EnableAutoConfiguration`. This annotation tells -Spring Boot to "`guess`" how you want to configure Spring, based on the jar dependencies -that you have added. Since `spring-boot-starter-web` added Tomcat and Spring MVC, the -auto-configuration assumes that you are developing a web application and sets up Spring -accordingly. - -.Starters and Auto-configuration -**** -Auto-configuration is designed to work well with "`Starters`", but the two concepts are -not directly tied. You are free to pick and choose jar dependencies outside of the -starters. Spring Boot still does its best to auto-configure your application. -**** - - - -[[getting-started-first-application-main-method]] -==== The "`main`" Method -The final part of our application is the `main` method. This is just a standard method -that follows the Java convention for an application entry point. Our main method -delegates to Spring Boot's `SpringApplication` class by calling `run`. -`SpringApplication` bootstraps our application, starting Spring, which, in turn, starts -the auto-configured Tomcat web server. We need to pass `Example.class` as an argument to -the `run` method to tell `SpringApplication` which is the primary Spring component. The -`args` array is also passed through to expose any command-line arguments. - - - -[[getting-started-first-application-run]] -=== Running the Example -At this point, your application should work. Since you used the -`spring-boot-starter-parent` POM, you have a useful `run` goal that you can use to start -the application. Type `mvn spring-boot:run` from the root project directory to start the -application. You should see output similar to the following: - -[indent=0,subs="attributes"] +[source,groovy,indent=0] ---- - $ mvn spring-boot:run +given: + ContractVerifierMessage inputMessage = contractVerifierMessaging.create( + \'\'\'{"bookName":"foo"}\'\'\', + ['sample': 'header'] + ) - . ____ _ __ _ _ - /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ - ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ - \\/ ___)| |_)| | | | | || (_| | ) ) ) ) - ' |____| .__|_| |_|_| |_\__, | / / / / - =========|_|==============|___/=/_/_/_/ - :: Spring Boot :: (v{spring-boot-version}) - ....... . . . - ....... . . . (log output here) - ....... . . . - ........ Started Example in 2.222 seconds (JVM running for 6.514) +when: + contractVerifierMessaging.send(inputMessage, 'jms:delete') + +then: + noExceptionThrown() + bookWasDeleted() ---- -If you open a web browser to `http://localhost:8080`, you should see the following output: +As the implementation of the functionalities described by the contracts is not yet +present, the tests fail. -[indent=0] +To make them pass, you must add the correct implementation of handling either HTTP +requests or messages. Also, you must add a correct base test class for auto-generated +tests to the project. This class is extended by all the auto-generated tests and should +contain all the setup necessary to run them (for example, `RestAssuredMockMvc` controller +setup or messaging test setup). + +Once the implementation and the test base class are in place, the tests pass, and both the +application and the stub artifacts are built and installed in the local Maven repository. +Information about installing the stubs jar to the local repository appears in the logs, as +shown in the following example: + +[source,bash,indent=0] ---- - Hello World! + [INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server --- + [INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar + [INFO] + [INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server --- + [INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar + [INFO] + [INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server --- + [INFO] + [INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server --- + [INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar + [INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom + [INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar ---- -To gracefully exit the application, press `ctrl-c`. +You can now merge the changes and publish both the application and the stub artifacts +in an online repository. +// TODO: Consider moving this section somewhere else +*Docker Project* +In order to enable working with contracts while creating applications in non-JVM +technologies, the `springcloud/spring-cloud-contract` Docker image has been created. It +contains a project that automatically generates tests for HTTP contracts and executes them +in `EXPLICIT` test mode. Then, if the tests pass, it generates Wiremock stubs and, +optionally, publishes them to an artifact manager. In order to use the image, you can +mount the contracts into the `/contracts` directory and set a few environment variables. +// TODO: We should answer the obvious question: Which environment variables? -[[getting-started-first-application-executable-jar]] -=== Creating an Executable Jar -We finish our example by creating a completely self-contained executable jar file that -we could run in production. Executable jars (sometimes called "`fat jars`") are archives -containing your compiled classes along with all of the jar dependencies that your code -needs to run. +[[getting-started-first-application-consumer]] +=== On the Consumer Side -.Executable jars and Java -**** -Java does not provide a standard way to load nested jar files (jar files that are -themselves contained within a jar). This can be problematic if you are looking to -distribute a self-contained application. +`Spring Cloud Contract Stub Runner` can be used in the integration tests to get a running +WireMock instance or messaging route that simulates the actual service. -To solve this problem, many developers use "`uber`" jars. An uber jar packages all the -classes from all the application's dependencies into a single archive. The problem with -this approach is that it becomes hard to see which libraries are in your application. It -can also be problematic if the same filename is used (but with different content) in -multiple jars. +To get started, add the dependency to `Spring Cloud Contract Stub Runner`: -Spring Boot takes a <> and lets you -actually nest jars directly. -**** - -To create an executable jar, we need to add the `spring-boot-maven-plugin` to our -`pom.xml`. To do so, insert the following lines just below the `dependencies` section: - -[source,xml,indent=0,subs="verbatim,quotes,attributes"] +[source,xml,indent=0] ---- - - - - org.springframework.boot - spring-boot-maven-plugin - - - +include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] ---- -NOTE: The `spring-boot-starter-parent` POM includes `` configuration to bind -the `repackage` goal. If you do not use the parent POM, you need to declare this -configuration yourself. See the {spring-boot-maven-plugin-site}/usage.html[plugin -documentation] for details. +You can get the Producer-side stubs installed in your Maven repository in either of two +ways: -Save your `pom.xml` and run `mvn package` from the command line, as follows: - -[indent=0,subs="attributes"] +* By checking out the Producer side repository and adding contracts and generating the +stubs by running the following commands: ++ +[source,bash,indent=0] ---- - $ mvn package - - [INFO] Scanning for projects... - [INFO] - [INFO] ------------------------------------------------------------------------ - [INFO] Building myproject 0.0.1-SNAPSHOT - [INFO] ------------------------------------------------------------------------ - [INFO] .... .. - [INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ myproject --- - [INFO] Building jar: /Users/developer/example/spring-boot-example/target/myproject-0.0.1-SNAPSHOT.jar - [INFO] - [INFO] --- spring-boot-maven-plugin:{spring-boot-version}:repackage (default) @ myproject --- - [INFO] ------------------------------------------------------------------------ - [INFO] BUILD SUCCESS - [INFO] ------------------------------------------------------------------------ +$ cd local-http-server-repo +$ ./mvnw clean install -DskipTests +---- +NOTE: The tests are skipped because the Producer-side contract implementation is not yet +in place, so the automatically-generated contract tests fail. +* Getting already existing producer service stubs from a remote repository. To do so, +pass the stub artifact IDs and artifact repository URl as `Spring Cloud Contract Stub +Runner` properties, as shown in the following example: ++ +[source,yaml,indent=0] +---- +include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ---- -If you look in the `target` directory, you should see `myproject-0.0.1-SNAPSHOT.jar`. The -file should be around 10 MB in size. If you want to peek inside, you can use `jar tvf`, -as follows: +Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, +provide the `group-id` and `artifact-id` for `Spring Cloud Contract Stub Runner` to run +the collaborators' stubs for you, as shown in the following example: -[indent=0] +[source,java, indent=0] ---- - $ jar tvf target/myproject-0.0.1-SNAPSHOT.jar +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment=WebEnvironment.NONE) +@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"}, + stubsMode = StubRunnerProperties.StubsMode.LOCAL) +public class LoanApplicationServiceTests { ---- -You should also see a much smaller file named `myproject-0.0.1-SNAPSHOT.jar.original` in -the `target` directory. This is the original jar file that Maven created before it was -repackaged by Spring Boot. +TIP: Use the `REMOTE` `stubsMode` when downloading stubs from an online repository and +`LOCAL` for offline work. -To run that application, use the `java -jar` command, as follows: +In your integration test, you can receive stubbed versions of HTTP responses or messages +that are expected to be emitted by the collaborator service. You can see entries similar +to the following in the build logs: -[indent=0,subs="attributes"] +[source,bash,indent=0] ---- - $ java -jar target/myproject-0.0.1-SNAPSHOT.jar - - . ____ _ __ _ _ - /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ - ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ - \\/ ___)| |_)| | | | | || (_| | ) ) ) ) - ' |____| .__|_| |_|_| |_\__, | / / / / - =========|_|==============|___/=/_/_/_/ - :: Spring Boot :: (v{spring-boot-version}) - ....... . . . - ....... . . . (log output here) - ....... . . . - ........ Started Example in 2.536 seconds (JVM running for 2.864) +2016-07-19 14:22:25.403 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Desired version is + - will try to resolve the latest version +2016-07-19 14:22:25.438 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved version is 0.0.1-SNAPSHOT +2016-07-19 14:22:25.439 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories [] +2016-07-19 14:22:25.451 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar +2016-07-19 14:22:25.465 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar] +2016-07-19 14:22:25.475 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265] +2016-07-19 14:22:27.737 INFO 41050 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}] ---- -As before, to exit the application, press `ctrl-c`. +[[getting-started-cdc]] +== Step-by-step Guide to Consumer Driven Contracts (CDC) +Consider an example of Fraud Detection and the Loan Issuance process. The business +scenario is such that we want to issue loans to people but do not want them to steal from +us. The current implementation of our system grants loans to everybody. +Assume that `Loan Issuance` is a client to the `Fraud Detection` server. In the current +sprint, we must develop a new feature: if a client wants to borrow too much money, then +we mark the client as a fraud. + +Technical remark - Fraud Detection has an `artifact-id` of `http-server`, while Loan +Issuance has an artifact-id of `http-client`, and both have a `group-id` of `com.example`. + +Social remark - both client and server development teams need to communicate directly and +discuss changes while going through the process. CDC is all about communication. + +The https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-server[server +side code is available here] and https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-client[the +client code here]. + +TIP: In this case, the producer owns the contracts. Physically, all the contract are +in the producer's repository. + +[[getting-started-cdc-technical-note]] +=== Technical note + +If using the *SNAPSHOT* / *Milestone* / *Release Candidate* versions please add the +following section to your build: + +[source,xml,indent=0,subs="verbatim,attributes",role="primary"] +.Maven +---- +include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=repos,indent=0] +---- + +[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] +.Gradle +---- +include::{introduction_url}/samples/standalone/dsl/http-server/build.gradle[tags=deps_repos,indent=0] +---- + +=== Consumer side (Loan Issuance) + +As a developer of the Loan Issuance service (a consumer of the Fraud Detection server), you might do the following steps: + +. Start doing TDD by writing a test for your feature. +. Write the missing implementation. +. Clone the Fraud Detection service repository locally. +. Define the contract locally in the repo of Fraud Detection service. +. Add the Spring Cloud Contract (SCC) plugin. +. Run the integration tests. +. File a pull request. +. Create an initial implementation. +. Take over the pull request. +. Write the missing implementation. +. Deploy your app. +. Work online. + +[plantuml, cdc, png] +---- +"Loan Issuance"->"Loan Issuance": start doing TDD\nby writing a test\nfor your feature +"Loan Issuance"->"Loan Issuance": write the \nmissing implementation +"Loan Issuance"->"Fraud Detection": clone the repository +"Loan Issuance"->"Fraud Detection Clone": start working on the clone +"Fraud Detection Clone"->"Fraud Detection Clone": add missing dependencies\ndefine contracts +"Fraud Detection Clone"->"Fraud Detection Clone": add the Spring Cloud \nContract plugin +"Fraud Detection Clone"->"Fraud Detection \nClone Build": install the stubs locally +"Fraud Detection \nClone Build"->"SCC Plugin": generate stubs \nand stubs \nartifact (e.g. stubs-jar) +"Fraud Detection \nClone Build"->"Local storage": install the stubs locally +"Local storage"->"Fraud Detection Build": stub sucessfully installed +"Fraud Detection Build"->"API Producer": Build successful +"API Consumer"->"API Consumer": add SCC Stub Runner \ndependency +"API Consumer"->"API Consumer": write a SCC Stub Runner \nbased contract test +"SCC Stub Runner"->"Nexus / Artifactory": test asks for [API Producer] stubs +"Nexus / Artifactory"->"SCC Stub Runner": fetch the [API Producer] stubs +"SCC Stub Runner"->"SCC Stub Runner": run in memory\n HTTP server stubs +"API Consumer"->"SCC Stub Runner": send a request \nto the HTTP server stub +"SCC Stub Runner"->"API Consumer": communication is correct +---- + +*Start doing TDD by writing a test for your feature.* + +[source,groovy,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=client_tdd,indent=0] +---- + +Assume that you have written a test of your new feature. If a loan application for a big +amount is received, the system should reject that loan application with some description. + +*Write the missing implementation.* + +At some point in time, you need to send a request to the Fraud Detection service. Assume +that you need to send the request containing the ID of the client and the amount the +client wants to borrow. You want to send it to the `/fraudcheck` url via the `PUT` method. + +[source,groovy,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-client/src/main/java/com/example/loan/LoanApplicationService.java[tags=client_call_server,indent=0] +---- + +For simplicity, the port of the Fraud Detection service is set to `8080`, and the +application runs on `8090`. + +If you start the test at this point, it breaks, because no service currently runs on port +`8080`. + +*Clone the Fraud Detection service repository locally.* + +You can start by playing around with the server side contract. To do so, you must first +clone it. + +[source,bash,indent=0] +---- +$ git clone https://your-git-server.com/server-side.git local-http-server-repo +---- + +*Define the contract locally in the repo of Fraud Detection service.* + +As a consumer, you need to define what exactly you want to achieve. You need to formulate +your expectations. To do so, write the following contract: + +IMPORTANT: Place the contract under `src/test/resources/contracts/fraud` folder. The `fraud` folder +is important because the producer's test base class name references that folder. + +==== +[source,groovy,indent=0,role="primary"] +.groovy +---- +include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[] +---- + +[source,yaml,indent=0,role="secondary"] +.yaml +---- +include::{introduction_url}/samples/standalone/yml/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.yml[] +---- +==== + +The YML contract is quite straight-forward. However when you take a look at the Contract +written using a statically typed Groovy DSL - you might wonder what the +`value(client(...), server(...))` parts are. By using this notation, Spring Cloud +Contract lets you define parts of a JSON block, a URL, etc., which are dynamic. In case +of an identifier or a timestamp, you need not hardcode a value. You want to allow some +different ranges of values. To enable ranges of values, you can set regular expressions +matching those values for the consumer side. You can provide the body by means of either +a map notation or String with interpolations. +Consult the <> section for more information. We highly recommend using the map notation! + +TIP: You must understand the map notation in order to set up contracts. Please read the +https://groovy-lang.org/json.html[Groovy docs regarding JSON]. + +The previously shown contract is an agreement between two sides that: + +- if an HTTP request is sent with all of +** a `PUT` method on the `/fraudcheck` endpoint, +** a JSON body with a `client.id` that matches the regular expression `[0-9]{10}` and +`loanAmount` equal to `99999`, +** and a `Content-Type` header with a value of `application/vnd.fraud.v1+json`, +- then an HTTP response is sent to the consumer that +** has status `200`, +** contains a JSON body with the `fraudCheckStatus` field containing a value `FRAUD` and +the `rejectionReason` field having value `Amount too high`, +** and a `Content-Type` header with a value of `application/vnd.fraud.v1+json`. + +Once you are ready to check the API in practice in the integration tests, you need to +install the stubs locally. + +*Add the Spring Cloud Contract Verifier plugin.* + +We can add either a Maven or a Gradle plugin. In this example, you see how to add Maven. +First, add the `Spring Cloud Contract` BOM. + +[source,xml,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_bom,indent=0] +---- + +Next, add the `Spring Cloud Contract Verifier` Maven plugin + +[source,xml,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0] +---- + +Since the plugin was added, you get the `Spring Cloud Contract Verifier` features which, +from the provided contracts: + +- generate and run tests +- produce and install stubs + +You do not want to generate tests since you, as the consumer, want only to play with the +stubs. You need to skip the test generation and execution. When you execute: + +[source,bash,indent=0] +---- +$ cd local-http-server-repo +$ ./mvnw clean install -DskipTests +---- + +In the logs, you see something like this: + +[source,bash,indent=0] +---- +[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server --- +[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar +[INFO] +[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server --- +[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar +[INFO] +[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server --- +[INFO] +[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server --- +[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar +[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom +[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar +---- + +The following line is extremely important: + +[source,bash,indent=0] +---- +[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar +---- + +It confirms that the stubs of the `http-server` have been installed in the local +repository. + +*Run the integration tests.* + +In order to profit from the Spring Cloud Contract Stub Runner functionality of automatic +stub downloading, you must do the following in your consumer side project (`Loan +Application service`): + +Add the `Spring Cloud Contract` BOM: + +[source,xml,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=contract_bom,indent=0] +---- + +Add the dependency to `Spring Cloud Contract Stub Runner`: + +[source,xml,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] +---- + +Annotate your test class with `@AutoConfigureStubRunner`. In the annotation, provide the +`group-id` and `artifact-id` for the Stub Runner to download the stubs of your +collaborators. (Optional step) Because you're playing with the collaborators offline, you +can also provide the offline work switch (`StubRunnerProperties.StubsMode.LOCAL`). + +[source,groovy,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=autoconfigure_stubrunner,indent=0] +---- + +Now, when you run your tests, you see something like this: + +[source,bash,indent=0] +---- +2016-07-19 14:22:25.403 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Desired version is + - will try to resolve the latest version +2016-07-19 14:22:25.438 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved version is 0.0.1-SNAPSHOT +2016-07-19 14:22:25.439 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories [] +2016-07-19 14:22:25.451 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar +2016-07-19 14:22:25.465 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar] +2016-07-19 14:22:25.475 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265] +2016-07-19 14:22:27.737 INFO 41050 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}] +---- + +This output means that Stub Runner has found your stubs and started a server for your app +with group id `com.example`, artifact id `http-server` with version `0.0.1-SNAPSHOT` of +the stubs and with `stubs` classifier on port `8080`. + +*File a pull request.* + +What you have done until now is an iterative process. You can play around with the +contract, install it locally, and work on the consumer side until the contract works as +you wish. + +Once you are satisfied with the results and the test passes, publish a pull request to +the server side. Currently, the consumer side work is done. + +=== Producer side (Fraud Detection server) + +As a developer of the Fraud Detection server (a server to the Loan Issuance service): + +*Create an initial implementation.* + +As a reminder, you can see the initial implementation here: + +[source,java,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=server_api,indent=0] +include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=initial_impl,indent=0] +} +---- + +*Take over the pull request.* + +[source,bash,indent=0] +---- +$ git checkout -b contract-change-pr master +$ git pull https://your-git-server.com/server-side-fork.git contract-change-pr +---- + +You must add the dependencies needed by the autogenerated tests: + +[source,xml,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] +---- + +In the configuration of the Maven plugin, pass the `packageWithBaseClasses` property + +[source,xml,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0] +---- + +IMPORTANT: This example uses "convention based" naming by setting the +`packageWithBaseClasses` property. Doing so means that the two last packages combine to +make the name of the base test class. In our case, the contracts were placed under +`src/test/resources/contracts/fraud`. Since you do not have two packages starting from +the `contracts` folder, pick only one, which should be `fraud`. Add the `Base` suffix and +capitalize `fraud`. That gives you the `FraudBase` test class name. + +All the generated tests extend that class. Over there, you can set up your Spring Context +or whatever is necessary. In this case, use https://github.com/rest-assured/rest-assured[Rest Assured MVC] to +start the server side `FraudDetectionController`. + +[source,java,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-server/src/test/java/com/example/fraud/FraudBase.java[] +---- + +Now, if you run the `./mvnw clean install`, you get something like this: + +[source,bash,indent=0] +---- +Results : + +Tests in error: + ContractVerifierTest.validate_shouldMarkClientAsFraud:32 » IllegalState Parsed... +---- + +This error occurs because you have a new contract from which a test was generated and it +failed since you have not implemented the feature. The auto-generated test would look +like this: + +[source,java,indent=0] +---- +@Test +public void validate_shouldMarkClientAsFraud() throws Exception { + // given: + MockMvcRequestSpecification request = given() + .header("Content-Type", "application/vnd.fraud.v1+json") + .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}"); + + // when: + ResponseOptions response = given().spec(request) + .put("/fraudcheck"); + + // then: + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*"); + // and: + DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); + assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}"); + assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high"); +} +---- + +If you used the Groovy DSL, you can see, all the `producer()` parts of the Contract that were present in the +`value(consumer(...), producer(...))` blocks got injected into the test. +In case of using YAML, the same applied for the `matchers` sections of the `response`. + +Note that, on the producer side, you are also doing TDD. The expectations are expressed +in the form of a test. This test sends a request to our own application with the URL, +headers, and body defined in the contract. It also is expecting precisely defined values +in the response. In other words, you have the `red` part of `red`, `green`, and +`refactor`. It is time to convert the `red` into the `green`. + +*Write the missing implementation.* + +Because you know the expected input and expected output, you can write the missing +implementation: + +[source,java,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=server_api,indent=0] +include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=new_impl,indent=0] +include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=initial_impl,indent=0] +} +---- + +When you execute `./mvnw clean install` again, the tests pass. Since the `Spring Cloud +Contract Verifier` plugin adds the tests to the `generated-test-sources`, you can +actually run those tests from your IDE. + +*Deploy your app.* + +Once you finish your work, you can deploy your change. First, merge the branch: + +[source,bash,indent=0] +---- +$ git checkout master +$ git merge --no-ff contract-change-pr +$ git push origin master +---- + +Your CI might run something like `./mvnw clean deploy`, which would publish both the +application and the stub artifacts. + +=== Consumer Side (Loan Issuance) Final Step + +As a developer of the Loan Issuance service (a consumer of the Fraud Detection server): + +*Merge branch to master.* + +[source,bash,indent=0] +---- +$ git checkout master +$ git merge --no-ff contract-change-pr +---- + +*Work online.* + +Now you can disable the offline work for Spring Cloud Contract Stub Runner and indicate +where the repository with your stubs is located. At this moment the stubs of the server +side are automatically downloaded from Nexus/Artifactory. You can set the value of +`stubsMode` to `REMOTE`. The following code shows an example of +achieving the same thing by changing the properties. + +[source,yaml,indent=0] +---- +include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] +---- + +That's it! [[getting-started-whats-next]] == What to Read Next -Hopefully, this section provided some of the Spring Boot basics and got you on your way +Hopefully, this section provided some of the {project-full-name} basics and got you on your way to writing your own applications. If you are a task-oriented type of developer, you might want to jump over to https://spring.io and check out some of the https://spring.io/guides/[getting started] guides that solve specific "`How do I do that -with Spring?`" problems. We also have Spring Boot-specific +with Spring?`" problems. We also have {project-full-name}-specific "`<>`" reference documentation. -Otherwise, the next logical step is to read _<>_. If +Otherwise, the next logical step is to read _<>_. If you are really impatient, you could also jump ahead and read about -_<>_. +_<>_. + +// TODO: Update the video +// TODO: Check if we can link courses +In addition to that you can check out the video from the Warsaw JUG about Spring Cloud Contract: + +video::sAAklvxmPmk[youtube,start=538,width=640,height=480] + +You can read the following articles / presentations: + +// TODO: Update the readings +- https://www.slideshare.net/MarcinGrzejszczak/stick-to-the-rules-consumer-driven-contracts-201507-confitura[Slides from Marcin Grzejszczak's talk about Accurest] +- https://toomuchcoding.com/blog/categories/accurest/[Accurest related articles from Marcin Grzejszczak's blog] +- https://toomuchcoding.com/blog/categories/spring-cloud-contract/[Spring Cloud Contract related articles from Marcin Grzejszczak's blog] +- https://groovy-lang.org/json.html[Groovy docs regarding JSON] + +You can find the default project samples at +https://github.com/spring-cloud-samples/spring-cloud-contract-samples[samples]. \ No newline at end of file diff --git a/docs/src/main/asciidoc/project-features.adoc b/docs/src/main/asciidoc/project-features.adoc new file mode 100644 index 0000000000..c48708d7cc --- /dev/null +++ b/docs/src/main/asciidoc/project-features.adoc @@ -0,0 +1,9041 @@ +[[boot-features]] += Spring Boot Features +include::attributes.adoc[] + +This section dives into the details of Spring Boot. Here you can learn about the key +features that you may want to use and customize. If you have not already done so, you +might want to read the "<>" and +"<>" sections, so that you have a good grounding of the +basics. + + + +[[boot-features-spring-application]] +== SpringApplication +The `SpringApplication` class provides a convenient way to bootstrap a Spring application +that is started from a `main()` method. In many situations, you can delegate to the +static `SpringApplication.run` method, as shown in the following example: + +[source,java,indent=0] +---- + public static void main(String[] args) { + SpringApplication.run(MySpringConfiguration.class, args); + } +---- + +When your application starts, you should see something similar to the following output: + +[indent=0,subs="attributes"] +---- + . ____ _ __ _ _ + /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ +( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ + \\/ ___)| |_)| | | | | || (_| | ) ) ) ) + ' |____| .__|_| |_|_| |_\__, | / / / / + =========|_|==============|___/=/_/_/_/ + :: Spring Boot :: v{spring-boot-version} + +2013-07-31 00:08:16.117 INFO 56603 --- [ main] o.s.b.s.app.SampleApplication : Starting SampleApplication v0.1.0 on mycomputer with PID 56603 (/apps/myapp.jar started by pwebb) +2013-07-31 00:08:16.166 INFO 56603 --- [ main] ationConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6e5a8246: startup date [Wed Jul 31 00:08:16 PDT 2013]; root of context hierarchy +2014-03-04 13:09:54.912 INFO 41370 --- [ main] .t.TomcatServletWebServerFactory : Server initialized with port: 8080 +2014-03-04 13:09:56.501 INFO 41370 --- [ main] o.s.b.s.app.SampleApplication : Started SampleApplication in 2.992 seconds (JVM running for 3.658) +---- + +By default, `INFO` logging messages are shown, including some relevant startup details, +such as the user that launched the application. If you need a log level other than `INFO`, +you can set it, as described in <>, + + + +[[boot-features-startup-failure]] +=== Startup Failure +If your application fails to start, registered `FailureAnalyzers` get a chance to provide +a dedicated error message and a concrete action to fix the problem. For instance, if you +start a web application on port `8080` and that port is already in use, you should see +something similar to the following message: + +[indent=0] +---- + *************************** + APPLICATION FAILED TO START + *************************** + + Description: + + Embedded servlet container failed to start. Port 8080 was already in use. + + Action: + + Identify and stop the process that's listening on port 8080 or configure this application to listen on another port. +---- + +NOTE: Spring Boot provides numerous `FailureAnalyzer` implementations, and you can +<>. + +If no failure analyzers are able to handle the exception, you can still display the full +conditions report to better understand what went wrong. To do so, you need to +<> or +<> for +`org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener`. + +For instance, if you are running your application by using `java -jar`, you can enable +the `debug` property as follows: + +[indent=0,subs="attributes"] +---- + $ java -jar myproject-0.0.1-SNAPSHOT.jar --debug +---- + + + +[[boot-features-lazy-initialization]] +=== Lazy Initialization +`SpringApplication` allows an application to be initialized lazily. When lazy +initialization is enabled, beans are created as they are needed rather than during +application startup. As a result, enabling lazy initialization can reduce the time that +it takes your application to start. In a web application, enabling lazy initialization +will result in many web-related beans not being initialized until an HTTP request is +received. + +A downside of lazy initialization is that it can delay the discovery of a problem with +the application. If a misconfigured bean is initialized lazily, a failure will no longer +occur during startup and the problem will only become apparent when the bean is +initialized. Care must also be taken to ensure that the JVM has sufficient memory to +accommodate all of the application's beans and not just those that are initialized during +startup. For these reasons, lazy initialization is not enabled by default and it is +recommended that fine-tuning of the JVM's heap size is done before enabling lazy +initialization. + +Lazy initialization can be enabled programatically using the `lazyInitialization` method +on `SpringApplicationBuilder` or the `setLazyInitialization` method on +`SpringApplication`. Alternatively, it can be enabled using the +`spring.main.lazy-initialization` property as shown in the following example: + +[source,properties,indent=0] +---- + spring.main.lazy-initialization=true +---- + +TIP: If you want to disable lazy initialization for certain beans while using lazy +initialization for the rest of the application, you can explicitly set their lazy attribute +to false using the `@Lazy(false)` annotation. + + + +[[boot-features-banner]] +=== Customizing the Banner +The banner that is printed on start up can be changed by adding a `banner.txt` file to +your classpath or by setting the `spring.banner.location` property to the location of such +a file. If the file has an encoding other than UTF-8, you can set `spring.banner.charset`. +In addition to a text file, you can also add a `banner.gif`, `banner.jpg`, or `banner.png` +image file to your classpath or set the `spring.banner.image.location` property. Images +are converted into an ASCII art representation and printed above any text banner. + +Inside your `banner.txt` file, you can use any of the following placeholders: + +.Banner variables +|=== +| Variable | Description + +|`${application.version}` +|The version number of your application, as declared in `MANIFEST.MF`. For example, +`Implementation-Version: 1.0` is printed as `1.0`. + +|`${application.formatted-version}` +|The version number of your application, as declared in `MANIFEST.MF` and formatted for +display (surrounded with brackets and prefixed with `v`). For example `(v1.0)`. + +|`${spring-boot.version}` +|The Spring Boot version that you are using. For example `{spring-boot-version}`. + +|`${spring-boot.formatted-version}` +|The Spring Boot version that you are using, formatted for display (surrounded with +brackets and prefixed with `v`). For example `(v{spring-boot-version})`. + +|`${Ansi.NAME}` (or `${AnsiColor.NAME}`, `${AnsiBackground.NAME}`, `${AnsiStyle.NAME}`) +|Where `NAME` is the name of an ANSI escape code. See +{sc-spring-boot}/ansi/AnsiPropertySource.{sc-ext}[`AnsiPropertySource`] for details. + +|`${application.title}` +|The title of your application, as declared in `MANIFEST.MF`. For example +`Implementation-Title: MyApp` is printed as `MyApp`. +|=== + +TIP: The `SpringApplication.setBanner(...)` method can be used if you want to generate +a banner programmatically. Use the `org.springframework.boot.Banner` interface and +implement your own `printBanner()` method. + +You can also use the `spring.main.banner-mode` property to determine if the banner has +to be printed on `System.out` (`console`), sent to the configured logger (`log`), or not +produced at all (`off`). + +The printed banner is registered as a singleton bean under the following name: +`springBootBanner`. + + + +[[boot-features-customizing-spring-application]] +=== Customizing SpringApplication +If the `SpringApplication` defaults are not to your taste, you can instead create a local +instance and customize it. For example, to turn off the banner, you could write: + +[source,java,indent=0] +---- + public static void main(String[] args) { + SpringApplication app = new SpringApplication(MySpringConfiguration.class); + app.setBannerMode(Banner.Mode.OFF); + app.run(args); + } +---- + +NOTE: The constructor arguments passed to `SpringApplication` are configuration sources +for Spring beans. In most cases, these are references to `@Configuration` classes, but +they could also be references to XML configuration or to packages that should be scanned. + +It is also possible to configure the `SpringApplication` by using an +`application.properties` file. See _<>_ for details. + +For a complete list of the configuration options, see the +{dc-spring-boot}/SpringApplication.{dc-ext}[`SpringApplication` Javadoc]. + + + +[[boot-features-fluent-builder-api]] +=== Fluent Builder API +If you need to build an `ApplicationContext` hierarchy (multiple contexts with a +parent/child relationship) or if you prefer using a "`fluent`" builder API, you can +use the `SpringApplicationBuilder`. + +The `SpringApplicationBuilder` lets you chain together multiple method calls and includes +`parent` and `child` methods that let you create a hierarchy, as shown in the following +example: + +[source,java,indent=0] +---- +include::{code-examples}/builder/SpringApplicationBuilderExample.java[tag=hierarchy] +---- + +NOTE: There are some restrictions when creating an `ApplicationContext` hierarchy. For +example, Web components *must* be contained within the child context, and the same +`Environment` is used for both parent and child contexts. See the +{dc-spring-boot}/builder/SpringApplicationBuilder.{dc-ext}[`SpringApplicationBuilder` +Javadoc] for full details. + + + +[[boot-features-application-events-and-listeners]] +=== Application Events and Listeners +In addition to the usual Spring Framework events, such as +{spring-javadoc}/context/event/ContextRefreshedEvent.{dc-ext}[`ContextRefreshedEvent`], +a `SpringApplication` sends some additional application events. + +[NOTE] +==== +Some events are actually triggered before the `ApplicationContext` is created, so you +cannot register a listener on those as a `@Bean`. You can register them with the +`SpringApplication.addListeners(...)` method or the +`SpringApplicationBuilder.listeners(...)` method. + +If you want those listeners to be registered automatically, regardless of the way the +application is created, you can add a `META-INF/spring.factories` file to your project +and reference your listener(s) by using the +`org.springframework.context.ApplicationListener` key, as shown in the following example: + +[indent=0] +---- + org.springframework.context.ApplicationListener=com.example.project.MyListener +---- + +==== + +Application events are sent in the following order, as your application runs: + +. An `ApplicationStartingEvent` is sent at the start of a run but before any processing, +except for the registration of listeners and initializers. +. An `ApplicationEnvironmentPreparedEvent` is sent when the `Environment` to be used in +the context is known but before the context is created. +. An `ApplicationContextInitializedEvent` is sent when the `ApplicationContext` is prepared +and ApplicationContextInitializers have been called but before any bean definitions are loaded. +. An `ApplicationPreparedEvent` is sent just before the refresh is started but after bean +definitions have been loaded. +. An `ApplicationStartedEvent` is sent after the context has been refreshed but before any +application and command-line runners have been called. +. An `ApplicationReadyEvent` is sent after any application and command-line runners have +been called. It indicates that the application is ready to service requests. +. An `ApplicationFailedEvent` is sent if there is an exception on startup. + +The above list only includes `SpringApplicationEvent`s that are tied to a `SpringApplication`. +In addition to these, the following events are also published after `ApplicationPreparedEvent` +and before `ApplicationStartedEvent`: + +. A `ContextRefreshedEvent` is sent when an `ApplicationContext` is refreshed. +. A `WebServerInitializedEvent` is sent after the `WebServer` is ready. `ServletWebServerInitializedEvent` +and `ReactiveWebServerInitializedEvent` are the servlet and reactive variants respectively. + +TIP: You often need not use application events, but it can be handy to know that they +exist. Internally, Spring Boot uses events to handle a variety of tasks. + +Application events are sent by using Spring Framework's event publishing mechanism. Part +of this mechanism ensures that an event published to the listeners in a child context is +also published to the listeners in any ancestor contexts. As a result of this, if your +application uses a hierarchy of `SpringApplication` instances, a listener may receive +multiple instances of the same type of application event. + +To allow your listener to distinguish between an event for its context and an event for +a descendant context, it should request that its application context is injected and then +compare the injected context with the context of the event. The context can be injected +by implementing `ApplicationContextAware` or, if the listener is a bean, by using +`@Autowired`. + + + +[[boot-features-web-environment]] +=== Web Environment +A `SpringApplication` attempts to create the right type of `ApplicationContext` on your +behalf. The algorithm used to determine a `WebApplicationType` is fairly simple: + +* If Spring MVC is present, an `AnnotationConfigServletWebServerApplicationContext` is +used +* If Spring MVC is not present and Spring WebFlux is present, an +`AnnotationConfigReactiveWebServerApplicationContext` is used +* Otherwise, `AnnotationConfigApplicationContext` is used + +This means that if you are using Spring MVC and the new `WebClient` from Spring WebFlux in +the same application, Spring MVC will be used by default. You can override that easily +by calling `setWebApplicationType(WebApplicationType)`. + +It is also possible to take complete control of the `ApplicationContext` type that is +used by calling `setApplicationContextClass(...)`. + +TIP: It is often desirable to call `setWebApplicationType(WebApplicationType.NONE)` when +using `SpringApplication` within a JUnit test. + + + +[[boot-features-application-arguments]] +=== Accessing Application Arguments +If you need to access the application arguments that were passed to +`SpringApplication.run(...)`, you can inject a +`org.springframework.boot.ApplicationArguments` bean. The `ApplicationArguments` +interface provides access to both the raw `String[]` arguments as well as parsed `option` +and `non-option` arguments, as shown in the following example: + +[source,java,indent=0] +---- + import org.springframework.boot.*; + import org.springframework.beans.factory.annotation.*; + import org.springframework.stereotype.*; + + @Component + public class MyBean { + + @Autowired + public MyBean(ApplicationArguments args) { + boolean debug = args.containsOption("debug"); + List files = args.getNonOptionArgs(); + // if run with "--debug logfile.txt" debug=true, files=["logfile.txt"] + } + + } +---- + +TIP: Spring Boot also registers a `CommandLinePropertySource` with the Spring +`Environment`. This lets you also inject single application arguments by using the +`@Value` annotation. + + + +[[boot-features-command-line-runner]] +=== Using the ApplicationRunner or CommandLineRunner +If you need to run some specific code once the `SpringApplication` has started, you can +implement the `ApplicationRunner` or `CommandLineRunner` interfaces. Both interfaces work +in the same way and offer a single `run` method, which is called just before +`SpringApplication.run(...)` completes. + +The `CommandLineRunner` interfaces provides access to application arguments as a simple +string array, whereas the `ApplicationRunner` uses the `ApplicationArguments` interface +discussed earlier. The following example shows a `CommandLineRunner` with a `run` method: + +[source,java,indent=0] +---- + import org.springframework.boot.*; + import org.springframework.stereotype.*; + + @Component + public class MyBean implements CommandLineRunner { + + public void run(String... args) { + // Do something... + } + + } +---- + +If several `CommandLineRunner` or `ApplicationRunner` beans are defined that must be +called in a specific order, you can additionally implement the +`org.springframework.core.Ordered` interface or use the +`org.springframework.core.annotation.Order` annotation. + + + +[[boot-features-application-exit]] +=== Application Exit +Each `SpringApplication` registers a shutdown hook with the JVM to ensure that the +`ApplicationContext` closes gracefully on exit. All the standard Spring lifecycle +callbacks (such as the `DisposableBean` interface or the `@PreDestroy` annotation) can be +used. + +In addition, beans may implement the `org.springframework.boot.ExitCodeGenerator` +interface if they wish to return a specific exit code when `SpringApplication.exit()` is +called. This exit code can then be passed to `System.exit()` to return it as a status +code, as shown in the following example: + +[source,java,indent=0] +---- +include::{code-examples}/ExitCodeApplication.java[tag=example] +---- + +Also, the `ExitCodeGenerator` interface may be implemented by exceptions. When such an +exception is encountered, Spring Boot returns the exit code provided by the implemented +`getExitCode()` method. + + +[[boot-features-application-admin]] +=== Admin Features +It is possible to enable admin-related features for the application by specifying the +`spring.application.admin.enabled` property. This exposes the +{sc-spring-boot}/admin/SpringApplicationAdminMXBean.{sc-ext}[`SpringApplicationAdminMXBean`] +on the platform `MBeanServer`. You could use this feature to administer your Spring Boot +application remotely. This feature could also be useful for any service wrapper +implementation. + +TIP: If you want to know on which HTTP port the application is running, get the property +with a key of `local.server.port`. + +CAUTION: Take care when enabling this feature, as the MBean exposes a method to shutdown +the application. + + + +[[boot-features-external-config]] +== Externalized Configuration +Spring Boot lets you externalize your configuration so that you can work with the same +application code in different environments. You can use properties files, YAML files, +environment variables, and command-line arguments to externalize configuration. Property +values can be injected directly into your beans by using the `@Value` annotation, +accessed through Spring's `Environment` abstraction, or be +<> through `@ConfigurationProperties`. + +Spring Boot uses a very particular `PropertySource` order that is designed to allow +sensible overriding of values. Properties are considered in the following order: + +. <> +on your home directory (`~/.spring-boot-devtools.properties` when devtools is active). +. {spring-javadoc}/test/context/TestPropertySource.{dc-ext}[`@TestPropertySource`] +annotations on your tests. +. `properties` attribute on your tests. Available on +{dc-spring-boot-test}/context/SpringBootTest.{dc-ext}[`@SpringBootTest`] and the +<>. +. Command line arguments. +. Properties from `SPRING_APPLICATION_JSON` (inline JSON embedded in an environment +variable or system property). +. `ServletConfig` init parameters. +. `ServletContext` init parameters. +. JNDI attributes from `java:comp/env`. +. Java System properties (`System.getProperties()`). +. OS environment variables. +. A `RandomValuePropertySource` that has properties only in `+random.*+`. +. <> outside of your packaged jar +(`application-\{profile}.properties` and YAML variants). +. <> packaged inside your jar (`application-\{profile}.properties` +and YAML variants). +. Application properties outside of your packaged jar (`application.properties` and YAML +variants). +. Application properties packaged inside your jar (`application.properties` and YAML +variants). +. {spring-javadoc}/context/annotation/PropertySource.{dc-ext}[`@PropertySource`] +annotations on your `@Configuration` classes. +. Default properties (specified by setting `SpringApplication.setDefaultProperties`). + +To provide a concrete example, suppose you develop a `@Component` that uses a `name` +property, as shown in the following example: + +[source,java,indent=0] +---- + import org.springframework.stereotype.*; + import org.springframework.beans.factory.annotation.*; + + @Component + public class MyBean { + + @Value("${name}") + private String name; + + // ... + + } +---- + +On your application classpath (for example, inside your jar) you can have an +`application.properties` file that provides a sensible default property value for `name`. +When running in a new environment, an `application.properties` file can be provided +outside of your jar that overrides the `name`. For one-off testing, you can launch with a +specific command line switch (for example, `java -jar app.jar --name="Spring"`). + +[TIP] +==== +The `SPRING_APPLICATION_JSON` properties can be supplied on the command line with an +environment variable. For example, you could use the following line in a UN{asterisk}X +shell: + +---- +$ SPRING_APPLICATION_JSON='{"acme":{"name":"test"}}' java -jar myapp.jar +---- + +In the preceding example, you end up with `acme.name=test` in the Spring `Environment`. +You can also supply the JSON as `spring.application.json` in a System property, as shown +in the following example: + +---- +$ java -Dspring.application.json='{"name":"test"}' -jar myapp.jar +---- + +You can also supply the JSON by using a command line argument, as shown in the following +example: + +---- +$ java -jar myapp.jar --spring.application.json='{"name":"test"}' +---- + +You can also supply the JSON as a JNDI variable, as follows: +`java:comp/env/spring.application.json`. +==== + + + +[[boot-features-external-config-random-values]] +=== Configuring Random Values +The `RandomValuePropertySource` is useful for injecting random values (for example, into +secrets or test cases). It can produce integers, longs, uuids, or strings, as shown in the +following example: + +[source,properties,indent=0] +---- + my.secret=${random.value} + my.number=${random.int} + my.bignumber=${random.long} + my.uuid=${random.uuid} + my.number.less.than.ten=${random.int(10)} + my.number.in.range=${random.int[1024,65536]} +---- + +The `+random.int*+` syntax is `OPEN value (,max) CLOSE` where the `OPEN,CLOSE` are any +character and `value,max` are integers. If `max` is provided, then `value` is the minimum +value and `max` is the maximum value (exclusive). + + + +[[boot-features-external-config-command-line-args]] +=== Accessing Command Line Properties +By default, `SpringApplication` converts any command line option arguments (that is, +arguments starting with `--`, such as `--server.port=9000`) to a `property` and adds +them to the Spring `Environment`. As mentioned previously, command line properties always +take precedence over other property sources. + +If you do not want command line properties to be added to the `Environment`, you can +disable them by using `SpringApplication.setAddCommandLineProperties(false)`. + + + +[[boot-features-external-config-application-property-files]] +=== Application Property Files +`SpringApplication` loads properties from `application.properties` files in the following +locations and adds them to the Spring `Environment`: + +. A `/config` subdirectory of the current directory +. The current directory +. A classpath `/config` package +. The classpath root + +The list is ordered by precedence (properties defined in locations higher in the list +override those defined in lower locations). + +NOTE: You can also <> as an +alternative to '.properties'. + +If you do not like `application.properties` as the configuration file name, you can +switch to another file name by specifying a `spring.config.name` environment property. +You can also refer to an explicit location by using the `spring.config.location` +environment property (which is a comma-separated list of directory locations or file +paths). The following example shows how to specify a different file name: + +[indent=0] +---- + $ java -jar myproject.jar --spring.config.name=myproject +---- + +The following example shows how to specify two locations: + +[indent=0] +---- + $ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties +---- + +WARNING: `spring.config.name` and `spring.config.location` are used very early to +determine which files have to be loaded, so they must be defined as an environment +property (typically an OS environment variable, a system property, or a command-line +argument). + +If `spring.config.location` contains directories (as opposed to files), they should end +in `/` (and, at runtime, be appended with the names generated from `spring.config.name` +before being loaded, including profile-specific file names). Files specified in +`spring.config.location` are used as-is, with no support for profile-specific variants, +and are overridden by any profile-specific properties. + +Config locations are searched in reverse order. By default, the configured locations are +`classpath:/,classpath:/config/,file:./,file:./config/`. The resulting search order is +the following: + +. `file:./config/` +. `file:./` +. `classpath:/config/` +. `classpath:/` + +When custom config locations are configured by using `spring.config.location`, they +replace the default locations. For example, if `spring.config.location` is configured with +the value `classpath:/custom-config/,file:./custom-config/`, the search order becomes the +following: + +. `file:./custom-config/` +. `classpath:custom-config/` + +Alternatively, when custom config locations are configured by using +`spring.config.additional-location`, they are used in addition to the default locations. +Additional locations are searched before the default locations. For example, if +additional locations of `classpath:/custom-config/,file:./custom-config/` are configured, +the search order becomes the following: + +. `file:./custom-config/` +. `classpath:custom-config/` +. `file:./config/` +. `file:./` +. `classpath:/config/` +. `classpath:/` + +This search ordering lets you specify default values in one configuration file and then +selectively override those values in another. You can provide default values for your +application in `application.properties` (or whatever other basename you choose with +`spring.config.name`) in one of the default locations. These default values can then be +overridden at runtime with a different file located in one of the custom locations. + +NOTE: If you use environment variables rather than system properties, most operating +systems disallow period-separated key names, but you can use underscores instead (for +example, `SPRING_CONFIG_NAME` instead of `spring.config.name`). + +NOTE: If your application runs in a container, then JNDI properties (in `java:comp/env`) +or servlet context initialization parameters can be used instead of, or as well as, +environment variables or system properties. + + + +[[boot-features-external-config-profile-specific-properties]] +=== Profile-specific Properties +In addition to `application.properties` files, profile-specific properties can also be +defined by using the following naming convention: `application-\{profile}.properties`. The +`Environment` has a set of default profiles (by default, `[default]`) that are used if no +active profiles are set. In other words, if no profiles are explicitly activated, then +properties from `application-default.properties` are loaded. + +Profile-specific properties are loaded from the same locations as standard +`application.properties`, with profile-specific files always overriding the non-specific +ones, whether or not the profile-specific files are inside or outside your +packaged jar. + +If several profiles are specified, a last-wins strategy applies. For example, profiles +specified by the `spring.profiles.active` property are added after those configured +through the `SpringApplication` API and therefore take precedence. + +NOTE: If you have specified any files in `spring.config.location`, profile-specific +variants of those files are not considered. Use directories in +`spring.config.location` if you want to also use profile-specific properties. + + + +[[boot-features-external-config-placeholders-in-properties]] +=== Placeholders in Properties +The values in `application.properties` are filtered through the existing `Environment` +when they are used, so you can refer back to previously defined values (for example, from +System properties). + +[source,properties,indent=0] +---- + app.name=MyApp + app.description=${app.name} is a Spring Boot application +---- + +TIP: You can also use this technique to create "`short`" variants of existing Spring Boot +properties. See the _<>_ how-to for +details. + + + +[[boot-features-encrypting-properties]] +=== Encrypting Properties +Spring Boot does not provide any built in support for encrypting property values, however, +it does provide the hook points necessary to modify values contained in the Spring +`Environment`. The `EnvironmentPostProcessor` interface allows you to manipulate the +`Environment` before the application starts. See <> +for details. + +If you're looking for a secure way to store credentials and passwords, the +https://cloud.spring.io/spring-cloud-vault/[Spring Cloud Vault] project provides +support for storing externalized configuration in +https://www.vaultproject.io/[HashiCorp Vault]. + + + +[[boot-features-external-config-yaml]] +=== Using YAML Instead of Properties +https://yaml.org[YAML] is a superset of JSON and, as such, is a convenient format for +specifying hierarchical configuration data. The `SpringApplication` class automatically +supports YAML as an alternative to properties whenever you have the +https://bitbucket.org/asomov/snakeyaml[SnakeYAML] library on your classpath. + +NOTE: If you use "`Starters`", SnakeYAML is automatically provided by +`spring-boot-starter`. + + + +[[boot-features-external-config-loading-yaml]] +==== Loading YAML +Spring Framework provides two convenient classes that can be used to load YAML documents. +The `YamlPropertiesFactoryBean` loads YAML as `Properties` and the `YamlMapFactoryBean` +loads YAML as a `Map`. + +For example, consider the following YAML document: + +[source,yaml,indent=0] +---- + environments: + dev: + url: https://dev.example.com + name: Developer Setup + prod: + url: https://another.example.com + name: My Cool App +---- + +The preceding example would be transformed into the following properties: + +[source,properties,indent=0] +---- + environments.dev.url=https://dev.example.com + environments.dev.name=Developer Setup + environments.prod.url=https://another.example.com + environments.prod.name=My Cool App +---- + +YAML lists are represented as property keys with `[index]` dereferencers. For example, +consider the following YAML: + +[source,yaml,indent=0] +---- + my: + servers: + - dev.example.com + - another.example.com +---- + +The preceding example would be transformed into these properties: + +[source,properties,indent=0] +---- + my.servers[0]=dev.example.com + my.servers[1]=another.example.com +---- + +To bind to properties like that by using Spring Boot's `Binder` utilities (which is what +`@ConfigurationProperties` does), you need to have a property in the target bean of type +`java.util.List` (or `Set`) and you either need to provide a setter or initialize it with +a mutable value. For example, the following example binds to the properties shown +previously: + +[source,java,indent=0] +---- + @ConfigurationProperties(prefix="my") + public class Config { + + private List servers = new ArrayList(); + + public List getServers() { + return this.servers; + } + } +---- + + + +[[boot-features-external-config-exposing-yaml-to-spring]] +==== Exposing YAML as Properties in the Spring Environment +The `YamlPropertySourceLoader` class can be used to expose YAML as a `PropertySource` in +the Spring `Environment`. Doing so lets you use the `@Value` annotation with placeholders +syntax to access YAML properties. + + + +[[boot-features-external-config-multi-profile-yaml]] +==== Multi-profile YAML Documents +You can specify multiple profile-specific YAML documents in a single file by using a +`spring.profiles` key to indicate when the document applies, as shown in the following +example: + +[source,yaml,indent=0] +---- + server: + address: 192.168.1.100 + --- + spring: + profiles: development + server: + address: 127.0.0.1 + --- + spring: + profiles: production & eu-central + server: + address: 192.168.1.120 +---- + +In the preceding example, if the `development` profile is active, the `server.address` +property is `127.0.0.1`. Similarly, if the `production` *and* `eu-central` profiles are +active, the `server.address` property is `192.168.1.120`. If the `development`, +`production` and `eu-central` profiles are *not* enabled, then the value for the property +is `192.168.1.100`. + +[NOTE] +==== +`spring.profiles` can therefore contain a simple profile name (for example `production`) +or a profile expression. A profile expression allows for more complicated profile logic +to be expressed, for example `production & (eu-central | eu-west)`. Check the +{spring-reference}core.html#beans-definition-profiles-java[reference guide] for more +details. +==== + +If none are explicitly active when the application context starts, the default profiles +are activated. So, in the following YAML, we set a value for `spring.security.user.password` +that is available *only* in the "default" profile: + +[source,yaml,indent=0] +---- + server: + port: 8000 + --- + spring: + profiles: default + security: + user: + password: weak +---- + +Whereas, in the following example, the password is always set because it is not attached +to any profile, and it would have to be explicitly reset in all other profiles as +necessary: + +[source,yaml,indent=0] +---- + server: + port: 8000 + spring: + security: + user: + password: weak +---- + +Spring profiles designated by using the `spring.profiles` element may optionally be +negated by using the `!` character. If both negated and non-negated profiles are +specified for a single document, at least one non-negated profile must match, and no +negated profiles may match. + + + +[[boot-features-external-config-yaml-shortcomings]] +==== YAML Shortcomings +YAML files cannot be loaded by using the `@PropertySource` annotation. So, in the case +that you need to load values that way, you need to use a properties file. + +Using the multi YAML document syntax in profile-specific YAML files can lead to unexpected +behavior. For example, consider the following config in a file called `application-dev.yml`, +with the `dev` profile being active: + +[source,yaml,indent=0] +---- + server: + port: 8000 + --- + spring: + profiles: !test + security: + user: + password: weak +---- + +In the example above, profile negation and profile expressions will not behave as expected. +We recommend that you don't combine profile-specific YAML files and multiple YAML documents and stick +to using only one of them. + + + +[[boot-features-external-config-typesafe-configuration-properties]] +=== Type-safe Configuration Properties +Using the `@Value("$\{property}")` annotation to inject configuration properties can +sometimes be cumbersome, especially if you are working with multiple properties or your +data is hierarchical in nature. Spring Boot provides an alternative method of working +with properties that lets strongly typed beans govern and validate the configuration of +your application. + +TIP: See also the <>. + + + +[[boot-features-external-config-java-bean-binding]] +==== JavaBean properties binding +It is possible to bind a bean declaring standard JavaBean properties as shown in the +following example: + +[source,java,indent=0] +---- + package com.example; + + import java.net.InetAddress; + import java.util.ArrayList; + import java.util.Collections; + import java.util.List; + + import org.springframework.boot.context.properties.ConfigurationProperties; + + @ConfigurationProperties("acme") + public class AcmeProperties { + + private boolean enabled; + + private InetAddress remoteAddress; + + private final Security security = new Security(); + + public boolean isEnabled() { ... } + + public void setEnabled(boolean enabled) { ... } + + public InetAddress getRemoteAddress() { ... } + + public void setRemoteAddress(InetAddress remoteAddress) { ... } + + public Security getSecurity() { ... } + + public static class Security { + + private String username; + + private String password; + + private List roles = new ArrayList<>(Collections.singleton("USER")); + + public String getUsername() { ... } + + public void setUsername(String username) { ... } + + public String getPassword() { ... } + + public void setPassword(String password) { ... } + + public List getRoles() { ... } + + public void setRoles(List roles) { ... } + + } + } +---- + +The preceding POJO defines the following properties: + +* `acme.enabled`, with a value of `false` by default. +* `acme.remote-address`, with a type that can be coerced from `String`. +* `acme.security.username`, with a nested "security" object whose name is determined by +the name of the property. In particular, the return type is not used at all there and +could have been `SecurityProperties`. +* `acme.security.password`. +* `acme.security.roles`, with a collection of `String` that defaults to `USER`. + +[NOTE] +==== +Such arrangement relies on a default empty constructor and getters and setters are usually +mandatory, since binding is through standard Java Beans property descriptors, just like in +Spring MVC. A setter may be omitted in the following cases: + +* Maps, as long as they are initialized, need a getter but not necessarily a setter, +since they can be mutated by the binder. +* Collections and arrays can be accessed either through an index (typically with YAML) or +by using a single comma-separated value (properties). In the latter case, a setter is +mandatory. We recommend to always add a setter for such types. If you initialize a +collection, make sure it is not immutable (as in the preceding example). +* If nested POJO properties are initialized (like the `Security` field in the preceding +example), a setter is not required. If you want the binder to create the instance on the +fly by using its default constructor, you need a setter. + +Some people use Project Lombok to add getters and setters automatically. Make sure that +Lombok does not generate any particular constructor for such a type, as it is used +automatically by the container to instantiate the object. + +Finally, only standard Java Bean properties are considered and binding on static +properties is not supported. +==== + + + +[[boot-features-external-config-constructor-binding]] +==== Constructor binding +The example in the previous section can be rewritten in an immutable fashion as shown in +the following example: + +[source,java,indent=0] +---- + package com.example; + + import java.net.InetAddress; + import java.util.List; + + import org.springframework.boot.context.properties.ConfigurationProperties; + import org.springframework.boot.context.properties.DefaultValue; + + @ConfigurationProperties("acme") + public class AcmeProperties { + + private final boolean enabled; + + private final InetAddress remoteAddress; + + private final Security security; + + public AcmeProperties(boolean enabled, InetAddress remoteAddress, Security security) { + this.enabled = enabled; + this.remoteAddress = remoteAddress; + this.security = security; + } + + public boolean isEnabled() { ... } + + public InetAddress getRemoteAddress() { ... } + + public Security getSecurity() { ... } + + public static class Security { + + private final String username; + + private final String password; + + private final List roles; + + public Security(String username, String password, + @DefaultValue("USER") List roles) { + this.username = username; + this.password = password; + this.roles = roles; + } + + public String getUsername() { ... } + + public String getPassword() { ... } + + public List getRoles() { ... } + + } + + } +---- + +In this setup one, and only one constructor must be defined with the list of properties +that you wish to bind and not other properties than the ones in the constructor are bound. + +Default values can be specified using `@DefaultValue` and the same conversion service will +be applied to coerce the `String` value to the target type of a missing property. + + + +[[boot-features-external-config-enabling]] +==== Enabling `@ConfigurationProperties`-annotated types +Spring Boot provides an infrastructure to bind such types and register them as beans +automatically. If your application uses `@SpringBootApplication`, classes annotated with +`@ConfigurationProperties` will automatically be scanned and registered as beans. By default, +scanning will occur from the package of the class that declares this annotation. If you want +to define specific packages to scan, you can do so using an explicit `@ConfigurationPropertiesScan` +directive on your `@SpringBootApplication`-annotated class as shown in the following example: + +[source,java,indent=0] +---- + @SpringBootApplication + @ConfigurationPropertiesScan({ "com.example.app", "org.acme.another" }) + public class MyApplication { + } +---- + +Sometimes, classes annotated with `@ConfigurationProperties` might not be suitable +for scanning, for example, if you're developing your own auto-configuration. In these +cases, you can specify the list of types to process on any `@Configuration` class as +shown in the following example: + +[source,java,indent=0] +---- + @Configuration(proxyBeanMethods = false) + @EnableConfigurationProperties(AcmeProperties.class) + public class MyConfiguration { + } +---- + +[NOTE] +==== +When the `@ConfigurationProperties` bean is registered using scanning or via +`@EnableConfigurationProperties`, the bean has a conventional name: `-`, +where `` is the environment key prefix specified in the `@ConfigurationProperties` +annotation and `` is the fully qualified name of the bean. If the annotation does not +provide any prefix, only the fully qualified name of the bean is used. + +The bean name in the example above is `acme-com.example.AcmeProperties`. +==== + +We recommend that `@ConfigurationProperties` only deal with the environment and, in +particular, does not inject other beans from the context. In particular, it is not +possible to inject other beans using the constructor as this would trigger the constructor +binder that only deals with the environment. + +For corner cases, setter injection can be used or any of the `*Aware` interfaces provided +by the framework (such as `EnvironmentAware` if you need access to the `Environment`). + +NOTE: Annotating a `@ConfigurationProperties` type with `@Component` will result in two +beans of the same type if the type is also scanned as part of classpath scanning. If you want +to register the bean yourself using `@Component`, consider disabling scanning of +`@ConfigurationProperties`. + + + +[[boot-features-external-config-using]] +==== Using `@ConfigurationProperties`-annotated types +This style of configuration works particularly well with the `SpringApplication` external +YAML configuration, as shown in the following example: + +[source,yaml,indent=0] +---- + # application.yml + + acme: + remote-address: 192.168.1.1 + security: + username: admin + roles: + - USER + - ADMIN + + # additional configuration as required +---- + +To work with `@ConfigurationProperties` beans, you can inject them in the same way +as any other bean, as shown in the following example: + +[source,java,indent=0] +---- + @Service + public class MyService { + + private final AcmeProperties properties; + + @Autowired + public MyService(AcmeProperties properties) { + this.properties = properties; + } + + //... + + @PostConstruct + public void openConnection() { + Server server = new Server(this.properties.getRemoteAddress()); + // ... + } + + } +---- + +TIP: Using `@ConfigurationProperties` also lets you generate metadata files that can be +used by IDEs to offer auto-completion for your own keys. See the +<> for details. + + + +[[boot-features-external-config-3rd-party-configuration]] +==== Third-party Configuration +As well as using `@ConfigurationProperties` to annotate a class, you can also use it on +public `@Bean` methods. Doing so can be particularly useful when you want to bind +properties to third-party components that are outside of your control. + +To configure a bean from the `Environment` properties, add `@ConfigurationProperties` to +its bean registration, as shown in the following example: + +[source,java,indent=0] +---- + @ConfigurationProperties(prefix = "another") + @Bean + public AnotherComponent anotherComponent() { + ... + } +---- + +Any JavaBean property defined with the `another` prefix is mapped onto that +`AnotherComponent` bean in manner similar to the preceding `AcmeProperties` example. + + + +[[boot-features-external-config-relaxed-binding]] +==== Relaxed Binding +Spring Boot uses some relaxed rules for binding `Environment` properties to +`@ConfigurationProperties` beans, so there does not need to be an exact match between the +`Environment` property name and the bean property name. Common examples where this is +useful include dash-separated environment properties (for example, `context-path` binds +to `contextPath`), and capitalized environment properties (for example, `PORT` binds to +`port`). + +For example, consider the following `@ConfigurationProperties` class: + +[source,java,indent=0] +---- + @ConfigurationProperties(prefix="acme.my-project.person") + public class OwnerProperties { + + private String firstName; + + public String getFirstName() { + return this.firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + } +---- + +In the preceding example, the following properties names can all be used: + +.relaxed binding +[cols="1,4"] +|=== +| Property | Note + +|`acme.my-project.person.first-name` +|Kebab case, which is recommended for use in `.properties` and `.yml` files. + +|`acme.myProject.person.firstName` +|Standard camel case syntax. + +|`acme.my_project.person.first_name` +|Underscore notation, which is an alternative format for use in `.properties` and `.yml` +files. + +|`ACME_MYPROJECT_PERSON_FIRSTNAME` +|Upper case format, which is recommended when using system environment variables. +|=== + +NOTE: The `prefix` value for the annotation _must_ be in kebab case (lowercase and +separated by `-`, such as `acme.my-project.person`). + +.relaxed binding rules per property source +[cols="2,4,4"] +|=== +| Property Source | Simple | List + +|Properties Files +|Camel case, kebab case, or underscore notation +|Standard list syntax using `[ ]` or comma-separated values + +|YAML Files +|Camel case, kebab case, or underscore notation +|Standard YAML list syntax or comma-separated values + +|Environment Variables +|Upper case format with underscore as the delimiter. `_` should not be used within a +property name +|Numeric values surrounded by underscores, such as `MY_ACME_1_OTHER = my.acme[1].other` + +|System properties +|Camel case, kebab case, or underscore notation +|Standard list syntax using `[ ]` or comma-separated values +|=== + +TIP: We recommend that, when possible, properties are stored in lower-case kebab format, +such as `my.property-name=acme`. + +When binding to `Map` properties, if the `key` contains anything other than lowercase +alpha-numeric characters or `-`, you need to use the bracket notation so that the original +value is preserved. If the key is not surrounded by `[]`, any characters that are not alpha-numeric +or `-` are removed. For example, consider binding the following properties to a `Map`: + +[source,yaml,indent=0] +---- + acme: + map: + "[/key1]": value1 + "[/key2]": value2 + /key3: value3 + +---- + +The properties above will bind to a `Map` with `/key1`, `/key2` and `key3` as the keys in the map. + + +[[boot-features-external-config-complex-type-merge]] +==== Merging Complex Types +When lists are configured in more than one place, overriding works by replacing the entire +list. + +For example, assume a `MyPojo` object with `name` and `description` attributes that are +`null` by default. The following example exposes a list of `MyPojo` objects from +`AcmeProperties`: + +[source,java,indent=0] +---- + @ConfigurationProperties("acme") + public class AcmeProperties { + + private final List list = new ArrayList<>(); + + public List getList() { + return this.list; + } + + } +---- + +Consider the following configuration: + +[source,yaml,indent=0] +---- + acme: + list: + - name: my name + description: my description + --- + spring: + profiles: dev + acme: + list: + - name: my another name +---- + +If the `dev` profile is not active, `AcmeProperties.list` contains one `MyPojo` entry, +as previously defined. If the `dev` profile is enabled, however, the `list` _still_ +contains only one entry (with a name of `my another name` and a description of `null`). +This configuration _does not_ add a second `MyPojo` instance to the list, and it does not +merge the items. + +When a `List` is specified in multiple profiles, the one with the highest priority +(and only that one) is used. Consider the following example: + +[source,yaml,indent=0] +---- + acme: + list: + - name: my name + description: my description + - name: another name + description: another description + --- + spring: + profiles: dev + acme: + list: + - name: my another name +---- + +In the preceding example, if the `dev` profile is active, `AcmeProperties.list` contains +_one_ `MyPojo` entry (with a name of `my another name` and a description of `null`). +For YAML, both comma-separated lists and YAML lists can be used for +completely overriding the contents of the list. + +For `Map` properties, you can bind with property values drawn from multiple sources. However, +for the same property in multiple sources, the one with the highest priority is used. +The following example exposes a `Map` from `AcmeProperties`: + +[source,java,indent=0] +---- + @ConfigurationProperties("acme") + public class AcmeProperties { + + private final Map map = new HashMap<>(); + + public Map getMap() { + return this.map; + } + + } +---- + +Consider the following configuration: + +[source,yaml,indent=0] +---- + acme: + map: + key1: + name: my name 1 + description: my description 1 + --- + spring: + profiles: dev + acme: + map: + key1: + name: dev name 1 + key2: + name: dev name 2 + description: dev description 2 +---- + +If the `dev` profile is not active, `AcmeProperties.map` contains one entry with key `key1` +(with a name of `my name 1` and a description of `my description 1`). +If the `dev` profile is enabled, however, `map` contains two entries with keys `key1` +(with a name of `dev name 1` and a description of `my description 1`) and +`key2` (with a name of `dev name 2` and a description of `dev description 2`). + +NOTE: The preceding merging rules apply to properties from all property sources and not just +YAML files. + +[[boot-features-external-config-conversion]] +==== Properties Conversion +Spring Boot attempts to coerce the external application properties to the right type when +it binds to the `@ConfigurationProperties` beans. If you need custom type conversion, you +can provide a `ConversionService` bean (with a bean named `conversionService`) or custom +property editors (through a `CustomEditorConfigurer` bean) or custom `Converters` (with +bean definitions annotated as `@ConfigurationPropertiesBinding`). + +NOTE: As this bean is requested very early during the application lifecycle, make sure to +limit the dependencies that your `ConversionService` is using. Typically, any dependency +that you require may not be fully initialized at creation time. You may want to rename +your custom `ConversionService` if it is not required for configuration keys coercion and +only rely on custom converters qualified with `@ConfigurationPropertiesBinding`. + + + +[[boot-features-external-config-conversion-duration]] +===== Converting durations +Spring Boot has dedicated support for expressing durations. If you expose a +`java.time.Duration` property, the following formats in application properties are +available: + +* A regular `long` representation (using milliseconds as the default unit unless a +`@DurationUnit` has been specified) +* The standard ISO-8601 format +{java-javadoc}/java/time/Duration.html#parse-java.lang.CharSequence-[used by +`java.time.Duration`] +* A more readable format where the value and the unit are coupled (e.g. `10s` means 10 +seconds) + +Consider the following example: + +[source,java,indent=0] +---- +include::{code-examples}/context/properties/bind/AppSystemProperties.java[tag=example] +---- + +To specify a session timeout of 30 seconds, `30`, `PT30S` and `30s` are all equivalent. A +read timeout of 500ms can be specified in any of the following form: `500`, `PT0.5S` and +`500ms`. + +You can also use any of the supported units. These are: + +* `ns` for nanoseconds +* `us` for microseconds +* `ms` for milliseconds +* `s` for seconds +* `m` for minutes +* `h` for hours +* `d` for days + +The default unit is milliseconds and can be overridden using `@DurationUnit` as illustrated +in the sample above. + +TIP: If you are upgrading from a previous version that is simply using `Long` to express +the duration, make sure to define the unit (using `@DurationUnit`) if it isn't +milliseconds alongside the switch to `Duration`. Doing so gives a transparent upgrade path +while supporting a much richer format. + + + +[[boot-features-external-config-conversion-datasize]] +===== Converting Data Sizes +Spring Framework has a `DataSize` value type that allows to express size in bytes. If you +expose a `DataSize` property, the following formats in application properties are +available: + +* A regular `long` representation (using bytes as the default unit unless a +`@DataSizeUnit` has been specified) +* A more readable format where the value and the unit are coupled (e.g. `10MB` means 10 +megabytes) + +Consider the following example: + +[source,java,indent=0] +---- +include::{code-examples}/context/properties/bind/AppIoProperties.java[tag=example] +---- + +To specify a buffer size of 10 megabytes, `10` and `10MB` are equivalent. A size threshold +of 256 bytes can be specified as `256` or `256B`. + +You can also use any of the supported units. These are: + +* `B` for bytes +* `KB` for kilobytes +* `MB` for megabytes +* `GB` for gigabytes +* `TB` for terabytes + +The default unit is bytes and can be overridden using `@DataSizeUnit` as illustrated +in the sample above. + +TIP: If you are upgrading from a previous version that is simply using `Long` to express +the size, make sure to define the unit (using `@DataSizeUnit`) if it isn't bytes alongside +the switch to `DataSize`. Doing so gives a transparent upgrade path while supporting a +much richer format. + + + +[[boot-features-external-config-validation]] +==== @ConfigurationProperties Validation +Spring Boot attempts to validate `@ConfigurationProperties` classes whenever they are +annotated with Spring's `@Validated` annotation. You can use JSR-303 `javax.validation` +constraint annotations directly on your configuration class. To do so, ensure that a +compliant JSR-303 implementation is on your classpath and then add constraint annotations +to your fields, as shown in the following example: + +[source,java,indent=0] +---- + @ConfigurationProperties(prefix="acme") + @Validated + public class AcmeProperties { + + @NotNull + private InetAddress remoteAddress; + + // ... getters and setters + + } +---- + +TIP: You can also trigger validation by annotating the `@Bean` method that creates the +configuration properties with `@Validated`. + +Although nested properties will also be validated when bound, it's good practice to +also annotate the associated field as `@Valid`. This ensure that validation is triggered +even if no nested properties are found. The following example builds on the preceding +`AcmeProperties` example: + +[source,java,indent=0] +---- + @ConfigurationProperties(prefix="acme") + @Validated + public class AcmeProperties { + + @NotNull + private InetAddress remoteAddress; + + @Valid + private final Security security = new Security(); + + // ... getters and setters + + public static class Security { + + @NotEmpty + public String username; + + // ... getters and setters + + } + + } +---- + +You can also add a custom Spring `Validator` by creating a bean definition called +`configurationPropertiesValidator`. The `@Bean` method should be declared `static`. The +configuration properties validator is created very early in the application's lifecycle, +and declaring the `@Bean` method as static lets the bean be created without having to +instantiate the `@Configuration` class. Doing so avoids any problems that may be caused +by early instantiation. + +TIP: The `spring-boot-actuator` module includes an endpoint that exposes all +`@ConfigurationProperties` beans. Point your web browser to +`/actuator/configprops` or use the equivalent JMX endpoint. See the +"<>" +section for details. + + + +[[boot-features-external-config-vs-value]] +==== @ConfigurationProperties vs. @Value +The `@Value` annotation is a core container feature, and it does not provide the same +features as type-safe configuration properties. The following table summarizes the +features that are supported by `@ConfigurationProperties` and `@Value`: + +[cols="4,2,2"] +|=== +|Feature |`@ConfigurationProperties` |`@Value` + +| <> +| Yes +| No + +| <> +| Yes +| No + +| `SpEL` evaluation +| No +| Yes +|=== + +If you define a set of configuration keys for your own components, we recommend you +group them in a POJO annotated with `@ConfigurationProperties`. You should also be aware +that, since `@Value` does not support relaxed binding, it is not a good candidate if you +need to provide the value by using environment variables. + +Finally, while you can write a `SpEL` expression in `@Value`, such expressions are not +processed from <>. + + + +[[boot-features-profiles]] +== Profiles +Spring Profiles provide a way to segregate parts of your application configuration and +make it be available only in certain environments. Any `@Component`, `@Configuration` +or `@ConfigurationProperties` can be marked with `@Profile` to limit when it is loaded, +as shown in the following example: + +[source,java,indent=0] +---- + @Configuration(proxyBeanMethods = false) + @Profile("production") + public class ProductionConfiguration { + + // ... + + } +---- + +NOTE: If `@ConfigurationProperties` beans are registered via `@EnableConfigurationProperties` +instead of automatic scanning, the `@Profile` annotation needs to be specified on the `@Configuration` +class that has the `@EnableConfigurationProperties` annotation. In the case where `@ConfigurationProperties` +are scanned, `@Profile` can be specified on the `@ConfigurationProperties` class itself. + +You can use a `spring.profiles.active` `Environment` property to specify which profiles +are active. You can specify the property in any of the ways described earlier in this +chapter. For example, you could include it in your `application.properties`, as shown in +the following example: + +[source,properties,indent=0] +---- + spring.profiles.active=dev,hsqldb +---- + +You could also specify it on the command line by using the following switch: +`--spring.profiles.active=dev,hsqldb`. + + + +[[boot-features-adding-active-profiles]] +=== Adding Active Profiles +The `spring.profiles.active` property follows the same ordering rules as other +properties: The highest `PropertySource` wins. This means that you can specify active +profiles in `application.properties` and then *replace* them by using the command line +switch. + +Sometimes, it is useful to have profile-specific properties that *add* to the active +profiles rather than replace them. The `spring.profiles.include` property can be used to +unconditionally add active profiles. The `SpringApplication` entry point also has a Java +API for setting additional profiles (that is, on top of those activated by the +`spring.profiles.active` property). See the `setAdditionalProfiles()` method in +{dc-spring-boot}/SpringApplication.html[SpringApplication]. + +For example, when an application with the following properties is run by using the +switch, `--spring.profiles.active=prod`, the `proddb` and `prodmq` profiles are also +activated: + +[source,yaml,indent=0] +---- + --- + my.property: fromyamlfile + --- + spring.profiles: prod + spring.profiles.include: + - proddb + - prodmq +---- + +NOTE: Remember that the `spring.profiles` property can be defined in a YAML document to +determine when this particular document is included in the configuration. See +<> for more details. + + + +[[boot-features-programmatically-setting-profiles]] +=== Programmatically Setting Profiles +You can programmatically set active profiles by calling +`SpringApplication.setAdditionalProfiles(...)` before your application runs. It is also +possible to activate profiles by using Spring's `ConfigurableEnvironment` interface. + + + +[[boot-features-profile-specific-configuration]] +=== Profile-specific Configuration Files +Profile-specific variants of both `application.properties` (or `application.yml`) and +files referenced through `@ConfigurationProperties` are considered as files and loaded. +See "<>" for details. + + + +[[boot-features-logging]] +== Logging +Spring Boot uses https://commons.apache.org/logging[Commons Logging] for all internal +logging but leaves the underlying log implementation open. Default configurations are +provided for +{java-javadoc}/java/util/logging/package-summary.html[Java Util +Logging], https://logging.apache.org/log4j/2.x/[Log4J2], and +https://logback.qos.ch/[Logback]. In each case, loggers are pre-configured to use console +output with optional file output also available. + +By default, if you use the "`Starters`", Logback is used for logging. Appropriate Logback +routing is also included to ensure that dependent libraries that use Java Util Logging, +Commons Logging, Log4J, or SLF4J all work correctly. + +TIP: There are a lot of logging frameworks available for Java. Do not worry if the above +list seems confusing. Generally, you do not need to change your logging dependencies and +the Spring Boot defaults work just fine. + + + +[[boot-features-logging-format]] +=== Log Format +The default log output from Spring Boot resembles the following example: + +[indent=0] +---- +2014-03-05 10:57:51.112 INFO 45469 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/7.0.52 +2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext +2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1358 ms +2014-03-05 10:57:51.698 INFO 45469 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/] +2014-03-05 10:57:51.702 INFO 45469 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] +---- + +The following items are output: + +* Date and Time: Millisecond precision and easily sortable. +* Log Level: `ERROR`, `WARN`, `INFO`, `DEBUG`, or `TRACE`. +* Process ID. +* A `---` separator to distinguish the start of actual log messages. +* Thread name: Enclosed in square brackets (may be truncated for console output). +* Logger name: This is usually the source class name (often abbreviated). +* The log message. + +NOTE: Logback does not have a `FATAL` level. It is mapped to `ERROR`. + + +[[boot-features-logging-console-output]] +=== Console Output +The default log configuration echoes messages to the console as they are written. By +default, `ERROR`-level, `WARN`-level, and `INFO`-level messages are logged. You can also +enable a "`debug`" mode by starting your application with a `--debug` flag. + +[indent=0] +---- + $ java -jar myapp.jar --debug +---- + +NOTE: You can also specify `debug=true` in your `application.properties`. + +When the debug mode is enabled, a selection of core loggers (embedded container, +Hibernate, and Spring Boot) are configured to output more information. Enabling the debug +mode does _not_ configure your application to log all messages with `DEBUG` level. + +Alternatively, you can enable a "`trace`" mode by starting your application with a +`--trace` flag (or `trace=true` in your `application.properties`). Doing so enables trace +logging for a selection of core loggers (embedded container, Hibernate schema generation, +and the whole Spring portfolio). + +[[boot-features-logging-color-coded-output]] +==== Color-coded Output +If your terminal supports ANSI, color output is used to aid readability. You can set +`spring.output.ansi.enabled` to a +{dc-spring-boot}/ansi/AnsiOutput.Enabled.{dc-ext}[supported value] to override the auto +detection. + +Color coding is configured by using the `%clr` conversion word. In its simplest form, the +converter colors the output according to the log level, as shown in the following +example: + +[source,indent=0] +---- +%clr(%5p) +---- + +The following table describes the mapping of log levels to colors: + +|=== +|Level | Color + +|`FATAL` +| Red + +|`ERROR` +| Red + +|`WARN` +| Yellow + +|`INFO` +| Green + +|`DEBUG` +| Green + +|`TRACE` +| Green +|=== + +Alternatively, you can specify the color or style that should be used by providing it as +an option to the conversion. For example, to make the text yellow, use the following +setting: + +[source,indent=0] +---- +%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){yellow} +---- + +The following colors and styles are supported: + +* `blue` +* `cyan` +* `faint` +* `green` +* `magenta` +* `red` +* `yellow` + +[[boot-features-logging-file-output]] +=== File Output +By default, Spring Boot logs only to the console and does not write log files. If you +want to write log files in addition to the console output, you need to set a +`logging.file.name` or `logging.file.path` property (for example, in your +`application.properties`). + +The following table shows how the `logging.*` properties can be used together: + +.Logging properties +[cols="1,1,1,4"] +|=== +|`logging.file.name` |`logging.file.path` |Example |Description + +|_(none)_ +|_(none)_ +| +|Console only logging. + +|Specific file +|_(none)_ +|`my.log` +|Writes to the specified log file. Names can be an exact location or relative to the +current directory. + +|_(none)_ +|Specific directory +|`/var/log` +|Writes `spring.log` to the specified directory. Names can be an exact location or +relative to the current directory. +|=== + +Log files rotate when they reach 10 MB and, as with console output, `ERROR`-level, +`WARN`-level, and `INFO`-level messages are logged by default. Size limits can be changed +using the `logging.file.max-size` property. Previously rotated files are archived +indefinitely unless the `logging.file.max-history` property has been set. The total size +of log archives can be capped using `logging.file.total-size-cap`. When the total size of +log archives exceeds that threshold, backups will be deleted. To force log archive cleanup +on application startup, use the `logging.file.clean-history-on-start` property. + +NOTE: The logging system is initialized early in the application lifecycle. Consequently, +logging properties are not found in property files loaded through `@PropertySource` +annotations. + +TIP: Logging properties are independent of the actual logging infrastructure. As a +result, specific configuration keys (such as `logback.configurationFile` for Logback) are +not managed by spring Boot. + + +[[boot-features-custom-log-levels]] +=== Log Levels +All the supported logging systems can have the logger levels set in the Spring +`Environment` (for example, in `application.properties`) by using +`+logging.level.=+` where `level` is one of TRACE, DEBUG, INFO, WARN, +ERROR, FATAL, or OFF. The `root` logger can be configured by using `logging.level.root`. + +The following example shows potential logging settings in `application.properties`: + +[source,properties,indent=0,subs="verbatim,quotes,attributes"] +---- + logging.level.root=WARN + logging.level.org.springframework.web=DEBUG + logging.level.org.hibernate=ERROR +---- + + + +[[boot-features-custom-log-groups]] +=== Log Groups +It's often useful to be able to group related loggers together so that they can all be +configured at the same time. For example, you might commonly change the logging levels for +_all_ Tomcat related loggers, but you can't easily remember top level packages. + +To help with this, Spring Boot allows you to define logging groups in your Spring +`Environment`. For example, here's how you could define a "`tomcat`" group by adding +it to your `application.properties`: + +[source,properties,indent=0,subs="verbatim,quotes,attributes"] +---- + logging.group.tomcat=org.apache.catalina, org.apache.coyote, org.apache.tomcat +---- + +Once defined, you can change the level for all the loggers in the group with a single +line: + +[source,properties,indent=0,subs="verbatim,quotes,attributes"] +---- + logging.level.tomcat=TRACE +---- + +Spring Boot includes the following pre-defined logging groups that can be used +out-of-the-box: + +[cols="1,4"] +|=== +|Name |Loggers + +|web +|`org.springframework.core.codec`, `org.springframework.http`, `org.springframework.web` + +|sql +|`org.springframework.jdbc.core`, `org.hibernate.SQL`, `org.jooq.tools.LoggerListener` + +|=== + + + +[[boot-features-custom-log-configuration]] +=== Custom Log Configuration +The various logging systems can be activated by including the appropriate libraries on +the classpath and can be further customized by providing a suitable configuration file in +the root of the classpath or in a location specified by the following Spring `Environment` +property: `logging.config`. + +You can force Spring Boot to use a particular logging system by using the +`org.springframework.boot.logging.LoggingSystem` system property. The value should be the +fully qualified class name of a `LoggingSystem` implementation. You can also disable +Spring Boot's logging configuration entirely by using a value of `none`. + +NOTE: Since logging is initialized *before* the `ApplicationContext` is created, it is +not possible to control logging from `@PropertySources` in Spring `@Configuration` files. +The only way to change the logging system or disable it entirely is via System properties. + +Depending on your logging system, the following files are loaded: + +|=== +|Logging System |Customization + +|Logback +|`logback-spring.xml`, `logback-spring.groovy`, `logback.xml`, or `logback.groovy` + +|Log4j2 +|`log4j2-spring.xml` or `log4j2.xml` + +|JDK (Java Util Logging) +|`logging.properties` +|=== + +NOTE: When possible, we recommend that you use the `-spring` variants for your logging +configuration (for example, `logback-spring.xml` rather than `logback.xml`). If you use +standard configuration locations, Spring cannot completely control log initialization. + +WARNING: There are known classloading issues with Java Util Logging that cause problems +when running from an 'executable jar'. We recommend that you avoid it when running from +an 'executable jar' if at all possible. + +To help with the customization, some other properties are transferred from the Spring +`Environment` to System properties, as described in the following table: + +|=== +|Spring Environment |System Property |Comments + +|`logging.exception-conversion-word` +|`LOG_EXCEPTION_CONVERSION_WORD` +|The conversion word used when logging exceptions. + +|`logging.file.clean-history-on-start` +|`LOG_FILE_CLEAN_HISTORY_ON_START` +|Whether to clean the archive log files on startup (if LOG_FILE enabled). (Only supported +with the default Logback setup.) + +|`logging.file.name` +|`LOG_FILE` +|If defined, it is used in the default log configuration. + +|`logging.file.max-size` +|`LOG_FILE_MAX_SIZE` +|Maximum log file size (if LOG_FILE enabled). (Only supported with the default Logback +setup.) + +|`logging.file.max-history` +|`LOG_FILE_MAX_HISTORY` +|Maximum number of archive log files to keep (if LOG_FILE enabled). (Only supported with +the default Logback setup.) + +|`logging.file.path` +|`LOG_PATH` +|If defined, it is used in the default log configuration. + +|`logging.file.total-size-cap` +|`LOG_FILE_TOTAL_SIZE_CAP` +|Total size of log backups to be kept (if LOG_FILE enabled). (Only supported with the +default Logback setup.) + +|`logging.pattern.console` +|`CONSOLE_LOG_PATTERN` +|The log pattern to use on the console (stdout). (Only supported with the default Logback +setup.) + +|`logging.pattern.dateformat` +|`LOG_DATEFORMAT_PATTERN` +|Appender pattern for log date format. (Only supported with the default Logback setup.) + +|`logging.pattern.file` +|`FILE_LOG_PATTERN` +|The log pattern to use in a file (if `LOG_FILE` is enabled). (Only supported with the +default Logback setup.) + +|`logging.pattern.level` +|`LOG_LEVEL_PATTERN` +|The format to use when rendering the log level (default `%5p`). (Only supported with the +default Logback setup.) + +|`PID` +|`PID` +|The current process ID (discovered if possible and when not already defined as an OS +environment variable). +|=== + +All the supported logging systems can consult System properties when parsing their +configuration files. See the default configurations in `spring-boot.jar` for examples: + +* {github-code}/spring-boot-project/spring-boot/src/main/resources/org/springframework/boot/logging/logback/defaults.xml[Logback] +* {github-code}/spring-boot-project/spring-boot/src/main/resources/org/springframework/boot/logging/log4j2/log4j2.xml[Log4j 2] +* {github-code}/spring-boot-project/spring-boot/src/main/resources/org/springframework/boot/logging/java/logging-file.properties[Java Util logging] + +[TIP] +==== +If you want to use a placeholder in a logging property, you should use +<> and not +the syntax of the underlying framework. Notably, if you use Logback, you should use `:` +as the delimiter between a property name and its default value and not use `:-`. +==== + +[TIP] +==== + +You can add MDC and other ad-hoc content to log lines by overriding only the +`LOG_LEVEL_PATTERN` (or `logging.pattern.level` with Logback). For example, if you use +`logging.pattern.level=user:%X\{user} %5p`, then the default log format contains an MDC +entry for "user", if it exists, as shown in the following example. + +---- +2015-09-30 12:30:04.031 user:someone INFO 22174 --- [ nio-8080-exec-0] demo.Controller +Handling authenticated request +---- +==== + + + +[[boot-features-logback-extensions]] +=== Logback Extensions +Spring Boot includes a number of extensions to Logback that can help with advanced +configuration. You can use these extensions in your `logback-spring.xml` configuration +file. + +NOTE: Because the standard `logback.xml` configuration file is loaded too early, you +cannot use extensions in it. You need to either use `logback-spring.xml` or define a +`logging.config` property. + +WARNING: The extensions cannot be used with Logback's +https://logback.qos.ch/manual/configuration.html#autoScan[configuration scanning]. If you +attempt to do so, making changes to the configuration file results in an error similar to +one of the following being logged: + +---- +ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProperty], current ElementPath is [[configuration][springProperty]] +ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProfile], current ElementPath is [[configuration][springProfile]] +---- + + + +==== Profile-specific Configuration +The `` tag lets you optionally include or exclude sections of +configuration based on the active Spring profiles. Profile sections are supported +anywhere within the `` element. Use the `name` attribute to specify which +profile accepts the configuration. The `` tag can contain a simple profile +name (for example `staging`) or a profile expression. A profile expression allows for more +complicated profile logic to be expressed, for example +`production & (eu-central | eu-west)`. Check the +{spring-reference}core.html#beans-definition-profiles-java[reference guide] for more +details. The following listing shows three sample profiles: + +[source,xml,indent=0] +---- + + + + + + + + + + + +---- + + + +==== Environment Properties +The `` tag lets you expose properties from the Spring `Environment` for +use within Logback. Doing so can be useful if you want to access values from your +`application.properties` file in your Logback configuration. The tag works in a similar +way to Logback's standard `` tag. However, rather than specifying a direct +`value`, you specify the `source` of the property (from the `Environment`). If you need +to store the property somewhere other than in `local` scope, you can use the `scope` +attribute. If you need a fallback value (in case the property is not set in the +`Environment`), you can use the `defaultValue` attribute. The following example shows how +to expose properties for use within Logback: + +[source,xml,indent=0] +---- + + + ${fluentHost} + ... + +---- + +NOTE: The `source` must be specified in kebab case (such as `my.property-name`). +However, properties can be added to the `Environment` by using the relaxed rules. + + + +[[boot-features-internationalization]] +== Internationalization +Spring Boot supports localized messages so that your application can cater to users +of different language preferences. By default, Spring Boot looks for the presence of +a `messages` resource bundle at the root of the classpath. + +NOTE: The auto-configuration applies when the default properties file for the configured +resource bundle is available (i.e. `messages.properties` by default). If your resource +bundle contains only language-specific properties files, you are required to add the +default. + +The basename of the resource bundle as well as several other attributes can be configured +using the `spring.messages` namespace, as shown in the following example: + +[source,properties,indent=0] +---- + spring.messages.basename=messages,config.i18n.messages + spring.messages.fallback-to-system-locale=false +---- + +TIP: `spring.messages.basename` supports comma-separated list of locations, either a +package qualifier or a resource resolved from the classpath root. + +See {sc-spring-boot-autoconfigure}/context/MessageSourceProperties.{sc-ext}[ +`MessageSourceProperties`] for more supported options. + + + + +[[boot-features-json]] +== JSON +Spring Boot provides integration with three JSON mapping libraries: + +- Gson +- Jackson +- JSON-B + +Jackson is the preferred and default library. + + + +[[boot-features-json-jackson]] +=== Jackson +Auto-configuration for Jackson is provided and Jackson is part of +`spring-boot-starter-json`. When Jackson is on the classpath an `ObjectMapper` +bean is automatically configured. Several configuration properties are provided for +<>. + + + +[[boot-features-json-gson]] +=== Gson +Auto-configuration for Gson is provided. When Gson is on the classpath a `Gson` bean is +automatically configured. Several `+spring.gson.*+` configuration properties are +provided for customizing the configuration. To take more control, one or more +`GsonBuilderCustomizer` beans can be used. + + + +[[boot-features-json-json-b]] +=== JSON-B +Auto-configuration for JSON-B is provided. When the JSON-B API and an implementation are +on the classpath a `Jsonb` bean will be automatically configured. The preferred JSON-B +implementation is Apache Johnzon for which dependency management is provided. + + + +[[boot-features-developing-web-applications]] +== Developing Web Applications +Spring Boot is well suited for web application development. You can create a +self-contained HTTP server by using embedded Tomcat, Jetty, Undertow, or Netty. Most web +applications use the `spring-boot-starter-web` module to get up and running quickly. You +can also choose to build reactive web applications by using the +`spring-boot-starter-webflux` module. + +If you have not yet developed a Spring Boot web application, you can follow the +"Hello World!" example in the +_<>_ section. + + + +[[boot-features-spring-mvc]] +=== The "`Spring Web MVC Framework`" +The {spring-reference}web.html#mvc[Spring Web MVC framework] (often referred to as simply +"`Spring MVC`") is a rich "`model view controller`" web framework. Spring MVC lets you +create special `@Controller` or `@RestController` beans to handle incoming HTTP requests. +Methods in your controller are mapped to HTTP by using `@RequestMapping` annotations. + +The following code shows a typical `@RestController` that serves JSON data: + +[source,java,indent=0] +---- + @RestController + @RequestMapping(value="/users") + public class MyRestController { + + @RequestMapping(value="/\{user}", method=RequestMethod.GET) + public User getUser(@PathVariable Long user) { + // ... + } + + @RequestMapping(value="/\{user}/customers", method=RequestMethod.GET) + List getUserCustomers(@PathVariable Long user) { + // ... + } + + @RequestMapping(value="/\{user}", method=RequestMethod.DELETE) + public User deleteUser(@PathVariable Long user) { + // ... + } + + } +---- + +Spring MVC is part of the core Spring Framework, and detailed information is available in +the {spring-reference}web.html#mvc[reference documentation]. There are also several +guides that cover Spring MVC available at https://spring.io/guides. + + + +[[boot-features-spring-mvc-auto-configuration]] +==== Spring MVC Auto-configuration +Spring Boot provides auto-configuration for Spring MVC that works well with most +applications. + +The auto-configuration adds the following features on top of Spring's defaults: + +* Inclusion of `ContentNegotiatingViewResolver` and `BeanNameViewResolver` beans. +* Support for serving static resources, including support for WebJars (covered +<>)). +* Automatic registration of `Converter`, `GenericConverter`, and `Formatter` beans. +* Support for `HttpMessageConverters` (covered +<>). +* Automatic registration of `MessageCodesResolver` (covered +<>). +* Static `index.html` support. +* Custom `Favicon` support (covered <>). +* Automatic use of a `ConfigurableWebBindingInitializer` bean (covered +<>). + +If you want to keep Spring Boot MVC features and you want to add additional +{spring-reference}web.html#mvc[MVC configuration] (interceptors, formatters, view +controllers, and other features), you can add your own `@Configuration` class of type +`WebMvcConfigurer` but *without* `@EnableWebMvc`. If you wish to provide custom +instances of `RequestMappingHandlerMapping`, `RequestMappingHandlerAdapter`, or +`ExceptionHandlerExceptionResolver`, you can declare a `WebMvcRegistrationsAdapter` +instance to provide such components. + +If you want to take complete control of Spring MVC, you can add your own `@Configuration` +annotated with `@EnableWebMvc`. + + +[[boot-features-spring-mvc-message-converters]] +==== HttpMessageConverters +Spring MVC uses the `HttpMessageConverter` interface to convert HTTP requests and +responses. Sensible defaults are included out of the box. For example, objects can be +automatically converted to JSON (by using the Jackson library) or XML (by using the +Jackson XML extension, if available, or by using JAXB if the Jackson XML extension is not +available). By default, strings are encoded in `UTF-8`. + +If you need to add or customize converters, you can use Spring Boot's +`HttpMessageConverters` class, as shown in the following listing: + +[source,java,indent=0] +---- + import org.springframework.boot.autoconfigure.http.HttpMessageConverters; + import org.springframework.context.annotation.*; + import org.springframework.http.converter.*; + + @Configuration(proxyBeanMethods = false) + public class MyConfiguration { + + @Bean + public HttpMessageConverters customConverters() { + HttpMessageConverter additional = ... + HttpMessageConverter another = ... + return new HttpMessageConverters(additional, another); + } + + } +---- + +Any `HttpMessageConverter` bean that is present in the context is added to the list of +converters. You can also override default converters in the same way. + + + +[[boot-features-json-components]] +==== Custom JSON Serializers and Deserializers +If you use Jackson to serialize and deserialize JSON data, you might want to write your +own `JsonSerializer` and `JsonDeserializer` classes. Custom serializers are usually +https://github.com/FasterXML/jackson-docs/wiki/JacksonHowToCustomSerializers[registered with Jackson through +a module], but Spring Boot provides an alternative `@JsonComponent` annotation that makes +it easier to directly register Spring Beans. + +You can use the `@JsonComponent` annotation directly on `JsonSerializer`, +`JsonDeserializer` or `KeyDeserializer` implementations. You can also use it on classes +that contain serializers/deserializers as inner classes, as shown in the following example: + +[source,java,indent=0] +---- + import java.io.*; + import com.fasterxml.jackson.core.*; + import com.fasterxml.jackson.databind.*; + import org.springframework.boot.jackson.*; + + @JsonComponent + public class Example { + + public static class Serializer extends JsonSerializer { + // ... + } + + public static class Deserializer extends JsonDeserializer { + // ... + } + + } +---- + +All `@JsonComponent` beans in the `ApplicationContext` are automatically registered with +Jackson. Because `@JsonComponent` is meta-annotated with `@Component`, the usual +component-scanning rules apply. + +Spring Boot also provides +{sc-spring-boot}/jackson/JsonObjectSerializer.{sc-ext}[`JsonObjectSerializer`] and +{sc-spring-boot}/jackson/JsonObjectDeserializer.{sc-ext}[`JsonObjectDeserializer`] base +classes that provide useful alternatives to the standard Jackson versions when +serializing objects. See +{dc-spring-boot}/jackson/JsonObjectSerializer.{dc-ext}[`JsonObjectSerializer`] +and {dc-spring-boot}/jackson/JsonObjectDeserializer.{dc-ext}[`JsonObjectDeserializer`] in +the Javadoc for details. + + + +[[boot-features-spring-message-codes]] +==== MessageCodesResolver +Spring MVC has a strategy for generating error codes for rendering error messages from +binding errors: `MessageCodesResolver`. If you set the +`spring.mvc.message-codes-resolver.format` property `PREFIX_ERROR_CODE` or +`POSTFIX_ERROR_CODE`, Spring Boot creates one for you (see the enumeration in +{spring-javadoc}/validation/DefaultMessageCodesResolver.Format.{dc-ext}[`DefaultMessageCodesResolver.Format`]). + + + +[[boot-features-spring-mvc-static-content]] +==== Static Content +By default, Spring Boot serves static content from a directory called `/static` (or +`/public` or `/resources` or `/META-INF/resources`) in the classpath or from the root of +the `ServletContext`. It uses the `ResourceHttpRequestHandler` from Spring MVC so that +you can modify that behavior by adding your own `WebMvcConfigurer` and overriding the +`addResourceHandlers` method. + +In a stand-alone web application, the default servlet from the container is also enabled +and acts as a fallback, serving content from the root of the `ServletContext` if Spring +decides not to handle it. Most of the time, this does not happen (unless you modify the +default MVC configuration), because Spring can always handle requests through the +`DispatcherServlet`. + +By default, resources are mapped on `+/**+`, but you can tune that with the +`spring.mvc.static-path-pattern` property. For instance, relocating all resources to +`/resources/**` can be achieved as follows: + +[source,properties,indent=0,subs="verbatim,quotes,attributes"] +---- + spring.mvc.static-path-pattern=/resources/** +---- + +You can also customize the static resource locations by using the +`spring.resources.static-locations` property (replacing the default values with a list of +directory locations). The root Servlet context path, `"/"`, is automatically added as a +location as well. + +In addition to the "`standard`" static resource locations mentioned earlier, a special +case is made for https://www.webjars.org/[Webjars content]. Any resources with a path in +`+/webjars/**+` are served from jar files if they are packaged in the Webjars format. + +TIP: Do not use the `src/main/webapp` directory if your application is packaged as a jar. +Although this directory is a common standard, it works *only* with war packaging, and it +is silently ignored by most build tools if you generate a jar. + +Spring Boot also supports the advanced resource handling features provided by Spring MVC, +allowing use cases such as cache-busting static resources or using version agnostic URLs +for Webjars. + +To use version agnostic URLs for Webjars, add the `webjars-locator-core` dependency. +Then declare your Webjar. Using jQuery as an example, adding +`"/webjars/jquery/jquery.min.js"` results in +`"/webjars/jquery/x.y.z/jquery.min.js"`. where `x.y.z` is the Webjar version. + +NOTE: If you use JBoss, you need to declare the `webjars-locator-jboss-vfs` +dependency instead of the `webjars-locator-core`. Otherwise, all Webjars resolve as a +`404`. + +To use cache busting, the following configuration configures a cache busting solution for +all static resources, effectively adding a content hash, such as +``, in URLs: + +[source,properties,indent=0,subs="verbatim,quotes,attributes"] +---- + spring.resources.chain.strategy.content.enabled=true + spring.resources.chain.strategy.content.paths=/** +---- + +NOTE: Links to resources are rewritten in templates at runtime, thanks to a +`ResourceUrlEncodingFilter` that is auto-configured for Thymeleaf and FreeMarker. You +should manually declare this filter when using JSPs. Other template engines are currently +not automatically supported but can be with custom template macros/helpers and the use of +the +{spring-javadoc}/web/servlet/resource/ResourceUrlProvider.{dc-ext}[`ResourceUrlProvider`]. + +When loading resources dynamically with, for example, a JavaScript module loader, +renaming files is not an option. That is why other strategies are also supported and can +be combined. A "fixed" strategy adds a static version string in the URL without changing +the file name, as shown in the following example: + +[source,properties,indent=0,subs="verbatim,quotes,attributes"] +---- + spring.resources.chain.strategy.content.enabled=true + spring.resources.chain.strategy.content.paths=/** + spring.resources.chain.strategy.fixed.enabled=true + spring.resources.chain.strategy.fixed.paths=/js/lib/ + spring.resources.chain.strategy.fixed.version=v12 +---- + +With this configuration, JavaScript modules located under `"/js/lib/"` use a fixed +versioning strategy (`"/v12/js/lib/mymodule.js"`), while other resources still use the +content one (``). + +See {sc-spring-boot-autoconfigure}/web/ResourceProperties.{sc-ext}[`ResourceProperties`] +for more supported options. + +[TIP] +==== +This feature has been thoroughly described in a dedicated +https://spring.io/blog/2014/07/24/spring-framework-4-1-handling-static-web-resources[blog +post] and in Spring Framework's +{spring-reference}web.html#mvc-config-static-resources[reference documentation]. +==== + +[[boot-features-spring-mvc-welcome-page]] +==== Welcome Page +Spring Boot supports both static and templated welcome pages. It first looks for an +`index.html` file in the configured static content locations. If one is not found, it +then looks for an `index` template. If either is found, it is automatically used as the +welcome page of the application. + + + +[[boot-features-spring-mvc-favicon]] +==== Custom Favicon +Spring Boot looks for a `favicon.ico` in the configured static content locations and the +root of the classpath (in that order). If such a file is present, it is automatically +used as the favicon of the application. + + +[[boot-features-spring-mvc-pathmatch]] +==== Path Matching and Content Negotiation +Spring MVC can map incoming HTTP requests to handlers by looking at the request path and +matching it to the mappings defined in your application (for example, `@GetMapping` +annotations on Controller methods). + +Spring Boot chooses to disable suffix pattern matching by default, which means that +requests like `"GET /projects/spring-boot.json"` won't be matched to +`@GetMapping("/projects/spring-boot")` mappings. +This is considered as a +{spring-reference}web.html#mvc-ann-requestmapping-suffix-pattern-match[best practice +for Spring MVC applications]. This feature was mainly useful in the past for HTTP +clients which did not send proper "Accept" request headers; we needed to make sure +to send the correct Content Type to the client. Nowadays, Content Negotiation +is much more reliable. + +There are other ways to deal with HTTP clients that don't consistently send proper +"Accept" request headers. Instead of using suffix matching, we can use a query +parameter to ensure that requests like `"GET /projects/spring-boot?format=json"` +will be mapped to `@GetMapping("/projects/spring-boot")`: + +[source,properties,indent=0,subs="verbatim,quotes,attributes"] +---- + spring.mvc.contentnegotiation.favor-parameter=true + + # We can change the parameter name, which is "format" by default: + # spring.mvc.contentnegotiation.parameter-name=myparam + + # We can also register additional file extensions/media types with: + spring.mvc.contentnegotiation.media-types.markdown=text/markdown +---- + +If you understand the caveats and would still like your application to use +suffix pattern matching, the following configuration is required: + +[source,properties,indent=0,subs="verbatim,quotes,attributes"] +---- + spring.mvc.contentnegotiation.favor-path-extension=true + spring.mvc.pathmatch.use-suffix-pattern=true +---- + +Alternatively, rather than open all suffix patterns, it's more secure to just support +registered suffix patterns: + +[source,properties,indent=0,subs="verbatim,quotes,attributes"] +---- + spring.mvc.contentnegotiation.favor-path-extension=true + spring.mvc.pathmatch.use-registered-suffix-pattern=true + + # You can also register additional file extensions/media types with: + # spring.mvc.contentnegotiation.media-types.adoc=text/asciidoc +---- + + + +[[boot-features-spring-mvc-web-binding-initializer]] +==== ConfigurableWebBindingInitializer +Spring MVC uses a `WebBindingInitializer` to initialize a `WebDataBinder` for a +particular request. If you create your own `ConfigurableWebBindingInitializer` `@Bean`, +Spring Boot automatically configures Spring MVC to use it. + + + +[[boot-features-spring-mvc-template-engines]] +==== Template Engines +As well as REST web services, you can also use Spring MVC to serve dynamic HTML content. +Spring MVC supports a variety of templating technologies, including Thymeleaf, +FreeMarker, and JSPs. Also, many other templating engines include their own Spring MVC +integrations. + +Spring Boot includes auto-configuration support for the following templating engines: + + * https://freemarker.apache.org/docs/[FreeMarker] + * http://docs.groovy-lang.org/docs/next/html/documentation/template-engines.html#_the_markuptemplateengine[Groovy] + * https://www.thymeleaf.org[Thymeleaf] + * https://mustache.github.io/[Mustache] + +TIP: If possible, JSPs should be avoided. There are several +<> when using them with embedded +servlet containers. + +When you use one of these templating engines with the default configuration, your +templates are picked up automatically from `src/main/resources/templates`. + +TIP: Depending on how you run your application, IntelliJ IDEA orders the classpath +differently. Running your application in the IDE from its main method results in a +different ordering than when you run your application by using Maven or Gradle or from +its packaged jar. This can cause Spring Boot to fail to find the templates on the +classpath. If you have this problem, you can reorder the classpath in the IDE to place +the module's classes and resources first. Alternatively, you can configure the template +prefix to search every `templates` directory on the classpath, as follows: +`classpath*:/templates/`. + + + +[[boot-features-error-handling]] +==== Error Handling +By default, Spring Boot provides an `/error` mapping that handles all errors in a +sensible way, and it is registered as a "`global`" error page in the servlet container. +For machine clients, it produces a JSON response with details of the error, the HTTP +status, and the exception message. For browser clients, there is a "`whitelabel`" error +view that renders the same data in HTML format (to customize it, add a `View` that +resolves to `error`). To replace the default behavior completely, you can implement +`ErrorController` and register a bean definition of that type or add a bean of type +`ErrorAttributes` to use the existing mechanism but replace the contents. + +TIP: The `BasicErrorController` can be used as a base class for a custom +`ErrorController`. This is particularly useful if you want to add a handler for a new +content type (the default is to handle `text/html` specifically and provide a fallback +for everything else). To do so, extend `BasicErrorController`, add a public method with a +`@RequestMapping` that has a `produces` attribute, and create a bean of your new type. + +You can also define a class annotated with `@ControllerAdvice` to customize the JSON +document to return for a particular controller and/or exception type, as shown in the +following example: + +[source,java,indent=0,subs="verbatim,quotes,attributes"] +---- + @ControllerAdvice(basePackageClasses = AcmeController.class) + public class AcmeControllerAdvice extends ResponseEntityExceptionHandler { + + @ExceptionHandler(YourException.class) + @ResponseBody + ResponseEntity handleControllerException(HttpServletRequest request, Throwable ex) { + HttpStatus status = getStatus(request); + return new ResponseEntity<>(new CustomErrorType(status.value(), ex.getMessage()), status); + } + + private HttpStatus getStatus(HttpServletRequest request) { + Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); + if (statusCode == null) { + return HttpStatus.INTERNAL_SERVER_ERROR; + } + return HttpStatus.valueOf(statusCode); + } + + } +---- + +In the preceding example, if `YourException` is thrown by a controller defined in the +same package as `AcmeController`, a JSON representation of the `CustomErrorType` POJO is +used instead of the `ErrorAttributes` representation. + + + +[[boot-features-error-handling-custom-error-pages]] +===== Custom Error Pages +If you want to display a custom HTML error page for a given status code, you can add a +file to an `/error` folder. Error pages can either be static HTML (that is, added under +any of the static resource folders) or be built by using templates. The name of the file +should be the exact status code or a series mask. + +For example, to map `404` to a static HTML file, your folder structure would be as +follows: + +[source,indent=0,subs="verbatim,quotes,attributes"] +---- + src/ + +- main/ + +- java/ + | + + +- resources/ + +- public/ + +- error/ + | +- 404.html + +- +---- + +To map all `5xx` errors by using a FreeMarker template, your folder structure would be as +follows: + +[source,indent=0,subs="verbatim,quotes,attributes"] +---- + src/ + +- main/ + +- java/ + | + + +- resources/ + +- templates/ + +- error/ + | +- 5xx.ftlh + +- +---- + +For more complex mappings, you can also add beans that implement the `ErrorViewResolver` +interface, as shown in the following example: + +[source,java,indent=0,subs="verbatim,quotes,attributes"] +---- + public class MyErrorViewResolver implements ErrorViewResolver { + + @Override + public ModelAndView resolveErrorView(HttpServletRequest request, + HttpStatus status, Map model) { + // Use the request or status to optionally return a ModelAndView + return ... + } + + } +---- + + +You can also use regular Spring MVC features such as +{spring-reference}web.html#mvc-exceptionhandlers[`@ExceptionHandler` methods] and +{spring-reference}web.html#mvc-ann-controller-advice[`@ControllerAdvice`]. The +`ErrorController` then picks up any unhandled exceptions. + + + +[[boot-features-error-handling-mapping-error-pages-without-mvc]] +===== Mapping Error Pages outside of Spring MVC +For applications that do not use Spring MVC, you can use the `ErrorPageRegistrar` +interface to directly register `ErrorPages`. This abstraction works directly with the +underlying embedded servlet container and works even if you do not have a Spring MVC +`DispatcherServlet`. + + +[source,java,indent=0,subs="verbatim,quotes,attributes"] +---- + @Bean + public ErrorPageRegistrar errorPageRegistrar(){ + return new MyErrorPageRegistrar(); + } + + // ... + + private static class MyErrorPageRegistrar implements ErrorPageRegistrar { + + @Override + public void registerErrorPages(ErrorPageRegistry registry) { + registry.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400")); + } + + } +---- + +NOTE: If you register an `ErrorPage` with a path that ends up being handled by a `Filter` +(as is common with some non-Spring web frameworks, like Jersey and Wicket), then the +`Filter` has to be explicitly registered as an `ERROR` dispatcher, as shown in the +following example: + +[source,java,indent=0,subs="verbatim,quotes,attributes"] +---- + @Bean + public FilterRegistrationBean myFilter() { + FilterRegistrationBean registration = new FilterRegistrationBean(); + registration.setFilter(new MyFilter()); + ... + registration.setDispatcherTypes(EnumSet.allOf(DispatcherType.class)); + return registration; + } +---- + +Note that the default `FilterRegistrationBean` does not include the `ERROR` dispatcher +type. + + + +[[boot-features-error-handling-websphere]] +CAUTION:When deployed to a servlet container, Spring Boot uses its error page filter to +forward a request with an error status to the appropriate error page. The request can only +be forwarded to the correct error page if the response has not already been committed. By +default, WebSphere Application Server 8.0 and later commits the response upon successful +completion of a servlet's service method. You should disable this behavior by setting +`com.ibm.ws.webcontainer.invokeFlushAfterService` to `false`. + + + +[[boot-features-spring-hateoas]] +==== Spring HATEOAS +If you develop a RESTful API that makes use of hypermedia, Spring Boot provides +auto-configuration for Spring HATEOAS that works well with most applications. The +auto-configuration replaces the need to use `@EnableHypermediaSupport` and registers a +number of beans to ease building hypermedia-based applications, including a +`LinkDiscoverers` (for client side support) and an `ObjectMapper` configured to correctly +marshal responses into the desired representation. The `ObjectMapper` is customized by +setting the various `spring.jackson.*` properties or, if one exists, by a +`Jackson2ObjectMapperBuilder` bean. + +You can take control of Spring HATEOAS's configuration by using +`@EnableHypermediaSupport`. Note that doing so disables the `ObjectMapper` customization +described earlier. + + + +[[boot-features-cors]] +==== CORS Support + +https://en.wikipedia.org/wiki/Cross-origin_resource_sharing[Cross-origin resource sharing] +(CORS) is a https://www.w3.org/TR/cors/[W3C specification] implemented by +https://caniuse.com/#feat=cors[most browsers] that lets you specify in a flexible +way what kind of cross-domain requests are authorized, instead of using some less secure +and less powerful approaches such as IFRAME or JSONP. + +As of version 4.2, Spring MVC {spring-reference}web.html#cors[supports CORS]. +Using {spring-reference}web.html#controller-method-cors-configuration[controller method +CORS configuration] with +{spring-javadoc}/web/bind/annotation/CrossOrigin.{dc-ext}[`@CrossOrigin`] +annotations in your Spring Boot application does not require any specific configuration. +{spring-reference}web.html#global-cors-configuration[Global CORS configuration] can be +defined by registering a `WebMvcConfigurer` bean with a customized +`addCorsMappings(CorsRegistry)` method, as shown in the following example: + +[source,java,indent=0] +---- + @Configuration(proxyBeanMethods = false) + public class MyConfiguration { + + @Bean + public WebMvcConfigurer corsConfigurer() { + return new WebMvcConfigurer() { + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/api/**"); + } + }; + } + } +---- + + + +[[boot-features-webflux]] +=== The "`Spring WebFlux Framework`" + +Spring WebFlux is the new reactive web framework introduced in Spring Framework 5.0. +Unlike Spring MVC, it does not require the Servlet API, is fully asynchronous and +non-blocking, and implements the https://www.reactive-streams.org/[Reactive Streams] +specification through https://projectreactor.io/[the Reactor project]. + +Spring WebFlux comes in two flavors: functional and annotation-based. The +annotation-based one is quite close to the Spring MVC model, as shown in the +following example: + +[source,java,indent=0] +---- + @RestController + @RequestMapping("/users") + public class MyRestController { + + @GetMapping("/\{user}") + public Mono getUser(@PathVariable Long user) { + // ... + } + + @GetMapping("/\{user}/customers") + public Flux getUserCustomers(@PathVariable Long user) { + // ... + } + + @DeleteMapping("/\{user}") + public Mono deleteUser(@PathVariable Long user) { + // ... + } + + } +---- + +"`WebFlux.fn`", the functional variant, separates the routing configuration from the +actual handling of the requests, as shown in the following example: + +[source,java,indent=0] +---- + @Configuration(proxyBeanMethods = false) + public class RoutingConfiguration { + + @Bean + public RouterFunction monoRouterFunction(UserHandler userHandler) { + return route(GET("/\{user}").and(accept(APPLICATION_JSON)), userHandler::getUser) + .andRoute(GET("/\{user}/customers").and(accept(APPLICATION_JSON)), userHandler::getUserCustomers) + .andRoute(DELETE("/\{user}").and(accept(APPLICATION_JSON)), userHandler::deleteUser); + } + + } + + @Component + public class UserHandler { + + public Mono getUser(ServerRequest request) { + // ... + } + + public Mono getUserCustomers(ServerRequest request) { + // ... + } + + public Mono deleteUser(ServerRequest request) { + // ... + } + } +---- + +WebFlux is part of the Spring Framework and detailed information is available in its +{spring-reference}web-reactive.html#webflux-fn[reference documentation]. + +TIP: You can define as many `RouterFunction` beans as you like to modularize the +definition of the router. Beans can be ordered if you need to apply a precedence. + +To get started, add the `spring-boot-starter-webflux` module to your application. + +NOTE: Adding both `spring-boot-starter-web` and `spring-boot-starter-webflux` modules in +your application results in Spring Boot auto-configuring Spring MVC, not WebFlux. This +behavior has been chosen because many Spring developers add `spring-boot-starter-webflux` +to their Spring MVC application to use the reactive `WebClient`. You can still enforce +your choice by setting the chosen application type to +`SpringApplication.setWebApplicationType(WebApplicationType.REACTIVE)`. + + + +[[boot-features-webflux-auto-configuration]] +==== Spring WebFlux Auto-configuration +Spring Boot provides auto-configuration for Spring WebFlux that works well with most +applications. + +The auto-configuration adds the following features on top of Spring's defaults: + +* Configuring codecs for `HttpMessageReader` and `HttpMessageWriter` instances (described +<>). +* Support for serving static resources, including support for WebJars (described +<>). + +If you want to keep Spring Boot WebFlux features and you want to add additional +{spring-reference}web.html#web-reactive[WebFlux configuration], you can add your own +`@Configuration` class of type `WebFluxConfigurer` but *without* `@EnableWebFlux`. + +If you want to take complete control of Spring WebFlux, you can add your own +`@Configuration` annotated with `@EnableWebFlux`. + + + +[[boot-features-webflux-httpcodecs]] +==== HTTP Codecs with HttpMessageReaders and HttpMessageWriters +Spring WebFlux uses the `HttpMessageReader` and `HttpMessageWriter` interfaces to convert +HTTP requests and responses. They are configured with `CodecConfigurer` to have sensible +defaults by looking at the libraries available in your classpath. + +Spring Boot applies further customization by using `CodecCustomizer` instances. For +example, `spring.jackson.*` configuration keys are applied to the Jackson codec. + +If you need to add or customize codecs, you can create a custom `CodecCustomizer` +component, as shown in the following example: + +[source,java,indent=0] +---- + import org.springframework.boot.web.codec.CodecCustomizer; + + @Configuration(proxyBeanMethods = false) + public class MyConfiguration { + + @Bean + public CodecCustomizer myCodecCustomizer() { + return codecConfigurer -> { + // ... + } + } + + } +---- + +You can also leverage <>. + + + +[[boot-features-webflux-static-content]] +==== Static Content +By default, Spring Boot serves static content from a directory called `/static` (or +`/public` or `/resources` or `/META-INF/resources`) in the classpath. It uses the +`ResourceWebHandler` from Spring WebFlux so that you can modify that behavior by adding +your own `WebFluxConfigurer` and overriding the `addResourceHandlers` method. + +By default, resources are mapped on `+/**+`, but you can tune that by setting the +`spring.webflux.static-path-pattern` property. For instance, relocating all resources to +`/resources/**` can be achieved as follows: + +[source,properties,indent=0,subs="verbatim,quotes,attributes"] +---- + spring.webflux.static-path-pattern=/resources/** +---- + +You can also customize the static resource locations by using +`spring.resources.static-locations`. Doing so replaces the default values with a list of +directory locations. If you do so, the default welcome page detection switches to your +custom locations. So, if there is an `index.html` in any of your locations on startup, it +is the home page of the application. + +In addition to the "`standard`" static resource locations listed earlier, a special case +is made for https://www.webjars.org/[Webjars content]. Any resources with a path in +`+/webjars/**+` are served from jar files if they are packaged in the Webjars format. + +TIP: Spring WebFlux applications do not strictly depend on the Servlet API, so they +cannot be deployed as war files and do not use the `src/main/webapp` directory. + + + +[[boot-features-webflux-template-engines]] +==== Template Engines +As well as REST web services, you can also use Spring WebFlux to serve dynamic HTML +content. Spring WebFlux supports a variety of templating technologies, including +Thymeleaf, FreeMarker, and Mustache. + +Spring Boot includes auto-configuration support for the following templating engines: + + * https://freemarker.apache.org/docs/[FreeMarker] + * https://www.thymeleaf.org[Thymeleaf] + * https://mustache.github.io/[Mustache] + +When you use one of these templating engines with the default configuration, your +templates are picked up automatically from `src/main/resources/templates`. + + + +[[boot-features-webflux-error-handling]] +==== Error Handling + +Spring Boot provides a `WebExceptionHandler` that handles all errors in a sensible way. +Its position in the processing order is immediately before the handlers provided by +WebFlux, which are considered last. For machine clients, it produces a JSON response +with details of the error, the HTTP status, and the exception message. For browser +clients, there is a "`whitelabel`" error handler that renders the same data in HTML +format. You can also provide your own HTML templates to display errors (see the +<>). + +The first step to customizing this feature often involves using the existing mechanism +but replacing or augmenting the error contents. For that, you can add a bean of type +`ErrorAttributes`. + +To change the error handling behavior, you can implement `ErrorWebExceptionHandler` and +register a bean definition of that type. Because a `WebExceptionHandler` is quite +low-level, Spring Boot also provides a convenient `AbstractErrorWebExceptionHandler` to +let you handle errors in a WebFlux functional way, as shown in the following example: + +[source,java,indent=0,subs="verbatim,quotes,attributes"] +---- + public class CustomErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler { + + // Define constructor here + + @Override + protected RouterFunction getRoutingFunction(ErrorAttributes errorAttributes) { + + return RouterFunctions + .route(aPredicate, aHandler) + .andRoute(anotherPredicate, anotherHandler); + } + + } +---- + +For a more complete picture, you can also subclass `DefaultErrorWebExceptionHandler` +directly and override specific methods. + + + +[[boot-features-webflux-error-handling-custom-error-pages]] +===== Custom Error Pages + +If you want to display a custom HTML error page for a given status code, you can add a +file to an `/error` folder. Error pages can either be static HTML (that is, added under +any of the static resource folders) or built with templates. The name of the file should +be the exact status code or a series mask. + +For example, to map `404` to a static HTML file, your folder structure would be as +follows: + +[source,indent=0,subs="verbatim,quotes,attributes"] +---- + src/ + +- main/ + +- java/ + | + + +- resources/ + +- public/ + +- error/ + | +- 404.html + +- +---- + +To map all `5xx` errors by using a Mustache template, your folder structure would be as +follows: + +[source,indent=0,subs="verbatim,quotes,attributes"] +---- + src/ + +- main/ + +- java/ + | + + +- resources/ + +- templates/ + +- error/ + | +- 5xx.mustache + +- +---- + + + +[[boot-features-webflux-web-filters]] +==== Web Filters +Spring WebFlux provides a `WebFilter` interface that can be implemented to filter HTTP +request-response exchanges. `WebFilter` beans found in the application context will +be automatically used to filter each exchange. + +Where the order of the filters is important they can implement `Ordered` or be annotated +with `@Order`. Spring Boot auto-configuration may configure web filters for you. When it +does so, the orders shown in the following table will be used: + +|=== +| Web Filter | Order + +|`MetricsWebFilter` +|`Ordered.HIGHEST_PRECEDENCE + 1` + +|`WebFilterChainProxy` (Spring Security) +|`-100` + +|`HttpTraceWebFilter` +|`Ordered.LOWEST_PRECEDENCE - 10` + +|=== + + + +[[boot-features-jersey]] +=== JAX-RS and Jersey +If you prefer the JAX-RS programming model for REST endpoints, you can use one of the +available implementations instead of Spring MVC. https://jersey.github.io/[Jersey] and +https://cxf.apache.org/[Apache CXF] work quite well out of the box. CXF requires you to +register its `Servlet` or `Filter` as a `@Bean` in your application context. Jersey has +some native Spring support, so we also provide auto-configuration support for it in +Spring Boot, together with a starter. + +To get started with Jersey, include the `spring-boot-starter-jersey` as a dependency +and then you need one `@Bean` of type `ResourceConfig` in which you register all the +endpoints, as shown in the following example: + +[source,java,indent=0,subs="verbatim,quotes,attributes"] +---- + @Component + public class JerseyConfig extends ResourceConfig { + + public JerseyConfig() { + register(Endpoint.class); + } + + } +---- + +WARNING: Jersey's support for scanning executable archives is rather limited. For example, +it cannot scan for endpoints in a package found in a <> or in `WEB-INF/classes` when running an executable war file. +To avoid this limitation, the `packages` method should not be used, and endpoints should +be registered individually by using the `register` method, as shown in the preceding +example. + +For more advanced customizations, you can also register an arbitrary number of beans that +implement `ResourceConfigCustomizer`. + +All the registered endpoints should be `@Components` with HTTP resource annotations +(`@GET` and others), as shown in the following example: + +[source,java,indent=0,subs="verbatim,quotes,attributes"] +---- + @Component + @Path("/hello") + public class Endpoint { + + @GET + public String message() { + return "Hello"; + } + + } +---- + +Since the `Endpoint` is a Spring `@Component`, its lifecycle is managed by Spring and you +can use the `@Autowired` annotation to inject dependencies and use the `@Value` +annotation to inject external configuration. By default, the Jersey servlet is registered +and mapped to `/*`. You can change the mapping by adding `@ApplicationPath` to your +`ResourceConfig`. + +By default, Jersey is set up as a Servlet in a `@Bean` of type `ServletRegistrationBean` +named `jerseyServletRegistration`. By default, the servlet is initialized lazily, but you +can customize that behavior by setting `spring.jersey.servlet.load-on-startup`. You can +disable or override that bean by creating one of your own with the same name. You can +also use a filter instead of a servlet by setting `spring.jersey.type=filter` (in which +case, the `@Bean` to replace or override is `jerseyFilterRegistration`). The filter has +an `@Order`, which you can set with `spring.jersey.filter.order`. Both the servlet and +the filter registrations can be given init parameters by using `spring.jersey.init.*` to +specify a map of properties. + + + +[[boot-features-embedded-container]] +=== Embedded Servlet Container Support +Spring Boot includes support for embedded https://tomcat.apache.org/[Tomcat], +https://www.eclipse.org/jetty/[Jetty], and +https://github.com/undertow-io/undertow[Undertow] servers. Most developers use the +appropriate "`Starter`" to obtain a fully configured instance. By default, the embedded +server listens for HTTP requests on port `8080`. + + + +[[boot-features-embedded-container-servlets-filters-listeners]] +==== Servlets, Filters, and listeners +When using an embedded servlet container, you can register servlets, filters, and all the +listeners (such as `HttpSessionListener`) from the Servlet spec, either by using Spring +beans or by scanning for Servlet components. + + +[[boot-features-embedded-container-servlets-filters-listeners-beans]] +===== Registering Servlets, Filters, and Listeners as Spring Beans +Any `Servlet`, `Filter`, or servlet `*Listener` instance that is a Spring bean is +registered with the embedded container. This can be particularly convenient if you want +to refer to a value from your `application.properties` during configuration. + +By default, if the context contains only a single Servlet, it is mapped to `/`. In the +case of multiple servlet beans, the bean name is used as a path prefix. Filters map to +`+/*+`. + +If convention-based mapping is not flexible enough, you can use the +`ServletRegistrationBean`, `FilterRegistrationBean`, and +`ServletListenerRegistrationBean` classes for complete control. + +Filter beans can be ordered to control their position in the filter chain by using +`@Order` or implemented `Ordered`. It is usually safe to leave Filter beans unordered. +However, if a specific order is required, you should avoid configuring a Filter that reads +the request body at `Ordered.HIGHEST_PRECEDENCE`, since it might go against the character +encoding configuration of your application. If a Servlet filter wraps the request, it +should be configured with an order that is less than or equal to +`OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER`. + +TIP: To see the order of every `Filter` in your application, enable debug level logging +for the `web` <> +(`logging.level.web=debug`). Details of the registered filters, including their order and +URL patterns, will then be logged at startup. + + + +[[boot-features-embedded-container-context-initializer]] +==== Servlet Context Initialization +Embedded servlet containers do not directly execute the Servlet 3.0+ +`javax.servlet.ServletContainerInitializer` interface or Spring's +`org.springframework.web.WebApplicationInitializer` interface. This is an intentional +design decision intended to reduce the risk that third party libraries designed to run +inside a war may break Spring Boot applications. + +If you need to perform servlet context initialization in a Spring Boot application, you +should register a bean that implements the +`org.springframework.boot.web.servlet.ServletContextInitializer` interface. The +single `onStartup` method provides access to the `ServletContext` and, if necessary, can +easily be used as an adapter to an existing `WebApplicationInitializer`. + + + +[[boot-features-embedded-container-servlets-filters-listeners-scanning]] +===== Scanning for Servlets, Filters, and listeners +When using an embedded container, automatic registration of classes annotated with +`@WebServlet`, `@WebFilter`, and `@WebListener` can be enabled by using +`@ServletComponentScan`. + +TIP: `@ServletComponentScan` has no effect in a standalone container, where the +container's built-in discovery mechanisms are used instead. + + + +[[boot-features-embedded-container-application-context]] +==== The ServletWebServerApplicationContext +Under the hood, Spring Boot uses a different type of `ApplicationContext` for embedded +servlet container support. The `ServletWebServerApplicationContext` is a special type of +`WebApplicationContext` that bootstraps itself by searching for a single +`ServletWebServerFactory` bean. Usually a `TomcatServletWebServerFactory`, +`JettyServletWebServerFactory`, or `UndertowServletWebServerFactory` +has been auto-configured. + +NOTE: You usually do not need to be aware of these implementation classes. Most +applications are auto-configured, and the appropriate `ApplicationContext` and +`ServletWebServerFactory` are created on your behalf. + + + +[[boot-features-customizing-embedded-containers]] +==== Customizing Embedded Servlet Containers +Common servlet container settings can be configured by using Spring `Environment` +properties. Usually, you would define the properties in your `application.properties` +file. + +Common server settings include: + +* Network settings: Listen port for incoming HTTP requests (`server.port`), interface +address to bind to `server.address`, and so on. +* Session settings: Whether the session is persistent (`server.servlet.session.persistent`), +session timeout (`server.servlet.session.timeout`), location of session data +(`server.servlet.session.store-dir`), and session-cookie configuration +(`server.servlet.session.cookie.*`). +* Error management: Location of the error page (`server.error.path`) and so on. +* <> +* <> + +Spring Boot tries as much as possible to expose common settings, but this is not always +possible. For those cases, dedicated namespaces offer server-specific customizations (see +`server.tomcat` and `server.undertow`). For instance, +<> can be configured with specific +features of the embedded servlet container. + +TIP: See the +{sc-spring-boot-autoconfigure}/web/ServerProperties.{sc-ext}[`ServerProperties`] class +for a complete list. + + + +[[boot-features-programmatic-embedded-container-customization]] +===== Programmatic Customization +If you need to programmatically configure your embedded servlet container, you can +register a Spring bean that implements the `WebServerFactoryCustomizer` interface. +`WebServerFactoryCustomizer` provides access to the +`ConfigurableServletWebServerFactory`, which includes numerous customization setter +methods. The following example shows programmatically setting the port: + +[source,java,indent=0] +---- + import org.springframework.boot.web.server.WebServerFactoryCustomizer; + import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; + import org.springframework.stereotype.Component; + + @Component + public class CustomizationBean implements WebServerFactoryCustomizer { + + @Override + public void customize(ConfigurableServletWebServerFactory server) { + server.setPort(9000); + } + + } +---- + +NOTE: `TomcatServletWebServerFactory`, `JettyServletWebServerFactory` and `UndertowServletWebServerFactory` +are dedicated variants of `ConfigurableServletWebServerFactory` that have additional customization setter methods +for Tomcat, Jetty and Undertow respectively. + + + +[[boot-features-customizing-configurableservletwebserverfactory-directly]] +===== Customizing ConfigurableServletWebServerFactory Directly +If the preceding customization techniques are too limited, you can register the +`TomcatServletWebServerFactory`, `JettyServletWebServerFactory`, or +`UndertowServletWebServerFactory` bean yourself. + +[source,java,indent=0] +---- + @Bean + public ConfigurableServletWebServerFactory webServerFactory() { + TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(); + factory.setPort(9000); + factory.setSessionTimeout(10, TimeUnit.MINUTES); + factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notfound.html")); + return factory; + } +---- + +Setters are provided for many configuration options. Several protected method "`hooks`" +are also provided should you need to do something more exotic. See the +{dc-spring-boot}/web/servlet/server/ConfigurableServletWebServerFactory.{dc-ext}[source +code documentation] for details. + + + +[[boot-features-jsp-limitations]] +==== JSP Limitations +When running a Spring Boot application that uses an embedded servlet container (and is +packaged as an executable archive), there are some limitations in the JSP support. + +* With Jetty and Tomcat, it should work if you use war packaging. An executable war will + work when launched with `java -jar`, and will also be deployable to any standard + container. JSPs are not supported when using an executable jar. + +* Undertow does not support JSPs. + +* Creating a custom `error.jsp` page does not override the default view for +<>. +<> should be used +instead. + + + +[[boot-features-reactive-server]] +=== Embedded Reactive Server Support +Spring Boot includes support for the following embedded reactive web servers: +Reactor Netty, Tomcat, Jetty, and Undertow. Most developers use the appropriate “Starter” +to obtain a fully configured instance. By default, the embedded server listens for HTTP +requests on port 8080. + + + +[[boot-features-reactive-server-resources]] +=== Reactive Server Resources Configuration +When auto-configuring a Reactor Netty or Jetty server, Spring Boot will create specific +beans that will provide HTTP resources to the server instance: `ReactorResourceFactory` +or `JettyResourceFactory`. + +By default, those resources will be also shared with the Reactor Netty and Jetty clients +for optimal performances, given: + +* the same technology is used for server and client +* the client instance is built using the `WebClient.Builder` bean auto-configured by +Spring Boot + +Developers can override the resource configuration for Jetty and Reactor Netty by providing +a custom `ReactorResourceFactory` or `JettyResourceFactory` bean - this will be applied to +both clients and servers. + +You can learn more about the resource configuration on the client side in the +<>. + + + +[[boot-features-rsocket]] +== RSocket + +https://rsocket.io[RSocket] is a binary protocol for use on byte stream transports. +It enables symmetric interaction models via async message passing over a single connection. + +Spring Framework, with the Spring Messaging module supports RSocket both on the server and +the client side. On the server side, it lets you create special `@Controller` beans +to handle incoming RSocket messages. +Methods in your controller are mapped to RSocket routes by using `@MessageMapping` annotations. + +The following code shows a typical `@Controller`: + +[source,java,indent=0] +---- + @Controller + public class MyRSocketController { + + @MessageMapping("chat.room.{name}") + public Flux enterChatRoom(@DestinationVariable String chatRoom, + Flux messages) { + // ... + } + + @MessageMapping("users.\{user}.info") + Mono getUserInfo(@DestinationVariable String user) { + // ... + } + + } +---- + + + +[[boot-features-rsocket-strategies-auto-configuration]] +=== RSocket Strategies Auto-configuration +Spring Boot auto-configures an `RSocketStrategies` bean that provides all the required +infrastructure for encoding and decoding RSocket payloads. By default, the +auto-configuration will try to configure the following (in order): + +1. https://cbor.io/[CBOR] codecs with Jackson +2. JSON codecs with Jackson + +The `spring-boot-starter-rsocket` Starter provides both dependencies. + +Developers can customize the `RSocketStrategies` component by creating beans that +implement the `RSocketStrategiesCustomizer` interface. Note that their `@Order` is +important, as it determines the order of codecs. + + + +[[boot-features-rsocket-server-auto-configuration]] +=== RSocket server Auto-configuration +Spring Boot provides auto-configuration for RSocket servers. The required dependencies +are provided by the `spring-boot-starter-rsocket`. + +Spring Boot will start an RSocket server as a new embedded server in your application, +or will plug the RSocket infrastructure into an existing reactive Web server. This +depends on the type of application and its configuration. + +In case of a WebFlux application (i.e. of type `WebApplicationType.REACTIVE`), the +RSocket server will be plugged into the existing Web Server only if the following +properties match: + +[source,properties,indent=0,subs="verbatim,quotes,attributes"] +---- + spring.rsocket.server.mapping-path=/rsocket # a mapping path is defined + spring.rsocket.server.transport=websocket # websocket is chosen as a transport + #spring.rsocket.server.port= # no port is defined +---- + +The only other way to create an RSocket server is to start an independent, embedded +RSocket server. Besides the dependency requirements, the only required configuration +is to define a port for that server: + +[source,properties,indent=0,subs="verbatim,quotes,attributes"] +---- + spring.rsocket.server.port=9898 # the only required configuration + spring.rsocket.server.transport=tcp # you're free to configure other properties +---- + + + +[[boot-features-rsocket-messaging]] +=== Spring Messaging RSocket support +Spring Boot will auto-configure the Spring Messaging infrastructure for RSocket. + +An `RSocketStrategies` bean is created to provide encoding and decoding support +for RSocket messages. By default, Spring Boot will try to auto-configure JSON +support with Jackson for `application/json` and `"application/*+json"` media types. +Check out the <> to know more +about customization possibilities. + +Developers can create `RSocketStrategiesCustomizer` beans to add other strategies, +assuming there are `Encoder` and `Decoder` implementations available. + + + +[[boot-features-rsocket-requester]] +=== Calling RSocket Services with `RSocketRequester` + +Once the `RSocket` channel is established between server and client, any party can send or +receive requests to the other. + +As a server, you can get injected an `RSocketRequester` instance on any handler method of +an RSocket `@Controller`. As a client, you need to configure and establish an RSocket +connection first. Spring Boot auto-configures an `RSocketRequester.Builder` for such cases +with the expected codecs. + +The `RSocketRequester.Builder` instance is a prototype bean, meaning each injection point +will provide you with a new instance - this is done on purpose since this builder is stateful +and you shouldn't create requesters with different setups using the same instance. + +The following code shows a typical example: + +[source,java,indent=0] +---- + @Service + public class MyService { + + private final RSocketRequester rsocketRequester; + + public MyService(RSocketRequester.Builder rsocketRequesterBuilder) { + this.rsocketRequester = rsocketRequesterBuilder + .connectTcp("example.org", 9090).block(); + } + + public Mono someRSocketCall(String name) { + return this.requester.route("user").data(name) + .retrieveMono(User.class); + } + + } +---- + + + +[[boot-features-security]] +== Security +If {spring-security}[Spring Security] is on the classpath, then web applications are +secured by default. Spring Boot relies on Spring Security’s content-negotiation strategy +to determine whether to use `httpBasic` or `formLogin`. To add method-level security to a +web application, you can also add `@EnableGlobalMethodSecurity` with your desired +settings. Additional information can be found in the +{spring-security-reference}#jc-method[Spring Security Reference Guide]. + +The default `UserDetailsService` has a single user. The user name is `user`, and the +password is random and is printed at INFO level when the application starts, as shown in +the following example: + +[indent=0] +---- + Using generated security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35 +---- + +NOTE: If you fine-tune your logging configuration, ensure that the +`org.springframework.boot.autoconfigure.security` category is set to log `INFO`-level +messages. Otherwise, the default password is not printed. + +You can change the username and password by providing a `spring.security.user.name` and +`spring.security.user.password`. + +The basic features you get by default in a web application are: + +* A `UserDetailsService` (or `ReactiveUserDetailsService` in case of a WebFlux application) +bean with in-memory store and a single user with a generated password (see +{dc-spring-boot}/autoconfigure/security/SecurityProperties.User.html[`SecurityProperties.User`] +for the properties of the user). +* Form-based login or HTTP Basic security (depending on the `Accept` header in the request) for +the entire application (including actuator endpoints if actuator is on the classpath). +* A `DefaultAuthenticationEventPublisher` for publishing authentication events. + +You can provide a different `AuthenticationEventPublisher` by adding a bean for it. + + + +[[boot-features-security-mvc]] +=== MVC Security +The default security configuration is implemented in `SecurityAutoConfiguration` and +`UserDetailsServiceAutoConfiguration`. `SecurityAutoConfiguration` imports +`SpringBootWebSecurityConfiguration` for web security and +`UserDetailsServiceAutoConfiguration` configures authentication, which is also +relevant in non-web applications. To switch off the default web application security +configuration completely, you can add a bean of type `WebSecurityConfigurerAdapter` (doing +so does not disable the `UserDetailsService` configuration or Actuator's security). + +To also switch off the `UserDetailsService` configuration, you can add a bean of type +`UserDetailsService`, `AuthenticationProvider`, or `AuthenticationManager`. + +Access rules can be overridden by adding a custom `WebSecurityConfigurerAdapter`. Spring +Boot provides convenience methods that can be used to override access rules for actuator +endpoints and static resources. `EndpointRequest` can be used to create a `RequestMatcher` +that is based on the `management.endpoints.web.base-path` property. +`PathRequest` can be used to create a `RequestMatcher` for resources in +commonly used locations. + + + +[[boot-features-security-webflux]] +=== WebFlux Security +Similar to Spring MVC applications, you can secure your WebFlux applications by adding +the `spring-boot-starter-security` dependency. The default security configuration is +implemented in `ReactiveSecurityAutoConfiguration` and +`UserDetailsServiceAutoConfiguration`. `ReactiveSecurityAutoConfiguration` imports +`WebFluxSecurityConfiguration` for web security and `UserDetailsServiceAutoConfiguration` +configures authentication, which is also relevant in non-web applications. To switch off the default web application security +configuration completely, you can add a bean of type `WebFilterChainProxy` (doing so does +not disable the `UserDetailsService` configuration or Actuator's security). + +To also switch off the `UserDetailsService` configuration, you can add a bean of type +`ReactiveUserDetailsService` or `ReactiveAuthenticationManager`. + +Access rules can be configured by adding a custom `SecurityWebFilterChain`. Spring +Boot provides convenience methods that can be used to override access rules for actuator +endpoints and static resources. `EndpointRequest` can be used to create a +`ServerWebExchangeMatcher` that is based on the `management.endpoints.web.base-path` +property. + +`PathRequest` can be used to create a `ServerWebExchangeMatcher` for resources in +commonly used locations. + +For example, you can customize your security configuration by adding something like: + +[source,java,indent=0] +---- +include::{code-examples}/web/security/CustomWebFluxSecurityExample.java[tag=configuration] +---- + + + +[[boot-features-security-oauth2]] +=== OAuth2 +https://oauth.net/2/[OAuth2] is a widely used authorization framework that is supported by +Spring. + + + +[[boot-features-security-oauth2-client]] +==== Client +If you have `spring-security-oauth2-client` on your classpath, you can take advantage of +some auto-configuration to make it easy to set up an OAuth2/Open ID Connect clients. This configuration +makes use of the properties under `OAuth2ClientProperties`. The same properties are applicable to both servlet and reactive applications. + +You can register multiple OAuth2 clients and providers under the +`spring.security.oauth2.client` prefix, as shown in the following example: + +[source,properties,indent=0] +---- + spring.security.oauth2.client.registration.my-client-1.client-id=abcd + spring.security.oauth2.client.registration.my-client-1.client-secret=password + spring.security.oauth2.client.registration.my-client-1.client-name=Client for user scope + spring.security.oauth2.client.registration.my-client-1.provider=my-oauth-provider + spring.security.oauth2.client.registration.my-client-1.scope=user + spring.security.oauth2.client.registration.my-client-1.redirect-uri-template=https://my-redirect-uri.com + spring.security.oauth2.client.registration.my-client-1.client-authentication-method=basic + spring.security.oauth2.client.registration.my-client-1.authorization-grant-type=authorization_code + + spring.security.oauth2.client.registration.my-client-2.client-id=abcd + spring.security.oauth2.client.registration.my-client-2.client-secret=password + spring.security.oauth2.client.registration.my-client-2.client-name=Client for email scope + spring.security.oauth2.client.registration.my-client-2.provider=my-oauth-provider + spring.security.oauth2.client.registration.my-client-2.scope=email + spring.security.oauth2.client.registration.my-client-2.redirect-uri-template=https://my-redirect-uri.com + spring.security.oauth2.client.registration.my-client-2.client-authentication-method=basic + spring.security.oauth2.client.registration.my-client-2.authorization-grant-type=authorization_code + + spring.security.oauth2.client.provider.my-oauth-provider.authorization-uri=https://my-auth-server/oauth/authorize + spring.security.oauth2.client.provider.my-oauth-provider.token-uri=https://my-auth-server/oauth/token + spring.security.oauth2.client.provider.my-oauth-provider.user-info-uri=https://my-auth-server/userinfo + spring.security.oauth2.client.provider.my-oauth-provider.user-info-authentication-method=header + spring.security.oauth2.client.provider.my-oauth-provider.jwk-set-uri=https://my-auth-server/token_keys + spring.security.oauth2.client.provider.my-oauth-provider.user-name-attribute=name +---- + +For OpenID Connect providers that support https://openid.net/specs/openid-connect-discovery-1_0.html[OpenID Connect discovery], +the configuration can be further simplified. The provider needs to be configured with an `issuer-uri` which is the +URI that the it asserts as its Issuer Identifier. For example, if the +`issuer-uri` provided is "https://example.com", then an `OpenID Provider Configuration Request` +will be made to "https://example.com/.well-known/openid-configuration". The result is expected +to be an `OpenID Provider Configuration Response`. The following example shows how an OpenID Connect +Provider can be configured with the `issuer-uri`: + +[source,properties,indent=0] +---- + spring.security.oauth2.client.provider.oidc-provider.issuer-uri=https://dev-123456.oktapreview.com/oauth2/default/ +---- + + + +By default, Spring Security's `OAuth2LoginAuthenticationFilter` only processes URLs +matching `/login/oauth2/code/*`. If you want to customize the `redirect-uri` to +use a different pattern, you need to provide configuration to process that custom pattern. +For example, for servlet applications, you can add your own `WebSecurityConfigurerAdapter` that resembles the +following: + +[source,java,indent=0] +---- +public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .authorizeRequests() + .anyRequest().authenticated() + .and() + .oauth2Login() + .redirectionEndpoint() + .baseUri("/custom-callback"); + } +} +---- + + + +[[boot-features-security-oauth2-common-providers]] +===== OAuth2 client registration for common providers +For common OAuth2 and OpenID providers, including Google, Github, Facebook, and Okta, +we provide a set of provider defaults (`google`, `github`, `facebook`, and `okta`, +respectively). + +If you do not need to customize these providers, you can set the `provider` attribute to +the one for which you need to infer defaults. Also, if the key for the client registration matches a +default supported provider, Spring Boot infers that as well. + +In other words, the two configurations in the following example use the Google provider: + +[source,properties,indent=0] +---- + spring.security.oauth2.client.registration.my-client.client-id=abcd + spring.security.oauth2.client.registration.my-client.client-secret=password + spring.security.oauth2.client.registration.my-client.provider=google + + spring.security.oauth2.client.registration.google.client-id=abcd + spring.security.oauth2.client.registration.google.client-secret=password +---- + + + +[[boot-features-security-oauth2-server]] +==== Resource Server +If you have `spring-security-oauth2-resource-server` on your classpath, Spring Boot can +set up an OAuth2 Resource Server. For JWT configuration, a JWK Set URI or OIDC Issuer URI +needs to be specified, as shown in the following examples: + +[source,properties,indent=0] +---- + spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://example.com/oauth2/default/v1/keys +---- + +[source,properties,indent=0] +---- + spring.security.oauth2.resourceserver.jwt.issuer-uri=https://dev-123456.oktapreview.com/oauth2/default/ +---- + +NOTE: If the authorization server does not support a JWK Set URI, you can configure the +resource server with the Public Key used for verifying the signature of the JWT. This can +be done using the `spring.security.oauth2.resourceserver.jwt.public-key-location` property, +where the value needs to point to a file containing the public key in the PEM-encoded x509 +format. + +The same properties are applicable for both servlet and reactive applications. + +Alternatively, you can define your own `JwtDecoder` bean for servlet applications +or a `ReactiveJwtDecoder` for reactive applications. + +In cases where opaque tokens are used instead of JWTs, you can configure the following properties +to validate tokens via introspection: + +[source,properties,indent=0] +---- + spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://example.com/check-token + spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id + spring.security.oauth2.resourceserver.opaquetoken.client-secret-my-client-secret +---- + +Again, the same properties are applicable for both servlet and reactive applications. + +Alternatively, you can define your own `OAuth2TokenIntrospectionClient` bean for servlet applications +or a `ReactiveOAuth2TokenIntrospectionClient` for reactive applications. + +==== Authorization Server +Currently, Spring Security does not provide support for implementing an OAuth 2.0 +Authorization Server. However, this functionality is available from +the https://projects.spring.io/spring-security-oauth/[Spring Security OAuth] project, +which will eventually be superseded by Spring Security completely. Until then, you can +use the `spring-security-oauth2-autoconfigure` module to easily set up an OAuth 2.0 authorization server; +see its https://docs.spring.io/spring-security-oauth2-boot[documentation] for instructions. + + + +[[boot-features-security-actuator]] +=== Actuator Security +For security purposes, all actuators other than `/health` and `/info` are disabled by +default. The `management.endpoints.web.exposure.include` property can be used to enable +the actuators. + +If Spring Security is on the classpath and no other WebSecurityConfigurerAdapter is +present, all actuators other than `/health` and `/info` are secured by Spring Boot +auto-configuration. If you define a custom `WebSecurityConfigurerAdapter`, Spring Boot +auto-configuration will back off and you will be in full control of actuator access rules. + +NOTE: Before setting the `management.endpoints.web.exposure.include`, ensure that the +exposed actuators do not contain sensitive information and/or are secured by placing them +behind a firewall or by something like Spring Security. + + + +[[boot-features-security-csrf]] +==== Cross Site Request Forgery Protection +Since Spring Boot relies on Spring Security's defaults, CSRF protection is turned on by +default. This means that the actuator endpoints that require a `POST` (shutdown and +loggers endpoints), `PUT` or `DELETE` will get a 403 forbidden error when the default +security configuration is in use. + +NOTE: We recommend disabling CSRF protection completely only if you are creating a service +that is used by non-browser clients. + +Additional information about CSRF protection can be found in the +{spring-security-reference}#csrf[Spring Security Reference Guide]. + + + +[[boot-features-sql]] +== Working with SQL Databases +The {spring-framework}[Spring Framework] provides extensive support for working with SQL +databases, from direct JDBC access using `JdbcTemplate` to complete "`object relational +mapping`" technologies such as Hibernate. {spring-data}[Spring Data] provides an +additional level of functionality: creating `Repository` implementations directly from +interfaces and using conventions to generate queries from your method names. + + + +[[boot-features-configure-datasource]] +=== Configure a DataSource +Java's `javax.sql.DataSource` interface provides a standard method of working with +database connections. Traditionally, a 'DataSource' uses a `URL` along with some +credentials to establish a database connection. + +TIP: See <> for more +advanced examples, typically to take full control over the configuration of the +DataSource. + + + +[[boot-features-embedded-database-support]] +==== Embedded Database Support +It is often convenient to develop applications by using an in-memory embedded database. +Obviously, in-memory databases do not provide persistent storage. You need to populate +your database when your application starts and be prepared to throw away data when your +application ends. + +TIP: The "`How-to`" section includes a <>. + +Spring Boot can auto-configure embedded https://www.h2database.com[H2], +http://hsqldb.org/[HSQL], and https://db.apache.org/derby/[Derby] databases. You need not +provide any connection URLs. You need only include a build dependency to the embedded +database that you want to use. + +[NOTE] +==== +If you are using this feature in your tests, you may notice that the same database is +reused by your whole test suite regardless of the number of application contexts that you +use. If you want to make sure that each context has a separate embedded database, you +should set `spring.datasource.generate-unique-name` to `true`. +==== + +For example, the typical POM dependencies would be as follows: + +[source,xml,indent=0] +---- + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.hsqldb + hsqldb + runtime + +---- + +NOTE: You need a dependency on `spring-jdbc` for an embedded database to be +auto-configured. In this example, it is pulled in transitively through +`spring-boot-starter-data-jpa`. + +TIP: If, for whatever reason, you do configure the connection URL for an embedded +database, take care to ensure that the database's automatic shutdown is disabled. If you +use H2, you should use `DB_CLOSE_ON_EXIT=FALSE` to do so. If you use HSQLDB, you should +ensure that `shutdown=true` is not used. Disabling the database's automatic shutdown lets +Spring Boot control when the database is closed, thereby ensuring that it happens once +access to the database is no longer needed. + + + +[[boot-features-connect-to-production-database]] +==== Connection to a Production Database +Production database connections can also be auto-configured by using a pooling +`DataSource`. Spring Boot uses the following algorithm for choosing a specific +implementation: + +. We prefer https://github.com/brettwooldridge/HikariCP[HikariCP] for its performance and +concurrency. If HikariCP is available, we always choose it. +. Otherwise, if the Tomcat pooling `DataSource` is available, we use it. +. If neither HikariCP nor the Tomcat pooling datasource are available and if +https://commons.apache.org/proper/commons-dbcp/[Commons DBCP2] is available, we use it. + +If you use the `spring-boot-starter-jdbc` or `spring-boot-starter-data-jpa` "`starters`", +you automatically get a dependency to `HikariCP`. + +NOTE: You can bypass that algorithm completely and specify the connection pool to use by +setting the `spring.datasource.type` property. This is especially important if you run +your application in a Tomcat container, as `tomcat-jdbc` is provided by default. + +TIP: Additional connection pools can always be configured manually. If you define your +own `DataSource` bean, auto-configuration does not occur. + +DataSource configuration is controlled by external configuration properties in +`+spring.datasource.*+`. For example, you might declare the following section in +`application.properties`: + +[source,properties,indent=0] +---- + spring.datasource.url=jdbc:mysql://localhost/test + spring.datasource.username=dbuser + spring.datasource.password=dbpass + spring.datasource.driver-class-name=com.mysql.jdbc.Driver +---- + +NOTE: You should at least specify the URL by setting the `spring.datasource.url` +property. Otherwise, Spring Boot tries to auto-configure an embedded database. + +TIP: You often do not need to specify the `driver-class-name`, since Spring Boot can +deduce it for most databases from the `url`. + +NOTE: For a pooling `DataSource` to be created, we need to be able to verify that a valid +`Driver` class is available, so we check for that before doing anything. In other words, +if you set `spring.datasource.driver-class-name=com.mysql.jdbc.Driver`, then that class +has to be loadable. + +See +{sc-spring-boot-autoconfigure}/jdbc/DataSourceProperties.{sc-ext}[`DataSourceProperties`] +for more of the supported options. These are the standard options that work regardless of +the actual implementation. It is also possible to fine-tune implementation-specific +settings by using their respective prefix (`+spring.datasource.hikari.*+`, +`+spring.datasource.tomcat.*+`, and `+spring.datasource.dbcp2.*+`). Refer to the +documentation of the connection pool implementation you are using for more details. + +For instance, if you use the +https://tomcat.apache.org/tomcat-8.0-doc/jdbc-pool.html#Common_Attributes[Tomcat +connection pool], you could customize many additional settings, as shown in the following +example: + + +[source,properties,indent=0] +---- + # Number of ms to wait before throwing an exception if no connection is available. + spring.datasource.tomcat.max-wait=10000 + + # Maximum number of active connections that can be allocated from this pool at the same time. + spring.datasource.tomcat.max-active=50 + + # Validate the connection before borrowing it from the pool. + spring.datasource.tomcat.test-on-borrow=true +---- + + + +[[boot-features-connecting-to-a-jndi-datasource]] +==== Connection to a JNDI DataSource +If you deploy your Spring Boot application to an Application Server, you might want to +configure and manage your DataSource by using your Application Server's built-in features +and access it by using JNDI. + +The `spring.datasource.jndi-name` property can be used as an alternative to the +`spring.datasource.url`, `spring.datasource.username`, and `spring.datasource.password` +properties to access the `DataSource` from a specific JNDI location. For example, the +following section in `application.properties` shows how you can access a JBoss AS defined +`DataSource`: + +[source,properties,indent=0] +---- + spring.datasource.jndi-name=java:jboss/datasources/customers +---- + + + +[[boot-features-using-jdbc-template]] +=== Using JdbcTemplate +Spring's `JdbcTemplate` and `NamedParameterJdbcTemplate` classes are auto-configured, and +you can `@Autowire` them directly into your own beans, as shown in the following example: + +[source,java,indent=0] +---- + import org.springframework.beans.factory.annotation.Autowired; + import org.springframework.jdbc.core.JdbcTemplate; + import org.springframework.stereotype.Component; + + @Component + public class MyBean { + + private final JdbcTemplate jdbcTemplate; + + @Autowired + public MyBean(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } + + // ... + + } +---- + +You can customize some properties of the template by using the `spring.jdbc.template.*` +properties, as shown in the following example: + +[source,properties,indent=0] +---- + spring.jdbc.template.max-rows=500 +---- + +NOTE: The `NamedParameterJdbcTemplate` reuses the same `JdbcTemplate` instance behind the +scenes. If more than one `JdbcTemplate` is defined and no primary candidate exists, the +`NamedParameterJdbcTemplate` is not auto-configured. + + + +[[boot-features-jpa-and-spring-data]] +=== JPA and Spring Data JPA +The Java Persistence API is a standard technology that lets you "`map`" objects to +relational databases. The `spring-boot-starter-data-jpa` POM provides a quick way to get +started. It provides the following key dependencies: + +* Hibernate: One of the most popular JPA implementations. +* Spring Data JPA: Makes it easy to implement JPA-based repositories. +* Spring ORMs: Core ORM support from the Spring Framework. + +TIP: We do not go into too many details of JPA or {spring-data}[Spring Data] here. You can +follow the https://spring.io/guides/gs/accessing-data-jpa/["`Accessing Data with JPA`"] +guide from https://spring.io and read the {spring-data-jpa}[Spring Data JPA] and +https://hibernate.org/orm/documentation/[Hibernate] reference documentation. + + + +[[boot-features-entity-classes]] +==== Entity Classes +Traditionally, JPA "`Entity`" classes are specified in a `persistence.xml` file. With +Spring Boot, this file is not necessary and "`Entity Scanning`" is used instead. By +default, all packages below your main configuration class (the one annotated with +`@EnableAutoConfiguration` or `@SpringBootApplication`) are searched. + +Any classes annotated with `@Entity`, `@Embeddable`, or `@MappedSuperclass` are +considered. A typical entity class resembles the following example: + +[source,java,indent=0] +---- + package com.example.myapp.domain; + + import java.io.Serializable; + import javax.persistence.*; + + @Entity + public class City implements Serializable { + + @Id + @GeneratedValue + private Long id; + + @Column(nullable = false) + private String name; + + @Column(nullable = false) + private String state; + + // ... additional members, often include @OneToMany mappings + + protected City() { + // no-args constructor required by JPA spec + // this one is protected since it shouldn't be used directly + } + + public City(String name, String state) { + this.name = name; + this.state = state; + } + + public String getName() { + return this.name; + } + + public String getState() { + return this.state; + } + + // ... etc + + } +---- + +TIP: You can customize entity scanning locations by using the `@EntityScan` annotation. +See the "`<>`" +how-to. + + + +[[boot-features-spring-data-jpa-repositories]] +==== Spring Data JPA Repositories +{spring-data-jpa}[Spring Data JPA] repositories are interfaces that you can define to +access data. JPA queries are created automatically from your method names. For example, a +`CityRepository` interface might declare a `findAllByState(String state)` method to find +all the cities in a given state. + +For more complex queries, you can annotate your method with Spring Data's +{spring-data-javadoc}/repository/Query.html[`Query`] annotation. + +Spring Data repositories usually extend from the +{spring-data-commons-javadoc}/repository/Repository.html[`Repository`] or +{spring-data-commons-javadoc}/repository/CrudRepository.html[`CrudRepository`] +interfaces. If you use auto-configuration, repositories are searched from the package +containing your main configuration class (the one annotated with +`@EnableAutoConfiguration` or `@SpringBootApplication`) down. + +The following example shows a typical Spring Data repository interface definition: + +[source,java,indent=0] +---- + package com.example.myapp.domain; + + import org.springframework.data.domain.*; + import org.springframework.data.repository.*; + + public interface CityRepository extends Repository { + + Page findAll(Pageable pageable); + + City findByNameAndStateAllIgnoringCase(String name, String state); + + } +---- + +Spring Data JPA repositories support three different modes of bootstrapping: default, +deferred, and lazy. To enable deferred or lazy bootstrapping, set the +`spring.data.jpa.repositories.bootstrap-mode` to `deferred` or `lazy` respectively. When +using deferred or lazy bootstrapping, the auto-configured `EntityManagerFactoryBuilder` +will use the context's `AsyncTaskExecutor`, if any, as the bootstrap executor. If more +than one exists, the one named `applicationTaskExecutor` will be used. + +TIP: We have barely scratched the surface of Spring Data JPA. For complete details, see +the https://docs.spring.io/spring-data/jpa/docs/current/reference/html/[Spring Data JPA +reference documentation]. + + + +[[boot-features-creating-and-dropping-jpa-databases]] +==== Creating and Dropping JPA Databases +By default, JPA databases are automatically created *only* if you use an embedded +database (H2, HSQL, or Derby). You can explicitly configure JPA settings by using +`+spring.jpa.*+` properties. For example, to create and drop tables you can add the +following line to your `application.properties`: + +[indent=0] +---- + spring.jpa.hibernate.ddl-auto=create-drop +---- + +NOTE: Hibernate's own internal property name for this (if you happen to remember it +better) is `hibernate.hbm2ddl.auto`. You can set it, along with other Hibernate native +properties, by using `+spring.jpa.properties.*+` (the prefix is stripped before adding +them to the entity manager). The following line shows an example of setting JPA +properties for Hibernate: + +[indent=0] +---- + spring.jpa.properties.hibernate.globally_quoted_identifiers=true +---- + +The line in the preceding example passes a value of `true` for the +`hibernate.globally_quoted_identifiers` property to the Hibernate entity manager. + +By default, the DDL execution (or validation) is deferred until the `ApplicationContext` +has started. There is also a `spring.jpa.generate-ddl` flag, but it is not used if +Hibernate auto-configuration is active, because the `ddl-auto` settings are more +fine-grained. + + + +[[boot-features-jpa-in-web-environment]] +==== Open EntityManager in View +If you are running a web application, Spring Boot by default registers +{spring-javadoc}/orm/jpa/support/OpenEntityManagerInViewInterceptor.{dc-ext}[`OpenEntityManagerInViewInterceptor`] +to apply the "`Open EntityManager in View`" pattern, to allow for lazy loading in web +views. If you do not want this behavior, you should set `spring.jpa.open-in-view` to +`false` in your `application.properties`. + + + +[[boot-features-data-jdbc]] +=== Spring Data JDBC +Spring Data includes repository support for JDBC and will automatically generate SQL for +the methods on `CrudRepository`. For more advanced queries, a `@Query` annotation is +provided. + +Spring Boot will auto-configure Spring Data's JDBC repositories when the necessary +dependencies are on the classpath. They can be added to your project with a single +dependency on `spring-boot-starter-data-jdbc`. If necessary, you can take control of +Spring Data JDBC's configuration by adding the `@EnableJdbcRepositories` annotation or a +`JdbcConfiguration` subclass to your application. + +TIP: For complete details of Spring Data JDBC, please refer to the +https://projects.spring.io/spring-data-jdbc/[reference documentation]. + + + +[[boot-features-sql-h2-console]] +=== Using H2's Web Console +The https://www.h2database.com[H2 database] provides a +https://www.h2database.com/html/quickstart.html#h2_console[browser-based console] that +Spring Boot can auto-configure for you. The console is auto-configured when the following +conditions are met: + +* You are developing a servlet-based web application. +* `com.h2database:h2` is on the classpath. +* You are using <>. + +TIP: If you are not using Spring Boot's developer tools but would still like to make use +of H2's console, you can configure the `spring.h2.console.enabled` property with a value +of `true`. + +NOTE: The H2 console is only intended for use during development, so you should take +care to ensure that `spring.h2.console.enabled` is not set to `true` in production. + + + +[[boot-features-sql-h2-console-custom-path]] +==== Changing the H2 Console's Path +By default, the console is available at `/h2-console`. You can customize the console's +path by using the `spring.h2.console.path` property. + + + +[[boot-features-jooq]] +=== Using jOOQ +jOOQ Object Oriented Querying (https://www.jooq.org/[jOOQ]) is a popular product from +https://www.datageekery.com/[Data Geekery] which generates Java code from your +database and lets you build type-safe SQL queries through its fluent API. Both the +commercial and open source editions can be used with Spring Boot. + + + +==== Code Generation +In order to use jOOQ type-safe queries, you need to generate Java classes from your +database schema. You can follow the instructions in the +{jooq-manual}/#jooq-in-7-steps-step3[jOOQ user manual]. If you use the +`jooq-codegen-maven` plugin and you also use the `spring-boot-starter-parent` +"`parent POM`", you can safely omit the plugin's `` tag. You can also use Spring +Boot-defined version variables (such as `h2.version`) to declare the plugin's database +dependency. The following listing shows an example: + +[source,xml,indent=0] +---- + + org.jooq + jooq-codegen-maven + + ... + + + + com.h2database + h2 + ${h2.version} + + + + + org.h2.Driver + jdbc:h2:~/yourdatabase + + + ... + + + +---- + + + +==== Using DSLContext +The fluent API offered by jOOQ is initiated through the `org.jooq.DSLContext` interface. +Spring Boot auto-configures a `DSLContext` as a Spring Bean and connects it to your +application `DataSource`. To use the `DSLContext`, you can `@Autowire` it, as shown in +the following example: + +[source,java,indent=0] +---- + @Component + public class JooqExample implements CommandLineRunner { + + private final DSLContext create; + + @Autowired + public JooqExample(DSLContext dslContext) { + this.create = dslContext; + } + + } +---- + +TIP: The jOOQ manual tends to use a variable named `create` to hold the `DSLContext`. + +You can then use the `DSLContext` to construct your queries, as shown in the following +example: + +[source,java,indent=0] +---- + public List authorsBornAfter1980() { + return this.create.selectFrom(AUTHOR) + .where(AUTHOR.DATE_OF_BIRTH.greaterThan(new GregorianCalendar(1980, 0, 1))) + .fetch(AUTHOR.DATE_OF_BIRTH); + } +---- + + + +==== jOOQ SQL Dialect +Unless the `spring.jooq.sql-dialect` property has been configured, Spring Boot determines +the SQL dialect to use for your datasource. If Spring Boot could not detect the dialect, +it uses `DEFAULT`. + +NOTE: Spring Boot can only auto-configure dialects supported by the open source version +of jOOQ. + + + +==== Customizing jOOQ +More advanced customizations can be achieved by defining your own `@Bean` definitions, +which is used when the jOOQ `Configuration` is created. You can define beans for the +following jOOQ Types: + +* `ConnectionProvider` +* `ExecutorProvider` +* `TransactionProvider` +* `RecordMapperProvider` +* `RecordUnmapperProvider` +* `RecordListenerProvider` +* `ExecuteListenerProvider` +* `VisitListenerProvider` +* `TransactionListenerProvider` + +You can also create your own `org.jooq.Configuration` `@Bean` if you want to take +complete control of the jOOQ configuration. + + + +[[boot-features-nosql]] +== Working with NoSQL Technologies +Spring Data provides additional projects that help you access a variety of NoSQL +technologies, including: +https://projects.spring.io/spring-data-mongodb/[MongoDB], +https://projects.spring.io/spring-data-neo4j/[Neo4J], +https://github.com/spring-projects/spring-data-elasticsearch/[Elasticsearch], +https://projects.spring.io/spring-data-solr/[Solr], +https://projects.spring.io/spring-data-redis/[Redis], +https://projects.spring.io/spring-data-gemfire/[Gemfire], +https://projects.spring.io/spring-data-cassandra/[Cassandra], +https://projects.spring.io/spring-data-couchbase/[Couchbase] and +https://projects.spring.io/spring-data-ldap/[LDAP]. +Spring Boot provides auto-configuration for Redis, MongoDB, Neo4j, Elasticsearch, Solr +Cassandra, Couchbase, and LDAP. You can make use of the other projects, but you must +configure them yourself. Refer to the appropriate reference documentation at +https://projects.spring.io/spring-data[projects.spring.io/spring-data]. + + + +[[boot-features-redis]] +=== Redis +https://redis.io/[Redis] is a cache, message broker, and richly-featured key-value store. +Spring Boot offers basic auto-configuration for the +https://github.com/lettuce-io/lettuce-core/[Lettuce] and +https://github.com/xetorthio/jedis/[Jedis] client libraries and the abstractions on top +of them provided by https://github.com/spring-projects/spring-data-redis[Spring Data +Redis]. + +There is a `spring-boot-starter-data-redis` "`Starter`" for collecting the dependencies +in a convenient way. By default, it uses +https://github.com/lettuce-io/lettuce-core/[Lettuce]. That starter handles both +traditional and reactive applications. + +TIP: we also provide a `spring-boot-starter-data-redis-reactive` "`Starter`" for +consistency with the other stores with reactive support. + + + +[[boot-features-connecting-to-redis]] +==== Connecting to Redis +You can inject an auto-configured `RedisConnectionFactory`, `StringRedisTemplate`, or +vanilla `RedisTemplate` instance as you would any other Spring Bean. By default, the +instance tries to connect to a Redis server at `localhost:6379`. The following listing +shows an example of such a bean: + +[source,java,indent=0] +---- + @Component + public class MyBean { + + private StringRedisTemplate template; + + @Autowired + public MyBean(StringRedisTemplate template) { + this.template = template; + } + + // ... + + } +---- + +TIP: You can also register an arbitrary number of beans that implement +`LettuceClientConfigurationBuilderCustomizer` for more advanced customizations. If you +use Jedis, `JedisClientConfigurationBuilderCustomizer` is also available. + +If you add your own `@Bean` of any of the auto-configured types, it replaces the default +(except in the case of `RedisTemplate`, when the exclusion is based on the bean name, +`redisTemplate`, not its type). By default, if `commons-pool2` is on the classpath, you +get a pooled connection factory. + + + +[[boot-features-mongodb]] +=== MongoDB +https://www.mongodb.com/[MongoDB] is an open-source NoSQL document database that uses a +JSON-like schema instead of traditional table-based relational data. Spring Boot offers +several conveniences for working with MongoDB, including the +`spring-boot-starter-data-mongodb` and `spring-boot-starter-data-mongodb-reactive` +"`Starters`". + + + +[[boot-features-connecting-to-mongodb]] +==== Connecting to a MongoDB Database +To access Mongo databases, you can inject an auto-configured +`org.springframework.data.mongodb.MongoDbFactory`. By default, the instance tries to +connect to a MongoDB server at `mongodb://localhost/test` The following example shows how +to connect to a MongoDB database: + +[source,java,indent=0] +---- + import org.springframework.data.mongodb.MongoDbFactory; + import com.mongodb.DB; + + @Component + public class MyBean { + + private final MongoDbFactory mongo; + + @Autowired + public MyBean(MongoDbFactory mongo) { + this.mongo = mongo; + } + + // ... + + public void example() { + DB db = mongo.getDb(); + // ... + } + + } +---- + +You can set the `spring.data.mongodb.uri` property to change the URL and configure +additional settings such as the _replica set_, as shown in the following example: + +[source,properties,indent=0] +---- + spring.data.mongodb.uri=mongodb://user:secret@mongo1.example.com:12345,mongo2.example.com:23456/test +---- + +Alternatively, as long as you use Mongo 2.x, you can specify a `host`/`port`. For +example, you might declare the following settings in your `application.properties`: + +[source,properties,indent=0] +---- + spring.data.mongodb.host=mongoserver + spring.data.mongodb.port=27017 +---- + +If you have defined your own `MongoClient`, it will be used to auto-configure a suitable +`MongoDbFactory`. Both `com.mongodb.MongoClient` and `com.mongodb.client.MongoClient` +are supported. + +NOTE: If you use the Mongo 3.0 Java driver, `spring.data.mongodb.host` and +`spring.data.mongodb.port` are not supported. In such cases, `spring.data.mongodb.uri` +should be used to provide all of the configuration. + +TIP: If `spring.data.mongodb.port` is not specified, the default of `27017` is used. You +could delete this line from the example shown earlier. + +TIP: If you do not use Spring Data Mongo, you can inject `com.mongodb.MongoClient` beans +instead of using `MongoDbFactory`. If you want to take complete control of establishing +the MongoDB connection, you can also declare your own `MongoDbFactory` or `MongoClient` +bean. + +NOTE: If you are using the reactive driver, Netty is required for SSL. The +auto-configuration configures this factory automatically if Netty is available and the +factory to use hasn't been customized already. + +[[boot-features-mongo-template]] +==== MongoTemplate +{spring-data-mongo}[Spring Data MongoDB] provides a +{spring-data-mongo-javadoc}/core/MongoTemplate.html[`MongoTemplate`] class that is very +similar in its design to Spring's `JdbcTemplate`. As with `JdbcTemplate`, Spring Boot +auto-configures a bean for you to inject the template, as follows: + +[source,java,indent=0] +---- + import org.springframework.beans.factory.annotation.Autowired; + import org.springframework.data.mongodb.core.MongoTemplate; + import org.springframework.stereotype.Component; + + @Component + public class MyBean { + + private final MongoTemplate mongoTemplate; + + @Autowired + public MyBean(MongoTemplate mongoTemplate) { + this.mongoTemplate = mongoTemplate; + } + + // ... + + } +---- + +See the +https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/MongoOperations.html[`MongoOperations` +Javadoc] for complete details. + + + +[[boot-features-spring-data-mongo-repositories]] +==== Spring Data MongoDB Repositories +Spring Data includes repository support for MongoDB. As with the JPA repositories +discussed earlier, the basic principle is that queries are constructed automatically, +based on method names. + +In fact, both Spring Data JPA and Spring Data MongoDB share the same common +infrastructure. You could take the JPA example from earlier and, assuming that `City` is +now a Mongo data class rather than a JPA `@Entity`, it works in the same way, as shown +in the following example: + +[source,java,indent=0] +---- + package com.example.myapp.domain; + + import org.springframework.data.domain.*; + import org.springframework.data.repository.*; + + public interface CityRepository extends Repository { + + Page findAll(Pageable pageable); + + City findByNameAndStateAllIgnoringCase(String name, String state); + + } +---- + +TIP: You can customize document scanning locations by using the `@EntityScan` annotation. + +TIP: For complete details of Spring Data MongoDB, including its rich object mapping +technologies, refer to its https://projects.spring.io/spring-data-mongodb/[reference +documentation]. + + + +[[boot-features-mongo-embedded]] +==== Embedded Mongo +Spring Boot offers auto-configuration for +https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo[Embedded Mongo]. To use it in +your Spring Boot application, add a dependency on +`de.flapdoodle.embed:de.flapdoodle.embed.mongo`. + +The port that Mongo listens on can be configured by setting the `spring.data.mongodb.port` +property. To use a randomly allocated free port, use a value of 0. The `MongoClient` +created by `MongoAutoConfiguration` is automatically configured to use the randomly +allocated port. + +NOTE: If you do not configure a custom port, the embedded support uses a random port +(rather than 27017) by default. + +If you have SLF4J on the classpath, the output produced by Mongo is automatically routed +to a logger named `org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongo`. + +You can declare your own `IMongodConfig` and `IRuntimeConfig` beans to take control of +the Mongo instance's configuration and logging routing. The download configuration can be +customized by declaring a `DownloadConfigBuilderCustomizer` bean. + + + +[[boot-features-neo4j]] +=== Neo4j +https://neo4j.com/[Neo4j] is an open-source NoSQL graph database that uses a rich data +model of nodes connected by first class relationships, which is better suited for +connected big data than traditional RDBMS approaches. Spring Boot offers several +conveniences for working with Neo4j, including the `spring-boot-starter-data-neo4j` +"`Starter`". + + + +[[boot-features-connecting-to-neo4j]] +==== Connecting to a Neo4j Database +To access a Neo4j server, you can inject an auto-configured +`org.neo4j.ogm.session.Session`. By default, the instance tries to connect to a Neo4j +server at `localhost:7687` using the Bolt protocol. The following example shows how to +inject a Neo4j `Session`: + +[source,java,indent=0] +---- + @Component + public class MyBean { + + private final Session session; + + @Autowired + public MyBean(Session session) { + this.session = session; + } + + // ... + + } +---- + +You can configure the uri and credentials to use by setting the `spring.data.neo4j.*` +properties, as shown in the following example: + +[source,properties,indent=0] +---- + spring.data.neo4j.uri=bolt://my-server:7687 + spring.data.neo4j.username=neo4j + spring.data.neo4j.password=secret +---- + +You can take full control over the session creation by adding a +`org.neo4j.ogm.config.Configuration` `@Bean`. Also, adding a `@Bean` of type +`SessionFactory` disables the auto-configuration and gives you full control. + + + +[[boot-features-connecting-to-neo4j-embedded]] +==== Using the Embedded Mode +If you add `org.neo4j:neo4j-ogm-embedded-driver` to the dependencies of your application, +Spring Boot automatically configures an in-process embedded instance of Neo4j that does +not persist any data when your application shuts down. + +[NOTE] +==== +As the embedded Neo4j OGM driver does not provide the Neo4j kernel itself, you have +to declare `org.neo4j:neo4j` as dependency yourself. Refer to +https://neo4j.com/docs/ogm-manual/current/reference/#reference:getting-started[the +Neo4j OGM documentation] for a list of compatible versions. +==== + +The embedded driver takes precedence over the other drivers when there are multiple +drivers on the classpath. You can explicitly disable the embedded mode by setting +`spring.data.neo4j.embedded.enabled=false`. + +<> +automatically make use of an embedded Neo4j instance if the embedded driver and Neo4j +kernel are on the classpath as described above. + +[NOTE] +==== +You can enable persistence for the embedded mode by providing a path to a database file +in your configuration, e.g. `spring.data.neo4j.uri=file://var/tmp/graph.db`. +==== + + + +[[boot-features-neo4j-ogm-native-types]] +==== Using Native Types +Neo4j-OGM can map some types, like those in `java.time.*`, to `String`-based properties +or to one of the native types that Neo4j provides. For backwards compatibility reasons +the default for Neo4j-OGM is to use a `String`-based representation. To use native types, +add a dependency on either `org.neo4j:neo4j-ogm-bolt-native-types` or +`org.neo4j:neo4j-ogm-embedded-native-types`, and configure the +`spring.data.neo4j.use-native-types` property as shown in the following example: + +[source,properties,indent=0] +---- + spring.data.neo4j.use-native-types=true +---- + + + +[[boot-features-neo4j-ogm-session]] +==== Neo4jSession +By default, if you are running a web application, the session is bound to the thread for +the entire processing of the request (that is, it uses the "Open Session in View" +pattern). If you do not want this behavior, add the following line to your +`application.properties` file: + +[source,properties,indent=0] +---- + spring.data.neo4j.open-in-view=false +---- + + + +[[boot-features-spring-data-neo4j-repositories]] +==== Spring Data Neo4j Repositories +Spring Data includes repository support for Neo4j. + +Spring Data Neo4j shares the common infrastructure with Spring Data JPA as many other +Spring Data modules do. You could take the JPA example from earlier and define +`City` as Neo4j OGM `@NodeEntity` rather than JPA `@Entity` and the repository +abstraction works in the same way, as shown in the following example: + +[source,java,indent=0] +---- + package com.example.myapp.domain; + + import java.util.Optional; + + import org.springframework.data.neo4j.repository.*; + + public interface CityRepository extends Neo4jRepository { + + Optional findOneByNameAndState(String name, String state); + + } +---- + +The `spring-boot-starter-data-neo4j` "`Starter`" enables the repository support as well +as transaction management. You can customize the locations to look for repositories and +entities by using `@EnableNeo4jRepositories` and `@EntityScan` respectively on a +`@Configuration`-bean. + +TIP: For complete details of Spring Data Neo4j, including its object mapping +technologies, refer to the https://projects.spring.io/spring-data-neo4j/[reference +documentation]. + + + +[[boot-features-gemfire]] +=== Gemfire +https://github.com/spring-projects/spring-data-gemfire[Spring Data Gemfire] provides +convenient Spring-friendly tools for accessing the +https://pivotal.io/big-data/pivotal-gemfire#details[Pivotal Gemfire] data management +platform. There is a `spring-boot-starter-data-gemfire` "`Starter`" for collecting the +dependencies in a convenient way. There is currently no auto-configuration support for +Gemfire, but you can enable Spring Data Repositories with a +https://github.com/spring-projects/spring-data-gemfire/blob/master/src/main/java/org/springframework/data/gemfire/repository/config/EnableGemfireRepositories.java[single annotation: `@EnableGemfireRepositories`]. + + + +[[boot-features-solr]] +=== Solr +https://lucene.apache.org/solr/[Apache Solr] is a search engine. Spring Boot offers basic +auto-configuration for the Solr 5 client library and the abstractions on top of it +provided by https://github.com/spring-projects/spring-data-solr[Spring Data Solr]. There +is a `spring-boot-starter-data-solr` "`Starter`" for collecting the dependencies in a +convenient way. + + +[[boot-features-connecting-to-solr]] +==== Connecting to Solr +You can inject an auto-configured `SolrClient` instance as you would any other Spring +bean. By default, the instance tries to connect to a server at +`http://localhost:8983/solr`. The following example shows how to inject a Solr bean: + +[source,java,indent=0] +---- + @Component + public class MyBean { + + private SolrClient solr; + + @Autowired + public MyBean(SolrClient solr) { + this.solr = solr; + } + + // ... + + } +---- + +If you add your own `@Bean` of type `SolrClient`, it replaces the default. + + + +[[boot-features-spring-data-solr-repositories]] +==== Spring Data Solr Repositories +Spring Data includes repository support for Apache Solr. As with the JPA repositories +discussed earlier, the basic principle is that queries are automatically constructed for \ +you based on method names. + +In fact, both Spring Data JPA and Spring Data Solr share the same common infrastructure. +You could take the JPA example from earlier and, assuming that `City` is now a +`@SolrDocument` class rather than a JPA `@Entity`, it works in the same way. + +TIP: For complete details of Spring Data Solr, refer to the +https://projects.spring.io/spring-data-solr/[reference documentation]. + + + +[[boot-features-elasticsearch]] +=== Elasticsearch +https://www.elastic.co/products/elasticsearch[Elasticsearch] is an open source, +distributed, RESTful search and analytics engine. Spring Boot offers basic +auto-configuration for Elasticsearch. + +Spring Boot supports several clients: + +* The official Java "Low Level" and "High Level" REST clients +* The `ReactiveElasticsearchClient` provided by Spring Data Elasticsearch + +The transport client is still available but its support has been deprecated in +https://github.com/spring-projects/spring-data-elasticsearch[Spring Data Elasticsearch] +and Elasticsearch itself. It will be removed in a future release. +Spring Boot provides a dedicated "`Starter`", `spring-boot-starter-data-elasticsearch`. + +The https://github.com/searchbox-io/Jest[Jest] client has been deprecated as well, since +both Elasticsearch and Spring Data Elasticsearch provide official support for REST clients. + +[[boot-features-connecting-to-elasticsearch-rest]] +==== Connecting to Elasticsearch using REST clients +Elasticsearch ships +https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/index.html[two different REST clients] +that you can use to query a cluster: the "Low Level" client and the "High Level" client. + +If you have the `org.elasticsearch.client:elasticsearch-rest-client` dependency on the +classpath, Spring Boot will auto-configure and register a `RestClient` bean that +by default targets `http://localhost:9200`. +You can further tune how `RestClient` is configured, as shown in the following example: + +[source,properties,indent=0] +---- + spring.elasticsearch.rest.uris=https://search.example.com:9200 + spring.elasticsearch.rest.read-timeout=10s + spring.elasticsearch.rest.username=user + spring.elasticsearch.rest.password=secret +---- + +You can also register an arbitrary number of beans that implement +`RestClientBuilderCustomizer` for more advanced customizations. +To take full control over the registration, define a `RestClient` bean. + +If you have the `org.elasticsearch.client:elasticsearch-rest-high-level-client` dependency +on the classpath, Spring Boot will auto-configure a `RestHighLevelClient`, which wraps +any existing `RestClient` bean, reusing its HTTP configuration. + +[[boot-features-connecting-to-elasticsearch-reactive-rest]] +==== Connecting to Elasticsearch using Reactive REST clients +{spring-data-elasticsearch}[Spring Data Elasticsearch] ships `ReactiveElasticsearchClient` +for querying Elasticsearch instances in a reactive fashion. It is built on top of WebFlux's +`WebClient`, so both `spring-boot-starter-elasticsearch` and `spring-boot-starter-webflux` +dependencies are useful to enable this support. + +By default, Spring Boot will auto-configure and register a `ReactiveElasticsearchClient` +bean that targets `http://localhost:9200`. +You can further tune how it is configured, as shown in the following example: + +[source,properties,indent=0] +---- + spring.elasticsearch.reactive.endpoints=search.example.com:9200 + spring.elasticsearch.reactive.use-ssl=true + spring.elasticsearch.reactive.socket-timeout=10s + spring.elasticsearch.reactive.username=user + spring.elasticsearch.reactive.password=secret +---- + +If the configuration properties are not enough and you'd like to fully control the client +configuration, you can register a custom `ClientConfiguration` bean. + +[[boot-features-connecting-to-elasticsearch-jest]] +==== Connecting to Elasticsearch using Jest +Now that Spring Boot supports the official `RestHighLevelClient`, Jest support is +deprecated. + +If you have `Jest` on the classpath, you can inject an auto-configured `JestClient` that +by default targets `http://localhost:9200`. You can further tune how the client is +configured, as shown in the following example: + +[source,properties,indent=0] +---- + spring.elasticsearch.jest.uris=https://search.example.com:9200 + spring.elasticsearch.jest.read-timeout=10000 + spring.elasticsearch.jest.username=user + spring.elasticsearch.jest.password=secret +---- + +You can also register an arbitrary number of beans that implement +`HttpClientConfigBuilderCustomizer` for more advanced customizations. The following +example tunes additional HTTP settings: + +[source,java,indent=0] +---- +include::{code-examples}/elasticsearch/jest/JestClientCustomizationExample.java[tag=customizer] +---- + +To take full control over the registration, define a `JestClient` bean. + + + +[[boot-features-connecting-to-elasticsearch-spring-data]] +==== Connecting to Elasticsearch by Using Spring Data + +To connect to Elasticsearch, a `RestHighLevelClient` bean must be defined, +auto-configured by Spring Boot or manually provided by the application (see previous sections). +With this configuration in place, an +`ElasticsearchRestTemplate` can be injected like any other Spring bean, +as shown in the following example: + +[source,java,indent=0] +---- + @Component + public class MyBean { + + private final ElasticsearchRestTemplate template; + + public MyBean(ElasticsearchRestTemplate template) { + this.template = template; + } + + // ... + + } +---- + +In the presence of `spring-data-elasticsearch` and the required dependencies +for using a `WebClient` (typically `spring-boot-starter-webflux`), Spring Boot can also +auto-configure a +<> +and a `ReactiveElasticsearchTemplate` as beans. They are the reactive equivalent of the +other REST clients. + + +[[boot-features-spring-data-elasticsearch-repositories]] +==== Spring Data Elasticsearch Repositories +Spring Data includes repository support for Elasticsearch. As with the JPA repositories +discussed earlier, the basic principle is that queries are constructed for you +automatically based on method names. + +In fact, both Spring Data JPA and Spring Data Elasticsearch share the same common +infrastructure. You could take the JPA example from earlier and, assuming that `City` is +now an Elasticsearch `@Document` class rather than a JPA `@Entity`, it works in the same +way. + +TIP: For complete details of Spring Data Elasticsearch, refer to the +{spring-data-elasticsearch-reference}[reference documentation]. + +Spring Boot supports both classic and reactive Elasticsearch repositories, using the +`ElasticsearchRestTemplate` or `ReactiveElasticsearchTemplate` beans. Most likely those +beans are auto-configured by Spring Boot given the required dependencies are present. + +If you wish to use your own template for backing the Elasticsearch repositories, you can +add your own `ElasticsearchRestTemplate` or `ElasticsearchOperations` `@Bean`, +as long as it is named `"elasticsearchTemplate"`. Same applies to +`ReactiveElasticsearchTemplate` and `ReactiveElasticsearchOperations`, with the bean +name `"reactiveElasticsearchTemplate"`. + +You can choose to disable the repositories support with the following property: + +[source,properties,indent=0] +---- + spring.data.elasticsearch.repositories.enabled=false +---- + + +[[boot-features-cassandra]] +=== Cassandra +https://cassandra.apache.org/[Cassandra] is an open source, distributed database +management system designed to handle large amounts of data across many commodity servers. +Spring Boot offers auto-configuration for Cassandra and the abstractions on top of it +provided by https://github.com/spring-projects/spring-data-cassandra[Spring Data +Cassandra]. There is a `spring-boot-starter-data-cassandra` "`Starter`" for collecting +the dependencies in a convenient way. + + + +[[boot-features-connecting-to-cassandra]] +==== Connecting to Cassandra +You can inject an auto-configured `CassandraTemplate` or a Cassandra `Session` instance +as you would with any other Spring Bean. The `spring.data.cassandra.*` properties can be +used to customize the connection. Generally, you provide `keyspace-name` and +`contact-points` properties, as shown in the following example: + +[source,properties,indent=0] +---- + spring.data.cassandra.keyspace-name=mykeyspace + spring.data.cassandra.contact-points=cassandrahost1,cassandrahost2 +---- + +You can also register an arbitrary number of beans that implement +`ClusterBuilderCustomizer` for more advanced customizations. + +The following code listing shows how to inject a Cassandra bean: + +[source,java,indent=0] +---- + @Component + public class MyBean { + + private CassandraTemplate template; + + @Autowired + public MyBean(CassandraTemplate template) { + this.template = template; + } + + // ... + + } +---- + +If you add your own `@Bean` of type `CassandraTemplate`, it replaces the default. + + + +[[boot-features-spring-data-cassandra-repositories]] +==== Spring Data Cassandra Repositories +Spring Data includes basic repository support for Cassandra. Currently, this is more +limited than the JPA repositories discussed earlier and needs to annotate finder methods +with `@Query`. + +TIP: For complete details of Spring Data Cassandra, refer to the +https://docs.spring.io/spring-data/cassandra/docs/[reference documentation]. + + + +[[boot-features-couchbase]] +=== Couchbase +https://www.couchbase.com/[Couchbase] is an open-source, distributed, multi-model NoSQL +document-oriented database that is optimized for interactive applications. Spring Boot +offers auto-configuration for Couchbase and the abstractions on top of it provided by +https://github.com/spring-projects/spring-data-couchbase[Spring Data Couchbase]. There are +`spring-boot-starter-data-couchbase` and `spring-boot-starter-data-couchbase-reactive` +"`Starters`" for collecting the dependencies in a convenient way. + + + +[[boot-features-connecting-to-couchbase]] +==== Connecting to Couchbase +You can get a `Bucket` and `Cluster` by adding the Couchbase SDK and some configuration. +The `spring.couchbase.*` properties can be used to customize the connection. Generally, +you provide the bootstrap hosts, bucket name, and password, as shown in the following +example: + +[source,properties,indent=0] +---- + spring.couchbase.bootstrap-hosts=my-host-1,192.168.1.123 + spring.couchbase.bucket.name=my-bucket + spring.couchbase.bucket.password=secret +---- + +[TIP] +==== +You need to provide _at least_ the bootstrap host(s), in which case the bucket name is +`default` and the password is an empty String. Alternatively, you can define your own +`org.springframework.data.couchbase.config.CouchbaseConfigurer` `@Bean` to take control +over the whole configuration. +==== + +It is also possible to customize some of the `CouchbaseEnvironment` settings. For +instance, the following configuration changes the timeout to use to open a new `Bucket` +and enables SSL support: + +[source,properties,indent=0] +---- + spring.couchbase.env.timeouts.connect=3000 + spring.couchbase.env.ssl.key-store=/location/of/keystore.jks + spring.couchbase.env.ssl.key-store-password=secret +---- + +Check the `spring.couchbase.env.*` properties for more details. + + + +[[boot-features-spring-data-couchbase-repositories]] +==== Spring Data Couchbase Repositories +Spring Data includes repository support for Couchbase. For complete details of Spring +Data Couchbase, refer to the +https://docs.spring.io/spring-data/couchbase/docs/current/reference/html/[reference +documentation]. + +You can inject an auto-configured `CouchbaseTemplate` instance as you would with any +other Spring Bean, provided a _default_ `CouchbaseConfigurer` is available (which +happens when you enable Couchbase support, as explained earlier). + +The following examples shows how to inject a Couchbase bean: + +[source,java,indent=0] +---- + @Component + public class MyBean { + + private final CouchbaseTemplate template; + + @Autowired + public MyBean(CouchbaseTemplate template) { + this.template = template; + } + + // ... + + } +---- + +There are a few beans that you can define in your own configuration to override those +provided by the auto-configuration: + +* A `CouchbaseTemplate` `@Bean` with a name of `couchbaseTemplate`. +* An `IndexManager` `@Bean` with a name of `couchbaseIndexManager`. +* A `CustomConversions` `@Bean` with a name of `couchbaseCustomConversions`. + +To avoid hard-coding those names in your own config, you can reuse `BeanNames` provided +by Spring Data Couchbase. For instance, you can customize the converters to use, as +follows: + +[source,java,indent=0] +---- + @Configuration(proxyBeanMethods = false) + public class SomeConfiguration { + + @Bean(BeanNames.COUCHBASE_CUSTOM_CONVERSIONS) + public CustomConversions myCustomConversions() { + return new CustomConversions(...); + } + + // ... + + } +---- + +TIP: If you want to fully bypass the auto-configuration for Spring Data Couchbase, +provide your own implementation of +`org.springframework.data.couchbase.config.AbstractCouchbaseDataConfiguration`. + + + +[[boot-features-ldap]] +=== LDAP +https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol[LDAP] (Lightweight +Directory Access Protocol) is an open, vendor-neutral, industry standard application +protocol for accessing and maintaining distributed directory information services over an +IP network. Spring Boot offers auto-configuration for any compliant LDAP server as well +as support for the embedded in-memory LDAP server from +https://www.ldap.com/unboundid-ldap-sdk-for-java[UnboundID]. + +LDAP abstractions are provided by +https://github.com/spring-projects/spring-data-ldap[Spring Data LDAP]. +There is a `spring-boot-starter-data-ldap` "`Starter`" for collecting the dependencies in +a convenient way. + + + +[[boot-features-ldap-connecting]] +==== Connecting to an LDAP Server +To connect to an LDAP server, make sure you declare a dependency on the +`spring-boot-starter-data-ldap` "`Starter`" or `spring-ldap-core` and then declare the +URLs of your server in your application.properties, as shown in the following example: + +[source,properties,indent=0] +---- + spring.ldap.urls=ldap://myserver:1235 + spring.ldap.username=admin + spring.ldap.password=secret +---- + +If you need to customize connection settings, you can use the `spring.ldap.base` and +`spring.ldap.base-environment` properties. + +An `LdapContextSource` is auto-configured based on these settings. If you need to customize +it, for instance to use a `PooledContextSource`, you can still inject the auto-configured +`LdapContextSource`. Make sure to flag your customized `ContextSource` as `@Primary` so +that the auto-configured `LdapTemplate` uses it. + + + +[[boot-features-ldap-spring-data-repositories]] +==== Spring Data LDAP Repositories +Spring Data includes repository support for LDAP. For complete details of Spring +Data LDAP, refer to the +https://docs.spring.io/spring-data/ldap/docs/1.0.x/reference/html/[reference +documentation]. + +You can also inject an auto-configured `LdapTemplate` instance as you would with any +other Spring Bean, as shown in the following example: + + +[source,java,indent=0] +---- + @Component + public class MyBean { + + private final LdapTemplate template; + + @Autowired + public MyBean(LdapTemplate template) { + this.template = template; + } + + // ... + + } +---- + + + +[[boot-features-ldap-embedded]] +==== Embedded In-memory LDAP Server +For testing purposes, Spring Boot supports auto-configuration of an in-memory LDAP server +from https://www.ldap.com/unboundid-ldap-sdk-for-java[UnboundID]. To configure the server, +add a dependency to `com.unboundid:unboundid-ldapsdk` and declare a `base-dn` property, as +follows: + +[source,properties,indent=0] +---- + spring.ldap.embedded.base-dn=dc=spring,dc=io +---- + +[NOTE] +==== +It is possible to define multiple base-dn values, however, since distinguished names +usually contain commas, they must be defined using the correct notation. + +In yaml files, you can use the yaml list notation: + +[source,yaml,indent=0] +---- + spring.ldap.embedded.base-dn: + - dc=spring,dc=io + - dc=pivotal,dc=io +---- + +In properties files, you must include the index as part of the property name: + +[source,properties,indent=0] +---- + spring.ldap.embedded.base-dn[0]=dc=spring,dc=io + spring.ldap.embedded.base-dn[1]=dc=pivotal,dc=io +---- + +==== + +By default, the server starts on a random port and triggers the regular LDAP support. +There is no need to specify a `spring.ldap.urls` property. + +If there is a `schema.ldif` file on your classpath, it is used to initialize the server. +If you want to load the initialization script from a different resource, you can also use +the `spring.ldap.embedded.ldif` property. + +By default, a standard schema is used to validate `LDIF` files. You can turn off +validation altogether by setting the `spring.ldap.embedded.validation.enabled` property. +If you have custom attributes, you can use `spring.ldap.embedded.validation.schema` to +define your custom attribute types or object classes. + + + +[[boot-features-influxdb]] +=== InfluxDB +https://www.influxdata.com/[InfluxDB] is an open-source time series database optimized +for fast, high-availability storage and retrieval of time series data in fields such as +operations monitoring, application metrics, Internet-of-Things sensor data, and real-time +analytics. + + + +[[boot-features-connecting-to-influxdb]] +==== Connecting to InfluxDB +Spring Boot auto-configures an `InfluxDB` instance, provided the `influxdb-java` client +is on the classpath and the URL of the database is set, as shown in the following +example: + +[source,properties,indent=0] +---- + spring.influx.url=https://172.0.0.1:8086 +---- + +If the connection to InfluxDB requires a user and password, you can set the +`spring.influx.user` and `spring.influx.password` properties accordingly. + +InfluxDB relies on OkHttp. If you need to tune the http client `InfluxDB` uses behind the +scenes, you can register an `InfluxDbOkHttpClientBuilderProvider` bean. + + + +[[boot-features-caching]] +== Caching +The Spring Framework provides support for transparently adding caching to an application. +At its core, the abstraction applies caching to methods, thus reducing the number of +executions based on the information available in the cache. The caching logic is applied +transparently, without any interference to the invoker. Spring Boot auto-configures the +cache infrastructure as long as caching support is enabled via the `@EnableCaching` +annotation. + +NOTE: Check the {spring-reference}integration.html#cache[relevant section] of the Spring +Framework reference for more details. + +In a nutshell, adding caching to an operation of your service is as easy as adding the +relevant annotation to its method, as shown in the following example: + +[source,java,indent=0] +---- + import org.springframework.cache.annotation.Cacheable; + import org.springframework.stereotype.Component; + + @Component + public class MathService { + + @Cacheable("piDecimals") + public int computePiDecimal(int i) { + // ... + } + + } +---- + +This example demonstrates the use of caching on a potentially costly operation. Before +invoking `computePiDecimal`, the abstraction looks for an entry in the `piDecimals` cache +that matches the `i` argument. If an entry is found, the content in the cache is +immediately returned to the caller, and the method is not invoked. Otherwise, the method +is invoked, and the cache is updated before returning the value. + +CAUTION: You can also use the standard JSR-107 (JCache) annotations (such as +`@CacheResult`) transparently. However, we strongly advise you to not mix and match the +Spring Cache and JCache annotations. + +If you do not add any specific cache library, Spring Boot auto-configures a +<> that uses concurrent maps in +memory. When a cache is required (such as `piDecimals` in the preceding example), this +provider creates it for you. The simple provider is not really recommended for +production usage, but it is great for getting started and making sure that you understand +the features. When you have made up your mind about the cache provider to use, please +make sure to read its documentation to figure out how to configure the caches that your +application uses. Nearly all providers require you to explicitly configure every cache +that you use in the application. Some offer a way to customize the default caches defined +by the `spring.cache.cache-names` property. + +TIP: It is also possible to transparently +{spring-reference}integration.html#cache-annotations-put[update] or +{spring-reference}integration.html#cache-annotations-evict[evict] data from the cache. + + + +[[boot-features-caching-provider]] +=== Supported Cache Providers +The cache abstraction does not provide an actual store and relies on abstraction +materialized by the `org.springframework.cache.Cache` and +`org.springframework.cache.CacheManager` interfaces. + +If you have not defined a bean of type `CacheManager` or a `CacheResolver` named +`cacheResolver` (see +{spring-javadoc}/cache/annotation/CachingConfigurer.html[`CachingConfigurer`]), +Spring Boot tries to detect the following providers (in the indicated order): + +. <> +. <> (EhCache 3, Hazelcast, + Infinispan, and others) +. <> +. <> +. <> +. <> +. <> +. <> +. <> + +TIP: It is also possible to _force_ a particular cache provider by setting the +`spring.cache.type` property. Use this property if you need to +<> in certain environment +(such as tests). + +TIP: Use the `spring-boot-starter-cache` "`Starter`" to quickly add basic caching +dependencies. The starter brings in `spring-context-support`. If you add dependencies +manually, you must include `spring-context-support` in order to use the JCache, +EhCache 2.x, or Caffeine support. + +If the `CacheManager` is auto-configured by Spring Boot, you can further tune its +configuration before it is fully initialized by exposing a bean that implements the +`CacheManagerCustomizer` interface. The following example sets a flag to say that null +values should be passed down to the underlying map: + +[source,java,indent=0] +---- + @Bean + public CacheManagerCustomizer cacheManagerCustomizer() { + return new CacheManagerCustomizer() { + @Override + public void customize(ConcurrentMapCacheManager cacheManager) { + cacheManager.setAllowNullValues(false); + } + }; + } +---- + +[NOTE] +==== +In the preceding example, an auto-configured `ConcurrentMapCacheManager` is expected. If +that is not the case (either you provided your own config or a different cache provider +was auto-configured), the customizer is not invoked at all. You can have as many +customizers as you want, and you can also order them by using `@Order` or `Ordered`. +==== + + + +[[boot-features-caching-provider-generic]] +==== Generic +Generic caching is used if the context defines _at least_ one +`org.springframework.cache.Cache` bean. A `CacheManager` wrapping all beans of that type +is created. + + + +[[boot-features-caching-provider-jcache]] +==== JCache (JSR-107) +https://jcp.org/en/jsr/detail?id=107[JCache] is bootstrapped through the presence of a +`javax.cache.spi.CachingProvider` on the classpath (that is, a JSR-107 compliant caching +library exists on the classpath), and the `JCacheCacheManager` is provided by the +`spring-boot-starter-cache` "`Starter`". Various compliant libraries are available, and +Spring Boot provides dependency management for Ehcache 3, Hazelcast, and Infinispan. Any +other compliant library can be added as well. + +It might happen that more than one provider is present, in which case the provider must +be explicitly specified. Even if the JSR-107 standard does not enforce a standardized way +to define the location of the configuration file, Spring Boot does its best to +accommodate setting a cache with implementation details, as shown in the following +example: + +[source,properties,indent=0] +---- + # Only necessary if more than one provider is present + spring.cache.jcache.provider=com.acme.MyCachingProvider + spring.cache.jcache.config=classpath:acme.xml +---- + +NOTE: When a cache library offers both a native implementation and JSR-107 support, +Spring Boot prefers the JSR-107 support, so that the same features are available if you +switch to a different JSR-107 implementation. + +TIP: Spring Boot has <>. If a +single `HazelcastInstance` is available, it is automatically reused for the +`CacheManager` as well, unless the `spring.cache.jcache.config` property is specified. + +There are two ways to customize the underlying `javax.cache.cacheManager`: + +* Caches can be created on startup by setting the `spring.cache.cache-names` property. If +a custom `javax.cache.configuration.Configuration` bean is defined, it is used to +customize them. +* `org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer` beans are +invoked with the reference of the `CacheManager` for full customization. + +TIP: If a standard `javax.cache.CacheManager` bean is defined, it is wrapped +automatically in an `org.springframework.cache.CacheManager` implementation that the +abstraction expects. No further customization is applied to it. + + + +[[boot-features-caching-provider-ehcache2]] +==== EhCache 2.x +https://www.ehcache.org/[EhCache] 2.x is used if a file named `ehcache.xml` can be found at +the root of the classpath. If EhCache 2.x is found, the `EhCacheCacheManager` provided by +the `spring-boot-starter-cache` "`Starter`" is used to bootstrap the cache manager. An +alternate configuration file can be provided as well, as shown in the following example: + +[source,properties,indent=0] +---- + spring.cache.ehcache.config=classpath:config/another-config.xml +---- + + + +[[boot-features-caching-provider-hazelcast]] +==== Hazelcast + +Spring Boot has <>. If a +`HazelcastInstance` has been auto-configured, it is automatically wrapped in a +`CacheManager`. + + + +[[boot-features-caching-provider-infinispan]] +==== Infinispan +https://infinispan.org/[Infinispan] has no default configuration file location, so it must +be specified explicitly. Otherwise, the default bootstrap is used. + +[source,properties,indent=0] +---- + spring.cache.infinispan.config=infinispan.xml +---- + +Caches can be created on startup by setting the `spring.cache.cache-names` property. If a +custom `ConfigurationBuilder` bean is defined, it is used to customize the caches. + +[NOTE] +==== +The support of Infinispan in Spring Boot is restricted to the embedded mode and is quite +basic. If you want more options, you should use the official Infinispan Spring Boot +starter instead. See +https://github.com/infinispan/infinispan-spring-boot[Infinispan's documentation] for more +details. +==== + + +[[boot-features-caching-provider-couchbase]] +==== Couchbase +If the https://www.couchbase.com/[Couchbase] Java client and the `couchbase-spring-cache` +implementation are available and Couchbase is <>, a +`CouchbaseCacheManager` is auto-configured. It is also possible to create additional +caches on startup by setting the `spring.cache.cache-names` property. These caches +operate on the `Bucket` that was auto-configured. You can _also_ create additional caches +on another `Bucket` by using the customizer. Assume you need two caches (`cache1` and +`cache2`) on the "main" `Bucket` and one (`cache3`) cache with a custom time to live of 2 +seconds on the "`another`" `Bucket`. You can create the first two caches through +configuration, as follows: + +[source,properties,indent=0] +---- + spring.cache.cache-names=cache1,cache2 +---- + +Then you can define a `@Configuration` class to configure the extra `Bucket` and the +`cache3` cache, as follows: + + +[source,java,indent=0] +---- + @Configuration(proxyBeanMethods = false) + public class CouchbaseCacheConfiguration { + + private final Cluster cluster; + + public CouchbaseCacheConfiguration(Cluster cluster) { + this.cluster = cluster; + } + + @Bean + public Bucket anotherBucket() { + return this.cluster.openBucket("another", "secret"); + } + + @Bean + public CacheManagerCustomizer cacheManagerCustomizer() { + return c -> { + c.prepareCache("cache3", CacheBuilder.newInstance(anotherBucket()) + .withExpiration(2)); + }; + } + + } +---- + +This sample configuration reuses the `Cluster` that was created through +auto-configuration. + + + +[[boot-features-caching-provider-redis]] +==== Redis +If https://redis.io/[Redis] is available and configured, a `RedisCacheManager` is +auto-configured. It is possible to create additional caches on startup by setting the +`spring.cache.cache-names` property and cache defaults can be configured by using +`spring.cache.redis.*` properties. For instance, the following configuration creates +`cache1` and `cache2` caches with a _time to live_ of 10 minutes: + +[source,properties,indent=0] +---- + spring.cache.cache-names=cache1,cache2 + spring.cache.redis.time-to-live=600000 +---- + +[NOTE] +==== +By default, a key prefix is added so that, if two separate caches use the same +key, Redis does not have overlapping keys and cannot return invalid values. We strongly +recommend keeping this setting enabled if you create your own `RedisCacheManager`. +==== + +TIP: You can take full control of the configuration by adding a `RedisCacheConfiguration` +`@Bean` of your own. This can be useful if you're looking for customizing the +serialization strategy. + + + +[[boot-features-caching-provider-caffeine]] +==== Caffeine +https://github.com/ben-manes/caffeine[Caffeine] is a Java 8 rewrite of Guava's cache that +supersedes support for Guava. If Caffeine is present, a `CaffeineCacheManager` (provided +by the `spring-boot-starter-cache` "`Starter`") is auto-configured. Caches can be created +on startup by setting the `spring.cache.cache-names` property and can be customized by one +of the following (in the indicated order): + +. A cache spec defined by `spring.cache.caffeine.spec` +. A `com.github.benmanes.caffeine.cache.CaffeineSpec` bean is defined +. A `com.github.benmanes.caffeine.cache.Caffeine` bean is defined + +For instance, the following configuration creates `cache1` and `cache2` caches with a +maximum size of 500 and a _time to live_ of 10 minutes + +[source,properties,indent=0] +---- + spring.cache.cache-names=cache1,cache2 + spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s +---- + +If a `com.github.benmanes.caffeine.cache.CacheLoader` bean is defined, it is +automatically associated to the `CaffeineCacheManager`. Since the `CacheLoader` is going +to be associated with _all_ caches managed by the cache manager, it must be defined as +`CacheLoader`. The auto-configuration ignores any other generic type. + + + +[[boot-features-caching-provider-simple]] +==== Simple +If none of the other providers can be found, a simple implementation using a +`ConcurrentHashMap` as the cache store is configured. This is the default if no caching +library is present in your application. By default, caches are created as needed, but you +can restrict the list of available caches by setting the `cache-names` property. For +instance, if you want only `cache1` and `cache2` caches, set the `cache-names` property +as follows: + +[source,properties,indent=0] +---- + spring.cache.cache-names=cache1,cache2 +---- + +If you do so and your application uses a cache not listed, then it fails at runtime when +the cache is needed, but not on startup. This is similar to the way the "real" cache +providers behave if you use an undeclared cache. + + +[[boot-features-caching-provider-none]] +==== None +When `@EnableCaching` is present in your configuration, a suitable cache configuration is +expected as well. If you need to disable caching altogether in certain environments, +force the cache type to `none` to use a no-op implementation, as shown in the following +example: + +[source,properties,indent=0] +---- + spring.cache.type=none +---- + + + +[[boot-features-messaging]] +== Messaging +The Spring Framework provides extensive support for integrating with messaging systems, +from simplified use of the JMS API using `JmsTemplate` to a complete infrastructure to +receive messages asynchronously. Spring AMQP provides a similar feature set for the +Advanced Message Queuing Protocol. Spring Boot also provides auto-configuration +options for `RabbitTemplate` and RabbitMQ. Spring WebSocket natively includes support for +STOMP messaging, and Spring Boot has support for that through starters and a small amount +of auto-configuration. Spring Boot also has support for Apache Kafka. + + + +[[boot-features-jms]] +=== JMS +The `javax.jms.ConnectionFactory` interface provides a standard method of creating a +`javax.jms.Connection` for interacting with a JMS broker. Although Spring needs a +`ConnectionFactory` to work with JMS, you generally need not use it directly yourself and +can instead rely on higher level messaging abstractions. (See the +{spring-reference}integration.html#jms[relevant section] of the Spring Framework +reference documentation for details.) Spring Boot also auto-configures the necessary +infrastructure to send and receive messages. + + + +[[boot-features-activemq]] +==== ActiveMQ Support +When https://activemq.apache.org/[ActiveMQ] is available on the classpath, Spring Boot can +also configure a `ConnectionFactory`. If the broker is present, an embedded broker is +automatically started and configured (provided no broker URL is specified through +configuration). + +NOTE: If you use `spring-boot-starter-activemq`, the necessary dependencies to connect or +embed an ActiveMQ instance are provided, as is the Spring infrastructure to integrate with +JMS. + +ActiveMQ configuration is controlled by external configuration properties in +`+spring.activemq.*+`. For example, you might declare the following section in +`application.properties`: + +[source,properties,indent=0] +---- + spring.activemq.broker-url=tcp://192.168.1.210:9876 + spring.activemq.user=admin + spring.activemq.password=secret +---- + +By default, a `CachingConnectionFactory` wraps the native `ConnectionFactory` with +sensible settings that you can control by external configuration properties in +`+spring.jms.*+`: + +[source,properties,indent=0] +---- + spring.jms.cache.session-cache-size=5 +---- + +If you'd rather use native pooling, you can do so by adding a dependency to +`org.messaginghub:pooled-jms` and configuring the `JmsPoolConnectionFactory` accordingly, +as shown in the following example: + +[source,properties,indent=0] +---- + spring.activemq.pool.enabled=true + spring.activemq.pool.max-connections=50 +---- + +TIP: See +{sc-spring-boot-autoconfigure}/jms/activemq/ActiveMQProperties.{sc-ext}[`ActiveMQProperties`] +for more of the supported options. You can also register an arbitrary number of beans +that implement `ActiveMQConnectionFactoryCustomizer` for more advanced customizations. + +By default, ActiveMQ creates a destination if it does not yet exist so that destinations +are resolved against their provided names. + + + +[[boot-features-artemis]] +==== Artemis Support +Spring Boot can auto-configure a `ConnectionFactory` when it detects that +https://activemq.apache.org/artemis/[Artemis] is available on the classpath. If the broker +is present, an embedded broker is automatically started and configured (unless the mode +property has been explicitly set). The supported modes are `embedded` (to make explicit +that an embedded broker is required and that an error should occur if the broker is not +available on the classpath) and `native` (to connect to a broker using the `netty` +transport protocol). When the latter is configured, Spring Boot configures a +`ConnectionFactory` that connects to a broker running on the local machine with the +default settings. + +NOTE: If you use `spring-boot-starter-artemis`, the necessary dependencies to +connect to an existing Artemis instance are provided, as well as the Spring +infrastructure to integrate with JMS. Adding `org.apache.activemq:artemis-jms-server` to +your application lets you use embedded mode. + +Artemis configuration is controlled by external configuration properties in +`+spring.artemis.*+`. For example, you might declare the following section in +`application.properties`: + +[source,properties,indent=0] +---- + spring.artemis.mode=native + spring.artemis.host=192.168.1.210 + spring.artemis.port=9876 + spring.artemis.user=admin + spring.artemis.password=secret +---- + +When embedding the broker, you can choose if you want to enable persistence and list the +destinations that should be made available. These can be specified as a comma-separated +list to create them with the default options, or you can define bean(s) of type +`org.apache.activemq.artemis.jms.server.config.JMSQueueConfiguration` or +`org.apache.activemq.artemis.jms.server.config.TopicConfiguration`, for advanced queue +and topic configurations, respectively. + +By default, a `CachingConnectionFactory` wraps the native `ConnectionFactory` with +sensible settings that you can control by external configuration properties in +`+spring.jms.*+`: + +[source,properties,indent=0] +---- + spring.jms.cache.session-cache-size=5 +---- + +If you'd rather use native pooling, you can do so by adding a dependency to +`org.messaginghub:pooled-jms` and configuring the `JmsPoolConnectionFactory` accordingly, +as shown in the following example: + +[source,properties,indent=0] +---- + spring.artemis.pool.enabled=true + spring.artemis.pool.max-connections=50 +---- + +See +{sc-spring-boot-autoconfigure}/jms/artemis/ArtemisProperties.{sc-ext}[`ArtemisProperties`] +for more supported options. + +No JNDI lookup is involved, and destinations are resolved against their names, using +either the `name` attribute in the Artemis configuration or the names provided through +configuration. + + + +[[boot-features-jms-jndi]] +==== Using a JNDI ConnectionFactory +If you are running your application in an application server, Spring Boot tries to +locate a JMS `ConnectionFactory` by using JNDI. By default, the `java:/JmsXA` and +`java:/XAConnectionFactory` location are checked. You can use the `spring.jms.jndi-name` +property if you need to specify an alternative location, as shown in the following +example: + +[source,properties,indent=0] +---- + spring.jms.jndi-name=java:/MyConnectionFactory +---- + + + +[[boot-features-using-jms-sending]] +==== Sending a Message +Spring's `JmsTemplate` is auto-configured, and you can autowire it directly into your own +beans, as shown in the following example: + +[source,java,indent=0] +---- + import org.springframework.beans.factory.annotation.Autowired; + import org.springframework.jms.core.JmsTemplate; + import org.springframework.stereotype.Component; + + @Component + public class MyBean { + + private final JmsTemplate jmsTemplate; + + @Autowired + public MyBean(JmsTemplate jmsTemplate) { + this.jmsTemplate = jmsTemplate; + } + + // ... + + } +---- + +NOTE: {spring-javadoc}/jms/core/JmsMessagingTemplate.{dc-ext}[`JmsMessagingTemplate`] can +be injected in a similar manner. If a `DestinationResolver` or a `MessageConverter` bean +is defined, it is associated automatically to the auto-configured `JmsTemplate`. + + +[[boot-features-using-jms-receiving]] +==== Receiving a Message +When the JMS infrastructure is present, any bean can be annotated with `@JmsListener` to +create a listener endpoint. If no `JmsListenerContainerFactory` has been defined, a +default one is configured automatically. If a `DestinationResolver` or a +`MessageConverter` beans is defined, it is associated automatically to the default +factory. + +By default, the default factory is transactional. If you run in an infrastructure where a +`JtaTransactionManager` is present, it is associated to the listener container by default. +If not, the `sessionTransacted` flag is enabled. In that latter scenario, you can +associate your local data store transaction to the processing of an incoming message by +adding `@Transactional` on your listener method (or a delegate thereof). This ensures that +the incoming message is acknowledged, once the local transaction has completed. This also +includes sending response messages that have been performed on the same JMS session. + +The following component creates a listener endpoint on the `someQueue` destination: + +[source,java,indent=0] +---- + @Component + public class MyBean { + + @JmsListener(destination = "someQueue") + public void processMessage(String content) { + // ... + } + + } +---- + +TIP: See {spring-javadoc}/jms/annotation/EnableJms.{dc-ext}[the Javadoc of `@EnableJms`] +for more details. + +If you need to create more `JmsListenerContainerFactory` instances or if you want to +override the default, Spring Boot provides a +`DefaultJmsListenerContainerFactoryConfigurer` that you can use to initialize a +`DefaultJmsListenerContainerFactory` with the same settings as the one that is +auto-configured. + +For instance, the following example exposes another factory that uses a specific +`MessageConverter`: + +[source,java,indent=0] +---- + @Configuration(proxyBeanMethods = false) + static class JmsConfiguration { + + @Bean + public DefaultJmsListenerContainerFactory myFactory( + DefaultJmsListenerContainerFactoryConfigurer configurer) { + DefaultJmsListenerContainerFactory factory = + new DefaultJmsListenerContainerFactory(); + configurer.configure(factory, connectionFactory()); + factory.setMessageConverter(myMessageConverter()); + return factory; + } + + } +---- + +Then you can use the factory in any `@JmsListener`-annotated method as follows: + +[source,java,indent=0] +[subs="verbatim,quotes"] +---- + @Component + public class MyBean { + + @JmsListener(destination = "someQueue", **containerFactory="myFactory"**) + public void processMessage(String content) { + // ... + } + + } +---- + + +[[boot-features-amqp]] +=== AMQP +The Advanced Message Queuing Protocol (AMQP) is a platform-neutral, wire-level protocol +for message-oriented middleware. The Spring AMQP project applies core Spring concepts to +the development of AMQP-based messaging solutions. Spring Boot offers several conveniences +for working with AMQP through RabbitMQ, including the `spring-boot-starter-amqp` +"`Starter`". + + + +[[boot-features-rabbitmq]] +==== RabbitMQ support +https://www.rabbitmq.com/[RabbitMQ] is a lightweight, reliable, scalable, and portable +message broker based on the AMQP protocol. Spring uses `RabbitMQ` to communicate through +the AMQP protocol. + +RabbitMQ configuration is controlled by external configuration properties in +`+spring.rabbitmq.*+`. For example, you might declare the following section in +`application.properties`: + +[source,properties,indent=0] +---- + spring.rabbitmq.host=localhost + spring.rabbitmq.port=5672 + spring.rabbitmq.username=admin + spring.rabbitmq.password=secret +---- + +If a `ConnectionNameStrategy` bean exists in the context, it will be automatically used to +name connections created by the auto-configured `ConnectionFactory`. See +{sc-spring-boot-autoconfigure}/amqp/RabbitProperties.{sc-ext}[`RabbitProperties`] for more +of the supported options. + +TIP: See +https://spring.io/blog/2010/06/14/understanding-amqp-the-protocol-used-by-rabbitmq/[Understanding +AMQP, the protocol used by RabbitMQ] for more details. + + + +[[boot-features-using-amqp-sending]] +==== Sending a Message +Spring's `AmqpTemplate` and `AmqpAdmin` are auto-configured, and you can autowire them +directly into your own beans, as shown in the following example: + +[source,java,indent=0] +---- + import org.springframework.amqp.core.AmqpAdmin; + import org.springframework.amqp.core.AmqpTemplate; + import org.springframework.beans.factory.annotation.Autowired; + import org.springframework.stereotype.Component; + + @Component + public class MyBean { + + private final AmqpAdmin amqpAdmin; + private final AmqpTemplate amqpTemplate; + + @Autowired + public MyBean(AmqpAdmin amqpAdmin, AmqpTemplate amqpTemplate) { + this.amqpAdmin = amqpAdmin; + this.amqpTemplate = amqpTemplate; + } + + // ... + + } +---- + +NOTE: {spring-amqp-javadoc}/rabbit/core/RabbitMessagingTemplate.{dc-ext}[`RabbitMessagingTemplate`] +can be injected in a similar manner. If a `MessageConverter` bean is defined, it is +associated automatically to the auto-configured `AmqpTemplate`. + +If necessary, any `org.springframework.amqp.core.Queue` that is defined as a bean is +automatically used to declare a corresponding queue on the RabbitMQ instance. + +To retry operations, you can enable retries on the `AmqpTemplate` (for example, in the +event that the broker connection is lost): + +[source,properties,indent=0] +---- + spring.rabbitmq.template.retry.enabled=true + spring.rabbitmq.template.retry.initial-interval=2s +---- + +Retries are disabled by default. You can also customize the `RetryTemplate` +programmatically by declaring a `RabbitRetryTemplateCustomizer` bean. + + + +[[boot-features-using-amqp-receiving]] +==== Receiving a Message +When the Rabbit infrastructure is present, any bean can be annotated with +`@RabbitListener` to create a listener endpoint. If no `RabbitListenerContainerFactory` +has been defined, a default `SimpleRabbitListenerContainerFactory` is automatically +configured and you can switch to a direct container using the +`spring.rabbitmq.listener.type` property. If a `MessageConverter` or a `MessageRecoverer` +bean is defined, it is automatically associated with the default factory. + +The following sample component creates a listener endpoint on the `someQueue` queue: + +[source,java,indent=0] +---- + @Component + public class MyBean { + + @RabbitListener(queues = "someQueue") + public void processMessage(String content) { + // ... + } + + } +---- + +TIP: See {spring-amqp-javadoc}/rabbit/annotation/EnableRabbit.{dc-ext}[the Javadoc of +`@EnableRabbit`] for more details. + +If you need to create more `RabbitListenerContainerFactory` instances or if you want to +override the default, Spring Boot provides a +`SimpleRabbitListenerContainerFactoryConfigurer` and a +`DirectRabbitListenerContainerFactoryConfigurer` that you can use to initialize a +`SimpleRabbitListenerContainerFactory` and a `DirectRabbitListenerContainerFactory` with +the same settings as the factories used by the auto-configuration. + +TIP: It does not matter which container type you chose. Those two beans are exposed by +the auto-configuration. + +For instance, the following configuration class exposes another factory that uses a +specific `MessageConverter`: + +[source,java,indent=0] +---- + @Configuration(proxyBeanMethods = false) + static class RabbitConfiguration { + + @Bean + public SimpleRabbitListenerContainerFactory myFactory( + SimpleRabbitListenerContainerFactoryConfigurer configurer) { + SimpleRabbitListenerContainerFactory factory = + new SimpleRabbitListenerContainerFactory(); + configurer.configure(factory, connectionFactory); + factory.setMessageConverter(myMessageConverter()); + return factory; + } + + } +---- + +Then you can use the factory in any `@RabbitListener`-annotated method, as follows: + +[source,java,indent=0] +[subs="verbatim,quotes"] +---- + @Component + public class MyBean { + + @RabbitListener(queues = "someQueue", **containerFactory="myFactory"**) + public void processMessage(String content) { + // ... + } + + } +---- + +You can enable retries to handle situations where your listener throws an exception. By +default, `RejectAndDontRequeueRecoverer` is used, but you can define a `MessageRecoverer` +of your own. When retries are exhausted, the message is rejected and either dropped or +routed to a dead-letter exchange if the broker is configured to do so. By default, +retries are disabled. You can also customize the `RetryTemplate` programmatically by +declaring a `RabbitRetryTemplateCustomizer` bean. + +IMPORTANT: By default, if retries are disabled and the listener throws an exception, the +delivery is retried indefinitely. You can modify this behavior in two ways: Set the +`defaultRequeueRejected` property to `false` so that zero re-deliveries are attempted or +throw an `AmqpRejectAndDontRequeueException` to signal the message should be rejected. +The latter is the mechanism used when retries are enabled and the maximum number of +delivery attempts is reached. + + + +[[boot-features-kafka]] +=== Apache Kafka Support +https://kafka.apache.org/[Apache Kafka] is supported by providing auto-configuration of +the `spring-kafka` project. + +Kafka configuration is controlled by external configuration properties in +`spring.kafka.*`. For example, you might declare the following section in +`application.properties`: + +[source,properties,indent=0] +---- + spring.kafka.bootstrap-servers=localhost:9092 + spring.kafka.consumer.group-id=myGroup +---- + +TIP: To create a topic on startup, add a bean of type `NewTopic`. If the topic already +exists, the bean is ignored. + +See {sc-spring-boot-autoconfigure}/kafka/KafkaProperties.{sc-ext}[`KafkaProperties`] +for more supported options. + + + +[[boot-features-kafka-sending-a-message]] +==== Sending a Message +Spring's `KafkaTemplate` is auto-configured, and you can autowire it directly in your own +beans, as shown in the following example: + +[source,java,indent=0] +---- +@Component +public class MyBean { + + private final KafkaTemplate kafkaTemplate; + + @Autowired + public MyBean(KafkaTemplate kafkaTemplate) { + this.kafkaTemplate = kafkaTemplate; + } + + // ... + +} +---- + +NOTE: If the property `spring.kafka.producer.transaction-id-prefix` is defined, a +`KafkaTransactionManager` is automatically configured. Also, if a `RecordMessageConverter` +bean is defined, it is automatically associated to the auto-configured `KafkaTemplate`. + + +[[boot-features-kafka-receiving-a-message]] +==== Receiving a Message +When the Apache Kafka infrastructure is present, any bean can be annotated with +`@KafkaListener` to create a listener endpoint. If no `KafkaListenerContainerFactory` has +been defined, a default one is automatically configured with keys defined in +`spring.kafka.listener.*`. + +The following component creates a listener endpoint on the `someTopic` topic: + +[source,java,indent=0] +---- + @Component + public class MyBean { + + @KafkaListener(topics = "someTopic") + public void processMessage(String content) { + // ... + } + + } +---- + +If a `KafkaTransactionManager` bean is defined, it is automatically associated to the +container factory. Similarly, if a `ErrorHandler`, `AfterRollbackProcessor` or +`ConsumerAwareRebalanceListener` bean is defined, it is automatically associated to the +default factory. + +Depending on the listener type, a `RecordMessageConverter` or `BatchMessageConverter` bean +is associated to the default factory. If only a `RecordMessageConverter` bean is present +for a batch listener, it is wrapped in a `BatchMessageConverter`. + +TIP: A custom `ChainedKafkaTransactionManager` must be marked `@Primary` as it usually +references the auto-configured `KafkaTransactionManager` bean. + + + +[[boot-features-kafka-streams]] +==== Kafka Streams +Spring for Apache Kafka provides a factory bean to create a `StreamsBuilder` object and +manage the lifecycle of its streams. Spring Boot auto-configures the required +`KafkaStreamsConfiguration` bean as long as `kafka-streams` is on the classpath and Kafka +Streams is enabled via the `@EnableKafkaStreams` annotation. + +Enabling Kafka Streams means that the application id and bootstrap servers must be set. +The former can be configured using `spring.kafka.streams.application-id`, defaulting to +`spring.application.name` if not set. The latter can be set globally or +specifically overridden just for streams. + +Several additional properties are available using dedicated properties; other arbitrary +Kafka properties can be set using the `spring.kafka.streams.properties` namespace. See +also <> for more information. + +To use the factory bean, simply wire `StreamsBuilder` into your `@Bean` as shown in the +following example: + +[source,java,indent=0] +---- +include::{code-examples}/kafka/KafkaStreamsBeanExample.java[tag=configuration] +---- + +By default, the streams managed by the `StreamBuilder` object it creates are started +automatically. You can customize this behaviour using the +`spring.kafka.streams.auto-startup` property. + + + +[[boot-features-kafka-extra-props]] +==== Additional Kafka Properties +The properties supported by auto configuration are shown in +<>. Note that, for the most part, these properties +(hyphenated or camelCase) map directly to the Apache Kafka dotted properties. Refer to the +Apache Kafka documentation for details. + +The first few of these properties apply to all components (producers, consumers, admins, +and streams) but can be +specified at the component level if you wish to use different values. +Apache Kafka designates properties with an importance of HIGH, MEDIUM, or LOW. Spring Boot +auto-configuration supports all HIGH importance properties, some selected MEDIUM and LOW +properties, and any properties that do not have a default value. + +Only a subset of the properties supported by Kafka are available directly through the +`KafkaProperties` class. If you wish to configure the producer or consumer with additional +properties that are not directly supported, use the following properties: + +[source,properties,indent=0] +---- + spring.kafka.properties.prop.one=first + spring.kafka.admin.properties.prop.two=second + spring.kafka.consumer.properties.prop.three=third + spring.kafka.producer.properties.prop.four=fourth + spring.kafka.streams.properties.prop.five=fifth +---- + +This sets the common `prop.one` Kafka property to `first` (applies to producers, +consumers and admins), the `prop.two` admin property to `second`, the `prop.three` +consumer property to `third`, the `prop.four` producer property to `fourth` and the +`prop.five` streams property to `fifth`. + +You can also configure the Spring Kafka `JsonDeserializer` as follows: + +[source,properties,indent=0] +---- +spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.JsonDeserializer +spring.kafka.consumer.properties.spring.json.value.default.type=com.example.Invoice +spring.kafka.consumer.properties.spring.json.trusted.packages=com.example,org.acme +---- + +Similarly, you can disable the `JsonSerializer` default behavior of sending type +information in headers: + +[source,properties,indent=0] +---- +spring.kafka.producer.value-serializer=org.springframework.kafka.support.serializer.JsonSerializer +spring.kafka.producer.properties.spring.json.add.type.headers=false +---- + +IMPORTANT: Properties set in this way override any configuration item that Spring Boot +explicitly supports. + +[[boot-features-resttemplate]] +== Calling REST Services with `RestTemplate` +If you need to call remote REST services from your application, you can use the Spring +Framework's {spring-javadoc}/web/client/RestTemplate.html[`RestTemplate`] class. Since +`RestTemplate` instances often need to be customized before being used, Spring Boot does +not provide any single auto-configured `RestTemplate` bean. It does, however, +auto-configure a `RestTemplateBuilder`, which can be used to create `RestTemplate` +instances when needed. The auto-configured `RestTemplateBuilder` ensures that sensible +`HttpMessageConverters` are applied to `RestTemplate` instances. + +The following code shows a typical example: + +[source,java,indent=0] +---- + @Service + public class MyService { + + private final RestTemplate restTemplate; + + public MyService(RestTemplateBuilder restTemplateBuilder) { + this.restTemplate = restTemplateBuilder.build(); + } + + public Details someRestCall(String name) { + return this.restTemplate.getForObject("/{name}/details", Details.class, name); + } + + } +---- + +TIP: `RestTemplateBuilder` includes a number of useful methods that can be used to +quickly configure a `RestTemplate`. For example, to add BASIC auth support, you can use +`builder.basicAuthentication("user", "password").build()`. + + + +[[boot-features-resttemplate-customization]] +=== RestTemplate Customization +There are three main approaches to `RestTemplate` customization, depending on how broadly +you want the customizations to apply. + +To make the scope of any customizations as narrow as possible, inject the auto-configured +`RestTemplateBuilder` and then call its methods as required. Each method call returns a +new `RestTemplateBuilder` instance, so the customizations only affect this use of the +builder. + +To make an application-wide, additive customization, use a `RestTemplateCustomizer` bean. +All such beans are automatically registered with the auto-configured `RestTemplateBuilder` +and are applied to any templates that are built with it. + +The following example shows a customizer that configures the use of a proxy for all hosts +except `192.168.0.5`: + +[source,java,indent=0] +---- +include::{code-examples}/web/client/RestTemplateProxyCustomizationExample.java[tag=customizer] +---- + +Finally, the most extreme (and rarely used) option is to create your own +`RestTemplateBuilder` bean. Doing so switches off the auto-configuration of a +`RestTemplateBuilder` and prevents any `RestTemplateCustomizer` beans from being used. + + + +[[boot-features-webclient]] +== Calling REST Services with `WebClient` +If you have Spring WebFlux on your classpath, you can also choose to use `WebClient` to +call remote REST services. Compared to `RestTemplate`, this client has a more functional +feel and is fully reactive. You can learn more about the `WebClient` in the dedicated +{spring-reference}web-reactive.html#webflux-client[section in the Spring Framework docs]. + +Spring Boot creates and pre-configures a `WebClient.Builder` for you; it is strongly +advised to inject it in your components and use it to create `WebClient` instances. +Spring Boot is configuring that builder to share HTTP resources, reflect codecs +setup in the same fashion as the server ones (see +<>), and more. + +The following code shows a typical example: + +[source,java,indent=0] +---- + @Service + public class MyService { + + private final WebClient webClient; + + public MyService(WebClient.Builder webClientBuilder) { + this.webClient = webClientBuilder.baseUrl("https://example.org").build(); + } + + public Mono
someRestCall(String name) { + return this.webClient.get().uri("/{name}/details", name) + .retrieve().bodyToMono(Details.class); + } + + } +---- + + + +[[boot-features-webclient-runtime]] +=== WebClient Runtime +Spring Boot will auto-detect which `ClientHttpConnector` to use to drive `WebClient`, +depending on the libraries available on the application classpath. For now, Reactor +Netty and Jetty RS client are supported. + +The `spring-boot-starter-webflux` starter depends on `io.projectreactor.netty:reactor-netty` +by default, which brings both server and client implementations. If you choose to use Jetty +as a reactive server instead, you should add a dependency on the Jetty Reactive HTTP +client library, `org.eclipse.jetty:jetty-reactive-httpclient`. Using the same technology +for server and client has it advantages, as it will automatically share HTTP resources +between client and server. + +Developers can override the resource configuration for Jetty and Reactor Netty by providing +a custom `ReactorResourceFactory` or `JettyResourceFactory` bean - this will be applied to +both clients and servers. + +If you wish to override that choice for the client, you can define your own +`ClientHttpConnector` bean and have full control over the client configuration. + +You can learn more about the +{spring-reference}web-reactive.html#webflux-client-builder[`WebClient` configuration +options in the Spring Framework reference documentation]. + + + +[[boot-features-webclient-customization]] +=== WebClient Customization +There are three main approaches to `WebClient` customization, depending on how broadly you +want the customizations to apply. + +To make the scope of any customizations as narrow as possible, inject the auto-configured +`WebClient.Builder` and then call its methods as required. `WebClient.Builder` instances +are stateful: Any change on the builder is reflected in all clients subsequently created +with it. If you want to create several clients with the same builder, you can also +consider cloning the builder with `WebClient.Builder other = builder.clone();`. + +To make an application-wide, additive customization to all `WebClient.Builder` instances, +you can declare `WebClientCustomizer` beans and change the `WebClient.Builder` locally at +the point of injection. + +Finally, you can fall back to the original API and use `WebClient.create()`. In that case, +no auto-configuration or `WebClientCustomizer` is applied. + + + +[[boot-features-validation]] +== Validation +The method validation feature supported by Bean Validation 1.1 is automatically enabled +as long as a JSR-303 implementation (such as Hibernate validator) is on the classpath. +This lets bean methods be annotated with `javax.validation` constraints on their +parameters and/or on their return value. Target classes with such annotated methods need +to be annotated with the `@Validated` annotation at the type level for their methods to +be searched for inline constraint annotations. + +For instance, the following service triggers the validation of the first argument, making +sure its size is between 8 and 10: + +[source,java,indent=0] +---- + @Service + @Validated + public class MyBean { + + public Archive findByCodeAndAuthor(@Size(min = 8, max = 10) String code, + Author author) { + ... + } + + } +---- + + + +[[boot-features-email]] +== Sending Email +The Spring Framework provides an easy abstraction for sending email by using the +`JavaMailSender` interface, and Spring Boot provides auto-configuration for it as well as +a starter module. + +TIP: See the {spring-reference}integration.html#mail[reference documentation] for a +detailed explanation of how you can use `JavaMailSender`. + +If `spring.mail.host` and the relevant libraries (as defined by +`spring-boot-starter-mail`) are available, a default `JavaMailSender` is created if none +exists. The sender can be further customized by configuration items from the +`spring.mail` namespace. See +{sc-spring-boot-autoconfigure}/mail/MailProperties.{sc-ext}[`MailProperties`] for more +details. + +In particular, certain default timeout values are infinite, and you may want to change +that to avoid having a thread blocked by an unresponsive mail server, as shown in the +following example: + +[source,properties,indent=0] +---- + spring.mail.properties.mail.smtp.connectiontimeout=5000 + spring.mail.properties.mail.smtp.timeout=3000 + spring.mail.properties.mail.smtp.writetimeout=5000 +---- + +It is also possible to configure a `JavaMailSender` with an existing `Session` from JNDI: + +[source,properties,indent=0] +---- + spring.mail.jndi-name=mail/Session +---- + +When a `jndi-name` is set, it takes precedence over all other Session-related settings. + + + +[[boot-features-jta]] +== Distributed Transactions with JTA +Spring Boot supports distributed JTA transactions across multiple XA resources by using +either an https://www.atomikos.com/[Atomikos] or https://github.com/bitronix/btm[Bitronix] +embedded transaction manager. JTA transactions are also supported when deploying to a +suitable Java EE Application Server. + +When a JTA environment is detected, Spring's `JtaTransactionManager` is used to manage +transactions. Auto-configured JMS, DataSource, and JPA beans are upgraded to support XA +transactions. You can use standard Spring idioms, such as `@Transactional`, to participate +in a distributed transaction. If you are within a JTA environment and still want to use +local transactions, you can set the `spring.jta.enabled` property to `false` to disable +the JTA auto-configuration. + + + +[[boot-features-jta-atomikos]] +=== Using an Atomikos Transaction Manager +https://www.atomikos.com/[Atomikos] is a popular open source transaction manager which can +be embedded into your Spring Boot application. You can use the +`spring-boot-starter-jta-atomikos` Starter to pull in the appropriate Atomikos libraries. +Spring Boot auto-configures Atomikos and ensures that appropriate `depends-on` settings +are applied to your Spring beans for correct startup and shutdown ordering. + +By default, Atomikos transaction logs are written to a `transaction-logs` directory in +your application's home directory (the directory in which your application jar file +resides). You can customize the location of this directory by setting a +`spring.jta.log-dir` property in your `application.properties` file. Properties starting +with `spring.jta.atomikos.properties` can also be used to customize the Atomikos +`UserTransactionServiceImp`. See the +{dc-spring-boot}/jta/atomikos/AtomikosProperties.{dc-ext}[`AtomikosProperties` Javadoc] +for complete details. + +NOTE: To ensure that multiple transaction managers can safely coordinate the same +resource managers, each Atomikos instance must be configured with a unique ID. By default, +this ID is the IP address of the machine on which Atomikos is running. To ensure +uniqueness in production, you should configure the `spring.jta.transaction-manager-id` +property with a different value for each instance of your application. + + + +[[boot-features-jta-bitronix]] +=== Using a Bitronix Transaction Manager +https://github.com/bitronix/btm[Bitronix] is a popular open-source JTA transaction +manager implementation. You can use the `spring-boot-starter-jta-bitronix` starter to add +the appropriate Bitronix dependencies to your project. As with Atomikos, Spring Boot +automatically configures Bitronix and post-processes your beans to ensure that startup and +shutdown ordering is correct. + +By default, Bitronix transaction log files (`part1.btm` and `part2.btm`) are written to +a `transaction-logs` directory in your application home directory. You can customize the +location of this directory by setting the `spring.jta.log-dir` property. Properties +starting with `spring.jta.bitronix.properties` are also bound to the +`bitronix.tm.Configuration` bean, allowing for complete customization. See the +https://github.com/bitronix/btm/wiki/Transaction-manager-configuration[Bitronix +documentation] for details. + +NOTE: To ensure that multiple transaction managers can safely coordinate the same +resource managers, each Bitronix instance must be configured with a unique ID. By default, +this ID is the IP address of the machine on which Bitronix is running. To ensure +uniqueness in production, you should configure the `spring.jta.transaction-manager-id` +property with a different value for each instance of your application. + + + +[[boot-features-jta-javaee]] +=== Using a Java EE Managed Transaction Manager +If you package your Spring Boot application as a `war` or `ear` file and deploy it to a +Java EE application server, you can use your application server's built-in transaction +manager. Spring Boot tries to auto-configure a transaction manager by looking at common +JNDI locations (`java:comp/UserTransaction`, `java:comp/TransactionManager`, and so on). +If you use a transaction service provided by your application server, you generally also +want to ensure that all resources are managed by the server and exposed over JNDI. Spring +Boot tries to auto-configure JMS by looking for a `ConnectionFactory` at the JNDI path +(`java:/JmsXA` or `java:/XAConnectionFactory`), and you can use the +<> +to configure your `DataSource`. + + + +[[boot-features-jta-mixed-jms]] +=== Mixing XA and Non-XA JMS Connections +When using JTA, the primary JMS `ConnectionFactory` bean is XA-aware and participates +in distributed transactions. In some situations, you might want to process certain JMS +messages by using a non-XA `ConnectionFactory`. For example, your JMS processing logic +might take longer than the XA timeout. + +If you want to use a non-XA `ConnectionFactory`, you can inject the +`nonXaJmsConnectionFactory` bean rather than the `@Primary` `jmsConnectionFactory` bean. +For consistency, the `jmsConnectionFactory` bean is also provided by using the bean alias +`xaJmsConnectionFactory`. + +The following example shows how to inject `ConnectionFactory` instances: + +[source,java,indent=0,subs="verbatim,quotes,attributes"] +---- + // Inject the primary (XA aware) ConnectionFactory + @Autowired + private ConnectionFactory defaultConnectionFactory; + + // Inject the XA aware ConnectionFactory (uses the alias and injects the same as above) + @Autowired + @Qualifier("xaJmsConnectionFactory") + private ConnectionFactory xaConnectionFactory; + + // Inject the non-XA aware ConnectionFactory + @Autowired + @Qualifier("nonXaJmsConnectionFactory") + private ConnectionFactory nonXaConnectionFactory; +---- + + + +[[boot-features-jta-supporting-alternative-embedded]] +=== Supporting an Alternative Embedded Transaction Manager +The {sc-spring-boot}/jms/XAConnectionFactoryWrapper.{sc-ext}[`XAConnectionFactoryWrapper`] +and {sc-spring-boot}/jdbc/XADataSourceWrapper.{sc-ext}[`XADataSourceWrapper`] interfaces +can be used to support alternative embedded transaction managers. The interfaces are +responsible for wrapping `XAConnectionFactory` and `XADataSource` beans and exposing them +as regular `ConnectionFactory` and `DataSource` beans, which transparently enroll in the +distributed transaction. DataSource and JMS auto-configuration use JTA variants, provided +you have a `JtaTransactionManager` bean and appropriate XA wrapper beans registered +within your `ApplicationContext`. + +The {sc-spring-boot}/jta/bitronix/BitronixXAConnectionFactoryWrapper.{sc-ext}[BitronixXAConnectionFactoryWrapper] +and {sc-spring-boot}/jta/bitronix/BitronixXADataSourceWrapper.{sc-ext}[BitronixXADataSourceWrapper] +provide good examples of how to write XA wrappers. + + + +[[boot-features-hazelcast]] +== Hazelcast + +If https://hazelcast.com/[Hazelcast] is on the classpath and a suitable configuration is +found, Spring Boot auto-configures a `HazelcastInstance` that you can inject in your +application. + +If you define a `com.hazelcast.config.Config` bean, Spring Boot uses that. If your +configuration defines an instance name, Spring Boot tries to locate an existing instance +rather than creating a new one. + +You could also specify the Hazelcast configuration file to use through configuration, as +shown in the following example: + +[source,properties,indent=0] +---- + spring.hazelcast.config=classpath:config/my-hazelcast.xml +---- + +Otherwise, Spring Boot tries to find the Hazelcast configuration from the default +locations: `hazelcast.xml` in the working directory or at the root of the classpath, or +a `.yaml` counterpart in the same locations. We also check if the `hazelcast.config` +system property is set. See the +https://docs.hazelcast.org/docs/latest/manual/html-single/[Hazelcast documentation] for +more details. + +If `hazelcast-client` is present on the classpath, Spring Boot first attempts to create a +client by checking the following configuration options: + +* The presence of a `com.hazelcast.client.config.ClientConfig` bean. +* A configuration file defined by the `spring.hazelcast.config` property. +* The presence of the `hazelcast.client.config` system property. +* A `hazelcast-client.xml` in the working directory or at the root of the classpath. +* A `hazelcast-client.yaml` in the working directory or at the root of the classpath. + +NOTE: Spring Boot also has +<>. If +caching is enabled, the `HazelcastInstance` is automatically wrapped in a `CacheManager` +implementation. + + + +[[boot-features-quartz]] +== Quartz Scheduler +Spring Boot offers several conveniences for working with the +https://www.quartz-scheduler.org/[Quartz scheduler], including the +`spring-boot-starter-quartz` "`Starter`". If Quartz is available, a `Scheduler` is +auto-configured (through the `SchedulerFactoryBean` abstraction). + +Beans of the following types are automatically picked up and associated with the +`Scheduler`: + +* `JobDetail`: defines a particular Job. `JobDetail` instances can be built with the +`JobBuilder` API. +* `Calendar`. +* `Trigger`: defines when a particular job is triggered. + +By default, an in-memory `JobStore` is used. However, it is possible to configure a +JDBC-based store if a `DataSource` bean is available in your application and if the +`spring.quartz.job-store-type` property is configured accordingly, as shown in the +following example: + +[source,properties,indent=0] +---- + spring.quartz.job-store-type=jdbc +---- + +When the JDBC store is used, the schema can be initialized on startup, as shown in the +following example: + +[source,properties,indent=0] +---- + spring.quartz.jdbc.initialize-schema=always +---- + +WARNING: By default, the database is detected and initialized by using the standard scripts +provided with the Quartz library. These scripts drop existing tables, deleting all triggers +on every restart. It is also possible to provide a custom script by setting the +`spring.quartz.jdbc.schema` property. + +To have Quartz use a `DataSource` other than the application's main `DataSource`, declare +a `DataSource` bean, annotating its `@Bean` method with `@QuartzDataSource`. Doing so +ensures that the Quartz-specific `DataSource` is used by both the `SchedulerFactoryBean` +and for schema initialization. + +By default, jobs created by configuration will not overwrite already registered jobs that +have been read from a persistent job store. To enable overwriting existing job definitions +set the `spring.quartz.overwrite-existing-jobs` property. + +Quartz Scheduler configuration can be customized using `spring.quartz` properties and +`SchedulerFactoryBeanCustomizer` beans, which allow programmatic `SchedulerFactoryBean` +customization. Advanced Quartz configuration properties can be customized using +`spring.quartz.properties.*`. + +NOTE: In particular, an `Executor` bean is not associated with the scheduler as Quartz +offers a way to configure the scheduler via `spring.quartz.properties`. If you need +to customize the task executor, consider implementing `SchedulerFactoryBeanCustomizer`. + +Jobs can define setters to inject data map properties. Regular beans can also be injected +in a similar manner, as shown in the following example: + +[source,java,indent=0] +---- + public class SampleJob extends QuartzJobBean { + + private MyService myService; + + private String name; + + // Inject "MyService" bean + public void setMyService(MyService myService) { ... } + + // Inject the "name" job data property + public void setName(String name) { ... } + + @Override + protected void executeInternal(JobExecutionContext context) + throws JobExecutionException { + ... + } + + } +---- + + + +[[boot-features-task-execution-scheduling]] +== Task Execution and Scheduling +In the absence of an `Executor` bean in the context, Spring Boot auto-configures a +`ThreadPoolTaskExecutor` with sensible defaults that can be automatically associated to +asynchronous task execution (`@EnableAsync`) and Spring MVC asynchronous request +processing. + +[TIP] +==== +If you have defined a custom `Executor` in the context, regular task execution (i.e. +`@EnableAsync`) will use it transparently but the Spring MVC support will not be +configured as it requires an `AsyncTaskExecutor` implementation (named +`applicationTaskExecutor`). Depending on your target arrangement, you could change your +`Executor` into a `ThreadPoolTaskExecutor` or define both a `ThreadPoolTaskExecutor` and +an `AsyncConfigurer` wrapping your custom `Executor`. + +The auto-configured `TaskExecutorBuilder` allows you to easily create instances that +reproduce what the auto-configuration does by default. +==== + +The thread pool uses 8 core threads that can grow and shrink according to the load. Those +default settings can be fine-tuned using the `spring.task.execution` namespace as shown in +the following example: + +[source,properties,indent=0] +---- + spring.task.execution.pool.max-threads=16 + spring.task.execution.pool.queue-capacity=100 + spring.task.execution.pool.keep-alive=10s +---- + +This changes the thread pool to use a bounded queue so that when the queue is full (100 +tasks), the thread pool increases to maximum 16 threads. Shrinking of the pool is more +aggressive as threads are reclaimed when they are idle for 10 seconds (rather than +60 seconds by default). + +A `ThreadPoolTaskScheduler` can also be auto-configured if need to be associated to +scheduled task execution (`@EnableScheduling`). The thread pool uses one thread by default +and those settings can be fine-tuned using the `spring.task.scheduling` namespace. + +Both a `TaskExecutorBuilder` bean and a `TaskSchedulerBuilder` bean are made available in +the context if a custom executor or scheduler needs to be created. + + + +[[boot-features-integration]] +== Spring Integration +Spring Boot offers several conveniences for working with {spring-integration}[Spring +Integration], including the `spring-boot-starter-integration` "`Starter`". Spring +Integration provides abstractions over messaging and also other transports such as HTTP, +TCP, and others. If Spring Integration is available on your classpath, it is initialized +through the `@EnableIntegration` annotation. + +Spring Boot also configures some features that are triggered by the presence of additional +Spring Integration modules. If `spring-integration-jmx` is also on the classpath, +message processing statistics are published over JMX . If `spring-integration-jdbc` is +available, the default database schema can be created on startup, as shown in the +following line: + +[source,properties,indent=0] +---- + spring.integration.jdbc.initialize-schema=always +---- + +See the +{sc-spring-boot-autoconfigure}/integration/IntegrationAutoConfiguration.{sc-ext}[`IntegrationAutoConfiguration`] +and {sc-spring-boot-autoconfigure}/integration/IntegrationProperties.{sc-ext}[`IntegrationProperties`] +classes for more details. + +By default, if a Micrometer `meterRegistry` bean is present, Spring Integration metrics +will be managed by Micrometer. If you wish to use legacy Spring Integration metrics, add +a `DefaultMetricsFactory` bean to the application context. + + + +[[boot-features-session]] +== Spring Session +Spring Boot provides {spring-session}[Spring Session] auto-configuration for a wide range +of data stores. When building a Servlet web application, the following stores can be +auto-configured: + +* JDBC +* Redis +* Hazelcast +* MongoDB + +When building a reactive web application, the following stores can be auto-configured: + +* Redis +* MongoDB + +If a single Spring Session module is present on the classpath, Spring Boot uses that store +implementation automatically. If you have more than one implementation, you must choose +the {sc-spring-boot-autoconfigure}/session/StoreType.{sc-ext}[`StoreType`] that you wish +to use to store the sessions. For instance, to use JDBC as the back-end store, you can +configure your application as follows: + +[source,properties,indent=0] +---- + spring.session.store-type=jdbc +---- + +TIP: You can disable Spring Session by setting the `store-type` to `none`. + +Each store has specific additional settings. For instance, it is possible to customize +the name of the table for the JDBC store, as shown in the following example: + +[source,properties,indent=0] +---- + spring.session.jdbc.table-name=SESSIONS +---- + +For setting the timeout of the session you can use the `spring.session.timeout` property. +If that property is not set, the auto-configuration falls back to the value of +`server.servlet.session.timeout`. + +[[boot-features-jmx]] +== Monitoring and Management over JMX +Java Management Extensions (JMX) provide a standard mechanism to monitor and manage +applications. Spring Boot exposes the most suitable `MBeanServer` as a bean with an ID of +`mbeanServer`. Any of your beans that are annotated with Spring JMX annotations ( +`@ManagedResource`, `@ManagedAttribute`, or `@ManagedOperation`) are exposed to it. + +If your platform provides a standard `MBeanServer`, Spring Boot will use that and default +to the VM `MBeanServer` if necessary. If all that fails, a new `MBeanServer` will be +created. + +See the +{sc-spring-boot-autoconfigure}/jmx/JmxAutoConfiguration.{sc-ext}[`JmxAutoConfiguration`] +class for more details. + + + +[[boot-features-testing]] +== Testing +Spring Boot provides a number of utilities and annotations to help when testing your +application. Test support is provided by two modules: `spring-boot-test` contains core +items, and `spring-boot-test-autoconfigure` supports auto-configuration for tests. + +Most developers use the `spring-boot-starter-test` "`Starter`", which imports both Spring +Boot test modules as well as JUnit Jupiter, AssertJ, Hamcrest, and a number of other +useful libraries. + +[TIP] +==== +The starter also brings the vintage engine so that you can run both JUnit 4 and JUnit 5 +tests. If you have migrated your tests to JUnit 5, you should exclude JUnit 4 support, as +shown in the following example: + +[source,xml,indent=0,subs="verbatim,quotes,attributes"] +---- + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + +---- +==== + + + +[[boot-features-test-scope-dependencies]] +=== Test Scope Dependencies +The `spring-boot-starter-test` "`Starter`" (in the `test` `scope`) contains +the following provided libraries: + +* https://junit.org/junit5[JUnit 5] (including the vintage engine for backward +compatibility with JUnit 4: The de-facto standard for unit testing Java applications. +* {spring-reference}testing.html#integration-testing[Spring Test] & Spring Boot Test: +Utilities and integration test support for Spring Boot applications. +* https://joel-costigliola.github.io/assertj/[AssertJ]: A fluent assertion library. +* https://github.com/hamcrest/JavaHamcrest[Hamcrest]: A library of matcher objects (also +known as constraints or predicates). +* https://mockito.github.io[Mockito]: A Java mocking framework. +* https://github.com/skyscreamer/JSONassert[JSONassert]: An assertion library for JSON. +* https://github.com/jayway/JsonPath[JsonPath]: XPath for JSON. + +We generally find these common libraries to be useful when writing tests. If these +libraries do not suit your needs, you can add additional test dependencies of your own. + + + +[[boot-features-testing-spring-applications]] +=== Testing Spring Applications +One of the major advantages of dependency injection is that it should make your code +easier to unit test. You can instantiate objects by using the `new` operator without +even involving Spring. You can also use _mock objects_ instead of real dependencies. + +Often, you need to move beyond unit testing and start integration testing (with +a Spring `ApplicationContext`). It is useful to be able to perform integration testing +without requiring deployment of your application or needing to connect to other +infrastructure. + +The Spring Framework includes a dedicated test module for such integration testing. You +can declare a dependency directly to `org.springframework:spring-test` or use the +`spring-boot-starter-test` "`Starter`" to pull it in transitively. + +If you have not used the `spring-test` module before, you should start by reading the +{spring-reference}testing.html#testing[relevant section] of the Spring Framework +reference documentation. + + + +[[boot-features-testing-spring-boot-applications]] +=== Testing Spring Boot Applications +A Spring Boot application is a Spring `ApplicationContext`, so nothing very special has +to be done to test it beyond what you would normally do with a vanilla Spring context. + +NOTE: External properties, logging, and other features of Spring Boot are installed in the +context by default only if you use `SpringApplication` to create it. + +Spring Boot provides a `@SpringBootTest` annotation, which can be used as an alternative +to the standard `spring-test` `@ContextConfiguration` annotation when you need Spring +Boot features. The annotation works by +<>. In addition to +`@SpringBootTest` a number of other annotations are also provided for +<> of an application. + +TIP: If you are using JUnit 4, don't forget to also add `@RunWith(SpringRunner.class)` to +your test, otherwise the annotations will be ignored. If you are using JUnit 5, there's no +need to add the equivalent `@RunWith(SpringExtension.class)` as `@SpringBootTest` and +the other `@…Test` annotations are already annotated with it. + +By default, `@SpringBootTest` will not start a server. You can use the `webEnvironment` +attribute of `@SpringBootTest` to further refine how your tests run: + +* `MOCK`(Default) : Loads a web `ApplicationContext` and provides a mock web +environment. Embedded servers are not started when using this annotation. If a web +environment is not available on your classpath, this mode transparently falls back to +creating a regular non-web `ApplicationContext`. It can be used in conjunction with +<> for mock-based testing of your +web application. +* `RANDOM_PORT`: Loads a `WebServerApplicationContext` and provides a real web +environment. Embedded servers are started and listen on a random port. +* `DEFINED_PORT`: Loads a `WebServerApplicationContext` and provides a real web +environment. Embedded servers are started and listen on a defined port (from your +`application.properties`) or on the default port of `8080`. +* `NONE`: Loads an `ApplicationContext` by using `SpringApplication` but does not provide +_any_ web environment (mock or otherwise). + +NOTE: If your test is `@Transactional`, it rolls back the transaction at the end of each +test method by default. However, as using this arrangement with either `RANDOM_PORT` or +`DEFINED_PORT` implicitly provides a real servlet environment, the HTTP client and server +run in separate threads and, thus, in separate transactions. Any transaction initiated on +the server does not roll back in this case. + +NOTE: `@SpringBootTest` with `webEnvironment = WebEnvironment.RANDOM_PORT` will also +start the management server on a separate random port if your application uses a different +port for the management server. + + + +[[boot-features-testing-spring-boot-applications-detecting-web-app-type]] +==== Detecting Web Application Type +If Spring MVC is available, a regular MVC-based application context is configured. If you +have only Spring WebFlux, we'll detect that and configure a WebFlux-based application +context instead. + +If both are present, Spring MVC takes precedence. If you want to test a reactive web +application in this scenario, you must set the `spring.main.web-application-type` +property: + +[source,java,indent=0] +---- + @SpringBootTest(properties = "spring.main.web-application-type=reactive") + class MyWebFluxTests { ... } +---- + + + +[[boot-features-testing-spring-boot-applications-detecting-config]] +==== Detecting Test Configuration +If you are familiar with the Spring Test Framework, you may be used to using +`@ContextConfiguration(classes=...)` in order to specify which Spring `@Configuration` to +load. Alternatively, you might have often used nested `@Configuration` classes within +your test. + +When testing Spring Boot applications, this is often not required. Spring Boot's `@*Test` +annotations search for your primary configuration automatically whenever you do not +explicitly define one. + +The search algorithm works up from the package that contains the test until it finds a +class annotated with `@SpringBootApplication` or `@SpringBootConfiguration`. As long as +you <> in a sensible way, your +main configuration is usually found. + +[NOTE] +==== +If you use a +<>, you should avoid adding +configuration settings that are specific to a particular area on the +<>. + +The underlying component scan configuration of `@SpringBootApplication` defines exclude +filters that are used to make sure slicing works as expected. If you are using an explicit +`@ComponentScan` directive on your `@SpringBootApplication`-annotated class, be aware that +those filters will be disabled. If you are using slicing, you should define them again. +==== + +If you want to customize the primary configuration, you can use a nested +`@TestConfiguration` class. Unlike a nested `@Configuration` class, which would be used +instead of your application's primary configuration, a nested `@TestConfiguration` class +is used in addition to your application's primary configuration. + +NOTE: Spring's test framework caches application contexts between tests. Therefore, as +long as your tests share the same configuration (no matter how it is discovered), the +potentially time-consuming process of loading the context happens only once. + + + +[[boot-features-testing-spring-boot-applications-excluding-config]] +==== Excluding Test Configuration +If your application uses component scanning (for example, if you use +`@SpringBootApplication` or `@ComponentScan`), you may find top-level configuration +classes that you created only for specific tests accidentally get picked up everywhere. + +As we <>, `@TestConfiguration` can be used on an inner class of a test to customize the +primary configuration. When placed on a top-level class, `@TestConfiguration` indicates +that classes in `src/test/java` should not be picked up by scanning. You can then import +that class explicitly where it is required, as shown in the following example: + +[source,java,indent=0] +---- + @SpringBootTest + @Import(MyTestsConfiguration.class) + class MyTests { + + @Test + void exampleTest() { + ... + } + + } +---- + +NOTE: If you directly use `@ComponentScan` (that is, not through +`@SpringBootApplication`) you need to register the `TypeExcludeFilter` with it. See +{dc-spring-boot}/context/TypeExcludeFilter.{dc-ext}[the Javadoc] for details. + + + +[[boot-features-testing-spring-boot-application-arguments]] +==== Using Application Arguments +If your application expects <>, you can +have `@SpringBootTest` inject them using the `args` attribute. + +[source,java,indent=0] +---- +include::{code-examples}/test/context/ApplicationArgumentsExampleTests.java[tag=example] +---- + + + +[[boot-features-testing-spring-boot-applications-testing-with-mock-environment]] +==== Testing with a mock environment +By default, `@SpringBootTest` does not start the server. If you have web endpoints that +you want to test against this mock environment, you can additionally configure +{spring-reference}/testing.html#spring-mvc-test-framework[`MockMvc`] as shown in the +following example: + +[source,java,indent=0] +---- +include::{code-examples}/test/web/MockMvcExampleTests.java[tag=test-mock-mvc] +---- + +TIP: If you want to focus only on the web layer and not start a complete +`ApplicationContext`, consider +<>. + +Alternatively, you can configure a +{spring-reference}testing.html#webtestclient-tests[`WebTestClient`] as shown in the +following example: + +[source,java,indent=0] +---- +include::{code-examples}/test/web/MockWebTestClientExampleTests.java[tag=test-mock-web-test-client] +---- + + + +[[boot-features-testing-spring-boot-applications-testing-with-running-server]] +==== Testing with a running server +If you need to start a full running server, we recommend that you use random ports. +If you use `@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)`, an +available port is picked at random each time your test runs. + +The `@LocalServerPort` annotation can be used to +<> into your test. +For convenience, tests that need to make REST calls to the started server can +additionally `@Autowire` a +{spring-reference}testing.html#webtestclient-tests[`WebTestClient`], which resolves +relative links to the running server and comes with a dedicated API for verifying +responses, as shown in the following example: + +[source,java,indent=0] +---- +include::{code-examples}/test/web/RandomPortWebTestClientExampleTests.java[tag=test-random-port] +---- + +This setup requires `spring-webflux` on the classpath. If you can't or won't add webflux, +Spring Boot also provides a `TestRestTemplate` facility: + +[source,java,indent=0] +---- +include::{code-examples}/test/web/RandomPortTestRestTemplateExampleTests.java[tag=test-random-port] +---- + + + +[[boot-features-testing-spring-boot-applications-jmx]] +==== Using JMX +As the test context framework caches context, JMX is disabled by default to prevent +identical components to register on the same domain. If such test needs access to an +`MBeanServer`, consider marking it dirty as well: + +[source,java,indent=0] +---- +include::{test-examples}/jmx/SampleJmxTests.java[tag=test] +---- + + + +[[boot-features-testing-spring-boot-applications-mocking-beans]] +==== Mocking and Spying Beans +When running tests, it is sometimes necessary to mock certain components within your +application context. For example, you may have a facade over some remote service that is +unavailable during development. Mocking can also be useful when you want to simulate +failures that might be hard to trigger in a real environment. + +Spring Boot includes a `@MockBean` annotation that can be used to define a Mockito mock +for a bean inside your `ApplicationContext`. You can use the annotation to add new beans +or replace a single existing bean definition. The annotation can be used directly on test +classes, on fields within your test, or on `@Configuration` classes and fields. When used +on a field, the instance of the created mock is also injected. Mock beans are +automatically reset after each test method. + +[NOTE] +==== +If your test uses one of Spring Boot's test annotations (such as `@SpringBootTest`), this +feature is automatically enabled. To use this feature with a different +arrangement, a listener must be explicitly added, as shown in the following example: + +[source,java,indent=0] +---- + @TestExecutionListeners(MockitoTestExecutionListener.class) +---- + +==== + +The following example replaces an existing `RemoteService` bean with a mock +implementation: + +[source,java,indent=0] +---- + import org.junit.jupiter.api.Test; + import org.springframework.beans.factory.annotation.*; + import org.springframework.boot.test.context.*; + import org.springframework.boot.test.mock.mockito.*; + + import static org.assertj.core.api.Assertions.*; + import static org.mockito.BDDMockito.*; + + @SpringBootTest + class MyTests { + + @MockBean + private RemoteService remoteService; + + @Autowired + private Reverser reverser; + + @Test + void exampleTest() { + // RemoteService has been injected into the reverser bean + given(this.remoteService.someCall()).willReturn("mock"); + String reverse = reverser.reverseSomeCall(); + assertThat(reverse).isEqualTo("kcom"); + } + + } +---- + +NOTE: `@MockBean` cannot be used to mock the behavior of a bean that's exercised during +application context refresh. By the time the test is executed, the application context refresh +has completed and it is too late to configure the mocked behavior. We recommend using a `@Bean` +method to create and configure the mock in this situation. + +Additionally, you can use `@SpyBean` to wrap any existing bean with a Mockito `spy`. See +the {dc-spring-boot-test}/mock/mockito/SpyBean.{dc-ext}[Javadoc] for full details. + +NOTE: While Spring's test framework caches application contexts between tests and reuses +a context for tests sharing the same configuration, the use of `@MockBean` or `@SpyBean` +influences the cache key, which will most likely increase the number of contexts. + +TIP: If you are using `@SpyBean` to spy on a bean with `@Cacheable` methods that refer +to parameters by name, your application must be compiled with `-parameters`. This +ensures that the parameter names are available to the caching infrastructure once the +bean has been spied upon. + + + +[[boot-features-testing-spring-boot-applications-testing-autoconfigured-tests]] +==== Auto-configured Tests +Spring Boot's auto-configuration system works well for applications but can sometimes be +a little too much for tests. It often helps to load only the parts of the configuration +that are required to test a "`slice`" of your application. For example, you might want to +test that Spring MVC controllers are mapping URLs correctly, and you do not want to +involve database calls in those tests, or you might want to test JPA entities, and you +are not interested in the web layer when those tests run. + +The `spring-boot-test-autoconfigure` module includes a number of annotations that can be +used to automatically configure such "`slices`". Each of them works in a similar way, +providing a `@...Test` annotation that loads the `ApplicationContext` and one or +more `@AutoConfigure...` annotations that can be used to customize auto-configuration +settings. + +NOTE: Each slice restricts component scan to appropriate components and loads a very +restricted set of auto-configuration classes. If you need to exclude one of them, +most `@...Test` annotations provide an `excludeAutoConfiguration` attribute. +Alternatively, you can use `@ImportAutoConfiguration#exclude`. + +NOTE: Including multiple "`slices`" by using several `@...Test` annotations in one test is +not supported. If you need multiple "`slices`", pick one of the `@...Test` annotations +and include the `@AutoConfigure...` annotations of the other "`slices`" by hand. + +TIP: It is also possible to use the `@AutoConfigure...` annotations with the standard +`@SpringBootTest` annotation. You can use this combination if you are not interested in +"`slicing`" your application but you want some of the auto-configured test beans. + + + +[[boot-features-testing-spring-boot-applications-testing-autoconfigured-json-tests]] +==== Auto-configured JSON Tests +To test that object JSON serialization and deserialization is working as expected, you can +use the `@JsonTest` annotation. `@JsonTest` auto-configures the available supported JSON +mapper, which can be one of the following libraries: + +* Jackson `ObjectMapper`, any `@JsonComponent` beans and any Jackson ``Module``s +* `Gson` +* `Jsonb` + +TIP: A list of the auto-configurations that are enabled by `@JsonTest` can be +<>. + +If you need to configure elements of the auto-configuration, you can use the +`@AutoConfigureJsonTesters` annotation. + +Spring Boot includes AssertJ-based helpers that work with the JSONAssert and JsonPath +libraries to check that JSON appears as expected. The `JacksonTester`, `GsonTester`, +`JsonbTester`, and `BasicJsonTester` classes can be used for Jackson, Gson, Jsonb, and +Strings respectively. Any helper fields on the test class can be `@Autowired` when using +`@JsonTest`. The following example shows a test class for Jackson: + +[source,java,indent=0] +---- + import org.junit.jupiter.api.Test; + import org.springframework.beans.factory.annotation.*; + import org.springframework.boot.test.autoconfigure.json.*; + import org.springframework.boot.test.context.*; + import org.springframework.boot.test.json.*; + + import static org.assertj.core.api.Assertions.*; + + @JsonTest + class MyJsonTests { + + @Autowired + private JacksonTester json; + + @Test + void testSerialize() throws Exception { + VehicleDetails details = new VehicleDetails("Honda", "Civic"); + // Assert against a `.json` file in the same package as the test + assertThat(this.json.write(details)).isEqualToJson("expected.json"); + // Or use JSON path based assertions + assertThat(this.json.write(details)).hasJsonPathStringValue("@.make"); + assertThat(this.json.write(details)).extractingJsonPathStringValue("@.make") + .isEqualTo("Honda"); + } + + @Test + void testDeserialize() throws Exception { + String content = "{\"make\":\"Ford\",\"model\":\"Focus\"}"; + assertThat(this.json.parse(content)) + .isEqualTo(new VehicleDetails("Ford", "Focus")); + assertThat(this.json.parseObject(content).getMake()).isEqualTo("Ford"); + } + + } +---- + +NOTE: JSON helper classes can also be used directly in standard unit tests. To do so, +call the `initFields` method of the helper in your `@Before` method if you do not use +`@JsonTest`. + +If you're using Spring Boot's AssertJ-based helpers to assert on a number value +at a given JSON path, you might not be able to use `isEqualTo` depending on the type. +Instead, you can use AssertJ's `satisfies` to assert that the value matches the given +condition. For instance, the following example asserts that the actual number is a float +value close to `0.15` within an offset of `0.01`. + +[source,java,indent=0] +---- +assertThat(json.write(message)) + .extractingJsonPathNumberValue("@.test.numberValue") + .satisfies((number) -> assertThat(number.floatValue()).isCloseTo(0.15f, within(0.01f))); +---- + + + +[[boot-features-testing-spring-boot-applications-testing-autoconfigured-mvc-tests]] +==== Auto-configured Spring MVC Tests +To test whether Spring MVC controllers are working as expected, use the `@WebMvcTest` +annotation. `@WebMvcTest` auto-configures the Spring MVC infrastructure and limits +scanned beans to `@Controller`, `@ControllerAdvice`, `@JsonComponent`, `Converter`, +`GenericConverter`, `Filter`, `WebMvcConfigurer`, and `HandlerMethodArgumentResolver`. +Regular `@Component` beans are not scanned when using this annotation. + +TIP: A list of the auto-configuration settings that are enabled by `@WebMvcTest` can be +<>. + +TIP: If you need to register extra components, such as the Jackson `Module`, you can +import additional configuration classes by using `@Import` on your test. + +Often, `@WebMvcTest` is limited to a single controller and is used in combination with +`@MockBean` to provide mock implementations for required collaborators. + +`@WebMvcTest` also auto-configures `MockMvc`. Mock MVC offers a powerful way to quickly +test MVC controllers without needing to start a full HTTP server. + +TIP: You can also auto-configure `MockMvc` in a non-`@WebMvcTest` (such as +`@SpringBootTest`) by annotating it with `@AutoConfigureMockMvc`. The following example +uses `MockMvc`: + +[source,java,indent=0] +---- + import org.junit.jupiter.api.*; + import org.springframework.beans.factory.annotation.*; + import org.springframework.boot.test.autoconfigure.web.servlet.*; + import org.springframework.boot.test.mock.mockito.*; + + import static org.assertj.core.api.Assertions.*; + import static org.mockito.BDDMockito.*; + import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; + import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + + @WebMvcTest(UserVehicleController.class) + class MyControllerTests { + + @Autowired + private MockMvc mvc; + + @MockBean + private UserVehicleService userVehicleService; + + @Test + void testExample() throws Exception { + given(this.userVehicleService.getVehicleDetails("sboot")) + .willReturn(new VehicleDetails("Honda", "Civic")); + this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)) + .andExpect(status().isOk()).andExpect(content().string("Honda Civic")); + } + + } +---- + +TIP: If you need to configure elements of the auto-configuration (for example, when +servlet filters should be applied) you can use attributes in the `@AutoConfigureMockMvc` +annotation. + +If you use HtmlUnit or Selenium, auto-configuration also provides an HTMLUnit `WebClient` +bean and/or a `WebDriver` bean. The following example uses HtmlUnit: + + +[source,java,indent=0] +---- + import com.gargoylesoftware.htmlunit.*; + import org.junit.jupiter.api.*; + import org.springframework.beans.factory.annotation.*; + import org.springframework.boot.test.autoconfigure.web.servlet.*; + import org.springframework.boot.test.mock.mockito.*; + + import static org.assertj.core.api.Assertions.*; + import static org.mockito.BDDMockito.*; + + @WebMvcTest(UserVehicleController.class) + class MyHtmlUnitTests { + + @Autowired + private WebClient webClient; + + @MockBean + private UserVehicleService userVehicleService; + + @Test + void testExample() throws Exception { + given(this.userVehicleService.getVehicleDetails("sboot")) + .willReturn(new VehicleDetails("Honda", "Civic")); + HtmlPage page = this.webClient.getPage("/sboot/vehicle.html"); + assertThat(page.getBody().getTextContent()).isEqualTo("Honda Civic"); + } + + } +---- + +NOTE: By default, Spring Boot puts `WebDriver` beans in a special "`scope`" to ensure +that the driver exits after each test and that a new instance is injected. If you do +not want this behavior, you can add `@Scope("singleton")` to your `WebDriver` `@Bean` +definition. + +WARNING: The `webDriver` scope created by Spring Boot will replace any user defined scope +of the same name. If you define your own `webDriver` scope you may find it stops working +when you use `@WebMvcTest`. + +If you have Spring Security on the classpath, `@WebMvcTest` will also scan `WebSecurityConfigurer` +beans. Instead of disabling security completely for such tests, you can use Spring Security's test support. +More details on how to use Spring Security's `MockMvc` support can be found in +this _<>_ how-to section. + +TIP: Sometimes writing Spring MVC tests is not enough; Spring Boot can help you run +<>. + + + +[[boot-features-testing-spring-boot-applications-testing-autoconfigured-webflux-tests]] +==== Auto-configured Spring WebFlux Tests +To test that {spring-reference}/web-reactive.html[Spring WebFlux] controllers are +working as expected, you can use the `@WebFluxTest` annotation. `@WebFluxTest` +auto-configures the Spring WebFlux infrastructure and limits scanned beans to +`@Controller`, `@ControllerAdvice`, `@JsonComponent`, `Converter`, `GenericConverter`, and +`WebFluxConfigurer`. Regular `@Component` beans are not scanned when the `@WebFluxTest` +annotation is used. + +TIP: A list of the auto-configurations that are enabled by `@WebFluxTest` can be +<>. + +TIP: If you need to register extra components, such as Jackson `Module`, you can import +additional configuration classes using `@Import` on your test. + +Often, `@WebFluxTest` is limited to a single controller and used in combination with the +`@MockBean` annotation to provide mock implementations for required collaborators. + +`@WebFluxTest` also auto-configures +{spring-reference}testing.html#webtestclient[`WebTestClient`], which offers +a powerful way to quickly test WebFlux controllers without needing to start a full HTTP +server. + +TIP: You can also auto-configure `WebTestClient` in a non-`@WebFluxTest` (such as +`@SpringBootTest`) by annotating it with `@AutoConfigureWebTestClient`. The following +example shows a class that uses both `@WebFluxTest` and a `WebTestClient`: + +[source,java,indent=0] +---- + import org.junit.jupiter.api.Test; + + import org.springframework.beans.factory.annotation.Autowired; + import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; + import org.springframework.http.MediaType; + import org.springframework.test.web.reactive.server.WebTestClient; + + @WebFluxTest(UserVehicleController.class) + class MyControllerTests { + + @Autowired + private WebTestClient webClient; + + @MockBean + private UserVehicleService userVehicleService; + + @Test + void testExample() throws Exception { + given(this.userVehicleService.getVehicleDetails("sboot")) + .willReturn(new VehicleDetails("Honda", "Civic")); + this.webClient.get().uri("/sboot/vehicle").accept(MediaType.TEXT_PLAIN) + .exchange() + .expectStatus().isOk() + .expectBody(String.class).isEqualTo("Honda Civic"); + } + + } +---- + +TIP: This setup is only supported by WebFlux applications as using `WebTestClient` in a +mocked web application only works with WebFlux at the moment. + +NOTE: `@WebFluxTest` cannot detect routes registered via the functional web framework. For +testing `RouterFunction` beans in the context, consider importing your `RouterFunction` +yourself via `@Import` or using `@SpringBootTest`. + +NOTE: `@WebFluxTest` cannot detect custom security configuration registered via a `@Bean` +of type `SecurityWebFilterChain`. To include that in your test, you will need to import +the configuration that registers the bean via `@Import` or use `@SpringBootTest`. + +TIP: Sometimes writing Spring WebFlux tests is not enough; Spring Boot can help you run +<>. + + + +[[boot-features-testing-spring-boot-applications-testing-autoconfigured-jpa-test]] +==== Auto-configured Data JPA Tests +You can use the `@DataJpaTest` annotation to test JPA applications. By default, it scans +for `@Entity` classes and configures Spring Data JPA repositories. If an embedded database +is available on the classpath, it configures one as well. Regular `@Component` beans are +not loaded into the `ApplicationContext`. + +TIP: A list of the auto-configuration settings that are enabled by `@DataJpaTest` can be +<>. + +By default, data JPA tests are transactional and roll back at the end of each test. See +the {spring-reference}testing.html#testcontext-tx-enabling-transactions[relevant section] +in the Spring Framework Reference Documentation for more details. If that is not what you +want, you can disable transaction management for a test or for the whole class as +follows: + +[source,java,indent=0] +---- + import org.junit.jupiter.api.Test; + import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; + import org.springframework.transaction.annotation.Propagation; + import org.springframework.transaction.annotation.Transactional; + + @DataJpaTest + @Transactional(propagation = Propagation.NOT_SUPPORTED) + class ExampleNonTransactionalTests { + + } +---- + +Data JPA tests may also inject a +{sc-spring-boot-test-autoconfigure}/orm/jpa/TestEntityManager.{sc-ext}[`TestEntityManager`] +bean, which provides an alternative to the standard JPA `EntityManager` that is +specifically designed for tests. If you want to use `TestEntityManager` outside of +`@DataJpaTest` instances, you can also use the `@AutoConfigureTestEntityManager` +annotation. A `JdbcTemplate` is also available if you need that. The following example +shows the `@DataJpaTest` annotation in use: + +[source,java,indent=0] +---- + import org.junit.jupiter.api.Test; + import org.springframework.boot.test.autoconfigure.orm.jpa.*; + + import static org.assertj.core.api.Assertions.*; + + @DataJpaTest + class ExampleRepositoryTests { + + @Autowired + private TestEntityManager entityManager; + + @Autowired + private UserRepository repository; + + @Test + void testExample() throws Exception { + this.entityManager.persist(new User("sboot", "1234")); + User user = this.repository.findByUsername("sboot"); + assertThat(user.getUsername()).isEqualTo("sboot"); + assertThat(user.getVin()).isEqualTo("1234"); + } + + } +---- + +In-memory embedded databases generally work well for tests, since they are fast and do +not require any installation. If, however, you prefer to run tests against a real +database you can use the `@AutoConfigureTestDatabase` annotation, as shown in the +following example: + +[source,java,indent=0] +---- + @DataJpaTest + @AutoConfigureTestDatabase(replace=Replace.NONE) + class ExampleRepositoryTests { + + // ... + + } +---- + + + +[[boot-features-testing-spring-boot-applications-testing-autoconfigured-jdbc-test]] +==== Auto-configured JDBC Tests +`@JdbcTest` is similar to `@DataJpaTest` but is for tests that only require a +`DataSource` and do not use Spring Data JDBC. By default, it configures an in-memory +embedded database and a `JdbcTemplate`. Regular `@Component` beans are not loaded into +the `ApplicationContext`. + +TIP: A list of the auto-configurations that are enabled by `@JdbcTest` can be +<>. + +By default, JDBC tests are transactional and roll back at the end of each test. See the +{spring-reference}testing.html#testcontext-tx-enabling-transactions[relevant section] in +the Spring Framework Reference Documentation for more details. If that is not what you +want, you can disable transaction management for a test or for the whole class, as +follows: + +[source,java,indent=0] +---- + import org.junit.jupiter.api.Test; + import org.springframework.boot.test.autoconfigure.jdbc.JdbcTest; + import org.springframework.transaction.annotation.Propagation; + import org.springframework.transaction.annotation.Transactional; + + @JdbcTest + @Transactional(propagation = Propagation.NOT_SUPPORTED) + class ExampleNonTransactionalTests { + + } +---- + +If you prefer your test to run against a real database, you can use the +`@AutoConfigureTestDatabase` annotation in the same way as for `DataJpaTest`. (See +"<>".) + + + +[[boot-features-testing-spring-boot-applications-testing-autoconfigured-data-jdbc-test]] +==== Auto-configured Data JDBC Tests +`@DataJdbcTest` is similar to `@JdbcTest` but is for tests that use Spring Data JDBC +repositories. By default, it configures an in-memory embedded database, a `JdbcTemplate`, +and Spring Data JDBC repositories. Regular `@Component` beans are not loaded into +the `ApplicationContext`. + +TIP: A list of the auto-configurations that are enabled by `@DataJdbcTest` can be +<>. + +By default, Data JDBC tests are transactional and roll back at the end of each test. See +the {spring-reference}testing.html#testcontext-tx-enabling-transactions[relevant section] +in the Spring Framework Reference Documentation for more details. If that is not what you +want, you can disable transaction management for a test or for the whole test class as +<>. + +If you prefer your test to run against a real database, you can use the +`@AutoConfigureTestDatabase` annotation in the same way as for `DataJpaTest`. (See +"<>".) + + + +[[boot-features-testing-spring-boot-applications-testing-autoconfigured-jooq-test]] +==== Auto-configured jOOQ Tests +You can use `@JooqTest` in a similar fashion as `@JdbcTest` but for jOOQ-related tests. +As jOOQ relies heavily on a Java-based schema that corresponds with the database schema, +the existing `DataSource` is used. If you want to replace it with an in-memory database, +you can use `@AutoConfigureTestDatabase` to override those settings. (For more about using +jOOQ with Spring Boot, see "<>", earlier in this chapter.) Regular +`@Component` beans are not loaded into the `ApplicationContext`. + +TIP: A list of the auto-configurations that are enabled by `@JooqTest` can be +<>. + +`@JooqTest` configures a `DSLContext`. Regular `@Component` beans are not loaded into the +`ApplicationContext`. The following example shows the `@JooqTest` annotation in use: + +[source,java,indent=0] +---- + import org.jooq.DSLContext; + import org.junit.jupiter.api.Test; + import org.springframework.boot.test.autoconfigure.jooq.JooqTest; + + @JooqTest + class ExampleJooqTests { + + @Autowired + private DSLContext dslContext; + } +---- + +JOOQ tests are transactional and roll back at the end of each test by default. If that is +not what you want, you can disable transaction management for a test or for the whole +test class as +<>. + + + + +[[boot-features-testing-spring-boot-applications-testing-autoconfigured-mongo-test]] +==== Auto-configured Data MongoDB Tests +You can use `@DataMongoTest` to test MongoDB applications. By default, it configures an +in-memory embedded MongoDB (if available), configures a `MongoTemplate`, scans for +`@Document` classes, and configures Spring Data MongoDB repositories. Regular +`@Component` beans are not loaded into the `ApplicationContext`. (For more about using +MongoDB with Spring Boot, see "<>", earlier in this chapter.) + +TIP: A list of the auto-configuration settings that are enabled by `@DataMongoTest` can be +<>. + +The following class shows the `@DataMongoTest` annotation in use: + +[source,java,indent=0] +---- + import org.springframework.beans.factory.annotation.Autowired; + import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest; + import org.springframework.data.mongodb.core.MongoTemplate; + + @DataMongoTest + class ExampleDataMongoTests { + + @Autowired + private MongoTemplate mongoTemplate; + + // + } +---- + +In-memory embedded MongoDB generally works well for tests, since it is fast and does not +require any developer installation. If, however, you prefer to run tests against a real +MongoDB server, you should exclude the embedded MongoDB auto-configuration, as shown in +the following example: + +[source,java,indent=0] +---- + import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration; + import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest; + + @DataMongoTest(excludeAutoConfiguration = EmbeddedMongoAutoConfiguration.class) + class ExampleDataMongoNonEmbeddedTests { + + } +---- + + + + +[[boot-features-testing-spring-boot-applications-testing-autoconfigured-neo4j-test]] +==== Auto-configured Data Neo4j Tests +You can use `@DataNeo4jTest` to test Neo4j applications. By default, it uses an in-memory +embedded Neo4j (if the embedded driver is available), scans for `@NodeEntity` classes, and +configures Spring Data Neo4j repositories. Regular `@Component` beans are not loaded into +the `ApplicationContext`. (For more about using Neo4J with Spring Boot, see +"<>", earlier in this chapter.) + +TIP: A list of the auto-configuration settings that are enabled by `@DataNeo4jTest` can be +<>. + +The following example shows a typical setup for using Neo4J tests in Spring Boot: + +[source,java,indent=0] +---- + import org.springframework.beans.factory.annotation.Autowired; + import org.springframework.boot.test.autoconfigure.data.neo4j.DataNeo4jTest; + + @DataNeo4jTest + class ExampleDataNeo4jTests { + + @Autowired + private YourRepository repository; + + // + } +---- + +By default, Data Neo4j tests are transactional and roll back at the end of each test. +See the {spring-reference}testing.html#testcontext-tx-enabling-transactions[relevant +section] in the Spring Framework Reference Documentation for more details. If that is not +what you want, you can disable transaction management for a test or for the whole class, +as follows: + +[source,java,indent=0] +---- + import org.springframework.boot.test.autoconfigure.data.neo4j.DataNeo4jTest; + import org.springframework.transaction.annotation.Propagation; + import org.springframework.transaction.annotation.Transactional; + + @DataNeo4jTest + @Transactional(propagation = Propagation.NOT_SUPPORTED) + class ExampleNonTransactionalTests { + + } +---- + + + + +[[boot-features-testing-spring-boot-applications-testing-autoconfigured-redis-test]] +==== Auto-configured Data Redis Tests +You can use `@DataRedisTest` to test Redis applications. By default, it scans for +`@RedisHash` classes and configures Spring Data Redis repositories. Regular `@Component` +beans are not loaded into the `ApplicationContext`. (For more about using Redis with +Spring Boot, see "<>", earlier in this chapter.) + +TIP: A list of the auto-configuration settings that are enabled by `@DataRedisTest` can be +<>. + +The following example shows the `@DataRedisTest` annotation in use: + +[source,java,indent=0] +---- + import org.springframework.beans.factory.annotation.Autowired; + import org.springframework.boot.test.autoconfigure.data.redis.DataRedisTest; + + @DataRedisTest + class ExampleDataRedisTests { + + @Autowired + private YourRepository repository; + + // + } +---- + + + +[[boot-features-testing-spring-boot-applications-testing-autoconfigured-ldap-test]] +==== Auto-configured Data LDAP Tests +You can use `@DataLdapTest` to test LDAP applications. By default, it configures an +in-memory embedded LDAP (if available), configures an `LdapTemplate`, scans for `@Entry` +classes, and configures Spring Data LDAP repositories. Regular `@Component` beans are not +loaded into the `ApplicationContext`. (For more about using LDAP with +Spring Boot, see "<>", earlier in this chapter.) + +TIP: A list of the auto-configuration settings that are enabled by `@DataLdapTest` can be +<>. + +The following example shows the `@DataLdapTest` annotation in use: + +[source,java,indent=0] +---- + import org.springframework.beans.factory.annotation.Autowired; + import org.springframework.boot.test.autoconfigure.data.ldap.DataLdapTest; + import org.springframework.ldap.core.LdapTemplate; + + @DataLdapTest + class ExampleDataLdapTests { + + @Autowired + private LdapTemplate ldapTemplate; + + // + } +---- + +In-memory embedded LDAP generally works well for tests, since it is fast and does not +require any developer installation. If, however, you prefer to run tests against a real +LDAP server, you should exclude the embedded LDAP auto-configuration, as shown in the +following example: + +[source,java,indent=0] +---- + import org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration; + import org.springframework.boot.test.autoconfigure.data.ldap.DataLdapTest; + + @DataLdapTest(excludeAutoConfiguration = EmbeddedLdapAutoConfiguration.class) + class ExampleDataLdapNonEmbeddedTests { + + } +---- + + + +[[boot-features-testing-spring-boot-applications-testing-autoconfigured-rest-client]] +==== Auto-configured REST Clients +You can use the `@RestClientTest` annotation to test REST clients. By default, it +auto-configures Jackson, GSON, and Jsonb support, configures a `RestTemplateBuilder`, and +adds support for `MockRestServiceServer`. Regular `@Component` beans are not loaded into +the `ApplicationContext`. + +TIP: A list of the auto-configuration settings that are enabled by `@RestClientTest` can +be <>. + +The specific beans that you want to test should be specified by using the `value` or +`components` attribute of `@RestClientTest`, as shown in the following example: + +[source,java,indent=0] +---- + @RestClientTest(RemoteVehicleDetailsService.class) + class ExampleRestClientTest { + + @Autowired + private RemoteVehicleDetailsService service; + + @Autowired + private MockRestServiceServer server; + + @Test + void getVehicleDetailsWhenResultIsSuccessShouldReturnDetails() + throws Exception { + this.server.expect(requestTo("/greet/details")) + .andRespond(withSuccess("hello", MediaType.TEXT_PLAIN)); + String greeting = this.service.callRestService(); + assertThat(greeting).isEqualTo("hello"); + } + + } +---- + + + +[[boot-features-testing-spring-boot-applications-testing-autoconfigured-rest-docs]] +==== Auto-configured Spring REST Docs Tests +You can use the `@AutoConfigureRestDocs` annotation to use {spring-rest-docs}[Spring REST +Docs] in your tests with Mock MVC, REST Assured, or WebTestClient. It removes the need for +the JUnit extension in Spring REST Docs. + +`@AutoConfigureRestDocs` can be used to override the default output directory +(`target/generated-snippets` if you are using Maven or `build/generated-snippets` if you +are using Gradle). It can also be used to configure the host, scheme, and port that +appears in any documented URIs. + + + +[[boot-features-testing-spring-boot-applications-testing-autoconfigured-rest-docs-mock-mvc]] +===== Auto-configured Spring REST Docs Tests with Mock MVC +`@AutoConfigureRestDocs` customizes the `MockMvc` bean to use Spring REST Docs. You can +inject it by using `@Autowired` and use it in your tests as you normally would when using +Mock MVC and Spring REST Docs, as shown in the following example: + +[source,java,indent=0] +---- + import org.junit.jupiter.api.Test; + + import org.springframework.beans.factory.annotation.Autowired; + import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; + import org.springframework.http.MediaType; + import org.springframework.test.web.servlet.MockMvc; + + import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; + import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; + import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + + @WebMvcTest(UserController.class) + @AutoConfigureRestDocs + class UserDocumentationTests { + + @Autowired + private MockMvc mvc; + + @Test + void listUsers() throws Exception { + this.mvc.perform(get("/users").accept(MediaType.TEXT_PLAIN)) + .andExpect(status().isOk()) + .andDo(document("list-users")); + } + + } +---- + +If you require more control over Spring REST Docs configuration than offered by the +attributes of `@AutoConfigureRestDocs`, you can use a +`RestDocsMockMvcConfigurationCustomizer` bean, as shown in the following example: + +[source,java,indent=0] +---- + @TestConfiguration + static class CustomizationConfiguration + implements RestDocsMockMvcConfigurationCustomizer { + + @Override + public void customize(MockMvcRestDocumentationConfigurer configurer) { + configurer.snippets().withTemplateFormat(TemplateFormats.markdown()); + } + + } +---- + +If you want to make use of Spring REST Docs support for a parameterized output directory, +you can create a `RestDocumentationResultHandler` bean. The auto-configuration calls +`alwaysDo` with this result handler, thereby causing each `MockMvc` call to automatically +generate the default snippets. The following example shows a +`RestDocumentationResultHandler` being defined: + +[source,java,indent=0] +---- + @TestConfiguration + static class ResultHandlerConfiguration { + + @Bean + public RestDocumentationResultHandler restDocumentation() { + return MockMvcRestDocumentation.document("{method-name}"); + } + + } +---- + + + +[[boot-features-testing-spring-boot-applications-testing-autoconfigured-rest-docs-web-test-client]] +===== Auto-configured Spring REST Docs Tests with WebTestClient +`@AutoConfigureRestDocs` can also be used with `WebTestClient`. You can inject it by using +`@Autowired` and use it in your tests as you normally would when using `@WebFluxTest` and +Spring REST Docs, as shown in the following example: + +[source,java,indent=0] +---- +include::{code-examples}/test/autoconfigure/restdocs/webclient/UsersDocumentationTests.java[tag=source] +---- + +If you require more control over Spring REST Docs configuration than offered by the +attributes of `@AutoConfigureRestDocs`, you can use a +`RestDocsWebTestClientConfigurationCustomizer` bean, as shown in the following example: + +[source,java,indent=0] +---- +include::{code-examples}/test/autoconfigure/restdocs/webclient/AdvancedConfigurationExample.java[tag=configuration] +---- + + + +[[boot-features-testing-spring-boot-applications-testing-autoconfigured-rest-docs-rest-assured]] +===== Auto-configured Spring REST Docs Tests with REST Assured +`@AutoConfigureRestDocs` makes a `RequestSpecification` bean, preconfigured to use Spring +REST Docs, available to your tests. You can inject it by using `@Autowired` and use it in +your tests as you normally would when using REST Assured and Spring REST Docs, as shown +in the following example: + +[source,java,indent=0] +---- +include::{code-examples}/test/autoconfigure/restdocs/restassured/UserDocumentationTests.java[tag=source] +---- + +If you require more control over Spring REST Docs configuration than offered by the +attributes of `@AutoConfigureRestDocs`, a `RestDocsRestAssuredConfigurationCustomizer` +bean can be used, as shown in the following example: + +[source,java,indent=0] +---- +include::{code-examples}/test/autoconfigure/restdocs/restassured/AdvancedConfigurationExample.java[tag=configuration] +---- + + + +[[boot-features-testing-spring-boot-applications-testing-auto-configured-additional-auto-config]] +==== Additional Auto-configuration and Slicing +Each slice provides one or more `@AutoConfigure...` annotations that namely defines the +auto-configurations that should be included as part of a slice. Additional +auto-configurations can be added by creating a custom `@AutoConfigure...` annotation or +simply by adding `@ImportAutoConfiguration` to the test as shown in the following example: + +[source,java,indent=0] +---- + @JdbcTest + @ImportAutoConfiguration(IntegrationAutoConfiguration.class) + class ExampleJdbcTests { + + } +---- + +NOTE: Make sure to not use the regular `@Import` annotation to import auto-configurations +as they are handled in a specific way by Spring Boot. + + + +[[boot-features-testing-spring-boot-applications-testing-user-configuration]] +==== User Configuration and Slicing +If you <> in a sensible way, your +`@SpringBootApplication` class is +<> as +the configuration of your tests. + +It then becomes important not to litter the application's main class with configuration +settings that are specific to a particular area of its functionality. + +Assume that you are using Spring Batch and you rely on the auto-configuration for it. +You could define your `@SpringBootApplication` as follows: + +[source,java,indent=0] +---- + @SpringBootApplication + @EnableBatchProcessing + public class SampleApplication { ... } +---- + +Because this class is the source configuration for the test, any slice test actually +tries to start Spring Batch, which is definitely not what you want to do. A recommended +approach is to move that area-specific configuration to a separate `@Configuration` class +at the same level as your application, as shown in the following example: + +[source,java,indent=0] +---- + @Configuration(proxyBeanMethods = false) + @EnableBatchProcessing + public class BatchConfiguration { ... } +---- + +NOTE: Depending on the complexity of your application, you may either have a single +`@Configuration` class for your customizations or one class per domain area. The latter +approach lets you enable it in one of your tests, if necessary, with the `@Import` +annotation. + +Test slices exclude `@Configuration` classes from scanning. For example, for a `@WebMvcTest`, +the following configuration will not include the given `WebMvcConfigurer` bean in the application +context loaded by the test slice: + +[source,java,indent=0] +---- + @Configuration + public class WebConfiguration { + @Bean + public WebMvcConfigurer testConfigurer() { + return new WebMvcConfigurer() { + ... + }; + } + } +---- + +The configuration below will, however, cause the custom `WebMvcConfigurer` to be loaded +by the test slice. + +[source,java,indent=0] +---- + @Component + public class TestWebMvcConfigurer implements WebMvcConfigurer { + ... + } +---- + +Another source of confusion is classpath scanning. Assume that, while you structured your +code in a sensible way, you need to scan an additional package. Your application may +resemble the following code: + +[source,java,indent=0] +---- + @SpringBootApplication + @ComponentScan({ "com.example.app", "org.acme.another" }) + public class SampleApplication { ... } +---- + +Doing so effectively overrides the default component scan directive with the side effect +of scanning those two packages regardless of the slice that you chose. For instance, a +`@DataJpaTest` seems to suddenly scan components and user configurations of your +application. Again, moving the custom directive to a separate class is a good way to fix +this issue. + +TIP: If this is not an option for you, you can create a `@SpringBootConfiguration` +somewhere in the hierarchy of your test so that it is used instead. Alternatively, you +can specify a source for your test, which disables the behavior of finding a default one. + + + +[[boot-features-testing-spring-boot-applications-with-spock]] +==== Using Spock to Test Spring Boot Applications +If you wish to use Spock to test a Spring Boot application, you should add a dependency +on Spock's `spock-spring` module to your application's build. `spock-spring` integrates +Spring's test framework into Spock. It is recommended that you use Spock 1.2 or later to +benefit from a number of improvements to Spock's Spring Framework and Spring Boot +integration. See http://spockframework.org/spock/docs/1.2/modules.html#_spring_module[the +documentation for Spock's Spring module] for further details. + + + +[[boot-features-test-utilities]] +=== Test Utilities +A few test utility classes that are generally useful when testing your application are +packaged as part of `spring-boot`. + + + +[[boot-features-configfileapplicationcontextinitializer-test-utility]] +==== ConfigFileApplicationContextInitializer +`ConfigFileApplicationContextInitializer` is an `ApplicationContextInitializer` that you +can apply to your tests to load Spring Boot `application.properties` files. You can use +it when you do not need the full set of features provided by `@SpringBootTest`, as shown +in the following example: + +[source,java,indent=0] +---- + @ContextConfiguration(classes = Config.class, + initializers = ConfigFileApplicationContextInitializer.class) +---- + +NOTE: Using `ConfigFileApplicationContextInitializer` alone does not provide support for +`@Value("${...}")` injection. Its only job is to ensure that `application.properties` +files are loaded into Spring's `Environment`. For `@Value` support, you need to either +additionally configure a `PropertySourcesPlaceholderConfigurer` or use `@SpringBootTest`, +which auto-configures one for you. + + + +[[boot-features-test-property-values]] +==== TestPropertyValues +`TestPropertyValues` lets you quickly add properties to a +`ConfigurableEnvironment` or `ConfigurableApplicationContext`. You can call it with +`key=value` strings, as follows: + +[source,java,indent=0] +---- + TestPropertyValues.of("org=Spring", "name=Boot").applyTo(env); +---- + + + +[[boot-features-output-capture-test-utility]] +==== OutputCapture +`OutputCapture` is a JUnit `Extension` that you can use to capture `System.out` and +`System.err` output. To use with {@link ExtendWith @ExtendWith}, you can inject +`CapturedOutput` as an argument to your test class constructor or test method as follows: + +[source,java,indent=0] +---- + import org.junit.jupiter.api.Test; + import org.junit.jupiter.api.extension.ExtendWith; + + import org.springframework.boot.test.system.CapturedOutput; + import org.springframework.boot.test.system.OutputCaptureExtension; + + import static org.assertj.core.api.Assertions.assertThat; + + @ExtendWith(OutputCaptureExtension.class) + class MyTest { + + @Test + void testName(CapturedOutput output) { + System.out.println("Hello World!"); + assertThat(output).contains("World")); + } + + } +---- + +[[boot-features-rest-templates-test-utility]] +==== TestRestTemplate + +TIP: Spring Framework 5.0 provides a new `WebTestClient` that works for +<> and both +<>. It provides a fluent API for assertions, +unlike `TestRestTemplate`. + + +`TestRestTemplate` is a convenience alternative to Spring's `RestTemplate` that is useful +in integration tests. You can get a vanilla template or one that sends Basic HTTP +authentication (with a username and password). In either case, the template behaves in a +test-friendly way by not throwing exceptions on server-side errors. It is recommended, +but not mandatory, to use the Apache HTTP Client (version 4.3.2 or better). If you have +that on your classpath, the `TestRestTemplate` responds by configuring the client +appropriately. If you do use Apache's HTTP client, some additional test-friendly features +are enabled: + +* Redirects are not followed (so you can assert the response location). +* Cookies are ignored (so the template is stateless). + +`TestRestTemplate` can be instantiated directly in your integration tests, as shown in +the following example: + +[source,java,indent=0] +---- + public class MyTest { + + private TestRestTemplate template = new TestRestTemplate(); + + @Test + public void testRequest() throws Exception { + HttpHeaders headers = this.template.getForEntity( + "https://myhost.example.com/example", String.class).getHeaders(); + assertThat(headers.getLocation()).hasHost("other.example.com"); + } + + } +---- + +Alternatively, if you use the `@SpringBootTest` annotation with +`WebEnvironment.RANDOM_PORT` or `WebEnvironment.DEFINED_PORT`, you can inject a +fully configured `TestRestTemplate` and start using it. If necessary, additional +customizations can be applied through the `RestTemplateBuilder` bean. Any URLs that do +not specify a host and port automatically connect to the embedded server, as shown in the +following example: + +[source,java,indent=0] +---- +include::{test-examples}/web/client/SampleWebClientTests.java[tag=test] +---- + + + +[[boot-features-websockets]] +== WebSockets +Spring Boot provides WebSockets auto-configuration for embedded Tomcat, Jetty, and +Undertow. If you deploy a war file to a standalone container, Spring Boot assumes that the +container is responsible for the configuration of its WebSocket support. + +Spring Framework provides {spring-reference}web.html#websocket[rich WebSocket support] +for MVC web applications that can be easily accessed through the +`spring-boot-starter-websocket` module. + +WebSocket support is also available for +{spring-reference}web-reactive.html#webflux-websocket[reactive web applications] and +requires to include the WebSocket API alongside `spring-boot-starter-webflux`: + +[source,xml,indent=0,subs="verbatim,quotes,attributes"] +---- + + javax.websocket + javax.websocket-api + +---- + + + +[[boot-features-webservices]] +== Web Services +Spring Boot provides Web Services auto-configuration so that all you must do is define +your `Endpoints`. + +The {spring-webservices-reference}[Spring Web Services features] can be easily accessed +with the `spring-boot-starter-webservices` module. + +`SimpleWsdl11Definition` and `SimpleXsdSchema` beans can be automatically created for +your WSDLs and XSDs respectively. To do so, configure their location, as shown in the +following example: + + +[source,properties,indent=0] +---- + spring.webservices.wsdl-locations=classpath:/wsdl +---- + + + +[[boot-features-webservices-template]] +=== Calling Web Services with `WebServiceTemplate` +If you need to call remote Web services from your application, you can use the +{spring-webservices-reference}#client-web-service-template[`WebServiceTemplate`] class. +Since `WebServiceTemplate` instances often need to be customized before being used, Spring +Boot does not provide any single auto-configured `WebServiceTemplate` bean. It does, +however, auto-configure a `WebServiceTemplateBuilder`, which can be used to create +`WebServiceTemplate` instances when needed. + +The following code shows a typical example: + +[source,java,indent=0] +---- + @Service + public class MyService { + + private final WebServiceTemplate webServiceTemplate; + + public MyService(WebServiceTemplateBuilder webServiceTemplateBuilder) { + this.webServiceTemplate = webServiceTemplateBuilder.build(); + } + + public DetailsResp someWsCall(DetailsReq detailsReq) { + return (DetailsResp) this.webServiceTemplate.marshalSendAndReceive(detailsReq, new SoapActionCallback(ACTION)); + + } + + } +---- + +By default, `WebServiceTemplateBuilder` detects a suitable HTTP-based +`WebServiceMessageSender` using the available HTTP client libraries on the classpath. You +can also customize read and connection timeouts as follows: + +[source,java,indent=0] +---- + @Bean + public WebServiceTemplate webServiceTemplate(WebServiceTemplateBuilder builder) { + return builder.messageSenders(new HttpWebServiceMessageSenderBuilder() + .setConnectTimeout(5000).setReadTimeout(2000).build()).build(); + } +---- + + + +[[boot-features-developing-auto-configuration]] +== Creating Your Own Auto-configuration +If you work in a company that develops shared libraries, or if you work on an open-source +or commercial library, you might want to develop your own auto-configuration. +Auto-configuration classes can be bundled in external jars and still be picked-up by +Spring Boot. + +Auto-configuration can be associated to a "`starter`" that provides the auto-configuration +code as well as the typical libraries that you would use with it. We first cover what +you need to know to build your own auto-configuration and then we move on to the +<>. + +TIP: A https://github.com/snicoll-demos/spring-boot-master-auto-configuration[demo +project] is available to showcase how you can create a starter step-by-step. + + + +[[boot-features-understanding-auto-configured-beans]] +=== Understanding Auto-configured Beans +Under the hood, auto-configuration is implemented with standard `@Configuration` classes. +Additional `@Conditional` annotations are used to constrain when the auto-configuration +should apply. Usually, auto-configuration classes use `@ConditionalOnClass` and +`@ConditionalOnMissingBean` annotations. This ensures that auto-configuration applies +only when relevant classes are found and when you have not declared your own +`@Configuration`. + +You can browse the source code of {sc-spring-boot-autoconfigure}[`spring-boot-autoconfigure`] +to see the `@Configuration` classes that Spring provides (see the +{github-code}/spring-boot-project/spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories[`META-INF/spring.factories`] +file). + + + +[[boot-features-locating-auto-configuration-candidates]] +=== Locating Auto-configuration Candidates +Spring Boot checks for the presence of a `META-INF/spring.factories` file within your +published jar. The file should list your configuration classes under the +`EnableAutoConfiguration` key, as shown in the following example: + +[indent=0] +---- + org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ + com.mycorp.libx.autoconfigure.LibXAutoConfiguration,\ + com.mycorp.libx.autoconfigure.LibXWebAutoConfiguration +---- + +[NOTE] +==== +Auto-configurations must be loaded that way _only_. Make sure that they are defined in +a specific package space and that they are never the target of component scanning. +Furthermore, auto-configuration classes should not enable component scanning to find +additional components. Specific ``@Import``s should be used instead. +==== + +You can use the +{sc-spring-boot-autoconfigure}/AutoConfigureAfter.{sc-ext}[`@AutoConfigureAfter`] or +{sc-spring-boot-autoconfigure}/AutoConfigureBefore.{sc-ext}[`@AutoConfigureBefore`] +annotations if your configuration needs to be applied in a specific order. For example, +if you provide web-specific configuration, your class may need to be applied after +`WebMvcAutoConfiguration`. + +If you want to order certain auto-configurations that should not have any direct +knowledge of each other, you can also use `@AutoConfigureOrder`. That annotation has the +same semantic as the regular `@Order` annotation but provides a dedicated order for +auto-configuration classes. + + + +[[boot-features-condition-annotations]] +=== Condition Annotations +You almost always want to include one or more `@Conditional` annotations on your +auto-configuration class. The `@ConditionalOnMissingBean` annotation is one common +example that is used to allow developers to override auto-configuration if they are +not happy with your defaults. + +Spring Boot includes a number of `@Conditional` annotations that you can reuse in your +own code by annotating `@Configuration` classes or individual `@Bean` methods. These +annotations include: + +* <> +* <> +* <> +* <> +* <> +* <> + + +[[boot-features-class-conditions]] +==== Class Conditions +The `@ConditionalOnClass` and `@ConditionalOnMissingClass` annotations let +`@Configuration` classes be included based on the presence or absence of specific classes. +Due to the fact that annotation metadata is parsed by using https://asm.ow2.org/[ASM], you +can use the `value` attribute to refer to the real class, even though that class might not +actually appear on the running application classpath. You can also use the `name` +attribute if you prefer to specify the class name by using a `String` value. + +This mechanism does not apply the same way to `@Bean` methods where typically the return +type is the target of the condition: before the condition on the method applies, the JVM +will have loaded the class and potentially processed method references which will fail if +the class is not present. + +To handle this scenario, a separate `@Configuration` class can be used to isolate the +condition, as shown in the following example: + +[source,java,indent=0] +---- + @Configuration(proxyBeanMethods = false) + // Some conditions + public class MyAutoConfiguration { + + // Auto-configured beans + + @Configuration(proxyBeanMethods = false) + @ConditionalOnClass(EmbeddedAcmeService.class) + static class EmbeddedConfiguration { + + @Bean + @ConditionalOnMissingBean + public EmbeddedAcmeService embeddedAcmeService() { ... } + + } + + } +---- + +[TIP] +==== +If you use `@ConditionalOnClass` or `@ConditionalOnMissingClass` as a part of a +meta-annotation to compose your own composed annotations, you must use `name` as referring +to the class in such a case is not handled. +==== + + + +[[boot-features-bean-conditions]] +==== Bean Conditions +The `@ConditionalOnBean` and `@ConditionalOnMissingBean` annotations let a bean be +included based on the presence or absence of specific beans. You can use the `value` +attribute to specify beans by type or `name` to specify beans by name. The `search` +attribute lets you limit the `ApplicationContext` hierarchy that should be considered +when searching for beans. + +When placed on a `@Bean` method, the target type defaults to the return type of the +method, as shown in the following example: + +[source,java,indent=0] +---- + @Configuration(proxyBeanMethods = false) + public class MyAutoConfiguration { + + @Bean + @ConditionalOnMissingBean + public MyService myService() { ... } + + } +---- + +In the preceding example, the `myService` bean is going to be created if no bean of type +`MyService` is already contained in the `ApplicationContext`. + +TIP: You need to be very careful about the order in which bean definitions are added, as +these conditions are evaluated based on what has been processed so far. For this reason, +we recommend using only `@ConditionalOnBean` and `@ConditionalOnMissingBean` annotations +on auto-configuration classes (since these are guaranteed to load after any user-defined +bean definitions have been added). + +NOTE: `@ConditionalOnBean` and `@ConditionalOnMissingBean` do not prevent `@Configuration` +classes from being created. The only difference between using these conditions at the class level +and marking each contained `@Bean` method with the annotation is that the former prevents +registration of the `@Configuration` class as a bean if the condition does not match. + + + +[[boot-features-property-conditions]] +==== Property Conditions +The `@ConditionalOnProperty` annotation lets configuration be included based on a Spring +Environment property. Use the `prefix` and `name` attributes to specify the property that +should be checked. By default, any property that exists and is not equal to `false` is +matched. You can also create more advanced checks by using the `havingValue` and +`matchIfMissing` attributes. + + + +[[boot-features-resource-conditions]] +==== Resource Conditions +The `@ConditionalOnResource` annotation lets configuration be included only when a +specific resource is present. Resources can be specified by using the usual Spring +conventions, as shown in the following example: `file:/home/user/test.dat`. + + + +[[boot-features-web-application-conditions]] +==== Web Application Conditions +The `@ConditionalOnWebApplication` and `@ConditionalOnNotWebApplication` annotations let +configuration be included depending on whether the application is a "`web application`". +A web application is any application that uses a Spring `WebApplicationContext`, +defines a `session` scope, or has a `StandardServletEnvironment`. + + + +[[boot-features-spel-conditions]] +==== SpEL Expression Conditions +The `@ConditionalOnExpression` annotation lets configuration be included based on the +result of a {spring-reference}core.html#expressions[SpEL expression]. + + + +[[boot-features-test-autoconfig]] +=== Testing your Auto-configuration +An auto-configuration can be affected by many factors: user configuration (`@Bean` +definition and `Environment` customization), condition evaluation (presence of a +particular library), and others. Concretely, each test should create a well defined +`ApplicationContext` that represents a combination of those customizations. +`ApplicationContextRunner` provides a great way to achieve that. + +`ApplicationContextRunner` is usually defined as a field of the test class to gather the +base, common configuration. The following example makes sure that +`UserServiceAutoConfiguration` is always invoked: + +[source,java,indent=0] +---- +include::{test-examples}/autoconfigure/UserServiceAutoConfigurationTests.java[tag=runner] +---- + +TIP: If multiple auto-configurations have to be defined, there is no need to order their +declarations as they are invoked in the exact same order as when running the +application. + +Each test can use the runner to represent a particular use case. For instance, the sample +below invokes a user configuration (`UserConfiguration`) and checks that the +auto-configuration backs off properly. Invoking `run` provides a callback context that can +be used with `Assert4J`. + +[source,java,indent=0] +---- +include::{test-examples}/autoconfigure/UserServiceAutoConfigurationTests.java[tag=test-user-config] +---- + +It is also possible to easily customize the `Environment`, as shown in the following +example: + +[source,java,indent=0] +---- +include::{test-examples}/autoconfigure/UserServiceAutoConfigurationTests.java[tag=test-env] +---- + +The runner can also be used to display the `ConditionEvaluationReport`. The report can be printed +at `INFO` or `DEBUG` level. The following example shows how to use the `ConditionEvaluationReportLoggingListener` +to print the report in auto-configuration tests. + +[source,java,indent=0] +---- + @Test + public void autoConfigTest { + ConditionEvaluationReportLoggingListener initializer = new ConditionEvaluationReportLoggingListener( + LogLevel.INFO); + ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withInitializer(initializer).run((context) -> { + // Do something... + }); + } +---- + + + +==== Simulating a Web Context +If you need to test an auto-configuration that only operates in a Servlet or Reactive web +application context, use the `WebApplicationContextRunner` or +`ReactiveWebApplicationContextRunner` respectively. + + + +==== Overriding the Classpath +It is also possible to test what happens when a particular class and/or package is not +present at runtime. Spring Boot ships with a `FilteredClassLoader` that can easily be used +by the runner. In the following example, we assert that if `UserService` is not present, the +auto-configuration is properly disabled: + +[source,java,indent=0] +---- +include::{test-examples}/autoconfigure/UserServiceAutoConfigurationTests.java[tag=test-classloader] +---- + + + +[[boot-features-custom-starter]] +=== Creating Your Own Starter +A full Spring Boot starter for a library may contain the following components: + +* The `autoconfigure` module that contains the auto-configuration code. +* The `starter` module that provides a dependency to the `autoconfigure` module as well +as the library and any additional dependencies that are typically useful. In a nutshell, +adding the starter should provide everything needed to start using that library. + +TIP: You may combine the auto-configuration code and the dependency management in a +single module if you do not need to separate those two concerns. + + + +[[boot-features-custom-starter-naming]] +==== Naming +You should make sure to provide a proper namespace for your starter. Do not start your +module names with `spring-boot`, even if you use a different Maven `groupId`. We may +offer official support for the thing you auto-configure in the future. + +As a rule of thumb, you should name a combined module after the starter. For example, +assume that you are creating a starter for "acme" and that you name the auto-configure +module `acme-spring-boot-autoconfigure` and the starter `acme-spring-boot-starter`. If +you only have one module that combines the two, name it `acme-spring-boot-starter`. + +Also, if your starter provides configuration keys, use a unique namespace for them. In +particular, do not include your keys in the namespaces that Spring Boot uses (such as +`server`, `management`, `spring`, and so on). If you use the same namespace, we may modify +these namespaces in the future in ways that break your modules. + +Make sure to +<> so that IDE assistance is available for your keys as well. You may want to +review the generated meta-data (`META-INF/spring-configuration-metadata.json`) to make +sure your keys are properly documented. + + + +[[boot-features-custom-starter-module-autoconfigure]] +==== `autoconfigure` Module +The `autoconfigure` module contains everything that is necessary to get started with the +library. It may also contain configuration key definitions (such as +`@ConfigurationProperties`) and any callback interface that can be used to further +customize how the components are initialized. + +TIP: You should mark the dependencies to the library as optional so that you can include +the `autoconfigure` module in your projects more easily. If you do it that way, the +library is not provided and, by default, Spring Boot backs off. + +Spring Boot uses an annotation processor to collect the conditions on auto-configurations +in a metadata file (`META-INF/spring-autoconfigure-metadata.properties`). If that file is +present, it is used to eagerly filter auto-configurations that do not match, which will +improve startup time. It is recommended to add the following dependency in a module that +contains auto-configurations: + +[source,xml,indent=0,subs="verbatim,quotes,attributes"] +---- + + org.springframework.boot + spring-boot-autoconfigure-processor + true + +---- + +With Gradle 4.5 and earlier, the dependency should be declared in the `compileOnly` +configuration, as shown in the following example: + +[source,groovy,indent=0,subs="verbatim,quotes,attributes"] +---- + dependencies { + compileOnly "org.springframework.boot:spring-boot-autoconfigure-processor" + } +---- + +With Gradle 4.6 and later, the dependency should be declared in the `annotationProcessor` +configuration, as shown in the following example: + +[source,groovy,indent=0,subs="verbatim,quotes,attributes"] +---- + dependencies { + annotationProcessor "org.springframework.boot:spring-boot-autoconfigure-processor" + } +---- + + + +[[boot-features-custom-starter-module-starter]] +==== Starter Module +The starter is really an empty jar. Its only purpose is to provide the necessary +dependencies to work with the library. You can think of it as an opinionated view of what +is required to get started. + +Do not make assumptions about the project in which your starter is added. If the library +you are auto-configuring typically requires other starters, mention them as well. +Providing a proper set of _default_ dependencies may be hard if the number of optional +dependencies is high, as you should avoid including dependencies that are unnecessary for +a typical usage of the library. In other words, you should not include optional +dependencies. + +NOTE: Either way, your starter must reference the core Spring Boot starter +(`spring-boot-starter`) directly or indirectly (i.e. no need to add it if your starter +relies on another starter). If a project is created with only your custom starter, Spring +Boot's core features will be honoured by the presence of the core starter. + + + +[[boot-features-kotlin]] +== Kotlin support +https://kotlinlang.org[Kotlin] is a statically-typed language targeting the JVM (and other +platforms) which allows writing concise and elegant code while providing +{kotlin-documentation}java-interop.html[interoperability] with existing libraries written +in Java. + +Spring Boot provides Kotlin support by leveraging the support in other Spring projects +such as Spring Framework, Spring Data, and Reactor. See the +{spring-reference}languages.html#kotlin[Spring Framework Kotlin support documentation] +for more information. + +The easiest way to start with Spring Boot and Kotlin is to follow +https://spring.io/guides/tutorials/spring-boot-kotlin/[this comprehensive tutorial]. You +can create new Kotlin projects via +https://start.spring.io/#!language=kotlin[start.spring.io]. Feel free to join the #spring +channel of https://slack.kotlinlang.org/[Kotlin Slack] or ask a question with the `spring` +and `kotlin` tags on https://stackoverflow.com/questions/tagged/spring+kotlin[Stack +Overflow] if you need support. + + + +[[boot-features-kotlin-requirements]] +=== Requirements +Spring Boot supports Kotlin 1.3.x. To use Kotlin, `org.jetbrains.kotlin:kotlin-stdlib` and +`org.jetbrains.kotlin:kotlin-reflect` must be present on the classpath. The +`kotlin-stdlib` variants `kotlin-stdlib-jdk7` and `kotlin-stdlib-jdk8` can also be used. + +Since https://discuss.kotlinlang.org/t/classes-final-by-default/166[Kotlin classes are +final by default], you are likely to want to configure +{kotlin-documentation}compiler-plugins.html#spring-support[kotlin-spring] +plugin in order to automatically open Spring-annotated classes so that they can be +proxied. + +https://github.com/FasterXML/jackson-module-kotlin[Jackson's Kotlin module] is required +for serializing / deserializing JSON data in Kotlin. It is automatically registered when +found on the classpath. A warning message is logged if Jackson and Kotlin are present but +the Jackson Kotlin module is not. + +TIP: These dependencies and plugins are provided by default if one bootstraps a Kotlin +project on https://start.spring.io/#!language=kotlin[start.spring.io]. + + + +[[boot-features-kotlin-null-safety]] +=== Null-safety +One of Kotlin's key features is {kotlin-documentation}null-safety.html[null-safety]. It +deals with `null` values at compile time rather than deferring the problem to runtime and +encountering a `NullPointerException`. This helps to eliminate a common source of bugs +without paying the cost of wrappers like `Optional`. Kotlin also allows using functional +constructs with nullable values as described in this +https://www.baeldung.com/kotlin-null-safety[comprehensive guide to null-safety in Kotlin]. + +Although Java does not allow one to express null-safety in its type system, Spring +Framework, Spring Data, and Reactor now provide null-safety of their API via +tooling-friendly annotations. By default, types from Java APIs used in Kotlin are +recognized as +{kotlin-documentation}java-interop.html#null-safety-and-platform-types[platform types] +for which null-checks are relaxed. +{kotlin-documentation}java-interop.html#jsr-305-support[Kotlin's support for JSR 305 +annotations] combined with nullability annotations provide null-safety for the related +Spring API in Kotlin. + +The JSR 305 checks can be configured by adding the `-Xjsr305` compiler flag with the +following options: `-Xjsr305={strict|warn|ignore}`. The default behavior is the same as +`-Xjsr305=warn`. The `strict` value is required to have null-safety taken in account in +Kotlin types inferred from Spring API but should be used with the knowledge that Spring +API nullability declaration could evolve even between minor releases and more checks may +be added in the future). + +WARNING: Generic type arguments, varargs and array elements nullability are not yet +supported. See https://jira.spring.io/browse/SPR-15942[SPR-15942] for up-to-date +information. Also be aware that Spring Boot's own API is {github-issues}10712[not yet +annotated]. + + + +[[boot-features-kotlin-api]] +=== Kotlin API + + + +[[boot-features-kotlin-api-runapplication]] +==== runApplication +Spring Boot provides an idiomatic way to run an application with +`runApplication(*args)` as shown in the following example: + +[source,kotlin,indent=0] +---- +import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.boot.runApplication + +@SpringBootApplication +class MyApplication + +fun main(args: Array) { + runApplication(*args) +} +---- + +This is a drop-in replacement for +`SpringApplication.run(MyApplication::class.java, *args)`. It also allows customization +of the application as shown in the following example: + +[source,kotlin,indent=0] +---- +runApplication(*args) { + setBannerMode(OFF) +} +---- + + + +[[boot-features-kotlin-api-extensions]] +==== Extensions +Kotlin {kotlin-documentation}extensions.html[extensions] provide the ability +to extend existing classes with additional functionality. The Spring Boot Kotlin API makes +use of these extensions to add new Kotlin specific conveniences to existing APIs. + +`TestRestTemplate` extensions, similar to those provided by Spring Framework for +`RestOperations` in Spring Framework, are provided. Among other things, the extensions +make it possible to take advantage of Kotlin reified type parameters. + + + +[[boot-features-kotlin-dependency-management]] +=== Dependency management +In order to avoid mixing different versions of Kotlin dependencies on the classpath, +Spring Boot imports the Kotlin BOM. + +With Maven, the Kotlin version can be customized via the `kotlin.version` property and +plugin management is provided for `kotlin-maven-plugin`. With Gradle, the Spring Boot +plugin automatically aligns the `kotlin.version` with the version of the Kotlin plugin. + + + +[[boot-features-kotlin-configuration-properties]] +=== `@ConfigurationProperties` +`@ConfigurationProperties` supports classes with immutable `val` properties as shown in +the following example: + +[source,kotlin,indent=0] +---- +@ConfigurationProperties("example.kotlin") +data class KotlinExampleProperties( + val name: String, + val description: String, + val myService: MyService +) + +data class MyService( + val apiToken: String, + val uri: URI +) +---- + +TIP: To generate <> using the annotation processor, {kotlin-documentation}kapt.html[`kapt` should +be configured] with the `spring-boot-configuration-processor` dependency. Note that some +features (such as detecting the default value or deperecated items) are not working due +to limitations in the model kapt provides. + + +[[boot-features-kotlin-testing]] +=== Testing +While it is possible to use JUnit 4 to test Kotlin code, JUnit 5 is recommended. JUnit 5 +enables a test class to be instantiated once and reused for all of the class's tests. This +makes it possible to use `@BeforeClass` and `@AfterClass` annotations on non-static +methods, which is a good fit for Kotlin. + +JUnit 5 is the default and the vintage engine is provided for backward compatibility with +JUnit 4. If you don't use it, exclude `org.junit.vintange:junit-vintage-engine`. See the +{junit5-documentation}/#dependency-metadata-junit-jupiter-samples[JUnit 5 documentation] +for more details. You also need to +{junit5-documentation}/#writing-tests-test-instance-lifecycle-changing-default[switch test +instance lifecycle to "per-class"]. + +To mock Kotlin classes, https://mockk.io/[MockK] is recommended. If you need the `Mockk` +equivalent of the Mockito specific +<>, you can use https://github.com/Ninja-Squad/springmockk[SpringMockK] which +provides similar `@MockkBean` and `@SpykBean` annotations. + + + +[[boot-features-kotlin-resources]] +=== Resources + + + +[[boot-features-kotlin-resources-further-reading]] +==== Further reading +* {kotlin-documentation}[Kotlin language reference] +* https://slack.kotlinlang.org/[Kotlin Slack] (with a dedicated #spring channel) +* https://stackoverflow.com/questions/tagged/spring+kotlin[Stackoverflow with `spring` and `kotlin` tags] +* https://try.kotlinlang.org/[Try Kotlin in your browser] +* https://blog.jetbrains.com/kotlin/[Kotlin blog] +* https://kotlin.link/[Awesome Kotlin] +* https://spring.io/guides/tutorials/spring-boot-kotlin/[Tutorial: building web applications with Spring Boot and Kotlin] +* https://spring.io/blog/2016/02/15/developing-spring-boot-applications-with-kotlin[Developing Spring Boot applications with Kotlin] +* https://spring.io/blog/2016/03/20/a-geospatial-messenger-with-kotlin-spring-boot-and-postgresql[A Geospatial Messenger with Kotlin, Spring Boot and PostgreSQL] +* https://spring.io/blog/2017/01/04/introducing-kotlin-support-in-spring-framework-5-0[Introducing Kotlin support in Spring Framework 5.0] +* https://spring.io/blog/2017/08/01/spring-framework-5-kotlin-apis-the-functional-way[Spring Framework 5 Kotlin APIs, the functional way] + + + +[[boot-features-kotlin-resources-examples]] +==== Examples + +* https://github.com/sdeleuze/spring-boot-kotlin-demo[spring-boot-kotlin-demo]: regular Spring Boot + Spring Data JPA project +* https://github.com/mixitconf/mixit[mixit]: Spring Boot 2 + WebFlux + Reactive Spring Data MongoDB +* https://github.com/sdeleuze/spring-kotlin-fullstack[spring-kotlin-fullstack]: WebFlux Kotlin fullstack example with Kotlin2js for frontend instead of JavaScript or TypeScript +* https://github.com/spring-petclinic/spring-petclinic-kotlin[spring-petclinic-kotlin]: Kotlin version of the Spring PetClinic Sample Application +* https://github.com/sdeleuze/spring-kotlin-deepdive[spring-kotlin-deepdive]: a step by step migration for Boot 1.0 + Java to Boot 2.0 + Kotlin + + + +[[boot-features-whats-next]] +== What to Read Next +If you want to learn more about any of the classes discussed in this section, you can +check out the {dc-root}[Spring Boot API documentation] or you can browse the +{github-code}[source code directly]. If you have specific questions, take a look at the +<> section. + +If you are comfortable with Spring Boot's core features, you can continue on and read +about <>. From 6aca340f71f92d34dc9ad3d863f0c5ce35955419 Mon Sep 17 00:00:00 2001 From: Marcin Grzejszczak Date: Mon, 22 Jul 2019 15:11:48 +0200 Subject: [PATCH 06/18] Added more workflows --- README.adoc | 192 +++++++++++++++++++- docs/src/main/asciidoc/_attributes.adoc | 2 +- docs/src/main/asciidoc/getting-started.adoc | 113 +++++++++--- docs/src/main/asciidoc/howto.adoc | 78 +++++++- 4 files changed, 346 insertions(+), 39 deletions(-) diff --git a/README.adoc b/README.adoc index 78c55fab50..3bc6dfc1bc 100644 --- a/README.adoc +++ b/README.adoc @@ -243,7 +243,9 @@ Stub Runner` properties, as shown in the following example: + [source,yaml,indent=0] ---- -Unresolved directive in _verifier_how_it_works.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] +stubrunner: + ids: 'com.example:http-server-dsl:+:stubs:8080' + repositoryRoot: https://repo.spring.io/libs-snapshot ---- Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, @@ -550,7 +552,9 @@ Runner` properties, as shown in the following example: + [source,yaml,indent=0] ---- -Unresolved directive in _verifier_how_it_works.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] +stubrunner: + ids: 'com.example:http-server-dsl:+:stubs:8080' + repositoryRoot: https://repo.spring.io/libs-snapshot ---- Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, @@ -1079,7 +1083,9 @@ achieving the same thing by changing the properties. [source,yaml,indent=0] ---- -Unresolved directive in _verifier_how_it_works.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] +stubrunner: + ids: 'com.example:http-server-dsl:+:stubs:8080' + repositoryRoot: https://repo.spring.io/libs-snapshot ---- That's it! @@ -1559,7 +1565,185 @@ You can read more about Spring Cloud Contract Verifier by reading the == Contributing -Unresolved directive in README.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/contributing.adoc[] +:spring-cloud-build-branch: master + +Spring Cloud is released under the non-restrictive Apache 2.0 license, +and follows a very standard Github development process, using Github +tracker for issues and merging pull requests into master. If you want +to contribute even something trivial please do not hesitate, but +follow the guidelines below. + +=== Sign the Contributor License Agreement +Before we accept a non-trivial patch or pull request we will need you to sign the +https://cla.pivotal.io/sign/spring[Contributor License Agreement]. +Signing the contributor's agreement does not grant anyone commit rights to the main +repository, but it does mean that we can accept your contributions, and you will get an +author credit if we do. Active contributors might be asked to join the core team, and +given the ability to merge pull requests. + +=== Code of Conduct +This project adheres to the Contributor Covenant https://github.com/spring-cloud/spring-cloud-build/blob/master/docs/src/main/asciidoc/code-of-conduct.adoc[code of +conduct]. By participating, you are expected to uphold this code. Please report +unacceptable behavior to spring-code-of-conduct@pivotal.io. + +=== Code Conventions and Housekeeping +None of these is essential for a pull request, but they will all help. They can also be +added after the original pull request but before a merge. + +* Use the Spring Framework code format conventions. If you use Eclipse + you can import formatter settings using the + `eclipse-code-formatter.xml` file from the + https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-dependencies-parent/eclipse-code-formatter.xml[Spring + Cloud Build] project. If using IntelliJ, you can use the + https://plugins.jetbrains.com/plugin/6546[Eclipse Code Formatter + Plugin] to import the same file. +* Make sure all new `.java` files to have a simple Javadoc class comment with at least an + `@author` tag identifying you, and preferably at least a paragraph on what the class is + for. +* Add the ASF license header comment to all new `.java` files (copy from existing files + in the project) +* Add yourself as an `@author` to the .java files that you modify substantially (more + than cosmetic changes). +* Add some Javadocs and, if you change the namespace, some XSD doc elements. +* A few unit tests would help a lot as well -- someone has to do it. +* If no-one else is using your branch, please rebase it against the current master (or + other target branch in the main project). +* When writing a commit message please follow https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html[these conventions], + if you are fixing an existing issue please add `Fixes gh-XXXX` at the end of the commit + message (where XXXX is the issue number). + +=== Checkstyle + +Spring Cloud Build comes with a set of checkstyle rules. You can find them in the `spring-cloud-build-tools` module. The most notable files under the module are: + +.spring-cloud-build-tools/ +---- +└── src +    ├── checkstyle +    │   └── checkstyle-suppressions.xml <3> +    └── main +    └── resources +    ├── checkstyle-header.txt <2> +    └── checkstyle.xml <1> +---- +<1> Default Checkstyle rules +<2> File header setup +<3> Default suppression rules + +==== Checkstyle configuration + +Checkstyle rules are *disabled by default*. To add checkstyle to your project just define the following properties and plugins. + +.pom.xml +---- + +true <1> + true + <2> + true + <3> + + + + + <4> + io.spring.javaformat + spring-javaformat-maven-plugin + + <5> + org.apache.maven.plugins + maven-checkstyle-plugin + + + + + + <5> + org.apache.maven.plugins + maven-checkstyle-plugin + + + + +---- +<1> Fails the build upon Checkstyle errors +<2> Fails the build upon Checkstyle violations +<3> Checkstyle analyzes also the test sources +<4> Add the Spring Java Format plugin that will reformat your code to pass most of the Checkstyle formatting rules +<5> Add checkstyle plugin to your build and reporting phases + +If you need to suppress some rules (e.g. line length needs to be longer), then it's enough for you to define a file under `${project.root}/src/checkstyle/checkstyle-suppressions.xml` with your suppressions. Example: + +.projectRoot/src/checkstyle/checkstyle-suppresions.xml +---- + + + + + + +---- + +It's advisable to copy the `${spring-cloud-build.rootFolder}/.editorconfig` and `${spring-cloud-build.rootFolder}/.springformat` to your project. That way, some default formatting rules will be applied. You can do so by running this script: + +```bash +$ curl https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/.editorconfig -o .editorconfig +$ touch .springformat +``` + +=== IDE setup + +==== Intellij IDEA + +In order to setup Intellij you should import our coding conventions, inspection profiles and set up the checkstyle plugin. +The following files can be found in the https://github.com/spring-cloud/spring-cloud-build/tree/master/spring-cloud-build-tools[Spring Cloud Build] project. + +.spring-cloud-build-tools/ +---- +└── src +    ├── checkstyle +    │   └── checkstyle-suppressions.xml <3> +    └── main +    └── resources +    ├── checkstyle-header.txt <2> +    ├── checkstyle.xml <1> +    └── intellij +       ├── Intellij_Project_Defaults.xml <4> +       └── Intellij_Spring_Boot_Java_Conventions.xml <5> +---- +<1> Default Checkstyle rules +<2> File header setup +<3> Default suppression rules +<4> Project defaults for Intellij that apply most of Checkstyle rules +<5> Project style conventions for Intellij that apply most of Checkstyle rules + +.Code style + +image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-code-style.png[Code style] + +Go to `File` -> `Settings` -> `Editor` -> `Code style`. There click on the icon next to the `Scheme` section. There, click on the `Import Scheme` value and pick the `Intellij IDEA code style XML` option. Import the `spring-cloud-build-tools/src/main/resources/intellij/Intellij_Spring_Boot_Java_Conventions.xml` file. + +.Inspection profiles + +image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-inspections.png[Code style] + +Go to `File` -> `Settings` -> `Editor` -> `Inspections`. There click on the icon next to the `Profile` section. There, click on the `Import Profile` and import the `spring-cloud-build-tools/src/main/resources/intellij/Intellij_Project_Defaults.xml` file. + +.Checkstyle + +To have Intellij work with Checkstyle, you have to install the `Checkstyle` plugin. It's advisable to also install the `Assertions2Assertj` to automatically convert the JUnit assertions + +image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-checkstyle.png[Checkstyle] + +Go to `File` -> `Settings` -> `Other settings` -> `Checkstyle`. There click on the `+` icon in the `Configuration file` section. There, you'll have to define where the checkstyle rules should be picked from. In the image above, we've picked the rules from the cloned Spring Cloud Build repository. However, you can point to the Spring Cloud Build's GitHub repository (e.g. for the `checkstyle.xml` : `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle.xml`). We need to provide the following variables: + +- `checkstyle.header.file` - please point it to the Spring Cloud Build's, `spring-cloud-build-tools/src/main/resources/checkstyle/checkstyle-header.txt` file either in your cloned repo or via the `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle-header.txt` URL. +- `checkstyle.suppressions.file` - default suppressions. Please point it to the Spring Cloud Build's, `spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` file either in your cloned repo or via the `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` URL. +- `checkstyle.additional.suppressions.file` - this variable corresponds to suppressions in your local project. E.g. you're working on `spring-cloud-contract`. Then point to the `project-root/src/checkstyle/checkstyle-suppressions.xml` folder. Example for `spring-cloud-contract` would be: `/home/username/spring-cloud-contract/src/checkstyle/checkstyle-suppressions.xml`. + +IMPORTANT: Remember to set the `Scan Scope` to `All sources` since we apply checkstyle rules for production and test sources. == How to build it diff --git a/docs/src/main/asciidoc/_attributes.adoc b/docs/src/main/asciidoc/_attributes.adoc index 34e0068487..247c730453 100644 --- a/docs/src/main/asciidoc/_attributes.adoc +++ b/docs/src/main/asciidoc/_attributes.adoc @@ -31,4 +31,4 @@ :tests_path: {core_path}/tests :samples_branch: 2.2.x :samples_url: https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/{samples_branch} -:introduction_url: ${core_path}/../../ \ No newline at end of file +:introduction_url: {core_path}/.. \ No newline at end of file diff --git a/docs/src/main/asciidoc/getting-started.adoc b/docs/src/main/asciidoc/getting-started.adoc index 5585967c82..9efbbb505f 100644 --- a/docs/src/main/asciidoc/getting-started.adoc +++ b/docs/src/main/asciidoc/getting-started.adoc @@ -134,7 +134,7 @@ This very brief tour walks through using Spring Cloud Contract: You can find a somewhat longer tour <>. -[plantuml, three-second, png] +[plantuml, getting-started-three-second, png] ---- "API Producer"->"API Producer": add Spring Cloud \nContract (SCC) plugin "API Producer"->"API Producer": add SCC Verifier dependency @@ -574,7 +574,7 @@ to the following in the build logs: ---- [[getting-started-cdc]] -== Step-by-step Guide to Consumer Driven Contracts (CDC) +== Step-by-step Guide to Consumer Driven Contracts (CDC) with contracts laying on the producer side Consider an example of Fraud Detection and the Loan Issuance process. The business scenario is such that we want to issue loans to people but do not want them to steal from @@ -615,6 +615,12 @@ include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=repo include::{introduction_url}/samples/standalone/dsl/http-server/build.gradle[tags=deps_repos,indent=0] ---- +For simplicity we will use the following acronyms: + +- Loan Issuance - LI - the http client +- Fraud Detection - FD - the http server +- Spring Cloud Contract - SCC + === Consumer side (Loan Issuance) As a developer of the Loan Issuance service (a consumer of the Fraud Detection server), you might do the following steps: @@ -632,26 +638,34 @@ As a developer of the Loan Issuance service (a consumer of the Fraud Detection s . Deploy your app. . Work online. -[plantuml, cdc, png] +Let's start with the Loan Issuance flow: + +[plantuml, getting-started-cdc-client, png] ---- -"Loan Issuance"->"Loan Issuance": start doing TDD\nby writing a test\nfor your feature -"Loan Issuance"->"Loan Issuance": write the \nmissing implementation -"Loan Issuance"->"Fraud Detection": clone the repository -"Loan Issuance"->"Fraud Detection Clone": start working on the clone -"Fraud Detection Clone"->"Fraud Detection Clone": add missing dependencies\ndefine contracts -"Fraud Detection Clone"->"Fraud Detection Clone": add the Spring Cloud \nContract plugin -"Fraud Detection Clone"->"Fraud Detection \nClone Build": install the stubs locally -"Fraud Detection \nClone Build"->"SCC Plugin": generate stubs \nand stubs \nartifact (e.g. stubs-jar) -"Fraud Detection \nClone Build"->"Local storage": install the stubs locally -"Local storage"->"Fraud Detection Build": stub sucessfully installed -"Fraud Detection Build"->"API Producer": Build successful -"API Consumer"->"API Consumer": add SCC Stub Runner \ndependency -"API Consumer"->"API Consumer": write a SCC Stub Runner \nbased contract test -"SCC Stub Runner"->"Nexus / Artifactory": test asks for [API Producer] stubs -"Nexus / Artifactory"->"SCC Stub Runner": fetch the [API Producer] stubs -"SCC Stub Runner"->"SCC Stub Runner": run in memory\n HTTP server stubs -"API Consumer"->"SCC Stub Runner": send a request \nto the HTTP server stub -"SCC Stub Runner"->"API Consumer": communication is correct +"Loan\nIssuance"->"Loan\nIssuance": start doing TDD\nby writing a test\nfor your feature +"Loan\nIssuance"->"Loan\nIssuance": write the \nmissing implementation +"Loan\nIssuance"->"Loan\nIssuance": run a test - it fails\ndue to no server running +"Loan\nIssuance"->"Fraud\nDetection\nClone": clone the repository +"Fraud\nDetection\nClone"->"Fraud\nDetection\nClone": add missing dependencies\n& define contracts +"Fraud\nDetection\nClone"->"Fraud\nDetection\nClone": add the SCC plugin +"Fraud\nDetection\nClone"->"FD \nClone Build": install the stubs locally +"FD \nClone Build"->"SCC Plugin \nin FD Clone": generate stubs \nand stubs \nartifact (e.g. stubs-jar) +"SCC Plugin \nin FD Clone"->"FD \nClone Build": stubs and artifacts\ngenerated +"FD \nClone Build"->"Local storage": install the stubs locally +"Local storage"->"FD \nClone Build": stub sucessfully installed +"FD \nClone Build"->"Fraud\nDetection\nClone": build successful +"Loan\nIssuance"->"Loan\nIssuance": add a SCC\nStub Runner\ndependency\nand setup +"Loan\nIssuance"->"LI\nSCC\nStub Runner": start stubs\nof FD from\nlocal storage +"LI\nSCC\nStub Runner"->"Local storage": find stubs of [FD] +"Local storage"->"LI\nSCC\nStub Runner": stubs of [FD] found +"LI\nSCC\nStub Runner"->"FD stub": run stubs of [FD] +"FD stub"->"LI\nSCC\nStub Runner": [FD] stub is running +"LI\nSCC\nStub Runner"->"Loan\nIssuance": stubs running and ready for the test +"Loan\nIssuance"->"Loan\nIssuance": run a test +"Loan\nIssuance"->"FD stub": the test\nsends a request\nto the running stub +"FD stub"->"Loan\nIssuance": stub responds successfuly +"Loan\nIssuance"->"Loan\nIssuance": the test passes successfully +"Loan\nIssuance"->"Fraud\nDetection": send a pull request\nwith the\nsuggested contracts ---- *Start doing TDD by writing a test for your feature.* @@ -721,6 +735,7 @@ of an identifier or a timestamp, you need not hardcode a value. You want to allo different ranges of values. To enable ranges of values, you can set regular expressions matching those values for the consumer side. You can provide the body by means of either a map notation or String with interpolations. +//TODO: Ensure that the links are correct Consult the <> section for more information. We highly recommend using the map notation! TIP: You must understand the map notation in order to set up contracts. Please read the @@ -860,9 +875,35 @@ the server side. Currently, the consumer side work is done. === Producer side (Fraud Detection server) -As a developer of the Fraud Detection server (a server to the Loan Issuance service): +As a developer of the Fraud Detection server (a server to the Loan Issuance service) we would like to: -*Create an initial implementation.* +- take over the pull request +- write the missing implementation +- deploy the application + +Let's look at the Fraud Detection flow: + +[plantuml, getting-started-cdc-server, png] +---- +"Fraud\nDetection"->"Fraud\nDetection": take over the\n pull request +"Fraud\nDetection"->"Fraud\nDetection": setup\nSpring Cloud\nContract plugin +"Fraud\nDetection"->"Fraud\nDetection\nBuild": run the build +"Fraud\nDetection\nBuild"->"SCC Plugin": generate tests\nstubs \nand stubs artifact \n(e.g. stubs-jar) +"SCC Plugin"->"Fraud\nDetection\nBuild": tests and stubs generated +"Fraud\nDetection\nBuild"->"Fraud\nDetection\nBuild": run tests +"Fraud\nDetection\nBuild"->"Fraud\nDetection": generated tests failed! +"Fraud\nDetection"->"Fraud\nDetection": setup\nbase classes\nfor contract tests +"Fraud\nDetection"->"Fraud\nDetection\nBuild": run the build +"Fraud\nDetection\nBuild"->"SCC Plugin": generate tests\nstubs \nand stubs artifact \n(e.g. stubs-jar) +"SCC Plugin"->"Fraud\nDetection\nBuild": tests and stubs generated +"Fraud\nDetection\nBuild"->"Fraud\nDetection\nBuild": run tests +"Fraud\nDetection\nBuild"->"Fraud\nDetection": all the tests passed! +"Fraud\nDetection"->"Fraud\nDetection": commit and push changes +"Fraud\nDetection"->"CI": commit pushed!\nTriggers the build +"CI"->"Nexus / Artifactory": build successful,\nupload artifacts +---- + +*Take over the pull request.* As a reminder, you can see the initial implementation here: @@ -873,8 +914,6 @@ include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com } ---- -*Take over the pull request.* - [source,bash,indent=0] ---- $ git checkout -b contract-change-pr master @@ -991,7 +1030,29 @@ application and the stub artifacts. === Consumer Side (Loan Issuance) Final Step -As a developer of the Loan Issuance service (a consumer of the Fraud Detection server): +As a developer of the Loan Issuance service (a consumer of the Fraud Detection server) we will want to: + +- merge our feature branch to `master` +- switch to online mode of working + + +[plantuml, getting-started-cdc-client, png] +---- +"Loan\nIssuance"->"Loan\nIssuance": merge the\nfeature branch\nto master branch +"Loan\nIssuance"->"Loan\nIssuance": setup SCC Stub Runner\nto fetch stubs\nfrom Nexus / Artifactory +"Loan\nIssuance"->"LI\nSCC\nStub Runner": start stubs\nof FD from\nNexus / Artifactory +"LI\nSCC\nStub Runner"->"Local storage": find stubs of [FD] +"Local storage"->"LI\nSCC\nStub Runner": stubs of [FD] found +"LI\nSCC\nStub Runner"->"FD stub": run stubs of [FD] +"FD stub"->"LI\nSCC\nStub Runner": [FD] stub is running +"LI\nSCC\nStub Runner"->"Loan\nIssuance": stubs running and ready for the test +"Loan\nIssuance"->"Loan\nIssuance": run a test +"Loan\nIssuance"->"FD stub": the test\nsends a request\nto the running stub +"FD stub"->"Loan\nIssuance": stub responds successfuly +"Loan\nIssuance"->"Loan\nIssuance": the test passes successfully +"Loan\nIssuance"->"Fraud\nDetection": send a pull request\nwith the\nsuggested contracts +---- + *Merge branch to master.* diff --git a/docs/src/main/asciidoc/howto.adoc b/docs/src/main/asciidoc/howto.adoc index 5043e5704d..1e31e36b0f 100644 --- a/docs/src/main/asciidoc/howto.adoc +++ b/docs/src/main/asciidoc/howto.adoc @@ -30,7 +30,7 @@ Spring Cloud Contract Verifier stand out on the "market" of Consumer Driven Cont - Via Docker adds support for any language & framework used [[how-to-not-write-contracts-in-groovy]] -== I don't want to write a contract in Groovy! +== How can I write contracts in a language different than Groovy? // TODO: Add a link No problem. You can write a contract in YAML! Check this section for more information @@ -38,7 +38,7 @@ No problem. You can write a contract in YAML! Check this section for more inform We are working on allowing more ways of describing the contracts. You can check the {github-issues}[github-issues] for more information. [[how-to-provide-dynamic-values]] -== What is this value(consumer(), producer()) ? +== How can I provide dynamic values for a contract? One of the biggest challenges related to stubs is their reusability. Only if they can be vastly used, will they serve their purpose. What typically makes that difficult are the hard-coded values of request / response elements. For example dates or ids. @@ -210,7 +210,7 @@ Example of tests using production version of stubs You can pass those values also via properties from your deployment pipeline. [[how-to-common-repo-with-contracts]] -== Common repo with contracts +== How can I use a common repo with contracts instead of storing them with the producer? Another way of storing contracts other than having them with the producer is keeping them in a common place. It can be related to security issues where the consumers can't clone the producer's code. Also if you keep @@ -279,7 +279,7 @@ include::{introduction_url}/samples/standalone/contracts/src/assembly/contracts. The workflow assumes that Spring Cloud Contract is setup both on the consumer and the producer side. There is also the proper plugin setup in the common repo with contracts. The CI jobs are set for common repo to build an artifact of all contracts and upload it to Nexus / Artifactory. -[plantuml, three-second, png] +[plantuml, how-to-common-repo, png] ---- "API Consumer"->"Common repo": create a folder \nfor producer [API Producer] "API Consumer"->"Common repo": under [API Producer] create a folder \nfor consumer \n[API Consumer] @@ -476,7 +476,7 @@ contracts { ---- [[how-to-use-git-as-storage]] -== Do I need a Binary Storage? Can't I use Git? +== How can I use Git as the storage for contracts and stubs? In the polyglot world, there are languages that don't use binary storages like Artifactory or Nexus. Starting from Spring Cloud Contract version 2.0.0 we provide @@ -707,7 +707,7 @@ to find stub definitions and contracts. E.g. for `com.example:foo:1.0.0` the pat * Messaging definitions will be read and used in the messaging tests [[how-to-use-pact-broker]] -== Can I use the Pact Broker? +== How can I use the Pact Broker? When using https://pact.io/[Pact] you can use the https://github.com/pact-foundation/pact_broker[Pact Broker] to store and share Pact definitions. Starting from Spring Cloud Contract @@ -935,8 +935,70 @@ You can use the `mappingsOutputFolder` property on `@AutoConfigureStubRunner`, ` was started will be attached. [[how-to-reference-text-from-file]] -== Can I reference text from file? +== How can I reference text from file? Yes! With version 1.2.0 we've added such a possibility. It's enough to call `file(...)` method in the DSL and provide a path relative to where the contract lays. -If you're using YAML just use the `bodyFromFile` property. \ No newline at end of file +If you're using YAML just use the `bodyFromFile` property. + +[[how-to-generate-pact-from-scc]] +== How can I generate Pact / YAML / X files from Spring Cloud Contract Contracts? + +Spring Cloud Contract comes with a `ToFileContractsTransformer` class that allows you to dump contracts as files for the given `ContractConverter`. It contains a `static void main` method, that allows you to execute the transformer as an executable. It takes the following arguments: + +- argument 1 : *FQN* - fully qualified name of the `ContractConverter` (e.g. the `PactContractConverter`) *REQUIRED* +- argument 2 : *path* - path where the dumped files should be stored *OPTIONAL* - defaults to `target/converted-contracts` +- argument 3 : *path* - path were the contracts should be searched for *OPTIONAL* - defaults to `src/test/resources/contracts` + +After executing the transformer, the Spring Cloud Contract files will be processed and depending on the provided FQN of the `ContractTransformer`, the contracts will be transformed to the required format and dumped to the provided folder. + +Below you can find an example for Pact integration: + +==== +[source,xml,indent=0,role="primary"] +.maven +---- + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + convert-dsl-to-pact + process-test-classes + + test + + org.springframework.cloud.contract.verifier.util.ToFileContractsTransformer + + + + org.springframework.cloud.contract.verifier.spec.pact.PactContractConverter + + ${project.basedir}/target/pacts + + ${project.basedir}/src/test/resources/contracts + + + + + java + + + + +---- + +[source,groovy,indent=0,role="secondary"] +.gradle +---- +task convertContracts(type: JavaExec) { + main = "org.springframework.cloud.contract.verifier.util.ToFileContractsTransformer" + classpath = sourceSets.test.compileClasspath + args("org.springframework.cloud.contract.verifier.spec.pact.PactContractConverter", + "${project.rootDir}/build/pacts", "${project.rootDir}/src/test/resources/contracts") +} + +test.dependsOn("convertContracts") +---- +==== \ No newline at end of file From 0db28a223f7a5016e92f1afe5757ae542eee1cc2 Mon Sep 17 00:00:00 2001 From: Marcin Grzejszczak Date: Mon, 22 Jul 2019 17:36:38 +0200 Subject: [PATCH 07/18] New videos, read files from remote --- docs/src/main/asciidoc/_attributes.adoc | 7 +++-- docs/src/main/asciidoc/getting-started.adoc | 33 ++++++++++----------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/docs/src/main/asciidoc/_attributes.adoc b/docs/src/main/asciidoc/_attributes.adoc index 247c730453..39e2411504 100644 --- a/docs/src/main/asciidoc/_attributes.adoc +++ b/docs/src/main/asciidoc/_attributes.adoc @@ -15,8 +15,8 @@ :project-full-name: Spring Cloud Contract // project-specific attributes -:core_path: ../../.. -:plugins_path: ../../../spring-cloud-contract-tools +:core_path: {github-raw} +:plugins_path: {github-raw}/spring-cloud-contract-tools :converters_path: {plugins_path}/spring-cloud-contract-converters :verifier_root_path: {core_path}/spring-cloud-contract-verifier :contract_spec_path: {core_path}/specs/spring-cloud-contract-spec-java @@ -31,4 +31,5 @@ :tests_path: {core_path}/tests :samples_branch: 2.2.x :samples_url: https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/{samples_branch} -:introduction_url: {core_path}/.. \ No newline at end of file + +:introduction_url: {core_path} \ No newline at end of file diff --git a/docs/src/main/asciidoc/getting-started.adoc b/docs/src/main/asciidoc/getting-started.adoc index 9efbbb505f..df57caf502 100644 --- a/docs/src/main/asciidoc/getting-started.adoc +++ b/docs/src/main/asciidoc/getting-started.adoc @@ -231,7 +231,7 @@ Stub Runner` properties, as shown in the following example: + [source,yaml,indent=0] ---- -include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] +include::{introduction_url}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ---- Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, @@ -539,7 +539,7 @@ Runner` properties, as shown in the following example: + [source,yaml,indent=0] ---- -include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] +include::{introduction_url}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ---- Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, @@ -1041,8 +1041,8 @@ As a developer of the Loan Issuance service (a consumer of the Fraud Detection s "Loan\nIssuance"->"Loan\nIssuance": merge the\nfeature branch\nto master branch "Loan\nIssuance"->"Loan\nIssuance": setup SCC Stub Runner\nto fetch stubs\nfrom Nexus / Artifactory "Loan\nIssuance"->"LI\nSCC\nStub Runner": start stubs\nof FD from\nNexus / Artifactory -"LI\nSCC\nStub Runner"->"Local storage": find stubs of [FD] -"Local storage"->"LI\nSCC\nStub Runner": stubs of [FD] found +"LI\nSCC\nStub Runner"->"Nexus / Artifactory": find stubs of [FD] +"Nexus / Artifactory"->"LI\nSCC\nStub Runner": stubs of [FD] found "LI\nSCC\nStub Runner"->"FD stub": run stubs of [FD] "FD stub"->"LI\nSCC\nStub Runner": [FD] stub is running "LI\nSCC\nStub Runner"->"Loan\nIssuance": stubs running and ready for the test @@ -1050,10 +1050,8 @@ As a developer of the Loan Issuance service (a consumer of the Fraud Detection s "Loan\nIssuance"->"FD stub": the test\nsends a request\nto the running stub "FD stub"->"Loan\nIssuance": stub responds successfuly "Loan\nIssuance"->"Loan\nIssuance": the test passes successfully -"Loan\nIssuance"->"Fraud\nDetection": send a pull request\nwith the\nsuggested contracts ---- - *Merge branch to master.* [source,bash,indent=0] @@ -1072,7 +1070,7 @@ achieving the same thing by changing the properties. [source,yaml,indent=0] ---- -include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] +include::{introduction_url}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ---- That's it! @@ -1086,23 +1084,24 @@ https://spring.io/guides/[getting started] guides that solve specific "`How do I with Spring?`" problems. We also have {project-full-name}-specific "`<>`" reference documentation. -Otherwise, the next logical step is to read _<>_. If +Otherwise, the next logical step is to read _<>_. If you are really impatient, you could also jump ahead and read about _<>_. -// TODO: Update the video // TODO: Check if we can link courses -In addition to that you can check out the video from the Warsaw JUG about Spring Cloud Contract: +In addition to that you can check out the following videos: -video::sAAklvxmPmk[youtube,start=538,width=640,height=480] +- "Consumer Driven Contracts and Your Microservice Architecture" by Olga Maciaszek-Sharma and Marcin Grzejszczak -You can read the following articles / presentations: +video::pDkC_00hhvA[youtube,width=640,height=480] -// TODO: Update the readings -- https://www.slideshare.net/MarcinGrzejszczak/stick-to-the-rules-consumer-driven-contracts-201507-confitura[Slides from Marcin Grzejszczak's talk about Accurest] -- https://toomuchcoding.com/blog/categories/accurest/[Accurest related articles from Marcin Grzejszczak's blog] -- https://toomuchcoding.com/blog/categories/spring-cloud-contract/[Spring Cloud Contract related articles from Marcin Grzejszczak's blog] -- https://groovy-lang.org/json.html[Groovy docs regarding JSON] +- "Contract Tests in the Enterprise" by Marcin Grzejszczak + +video::ZyHG-VOzPZg[youtube,width=640,height=480] + +- "Why Contract Tests Matter?" by Marcin Grzejszczak + +video::TvpkZu1e2Dc[youtube,start=6262,width=640,height=480] You can find the default project samples at https://github.com/spring-cloud-samples/spring-cloud-contract-samples[samples]. \ No newline at end of file From 613b4586ac90d3c1dea1de20618e0f8e41644741 Mon Sep 17 00:00:00 2001 From: Marcin Grzejszczak Date: Tue, 23 Jul 2019 13:17:21 +0200 Subject: [PATCH 08/18] Getting started done --- docs/src/main/asciidoc/_attributes.adoc | 2 +- docs/src/main/asciidoc/getting-started.adoc | 128 +++++++++++--------- 2 files changed, 75 insertions(+), 55 deletions(-) diff --git a/docs/src/main/asciidoc/_attributes.adoc b/docs/src/main/asciidoc/_attributes.adoc index 39e2411504..ad4e5c5729 100644 --- a/docs/src/main/asciidoc/_attributes.adoc +++ b/docs/src/main/asciidoc/_attributes.adoc @@ -15,7 +15,7 @@ :project-full-name: Spring Cloud Contract // project-specific attributes -:core_path: {github-raw} +:core_path: {project-root} :plugins_path: {github-raw}/spring-cloud-contract-tools :converters_path: {plugins_path}/spring-cloud-contract-converters :verifier_root_path: {core_path}/spring-cloud-contract-verifier diff --git a/docs/src/main/asciidoc/getting-started.adoc b/docs/src/main/asciidoc/getting-started.adoc index df57caf502..f07bf93827 100644 --- a/docs/src/main/asciidoc/getting-started.adoc +++ b/docs/src/main/asciidoc/getting-started.adoc @@ -264,10 +264,33 @@ This brief tour walks through using Spring Cloud Contract: You can find an even more brief tour <>. +image::getting-started-three-second.png[Getting started first application] + [[getting-started-first-application-producer]] === On the Producer Side -To start working with `Spring Cloud Contract`, add files with `REST/` messaging contracts +To start working with `Spring Cloud Contract`, add Spring Cloud Contract Verifier dependency and plugin to your build file, +as shown in the following example: + +[source,xml,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] +---- + +The following listing shows how to add the plugin, which should go in the build/plugins +portion of the file: + +[source,xml,indent=0] +---- + + org.springframework.cloud + spring-cloud-contract-maven-plugin + ${spring-cloud-contract.version} + true + +---- + +Now let's add files with `REST/` messaging contracts expressed in either Groovy DSL or YAML to the contracts directory, which is set by the `contractsDslDir` property. By default, it is `$rootDir/src/test/resources/contracts`. @@ -355,35 +378,22 @@ include::{verifier_core_path}/src/test/resources/yml/contract_message_scenario3. ---- ==== - -Then you can add Spring Cloud Contract Verifier dependency and plugin to your build file, -as shown in the following example: - -[source,xml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] ----- - -The following listing shows how to add the plugin, which should go in the build/plugins -portion of the file: - -[source,xml,indent=0] ----- - - org.springframework.cloud - spring-cloud-contract-maven-plugin - ${spring-cloud-contract.version} - true - ----- - Running `./mvnw clean install` automatically generates tests that verify the application compliance with the added contracts. By default, the generated tests are under `org.springframework.cloud.contract.verifier.tests.`. -The following example shows a sample auto-generated test for an HTTP contract: +The generated tests will differ, depending on which framework and test type you've setup in your plugin. -[source,java,indent=0] +In the samples below you'll find: + +- the default test mode for HTTP contracts via `MockMvc` +- JAX-RS client via the `JAXRS` test mode +- `WebTestClient` based test (this is particularly recommended while working with Reactive, `Web-Flux`-based applications) set via `WEBTESTCLIENT` test mode +- Spock based test via the `testFramework` property set to `SPOCK` + +==== +[source,java,indent=0,role="primary"] +.mockmvc ---- @Test public void validate_shouldMarkClientAsFraud() throws Exception { @@ -406,18 +416,45 @@ public void validate_shouldMarkClientAsFraud() throws Exception { } ---- -The preceding example uses Spring's `MockMvc` to run the tests. This is the default test -mode for HTTP contracts. However, JAX-RS client and explicit HTTP invocations can also be -used. (To do so, change the `testMode` property of the plugin to `JAX-RS` or `EXPLICIT`, -respectively.) +[source,java,indent=0,role="secondary"] +.jaxrs +---- +@SuppressWarnings("rawtypes") +public class FooTest { + WebTarget webTarget; -Since 2.1.0, it is also possible to use `RestAssuredWebTestClient`with Spring's reactive `WebTestClient` -run under the hood. This is particularly recommended while working with Reactive, `Web-Flux`-based applications. -In order to use `WebTestClient` set `testMode` to `WEBTESTCLIENT`. + @Test + public void validate_() throws Exception { -Here is an example of a test generated in `WEBTESTCLIENT` test mode: + // when: + Response response = webTarget + .path("/users") + .queryParam("limit", "10") + .queryParam("offset", "20") + .queryParam("filter", "email") + .queryParam("sort", "name") + .queryParam("search", "55") + .queryParam("age", "99") + .queryParam("name", "Denis.Stepanov") + .queryParam("email", "bob@email.com") + .request() + .build("GET") + .invoke(); + String responseAsString = response.readEntity(String.class); -[source,java,indent=0] + // then: + assertThat(response.getStatus()).isEqualTo(200); + + // and: + DocumentContext parsedJson = JsonPath.parse(responseAsString); + assertThatJson(parsedJson).field("['property1']").isEqualTo("a"); + } + +} +---- + +[source,java,indent=0,role="secondary"] +.webtestclient ---- @Test public void validate_shouldRejectABeerIfTooYoung() throws Exception { @@ -439,15 +476,8 @@ Here is an example of a test generated in `WEBTESTCLIENT` test mode: } ---- -Apart from the default JUnit 4, you can instead use JUnit 5 or Spock tests, by setting the plugin -`testFramework` property to either `JUNIT5` or `Spock`. - -TIP: You can now also generate WireMock scenarios based on the contracts, by including an -order number followed by an underscore at the beginning of the contract file names. - -The following example shows an auto-generated test in Spock for a messaging stub contract: - -[source,groovy,indent=0] +[source,groovy,indent=0,role="secondary"] +.spock ---- given: ContractVerifierMessage inputMessage = contractVerifierMessaging.create( @@ -462,6 +492,7 @@ then: noExceptionThrown() bookWasDeleted() ---- +==== As the implementation of the functionalities described by the contracts is not yet present, the tests fail. @@ -496,17 +527,6 @@ shown in the following example: You can now merge the changes and publish both the application and the stub artifacts in an online repository. -// TODO: Consider moving this section somewhere else -*Docker Project* - -In order to enable working with contracts while creating applications in non-JVM -technologies, the `springcloud/spring-cloud-contract` Docker image has been created. It -contains a project that automatically generates tests for HTTP contracts and executes them -in `EXPLICIT` test mode. Then, if the tests pass, it generates Wiremock stubs and, -optionally, publishes them to an artifact manager. In order to use the image, you can -mount the contracts into the `/contracts` directory and set a few environment variables. -// TODO: We should answer the obvious question: Which environment variables? - [[getting-started-first-application-consumer]] === On the Consumer Side From ba554aa60561892262e63f116b383f8d46bd4d6b Mon Sep 17 00:00:00 2001 From: Marcin Grzejszczak Date: Tue, 23 Jul 2019 18:13:46 +0200 Subject: [PATCH 09/18] Started adding flows --- docs/src/main/asciidoc/_attributes.adoc | 1 + docs/src/main/asciidoc/_contract_flows.adoc | 8 - .../main/asciidoc/documentation-overview.adoc | 13 +- docs/src/main/asciidoc/getting-started.adoc | 4 +- docs/src/main/asciidoc/project-features.adoc | 9040 +---------------- docs/src/main/asciidoc/using.adoc | 1339 +-- 6 files changed, 247 insertions(+), 10158 deletions(-) delete mode 100644 docs/src/main/asciidoc/_contract_flows.adoc diff --git a/docs/src/main/asciidoc/_attributes.adoc b/docs/src/main/asciidoc/_attributes.adoc index ad4e5c5729..4560b15951 100644 --- a/docs/src/main/asciidoc/_attributes.adoc +++ b/docs/src/main/asciidoc/_attributes.adoc @@ -31,5 +31,6 @@ :tests_path: {core_path}/tests :samples_branch: 2.2.x :samples_url: https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/{samples_branch} +:samples_code: https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/ :introduction_url: {core_path} \ No newline at end of file diff --git a/docs/src/main/asciidoc/_contract_flows.adoc b/docs/src/main/asciidoc/_contract_flows.adoc deleted file mode 100644 index 72ec8a01e5..0000000000 --- a/docs/src/main/asciidoc/_contract_flows.adoc +++ /dev/null @@ -1,8 +0,0 @@ -- Provider contract testing with Maven / Gradle, stubs in artifactory -- Provider contract testing with Maven / Gradle, stubs in git -- Consumer Driven Contracts with contracts on the producer side -- Consumer Driven Contracts with contracts in external repo -- Consumer Driven Contracts with contracts and stubs in git -- Provider contract testing with Maven / Gradle, stubs in artifactory in non Spring world -- Provider contract testing with Maven / Gradle, stubs in artifactory in non JVM world -- Provider contract testing with REST Docs and with Maven / Gradle stubs in Artifactory \ No newline at end of file diff --git a/docs/src/main/asciidoc/documentation-overview.adoc b/docs/src/main/asciidoc/documentation-overview.adoc index 5457895431..81fc6b99bb 100644 --- a/docs/src/main/asciidoc/documentation-overview.adoc +++ b/docs/src/main/asciidoc/documentation-overview.adoc @@ -46,14 +46,13 @@ If you are getting started with {project-full-name} or 'Spring' in general, star * *From scratch:* <> | -<> | -<> +<> | +<> * *Tutorial:* -<> | -<> -* *Running your example:* -<> | -<> +<> | +<> | +<> | +<> diff --git a/docs/src/main/asciidoc/getting-started.adoc b/docs/src/main/asciidoc/getting-started.adoc index f07bf93827..845c181903 100644 --- a/docs/src/main/asciidoc/getting-started.adoc +++ b/docs/src/main/asciidoc/getting-started.adoc @@ -1124,4 +1124,6 @@ video::ZyHG-VOzPZg[youtube,width=640,height=480] video::TvpkZu1e2Dc[youtube,start=6262,width=640,height=480] You can find the default project samples at -https://github.com/spring-cloud-samples/spring-cloud-contract-samples[samples]. \ No newline at end of file +https://github.com/spring-cloud-samples/spring-cloud-contract-samples[samples]. + +You can find the Spring Cloud Contract workshops https://cloud-samples.spring.io/spring-cloud-contract-samples/[over here]. \ No newline at end of file diff --git a/docs/src/main/asciidoc/project-features.adoc b/docs/src/main/asciidoc/project-features.adoc index c48708d7cc..f5614b1b18 100644 --- a/docs/src/main/asciidoc/project-features.adoc +++ b/docs/src/main/asciidoc/project-features.adoc @@ -1,9041 +1,19 @@ -[[boot-features]] -= Spring Boot Features -include::attributes.adoc[] +[[features]] += Spring Cloud Contract Features +include::_attributes.adoc[] -This section dives into the details of Spring Boot. Here you can learn about the key +This section dives into the details of {project-full-name}. Here you can learn about the key features that you may want to use and customize. If you have not already done so, you might want to read the "<>" and -"<>" sections, so that you have a good grounding of the +"<>" sections, so that you have a good grounding of the basics. - -[[boot-features-spring-application]] -== SpringApplication -The `SpringApplication` class provides a convenient way to bootstrap a Spring application -that is started from a `main()` method. In many situations, you can delegate to the -static `SpringApplication.run` method, as shown in the following example: - -[source,java,indent=0] ----- - public static void main(String[] args) { - SpringApplication.run(MySpringConfiguration.class, args); - } ----- - -When your application starts, you should see something similar to the following output: - -[indent=0,subs="attributes"] ----- - . ____ _ __ _ _ - /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ -( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ - \\/ ___)| |_)| | | | | || (_| | ) ) ) ) - ' |____| .__|_| |_|_| |_\__, | / / / / - =========|_|==============|___/=/_/_/_/ - :: Spring Boot :: v{spring-boot-version} - -2013-07-31 00:08:16.117 INFO 56603 --- [ main] o.s.b.s.app.SampleApplication : Starting SampleApplication v0.1.0 on mycomputer with PID 56603 (/apps/myapp.jar started by pwebb) -2013-07-31 00:08:16.166 INFO 56603 --- [ main] ationConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6e5a8246: startup date [Wed Jul 31 00:08:16 PDT 2013]; root of context hierarchy -2014-03-04 13:09:54.912 INFO 41370 --- [ main] .t.TomcatServletWebServerFactory : Server initialized with port: 8080 -2014-03-04 13:09:56.501 INFO 41370 --- [ main] o.s.b.s.app.SampleApplication : Started SampleApplication in 2.992 seconds (JVM running for 3.658) ----- - -By default, `INFO` logging messages are shown, including some relevant startup details, -such as the user that launched the application. If you need a log level other than `INFO`, -you can set it, as described in <>, - - - -[[boot-features-startup-failure]] -=== Startup Failure -If your application fails to start, registered `FailureAnalyzers` get a chance to provide -a dedicated error message and a concrete action to fix the problem. For instance, if you -start a web application on port `8080` and that port is already in use, you should see -something similar to the following message: - -[indent=0] ----- - *************************** - APPLICATION FAILED TO START - *************************** - - Description: - - Embedded servlet container failed to start. Port 8080 was already in use. - - Action: - - Identify and stop the process that's listening on port 8080 or configure this application to listen on another port. ----- - -NOTE: Spring Boot provides numerous `FailureAnalyzer` implementations, and you can -<>. - -If no failure analyzers are able to handle the exception, you can still display the full -conditions report to better understand what went wrong. To do so, you need to -<> or -<> for -`org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener`. - -For instance, if you are running your application by using `java -jar`, you can enable -the `debug` property as follows: - -[indent=0,subs="attributes"] ----- - $ java -jar myproject-0.0.1-SNAPSHOT.jar --debug ----- - - - -[[boot-features-lazy-initialization]] -=== Lazy Initialization -`SpringApplication` allows an application to be initialized lazily. When lazy -initialization is enabled, beans are created as they are needed rather than during -application startup. As a result, enabling lazy initialization can reduce the time that -it takes your application to start. In a web application, enabling lazy initialization -will result in many web-related beans not being initialized until an HTTP request is -received. - -A downside of lazy initialization is that it can delay the discovery of a problem with -the application. If a misconfigured bean is initialized lazily, a failure will no longer -occur during startup and the problem will only become apparent when the bean is -initialized. Care must also be taken to ensure that the JVM has sufficient memory to -accommodate all of the application's beans and not just those that are initialized during -startup. For these reasons, lazy initialization is not enabled by default and it is -recommended that fine-tuning of the JVM's heap size is done before enabling lazy -initialization. - -Lazy initialization can be enabled programatically using the `lazyInitialization` method -on `SpringApplicationBuilder` or the `setLazyInitialization` method on -`SpringApplication`. Alternatively, it can be enabled using the -`spring.main.lazy-initialization` property as shown in the following example: - -[source,properties,indent=0] ----- - spring.main.lazy-initialization=true ----- - -TIP: If you want to disable lazy initialization for certain beans while using lazy -initialization for the rest of the application, you can explicitly set their lazy attribute -to false using the `@Lazy(false)` annotation. - - - -[[boot-features-banner]] -=== Customizing the Banner -The banner that is printed on start up can be changed by adding a `banner.txt` file to -your classpath or by setting the `spring.banner.location` property to the location of such -a file. If the file has an encoding other than UTF-8, you can set `spring.banner.charset`. -In addition to a text file, you can also add a `banner.gif`, `banner.jpg`, or `banner.png` -image file to your classpath or set the `spring.banner.image.location` property. Images -are converted into an ASCII art representation and printed above any text banner. - -Inside your `banner.txt` file, you can use any of the following placeholders: - -.Banner variables -|=== -| Variable | Description - -|`${application.version}` -|The version number of your application, as declared in `MANIFEST.MF`. For example, -`Implementation-Version: 1.0` is printed as `1.0`. - -|`${application.formatted-version}` -|The version number of your application, as declared in `MANIFEST.MF` and formatted for -display (surrounded with brackets and prefixed with `v`). For example `(v1.0)`. - -|`${spring-boot.version}` -|The Spring Boot version that you are using. For example `{spring-boot-version}`. - -|`${spring-boot.formatted-version}` -|The Spring Boot version that you are using, formatted for display (surrounded with -brackets and prefixed with `v`). For example `(v{spring-boot-version})`. - -|`${Ansi.NAME}` (or `${AnsiColor.NAME}`, `${AnsiBackground.NAME}`, `${AnsiStyle.NAME}`) -|Where `NAME` is the name of an ANSI escape code. See -{sc-spring-boot}/ansi/AnsiPropertySource.{sc-ext}[`AnsiPropertySource`] for details. - -|`${application.title}` -|The title of your application, as declared in `MANIFEST.MF`. For example -`Implementation-Title: MyApp` is printed as `MyApp`. -|=== - -TIP: The `SpringApplication.setBanner(...)` method can be used if you want to generate -a banner programmatically. Use the `org.springframework.boot.Banner` interface and -implement your own `printBanner()` method. - -You can also use the `spring.main.banner-mode` property to determine if the banner has -to be printed on `System.out` (`console`), sent to the configured logger (`log`), or not -produced at all (`off`). - -The printed banner is registered as a singleton bean under the following name: -`springBootBanner`. - - - -[[boot-features-customizing-spring-application]] -=== Customizing SpringApplication -If the `SpringApplication` defaults are not to your taste, you can instead create a local -instance and customize it. For example, to turn off the banner, you could write: - -[source,java,indent=0] ----- - public static void main(String[] args) { - SpringApplication app = new SpringApplication(MySpringConfiguration.class); - app.setBannerMode(Banner.Mode.OFF); - app.run(args); - } ----- - -NOTE: The constructor arguments passed to `SpringApplication` are configuration sources -for Spring beans. In most cases, these are references to `@Configuration` classes, but -they could also be references to XML configuration or to packages that should be scanned. - -It is also possible to configure the `SpringApplication` by using an -`application.properties` file. See _<>_ for details. - -For a complete list of the configuration options, see the -{dc-spring-boot}/SpringApplication.{dc-ext}[`SpringApplication` Javadoc]. - - - -[[boot-features-fluent-builder-api]] -=== Fluent Builder API -If you need to build an `ApplicationContext` hierarchy (multiple contexts with a -parent/child relationship) or if you prefer using a "`fluent`" builder API, you can -use the `SpringApplicationBuilder`. - -The `SpringApplicationBuilder` lets you chain together multiple method calls and includes -`parent` and `child` methods that let you create a hierarchy, as shown in the following -example: - -[source,java,indent=0] ----- -include::{code-examples}/builder/SpringApplicationBuilderExample.java[tag=hierarchy] ----- - -NOTE: There are some restrictions when creating an `ApplicationContext` hierarchy. For -example, Web components *must* be contained within the child context, and the same -`Environment` is used for both parent and child contexts. See the -{dc-spring-boot}/builder/SpringApplicationBuilder.{dc-ext}[`SpringApplicationBuilder` -Javadoc] for full details. - - - -[[boot-features-application-events-and-listeners]] -=== Application Events and Listeners -In addition to the usual Spring Framework events, such as -{spring-javadoc}/context/event/ContextRefreshedEvent.{dc-ext}[`ContextRefreshedEvent`], -a `SpringApplication` sends some additional application events. - -[NOTE] -==== -Some events are actually triggered before the `ApplicationContext` is created, so you -cannot register a listener on those as a `@Bean`. You can register them with the -`SpringApplication.addListeners(...)` method or the -`SpringApplicationBuilder.listeners(...)` method. - -If you want those listeners to be registered automatically, regardless of the way the -application is created, you can add a `META-INF/spring.factories` file to your project -and reference your listener(s) by using the -`org.springframework.context.ApplicationListener` key, as shown in the following example: - -[indent=0] ----- - org.springframework.context.ApplicationListener=com.example.project.MyListener ----- - -==== - -Application events are sent in the following order, as your application runs: - -. An `ApplicationStartingEvent` is sent at the start of a run but before any processing, -except for the registration of listeners and initializers. -. An `ApplicationEnvironmentPreparedEvent` is sent when the `Environment` to be used in -the context is known but before the context is created. -. An `ApplicationContextInitializedEvent` is sent when the `ApplicationContext` is prepared -and ApplicationContextInitializers have been called but before any bean definitions are loaded. -. An `ApplicationPreparedEvent` is sent just before the refresh is started but after bean -definitions have been loaded. -. An `ApplicationStartedEvent` is sent after the context has been refreshed but before any -application and command-line runners have been called. -. An `ApplicationReadyEvent` is sent after any application and command-line runners have -been called. It indicates that the application is ready to service requests. -. An `ApplicationFailedEvent` is sent if there is an exception on startup. - -The above list only includes `SpringApplicationEvent`s that are tied to a `SpringApplication`. -In addition to these, the following events are also published after `ApplicationPreparedEvent` -and before `ApplicationStartedEvent`: - -. A `ContextRefreshedEvent` is sent when an `ApplicationContext` is refreshed. -. A `WebServerInitializedEvent` is sent after the `WebServer` is ready. `ServletWebServerInitializedEvent` -and `ReactiveWebServerInitializedEvent` are the servlet and reactive variants respectively. - -TIP: You often need not use application events, but it can be handy to know that they -exist. Internally, Spring Boot uses events to handle a variety of tasks. - -Application events are sent by using Spring Framework's event publishing mechanism. Part -of this mechanism ensures that an event published to the listeners in a child context is -also published to the listeners in any ancestor contexts. As a result of this, if your -application uses a hierarchy of `SpringApplication` instances, a listener may receive -multiple instances of the same type of application event. - -To allow your listener to distinguish between an event for its context and an event for -a descendant context, it should request that its application context is injected and then -compare the injected context with the context of the event. The context can be injected -by implementing `ApplicationContextAware` or, if the listener is a bean, by using -`@Autowired`. - - - -[[boot-features-web-environment]] -=== Web Environment -A `SpringApplication` attempts to create the right type of `ApplicationContext` on your -behalf. The algorithm used to determine a `WebApplicationType` is fairly simple: - -* If Spring MVC is present, an `AnnotationConfigServletWebServerApplicationContext` is -used -* If Spring MVC is not present and Spring WebFlux is present, an -`AnnotationConfigReactiveWebServerApplicationContext` is used -* Otherwise, `AnnotationConfigApplicationContext` is used - -This means that if you are using Spring MVC and the new `WebClient` from Spring WebFlux in -the same application, Spring MVC will be used by default. You can override that easily -by calling `setWebApplicationType(WebApplicationType)`. - -It is also possible to take complete control of the `ApplicationContext` type that is -used by calling `setApplicationContextClass(...)`. - -TIP: It is often desirable to call `setWebApplicationType(WebApplicationType.NONE)` when -using `SpringApplication` within a JUnit test. - - - -[[boot-features-application-arguments]] -=== Accessing Application Arguments -If you need to access the application arguments that were passed to -`SpringApplication.run(...)`, you can inject a -`org.springframework.boot.ApplicationArguments` bean. The `ApplicationArguments` -interface provides access to both the raw `String[]` arguments as well as parsed `option` -and `non-option` arguments, as shown in the following example: - -[source,java,indent=0] ----- - import org.springframework.boot.*; - import org.springframework.beans.factory.annotation.*; - import org.springframework.stereotype.*; - - @Component - public class MyBean { - - @Autowired - public MyBean(ApplicationArguments args) { - boolean debug = args.containsOption("debug"); - List files = args.getNonOptionArgs(); - // if run with "--debug logfile.txt" debug=true, files=["logfile.txt"] - } - - } ----- - -TIP: Spring Boot also registers a `CommandLinePropertySource` with the Spring -`Environment`. This lets you also inject single application arguments by using the -`@Value` annotation. - - - -[[boot-features-command-line-runner]] -=== Using the ApplicationRunner or CommandLineRunner -If you need to run some specific code once the `SpringApplication` has started, you can -implement the `ApplicationRunner` or `CommandLineRunner` interfaces. Both interfaces work -in the same way and offer a single `run` method, which is called just before -`SpringApplication.run(...)` completes. - -The `CommandLineRunner` interfaces provides access to application arguments as a simple -string array, whereas the `ApplicationRunner` uses the `ApplicationArguments` interface -discussed earlier. The following example shows a `CommandLineRunner` with a `run` method: - -[source,java,indent=0] ----- - import org.springframework.boot.*; - import org.springframework.stereotype.*; - - @Component - public class MyBean implements CommandLineRunner { - - public void run(String... args) { - // Do something... - } - - } ----- - -If several `CommandLineRunner` or `ApplicationRunner` beans are defined that must be -called in a specific order, you can additionally implement the -`org.springframework.core.Ordered` interface or use the -`org.springframework.core.annotation.Order` annotation. - - - -[[boot-features-application-exit]] -=== Application Exit -Each `SpringApplication` registers a shutdown hook with the JVM to ensure that the -`ApplicationContext` closes gracefully on exit. All the standard Spring lifecycle -callbacks (such as the `DisposableBean` interface or the `@PreDestroy` annotation) can be -used. - -In addition, beans may implement the `org.springframework.boot.ExitCodeGenerator` -interface if they wish to return a specific exit code when `SpringApplication.exit()` is -called. This exit code can then be passed to `System.exit()` to return it as a status -code, as shown in the following example: - -[source,java,indent=0] ----- -include::{code-examples}/ExitCodeApplication.java[tag=example] ----- - -Also, the `ExitCodeGenerator` interface may be implemented by exceptions. When such an -exception is encountered, Spring Boot returns the exit code provided by the implemented -`getExitCode()` method. - - -[[boot-features-application-admin]] -=== Admin Features -It is possible to enable admin-related features for the application by specifying the -`spring.application.admin.enabled` property. This exposes the -{sc-spring-boot}/admin/SpringApplicationAdminMXBean.{sc-ext}[`SpringApplicationAdminMXBean`] -on the platform `MBeanServer`. You could use this feature to administer your Spring Boot -application remotely. This feature could also be useful for any service wrapper -implementation. - -TIP: If you want to know on which HTTP port the application is running, get the property -with a key of `local.server.port`. - -CAUTION: Take care when enabling this feature, as the MBean exposes a method to shutdown -the application. - - - -[[boot-features-external-config]] -== Externalized Configuration -Spring Boot lets you externalize your configuration so that you can work with the same -application code in different environments. You can use properties files, YAML files, -environment variables, and command-line arguments to externalize configuration. Property -values can be injected directly into your beans by using the `@Value` annotation, -accessed through Spring's `Environment` abstraction, or be -<> through `@ConfigurationProperties`. - -Spring Boot uses a very particular `PropertySource` order that is designed to allow -sensible overriding of values. Properties are considered in the following order: - -. <> -on your home directory (`~/.spring-boot-devtools.properties` when devtools is active). -. {spring-javadoc}/test/context/TestPropertySource.{dc-ext}[`@TestPropertySource`] -annotations on your tests. -. `properties` attribute on your tests. Available on -{dc-spring-boot-test}/context/SpringBootTest.{dc-ext}[`@SpringBootTest`] and the -<>. -. Command line arguments. -. Properties from `SPRING_APPLICATION_JSON` (inline JSON embedded in an environment -variable or system property). -. `ServletConfig` init parameters. -. `ServletContext` init parameters. -. JNDI attributes from `java:comp/env`. -. Java System properties (`System.getProperties()`). -. OS environment variables. -. A `RandomValuePropertySource` that has properties only in `+random.*+`. -. <> outside of your packaged jar -(`application-\{profile}.properties` and YAML variants). -. <> packaged inside your jar (`application-\{profile}.properties` -and YAML variants). -. Application properties outside of your packaged jar (`application.properties` and YAML -variants). -. Application properties packaged inside your jar (`application.properties` and YAML -variants). -. {spring-javadoc}/context/annotation/PropertySource.{dc-ext}[`@PropertySource`] -annotations on your `@Configuration` classes. -. Default properties (specified by setting `SpringApplication.setDefaultProperties`). - -To provide a concrete example, suppose you develop a `@Component` that uses a `name` -property, as shown in the following example: - -[source,java,indent=0] ----- - import org.springframework.stereotype.*; - import org.springframework.beans.factory.annotation.*; - - @Component - public class MyBean { - - @Value("${name}") - private String name; - - // ... - - } ----- - -On your application classpath (for example, inside your jar) you can have an -`application.properties` file that provides a sensible default property value for `name`. -When running in a new environment, an `application.properties` file can be provided -outside of your jar that overrides the `name`. For one-off testing, you can launch with a -specific command line switch (for example, `java -jar app.jar --name="Spring"`). - -[TIP] -==== -The `SPRING_APPLICATION_JSON` properties can be supplied on the command line with an -environment variable. For example, you could use the following line in a UN{asterisk}X -shell: - ----- -$ SPRING_APPLICATION_JSON='{"acme":{"name":"test"}}' java -jar myapp.jar ----- - -In the preceding example, you end up with `acme.name=test` in the Spring `Environment`. -You can also supply the JSON as `spring.application.json` in a System property, as shown -in the following example: - ----- -$ java -Dspring.application.json='{"name":"test"}' -jar myapp.jar ----- - -You can also supply the JSON by using a command line argument, as shown in the following -example: - ----- -$ java -jar myapp.jar --spring.application.json='{"name":"test"}' ----- - -You can also supply the JSON as a JNDI variable, as follows: -`java:comp/env/spring.application.json`. -==== - - - -[[boot-features-external-config-random-values]] -=== Configuring Random Values -The `RandomValuePropertySource` is useful for injecting random values (for example, into -secrets or test cases). It can produce integers, longs, uuids, or strings, as shown in the -following example: - -[source,properties,indent=0] ----- - my.secret=${random.value} - my.number=${random.int} - my.bignumber=${random.long} - my.uuid=${random.uuid} - my.number.less.than.ten=${random.int(10)} - my.number.in.range=${random.int[1024,65536]} ----- - -The `+random.int*+` syntax is `OPEN value (,max) CLOSE` where the `OPEN,CLOSE` are any -character and `value,max` are integers. If `max` is provided, then `value` is the minimum -value and `max` is the maximum value (exclusive). - - - -[[boot-features-external-config-command-line-args]] -=== Accessing Command Line Properties -By default, `SpringApplication` converts any command line option arguments (that is, -arguments starting with `--`, such as `--server.port=9000`) to a `property` and adds -them to the Spring `Environment`. As mentioned previously, command line properties always -take precedence over other property sources. - -If you do not want command line properties to be added to the `Environment`, you can -disable them by using `SpringApplication.setAddCommandLineProperties(false)`. - - - -[[boot-features-external-config-application-property-files]] -=== Application Property Files -`SpringApplication` loads properties from `application.properties` files in the following -locations and adds them to the Spring `Environment`: - -. A `/config` subdirectory of the current directory -. The current directory -. A classpath `/config` package -. The classpath root - -The list is ordered by precedence (properties defined in locations higher in the list -override those defined in lower locations). - -NOTE: You can also <> as an -alternative to '.properties'. - -If you do not like `application.properties` as the configuration file name, you can -switch to another file name by specifying a `spring.config.name` environment property. -You can also refer to an explicit location by using the `spring.config.location` -environment property (which is a comma-separated list of directory locations or file -paths). The following example shows how to specify a different file name: - -[indent=0] ----- - $ java -jar myproject.jar --spring.config.name=myproject ----- - -The following example shows how to specify two locations: - -[indent=0] ----- - $ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties ----- - -WARNING: `spring.config.name` and `spring.config.location` are used very early to -determine which files have to be loaded, so they must be defined as an environment -property (typically an OS environment variable, a system property, or a command-line -argument). - -If `spring.config.location` contains directories (as opposed to files), they should end -in `/` (and, at runtime, be appended with the names generated from `spring.config.name` -before being loaded, including profile-specific file names). Files specified in -`spring.config.location` are used as-is, with no support for profile-specific variants, -and are overridden by any profile-specific properties. - -Config locations are searched in reverse order. By default, the configured locations are -`classpath:/,classpath:/config/,file:./,file:./config/`. The resulting search order is -the following: - -. `file:./config/` -. `file:./` -. `classpath:/config/` -. `classpath:/` - -When custom config locations are configured by using `spring.config.location`, they -replace the default locations. For example, if `spring.config.location` is configured with -the value `classpath:/custom-config/,file:./custom-config/`, the search order becomes the -following: - -. `file:./custom-config/` -. `classpath:custom-config/` - -Alternatively, when custom config locations are configured by using -`spring.config.additional-location`, they are used in addition to the default locations. -Additional locations are searched before the default locations. For example, if -additional locations of `classpath:/custom-config/,file:./custom-config/` are configured, -the search order becomes the following: - -. `file:./custom-config/` -. `classpath:custom-config/` -. `file:./config/` -. `file:./` -. `classpath:/config/` -. `classpath:/` - -This search ordering lets you specify default values in one configuration file and then -selectively override those values in another. You can provide default values for your -application in `application.properties` (or whatever other basename you choose with -`spring.config.name`) in one of the default locations. These default values can then be -overridden at runtime with a different file located in one of the custom locations. - -NOTE: If you use environment variables rather than system properties, most operating -systems disallow period-separated key names, but you can use underscores instead (for -example, `SPRING_CONFIG_NAME` instead of `spring.config.name`). - -NOTE: If your application runs in a container, then JNDI properties (in `java:comp/env`) -or servlet context initialization parameters can be used instead of, or as well as, -environment variables or system properties. - - - -[[boot-features-external-config-profile-specific-properties]] -=== Profile-specific Properties -In addition to `application.properties` files, profile-specific properties can also be -defined by using the following naming convention: `application-\{profile}.properties`. The -`Environment` has a set of default profiles (by default, `[default]`) that are used if no -active profiles are set. In other words, if no profiles are explicitly activated, then -properties from `application-default.properties` are loaded. - -Profile-specific properties are loaded from the same locations as standard -`application.properties`, with profile-specific files always overriding the non-specific -ones, whether or not the profile-specific files are inside or outside your -packaged jar. - -If several profiles are specified, a last-wins strategy applies. For example, profiles -specified by the `spring.profiles.active` property are added after those configured -through the `SpringApplication` API and therefore take precedence. - -NOTE: If you have specified any files in `spring.config.location`, profile-specific -variants of those files are not considered. Use directories in -`spring.config.location` if you want to also use profile-specific properties. - - - -[[boot-features-external-config-placeholders-in-properties]] -=== Placeholders in Properties -The values in `application.properties` are filtered through the existing `Environment` -when they are used, so you can refer back to previously defined values (for example, from -System properties). - -[source,properties,indent=0] ----- - app.name=MyApp - app.description=${app.name} is a Spring Boot application ----- - -TIP: You can also use this technique to create "`short`" variants of existing Spring Boot -properties. See the _<>_ how-to for -details. - - - -[[boot-features-encrypting-properties]] -=== Encrypting Properties -Spring Boot does not provide any built in support for encrypting property values, however, -it does provide the hook points necessary to modify values contained in the Spring -`Environment`. The `EnvironmentPostProcessor` interface allows you to manipulate the -`Environment` before the application starts. See <> -for details. - -If you're looking for a secure way to store credentials and passwords, the -https://cloud.spring.io/spring-cloud-vault/[Spring Cloud Vault] project provides -support for storing externalized configuration in -https://www.vaultproject.io/[HashiCorp Vault]. - - - -[[boot-features-external-config-yaml]] -=== Using YAML Instead of Properties -https://yaml.org[YAML] is a superset of JSON and, as such, is a convenient format for -specifying hierarchical configuration data. The `SpringApplication` class automatically -supports YAML as an alternative to properties whenever you have the -https://bitbucket.org/asomov/snakeyaml[SnakeYAML] library on your classpath. - -NOTE: If you use "`Starters`", SnakeYAML is automatically provided by -`spring-boot-starter`. - - - -[[boot-features-external-config-loading-yaml]] -==== Loading YAML -Spring Framework provides two convenient classes that can be used to load YAML documents. -The `YamlPropertiesFactoryBean` loads YAML as `Properties` and the `YamlMapFactoryBean` -loads YAML as a `Map`. - -For example, consider the following YAML document: - -[source,yaml,indent=0] ----- - environments: - dev: - url: https://dev.example.com - name: Developer Setup - prod: - url: https://another.example.com - name: My Cool App ----- - -The preceding example would be transformed into the following properties: - -[source,properties,indent=0] ----- - environments.dev.url=https://dev.example.com - environments.dev.name=Developer Setup - environments.prod.url=https://another.example.com - environments.prod.name=My Cool App ----- - -YAML lists are represented as property keys with `[index]` dereferencers. For example, -consider the following YAML: - -[source,yaml,indent=0] ----- - my: - servers: - - dev.example.com - - another.example.com ----- - -The preceding example would be transformed into these properties: - -[source,properties,indent=0] ----- - my.servers[0]=dev.example.com - my.servers[1]=another.example.com ----- - -To bind to properties like that by using Spring Boot's `Binder` utilities (which is what -`@ConfigurationProperties` does), you need to have a property in the target bean of type -`java.util.List` (or `Set`) and you either need to provide a setter or initialize it with -a mutable value. For example, the following example binds to the properties shown -previously: - -[source,java,indent=0] ----- - @ConfigurationProperties(prefix="my") - public class Config { - - private List servers = new ArrayList(); - - public List getServers() { - return this.servers; - } - } ----- - - - -[[boot-features-external-config-exposing-yaml-to-spring]] -==== Exposing YAML as Properties in the Spring Environment -The `YamlPropertySourceLoader` class can be used to expose YAML as a `PropertySource` in -the Spring `Environment`. Doing so lets you use the `@Value` annotation with placeholders -syntax to access YAML properties. - - - -[[boot-features-external-config-multi-profile-yaml]] -==== Multi-profile YAML Documents -You can specify multiple profile-specific YAML documents in a single file by using a -`spring.profiles` key to indicate when the document applies, as shown in the following -example: - -[source,yaml,indent=0] ----- - server: - address: 192.168.1.100 - --- - spring: - profiles: development - server: - address: 127.0.0.1 - --- - spring: - profiles: production & eu-central - server: - address: 192.168.1.120 ----- - -In the preceding example, if the `development` profile is active, the `server.address` -property is `127.0.0.1`. Similarly, if the `production` *and* `eu-central` profiles are -active, the `server.address` property is `192.168.1.120`. If the `development`, -`production` and `eu-central` profiles are *not* enabled, then the value for the property -is `192.168.1.100`. - -[NOTE] -==== -`spring.profiles` can therefore contain a simple profile name (for example `production`) -or a profile expression. A profile expression allows for more complicated profile logic -to be expressed, for example `production & (eu-central | eu-west)`. Check the -{spring-reference}core.html#beans-definition-profiles-java[reference guide] for more -details. -==== - -If none are explicitly active when the application context starts, the default profiles -are activated. So, in the following YAML, we set a value for `spring.security.user.password` -that is available *only* in the "default" profile: - -[source,yaml,indent=0] ----- - server: - port: 8000 - --- - spring: - profiles: default - security: - user: - password: weak ----- - -Whereas, in the following example, the password is always set because it is not attached -to any profile, and it would have to be explicitly reset in all other profiles as -necessary: - -[source,yaml,indent=0] ----- - server: - port: 8000 - spring: - security: - user: - password: weak ----- - -Spring profiles designated by using the `spring.profiles` element may optionally be -negated by using the `!` character. If both negated and non-negated profiles are -specified for a single document, at least one non-negated profile must match, and no -negated profiles may match. - - - -[[boot-features-external-config-yaml-shortcomings]] -==== YAML Shortcomings -YAML files cannot be loaded by using the `@PropertySource` annotation. So, in the case -that you need to load values that way, you need to use a properties file. - -Using the multi YAML document syntax in profile-specific YAML files can lead to unexpected -behavior. For example, consider the following config in a file called `application-dev.yml`, -with the `dev` profile being active: - -[source,yaml,indent=0] ----- - server: - port: 8000 - --- - spring: - profiles: !test - security: - user: - password: weak ----- - -In the example above, profile negation and profile expressions will not behave as expected. -We recommend that you don't combine profile-specific YAML files and multiple YAML documents and stick -to using only one of them. - - - -[[boot-features-external-config-typesafe-configuration-properties]] -=== Type-safe Configuration Properties -Using the `@Value("$\{property}")` annotation to inject configuration properties can -sometimes be cumbersome, especially if you are working with multiple properties or your -data is hierarchical in nature. Spring Boot provides an alternative method of working -with properties that lets strongly typed beans govern and validate the configuration of -your application. - -TIP: See also the <>. - - - -[[boot-features-external-config-java-bean-binding]] -==== JavaBean properties binding -It is possible to bind a bean declaring standard JavaBean properties as shown in the -following example: - -[source,java,indent=0] ----- - package com.example; - - import java.net.InetAddress; - import java.util.ArrayList; - import java.util.Collections; - import java.util.List; - - import org.springframework.boot.context.properties.ConfigurationProperties; - - @ConfigurationProperties("acme") - public class AcmeProperties { - - private boolean enabled; - - private InetAddress remoteAddress; - - private final Security security = new Security(); - - public boolean isEnabled() { ... } - - public void setEnabled(boolean enabled) { ... } - - public InetAddress getRemoteAddress() { ... } - - public void setRemoteAddress(InetAddress remoteAddress) { ... } - - public Security getSecurity() { ... } - - public static class Security { - - private String username; - - private String password; - - private List roles = new ArrayList<>(Collections.singleton("USER")); - - public String getUsername() { ... } - - public void setUsername(String username) { ... } - - public String getPassword() { ... } - - public void setPassword(String password) { ... } - - public List getRoles() { ... } - - public void setRoles(List roles) { ... } - - } - } ----- - -The preceding POJO defines the following properties: - -* `acme.enabled`, with a value of `false` by default. -* `acme.remote-address`, with a type that can be coerced from `String`. -* `acme.security.username`, with a nested "security" object whose name is determined by -the name of the property. In particular, the return type is not used at all there and -could have been `SecurityProperties`. -* `acme.security.password`. -* `acme.security.roles`, with a collection of `String` that defaults to `USER`. - -[NOTE] -==== -Such arrangement relies on a default empty constructor and getters and setters are usually -mandatory, since binding is through standard Java Beans property descriptors, just like in -Spring MVC. A setter may be omitted in the following cases: - -* Maps, as long as they are initialized, need a getter but not necessarily a setter, -since they can be mutated by the binder. -* Collections and arrays can be accessed either through an index (typically with YAML) or -by using a single comma-separated value (properties). In the latter case, a setter is -mandatory. We recommend to always add a setter for such types. If you initialize a -collection, make sure it is not immutable (as in the preceding example). -* If nested POJO properties are initialized (like the `Security` field in the preceding -example), a setter is not required. If you want the binder to create the instance on the -fly by using its default constructor, you need a setter. - -Some people use Project Lombok to add getters and setters automatically. Make sure that -Lombok does not generate any particular constructor for such a type, as it is used -automatically by the container to instantiate the object. - -Finally, only standard Java Bean properties are considered and binding on static -properties is not supported. -==== - - - -[[boot-features-external-config-constructor-binding]] -==== Constructor binding -The example in the previous section can be rewritten in an immutable fashion as shown in -the following example: - -[source,java,indent=0] ----- - package com.example; - - import java.net.InetAddress; - import java.util.List; - - import org.springframework.boot.context.properties.ConfigurationProperties; - import org.springframework.boot.context.properties.DefaultValue; - - @ConfigurationProperties("acme") - public class AcmeProperties { - - private final boolean enabled; - - private final InetAddress remoteAddress; - - private final Security security; - - public AcmeProperties(boolean enabled, InetAddress remoteAddress, Security security) { - this.enabled = enabled; - this.remoteAddress = remoteAddress; - this.security = security; - } - - public boolean isEnabled() { ... } - - public InetAddress getRemoteAddress() { ... } - - public Security getSecurity() { ... } - - public static class Security { - - private final String username; - - private final String password; - - private final List roles; - - public Security(String username, String password, - @DefaultValue("USER") List roles) { - this.username = username; - this.password = password; - this.roles = roles; - } - - public String getUsername() { ... } - - public String getPassword() { ... } - - public List getRoles() { ... } - - } - - } ----- - -In this setup one, and only one constructor must be defined with the list of properties -that you wish to bind and not other properties than the ones in the constructor are bound. - -Default values can be specified using `@DefaultValue` and the same conversion service will -be applied to coerce the `String` value to the target type of a missing property. - - - -[[boot-features-external-config-enabling]] -==== Enabling `@ConfigurationProperties`-annotated types -Spring Boot provides an infrastructure to bind such types and register them as beans -automatically. If your application uses `@SpringBootApplication`, classes annotated with -`@ConfigurationProperties` will automatically be scanned and registered as beans. By default, -scanning will occur from the package of the class that declares this annotation. If you want -to define specific packages to scan, you can do so using an explicit `@ConfigurationPropertiesScan` -directive on your `@SpringBootApplication`-annotated class as shown in the following example: - -[source,java,indent=0] ----- - @SpringBootApplication - @ConfigurationPropertiesScan({ "com.example.app", "org.acme.another" }) - public class MyApplication { - } ----- - -Sometimes, classes annotated with `@ConfigurationProperties` might not be suitable -for scanning, for example, if you're developing your own auto-configuration. In these -cases, you can specify the list of types to process on any `@Configuration` class as -shown in the following example: - -[source,java,indent=0] ----- - @Configuration(proxyBeanMethods = false) - @EnableConfigurationProperties(AcmeProperties.class) - public class MyConfiguration { - } ----- - -[NOTE] -==== -When the `@ConfigurationProperties` bean is registered using scanning or via -`@EnableConfigurationProperties`, the bean has a conventional name: `-`, -where `` is the environment key prefix specified in the `@ConfigurationProperties` -annotation and `` is the fully qualified name of the bean. If the annotation does not -provide any prefix, only the fully qualified name of the bean is used. - -The bean name in the example above is `acme-com.example.AcmeProperties`. -==== - -We recommend that `@ConfigurationProperties` only deal with the environment and, in -particular, does not inject other beans from the context. In particular, it is not -possible to inject other beans using the constructor as this would trigger the constructor -binder that only deals with the environment. - -For corner cases, setter injection can be used or any of the `*Aware` interfaces provided -by the framework (such as `EnvironmentAware` if you need access to the `Environment`). - -NOTE: Annotating a `@ConfigurationProperties` type with `@Component` will result in two -beans of the same type if the type is also scanned as part of classpath scanning. If you want -to register the bean yourself using `@Component`, consider disabling scanning of -`@ConfigurationProperties`. - - - -[[boot-features-external-config-using]] -==== Using `@ConfigurationProperties`-annotated types -This style of configuration works particularly well with the `SpringApplication` external -YAML configuration, as shown in the following example: - -[source,yaml,indent=0] ----- - # application.yml - - acme: - remote-address: 192.168.1.1 - security: - username: admin - roles: - - USER - - ADMIN - - # additional configuration as required ----- - -To work with `@ConfigurationProperties` beans, you can inject them in the same way -as any other bean, as shown in the following example: - -[source,java,indent=0] ----- - @Service - public class MyService { - - private final AcmeProperties properties; - - @Autowired - public MyService(AcmeProperties properties) { - this.properties = properties; - } - - //... - - @PostConstruct - public void openConnection() { - Server server = new Server(this.properties.getRemoteAddress()); - // ... - } - - } ----- - -TIP: Using `@ConfigurationProperties` also lets you generate metadata files that can be -used by IDEs to offer auto-completion for your own keys. See the -<> for details. - - - -[[boot-features-external-config-3rd-party-configuration]] -==== Third-party Configuration -As well as using `@ConfigurationProperties` to annotate a class, you can also use it on -public `@Bean` methods. Doing so can be particularly useful when you want to bind -properties to third-party components that are outside of your control. - -To configure a bean from the `Environment` properties, add `@ConfigurationProperties` to -its bean registration, as shown in the following example: - -[source,java,indent=0] ----- - @ConfigurationProperties(prefix = "another") - @Bean - public AnotherComponent anotherComponent() { - ... - } ----- - -Any JavaBean property defined with the `another` prefix is mapped onto that -`AnotherComponent` bean in manner similar to the preceding `AcmeProperties` example. - - - -[[boot-features-external-config-relaxed-binding]] -==== Relaxed Binding -Spring Boot uses some relaxed rules for binding `Environment` properties to -`@ConfigurationProperties` beans, so there does not need to be an exact match between the -`Environment` property name and the bean property name. Common examples where this is -useful include dash-separated environment properties (for example, `context-path` binds -to `contextPath`), and capitalized environment properties (for example, `PORT` binds to -`port`). - -For example, consider the following `@ConfigurationProperties` class: - -[source,java,indent=0] ----- - @ConfigurationProperties(prefix="acme.my-project.person") - public class OwnerProperties { - - private String firstName; - - public String getFirstName() { - return this.firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - } ----- - -In the preceding example, the following properties names can all be used: - -.relaxed binding -[cols="1,4"] -|=== -| Property | Note - -|`acme.my-project.person.first-name` -|Kebab case, which is recommended for use in `.properties` and `.yml` files. - -|`acme.myProject.person.firstName` -|Standard camel case syntax. - -|`acme.my_project.person.first_name` -|Underscore notation, which is an alternative format for use in `.properties` and `.yml` -files. - -|`ACME_MYPROJECT_PERSON_FIRSTNAME` -|Upper case format, which is recommended when using system environment variables. -|=== - -NOTE: The `prefix` value for the annotation _must_ be in kebab case (lowercase and -separated by `-`, such as `acme.my-project.person`). - -.relaxed binding rules per property source -[cols="2,4,4"] -|=== -| Property Source | Simple | List - -|Properties Files -|Camel case, kebab case, or underscore notation -|Standard list syntax using `[ ]` or comma-separated values - -|YAML Files -|Camel case, kebab case, or underscore notation -|Standard YAML list syntax or comma-separated values - -|Environment Variables -|Upper case format with underscore as the delimiter. `_` should not be used within a -property name -|Numeric values surrounded by underscores, such as `MY_ACME_1_OTHER = my.acme[1].other` - -|System properties -|Camel case, kebab case, or underscore notation -|Standard list syntax using `[ ]` or comma-separated values -|=== - -TIP: We recommend that, when possible, properties are stored in lower-case kebab format, -such as `my.property-name=acme`. - -When binding to `Map` properties, if the `key` contains anything other than lowercase -alpha-numeric characters or `-`, you need to use the bracket notation so that the original -value is preserved. If the key is not surrounded by `[]`, any characters that are not alpha-numeric -or `-` are removed. For example, consider binding the following properties to a `Map`: - -[source,yaml,indent=0] ----- - acme: - map: - "[/key1]": value1 - "[/key2]": value2 - /key3: value3 - ----- - -The properties above will bind to a `Map` with `/key1`, `/key2` and `key3` as the keys in the map. - - -[[boot-features-external-config-complex-type-merge]] -==== Merging Complex Types -When lists are configured in more than one place, overriding works by replacing the entire -list. - -For example, assume a `MyPojo` object with `name` and `description` attributes that are -`null` by default. The following example exposes a list of `MyPojo` objects from -`AcmeProperties`: - -[source,java,indent=0] ----- - @ConfigurationProperties("acme") - public class AcmeProperties { - - private final List list = new ArrayList<>(); - - public List getList() { - return this.list; - } - - } ----- - -Consider the following configuration: - -[source,yaml,indent=0] ----- - acme: - list: - - name: my name - description: my description - --- - spring: - profiles: dev - acme: - list: - - name: my another name ----- - -If the `dev` profile is not active, `AcmeProperties.list` contains one `MyPojo` entry, -as previously defined. If the `dev` profile is enabled, however, the `list` _still_ -contains only one entry (with a name of `my another name` and a description of `null`). -This configuration _does not_ add a second `MyPojo` instance to the list, and it does not -merge the items. - -When a `List` is specified in multiple profiles, the one with the highest priority -(and only that one) is used. Consider the following example: - -[source,yaml,indent=0] ----- - acme: - list: - - name: my name - description: my description - - name: another name - description: another description - --- - spring: - profiles: dev - acme: - list: - - name: my another name ----- - -In the preceding example, if the `dev` profile is active, `AcmeProperties.list` contains -_one_ `MyPojo` entry (with a name of `my another name` and a description of `null`). -For YAML, both comma-separated lists and YAML lists can be used for -completely overriding the contents of the list. - -For `Map` properties, you can bind with property values drawn from multiple sources. However, -for the same property in multiple sources, the one with the highest priority is used. -The following example exposes a `Map` from `AcmeProperties`: - -[source,java,indent=0] ----- - @ConfigurationProperties("acme") - public class AcmeProperties { - - private final Map map = new HashMap<>(); - - public Map getMap() { - return this.map; - } - - } ----- - -Consider the following configuration: - -[source,yaml,indent=0] ----- - acme: - map: - key1: - name: my name 1 - description: my description 1 - --- - spring: - profiles: dev - acme: - map: - key1: - name: dev name 1 - key2: - name: dev name 2 - description: dev description 2 ----- - -If the `dev` profile is not active, `AcmeProperties.map` contains one entry with key `key1` -(with a name of `my name 1` and a description of `my description 1`). -If the `dev` profile is enabled, however, `map` contains two entries with keys `key1` -(with a name of `dev name 1` and a description of `my description 1`) and -`key2` (with a name of `dev name 2` and a description of `dev description 2`). - -NOTE: The preceding merging rules apply to properties from all property sources and not just -YAML files. - -[[boot-features-external-config-conversion]] -==== Properties Conversion -Spring Boot attempts to coerce the external application properties to the right type when -it binds to the `@ConfigurationProperties` beans. If you need custom type conversion, you -can provide a `ConversionService` bean (with a bean named `conversionService`) or custom -property editors (through a `CustomEditorConfigurer` bean) or custom `Converters` (with -bean definitions annotated as `@ConfigurationPropertiesBinding`). - -NOTE: As this bean is requested very early during the application lifecycle, make sure to -limit the dependencies that your `ConversionService` is using. Typically, any dependency -that you require may not be fully initialized at creation time. You may want to rename -your custom `ConversionService` if it is not required for configuration keys coercion and -only rely on custom converters qualified with `@ConfigurationPropertiesBinding`. - - - -[[boot-features-external-config-conversion-duration]] -===== Converting durations -Spring Boot has dedicated support for expressing durations. If you expose a -`java.time.Duration` property, the following formats in application properties are -available: - -* A regular `long` representation (using milliseconds as the default unit unless a -`@DurationUnit` has been specified) -* The standard ISO-8601 format -{java-javadoc}/java/time/Duration.html#parse-java.lang.CharSequence-[used by -`java.time.Duration`] -* A more readable format where the value and the unit are coupled (e.g. `10s` means 10 -seconds) - -Consider the following example: - -[source,java,indent=0] ----- -include::{code-examples}/context/properties/bind/AppSystemProperties.java[tag=example] ----- - -To specify a session timeout of 30 seconds, `30`, `PT30S` and `30s` are all equivalent. A -read timeout of 500ms can be specified in any of the following form: `500`, `PT0.5S` and -`500ms`. - -You can also use any of the supported units. These are: - -* `ns` for nanoseconds -* `us` for microseconds -* `ms` for milliseconds -* `s` for seconds -* `m` for minutes -* `h` for hours -* `d` for days - -The default unit is milliseconds and can be overridden using `@DurationUnit` as illustrated -in the sample above. - -TIP: If you are upgrading from a previous version that is simply using `Long` to express -the duration, make sure to define the unit (using `@DurationUnit`) if it isn't -milliseconds alongside the switch to `Duration`. Doing so gives a transparent upgrade path -while supporting a much richer format. - - - -[[boot-features-external-config-conversion-datasize]] -===== Converting Data Sizes -Spring Framework has a `DataSize` value type that allows to express size in bytes. If you -expose a `DataSize` property, the following formats in application properties are -available: - -* A regular `long` representation (using bytes as the default unit unless a -`@DataSizeUnit` has been specified) -* A more readable format where the value and the unit are coupled (e.g. `10MB` means 10 -megabytes) - -Consider the following example: - -[source,java,indent=0] ----- -include::{code-examples}/context/properties/bind/AppIoProperties.java[tag=example] ----- - -To specify a buffer size of 10 megabytes, `10` and `10MB` are equivalent. A size threshold -of 256 bytes can be specified as `256` or `256B`. - -You can also use any of the supported units. These are: - -* `B` for bytes -* `KB` for kilobytes -* `MB` for megabytes -* `GB` for gigabytes -* `TB` for terabytes - -The default unit is bytes and can be overridden using `@DataSizeUnit` as illustrated -in the sample above. - -TIP: If you are upgrading from a previous version that is simply using `Long` to express -the size, make sure to define the unit (using `@DataSizeUnit`) if it isn't bytes alongside -the switch to `DataSize`. Doing so gives a transparent upgrade path while supporting a -much richer format. - - - -[[boot-features-external-config-validation]] -==== @ConfigurationProperties Validation -Spring Boot attempts to validate `@ConfigurationProperties` classes whenever they are -annotated with Spring's `@Validated` annotation. You can use JSR-303 `javax.validation` -constraint annotations directly on your configuration class. To do so, ensure that a -compliant JSR-303 implementation is on your classpath and then add constraint annotations -to your fields, as shown in the following example: - -[source,java,indent=0] ----- - @ConfigurationProperties(prefix="acme") - @Validated - public class AcmeProperties { - - @NotNull - private InetAddress remoteAddress; - - // ... getters and setters - - } ----- - -TIP: You can also trigger validation by annotating the `@Bean` method that creates the -configuration properties with `@Validated`. - -Although nested properties will also be validated when bound, it's good practice to -also annotate the associated field as `@Valid`. This ensure that validation is triggered -even if no nested properties are found. The following example builds on the preceding -`AcmeProperties` example: - -[source,java,indent=0] ----- - @ConfigurationProperties(prefix="acme") - @Validated - public class AcmeProperties { - - @NotNull - private InetAddress remoteAddress; - - @Valid - private final Security security = new Security(); - - // ... getters and setters - - public static class Security { - - @NotEmpty - public String username; - - // ... getters and setters - - } - - } ----- - -You can also add a custom Spring `Validator` by creating a bean definition called -`configurationPropertiesValidator`. The `@Bean` method should be declared `static`. The -configuration properties validator is created very early in the application's lifecycle, -and declaring the `@Bean` method as static lets the bean be created without having to -instantiate the `@Configuration` class. Doing so avoids any problems that may be caused -by early instantiation. - -TIP: The `spring-boot-actuator` module includes an endpoint that exposes all -`@ConfigurationProperties` beans. Point your web browser to -`/actuator/configprops` or use the equivalent JMX endpoint. See the -"<>" -section for details. - - - -[[boot-features-external-config-vs-value]] -==== @ConfigurationProperties vs. @Value -The `@Value` annotation is a core container feature, and it does not provide the same -features as type-safe configuration properties. The following table summarizes the -features that are supported by `@ConfigurationProperties` and `@Value`: - -[cols="4,2,2"] -|=== -|Feature |`@ConfigurationProperties` |`@Value` - -| <> -| Yes -| No - -| <> -| Yes -| No - -| `SpEL` evaluation -| No -| Yes -|=== - -If you define a set of configuration keys for your own components, we recommend you -group them in a POJO annotated with `@ConfigurationProperties`. You should also be aware -that, since `@Value` does not support relaxed binding, it is not a good candidate if you -need to provide the value by using environment variables. - -Finally, while you can write a `SpEL` expression in `@Value`, such expressions are not -processed from <>. - - - -[[boot-features-profiles]] -== Profiles -Spring Profiles provide a way to segregate parts of your application configuration and -make it be available only in certain environments. Any `@Component`, `@Configuration` -or `@ConfigurationProperties` can be marked with `@Profile` to limit when it is loaded, -as shown in the following example: - -[source,java,indent=0] ----- - @Configuration(proxyBeanMethods = false) - @Profile("production") - public class ProductionConfiguration { - - // ... - - } ----- - -NOTE: If `@ConfigurationProperties` beans are registered via `@EnableConfigurationProperties` -instead of automatic scanning, the `@Profile` annotation needs to be specified on the `@Configuration` -class that has the `@EnableConfigurationProperties` annotation. In the case where `@ConfigurationProperties` -are scanned, `@Profile` can be specified on the `@ConfigurationProperties` class itself. - -You can use a `spring.profiles.active` `Environment` property to specify which profiles -are active. You can specify the property in any of the ways described earlier in this -chapter. For example, you could include it in your `application.properties`, as shown in -the following example: - -[source,properties,indent=0] ----- - spring.profiles.active=dev,hsqldb ----- - -You could also specify it on the command line by using the following switch: -`--spring.profiles.active=dev,hsqldb`. - - - -[[boot-features-adding-active-profiles]] -=== Adding Active Profiles -The `spring.profiles.active` property follows the same ordering rules as other -properties: The highest `PropertySource` wins. This means that you can specify active -profiles in `application.properties` and then *replace* them by using the command line -switch. - -Sometimes, it is useful to have profile-specific properties that *add* to the active -profiles rather than replace them. The `spring.profiles.include` property can be used to -unconditionally add active profiles. The `SpringApplication` entry point also has a Java -API for setting additional profiles (that is, on top of those activated by the -`spring.profiles.active` property). See the `setAdditionalProfiles()` method in -{dc-spring-boot}/SpringApplication.html[SpringApplication]. - -For example, when an application with the following properties is run by using the -switch, `--spring.profiles.active=prod`, the `proddb` and `prodmq` profiles are also -activated: - -[source,yaml,indent=0] ----- - --- - my.property: fromyamlfile - --- - spring.profiles: prod - spring.profiles.include: - - proddb - - prodmq ----- - -NOTE: Remember that the `spring.profiles` property can be defined in a YAML document to -determine when this particular document is included in the configuration. See -<> for more details. - - - -[[boot-features-programmatically-setting-profiles]] -=== Programmatically Setting Profiles -You can programmatically set active profiles by calling -`SpringApplication.setAdditionalProfiles(...)` before your application runs. It is also -possible to activate profiles by using Spring's `ConfigurableEnvironment` interface. - - - -[[boot-features-profile-specific-configuration]] -=== Profile-specific Configuration Files -Profile-specific variants of both `application.properties` (or `application.yml`) and -files referenced through `@ConfigurationProperties` are considered as files and loaded. -See "<>" for details. - - - -[[boot-features-logging]] -== Logging -Spring Boot uses https://commons.apache.org/logging[Commons Logging] for all internal -logging but leaves the underlying log implementation open. Default configurations are -provided for -{java-javadoc}/java/util/logging/package-summary.html[Java Util -Logging], https://logging.apache.org/log4j/2.x/[Log4J2], and -https://logback.qos.ch/[Logback]. In each case, loggers are pre-configured to use console -output with optional file output also available. - -By default, if you use the "`Starters`", Logback is used for logging. Appropriate Logback -routing is also included to ensure that dependent libraries that use Java Util Logging, -Commons Logging, Log4J, or SLF4J all work correctly. - -TIP: There are a lot of logging frameworks available for Java. Do not worry if the above -list seems confusing. Generally, you do not need to change your logging dependencies and -the Spring Boot defaults work just fine. - - - -[[boot-features-logging-format]] -=== Log Format -The default log output from Spring Boot resembles the following example: - -[indent=0] ----- -2014-03-05 10:57:51.112 INFO 45469 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/7.0.52 -2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext -2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1358 ms -2014-03-05 10:57:51.698 INFO 45469 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/] -2014-03-05 10:57:51.702 INFO 45469 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] ----- - -The following items are output: - -* Date and Time: Millisecond precision and easily sortable. -* Log Level: `ERROR`, `WARN`, `INFO`, `DEBUG`, or `TRACE`. -* Process ID. -* A `---` separator to distinguish the start of actual log messages. -* Thread name: Enclosed in square brackets (may be truncated for console output). -* Logger name: This is usually the source class name (often abbreviated). -* The log message. - -NOTE: Logback does not have a `FATAL` level. It is mapped to `ERROR`. - - -[[boot-features-logging-console-output]] -=== Console Output -The default log configuration echoes messages to the console as they are written. By -default, `ERROR`-level, `WARN`-level, and `INFO`-level messages are logged. You can also -enable a "`debug`" mode by starting your application with a `--debug` flag. - -[indent=0] ----- - $ java -jar myapp.jar --debug ----- - -NOTE: You can also specify `debug=true` in your `application.properties`. - -When the debug mode is enabled, a selection of core loggers (embedded container, -Hibernate, and Spring Boot) are configured to output more information. Enabling the debug -mode does _not_ configure your application to log all messages with `DEBUG` level. - -Alternatively, you can enable a "`trace`" mode by starting your application with a -`--trace` flag (or `trace=true` in your `application.properties`). Doing so enables trace -logging for a selection of core loggers (embedded container, Hibernate schema generation, -and the whole Spring portfolio). - -[[boot-features-logging-color-coded-output]] -==== Color-coded Output -If your terminal supports ANSI, color output is used to aid readability. You can set -`spring.output.ansi.enabled` to a -{dc-spring-boot}/ansi/AnsiOutput.Enabled.{dc-ext}[supported value] to override the auto -detection. - -Color coding is configured by using the `%clr` conversion word. In its simplest form, the -converter colors the output according to the log level, as shown in the following -example: - -[source,indent=0] ----- -%clr(%5p) ----- - -The following table describes the mapping of log levels to colors: - -|=== -|Level | Color - -|`FATAL` -| Red - -|`ERROR` -| Red - -|`WARN` -| Yellow - -|`INFO` -| Green - -|`DEBUG` -| Green - -|`TRACE` -| Green -|=== - -Alternatively, you can specify the color or style that should be used by providing it as -an option to the conversion. For example, to make the text yellow, use the following -setting: - -[source,indent=0] ----- -%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){yellow} ----- - -The following colors and styles are supported: - -* `blue` -* `cyan` -* `faint` -* `green` -* `magenta` -* `red` -* `yellow` - -[[boot-features-logging-file-output]] -=== File Output -By default, Spring Boot logs only to the console and does not write log files. If you -want to write log files in addition to the console output, you need to set a -`logging.file.name` or `logging.file.path` property (for example, in your -`application.properties`). - -The following table shows how the `logging.*` properties can be used together: - -.Logging properties -[cols="1,1,1,4"] -|=== -|`logging.file.name` |`logging.file.path` |Example |Description - -|_(none)_ -|_(none)_ -| -|Console only logging. - -|Specific file -|_(none)_ -|`my.log` -|Writes to the specified log file. Names can be an exact location or relative to the -current directory. - -|_(none)_ -|Specific directory -|`/var/log` -|Writes `spring.log` to the specified directory. Names can be an exact location or -relative to the current directory. -|=== - -Log files rotate when they reach 10 MB and, as with console output, `ERROR`-level, -`WARN`-level, and `INFO`-level messages are logged by default. Size limits can be changed -using the `logging.file.max-size` property. Previously rotated files are archived -indefinitely unless the `logging.file.max-history` property has been set. The total size -of log archives can be capped using `logging.file.total-size-cap`. When the total size of -log archives exceeds that threshold, backups will be deleted. To force log archive cleanup -on application startup, use the `logging.file.clean-history-on-start` property. - -NOTE: The logging system is initialized early in the application lifecycle. Consequently, -logging properties are not found in property files loaded through `@PropertySource` -annotations. - -TIP: Logging properties are independent of the actual logging infrastructure. As a -result, specific configuration keys (such as `logback.configurationFile` for Logback) are -not managed by spring Boot. - - -[[boot-features-custom-log-levels]] -=== Log Levels -All the supported logging systems can have the logger levels set in the Spring -`Environment` (for example, in `application.properties`) by using -`+logging.level.=+` where `level` is one of TRACE, DEBUG, INFO, WARN, -ERROR, FATAL, or OFF. The `root` logger can be configured by using `logging.level.root`. - -The following example shows potential logging settings in `application.properties`: - -[source,properties,indent=0,subs="verbatim,quotes,attributes"] ----- - logging.level.root=WARN - logging.level.org.springframework.web=DEBUG - logging.level.org.hibernate=ERROR ----- - - - -[[boot-features-custom-log-groups]] -=== Log Groups -It's often useful to be able to group related loggers together so that they can all be -configured at the same time. For example, you might commonly change the logging levels for -_all_ Tomcat related loggers, but you can't easily remember top level packages. - -To help with this, Spring Boot allows you to define logging groups in your Spring -`Environment`. For example, here's how you could define a "`tomcat`" group by adding -it to your `application.properties`: - -[source,properties,indent=0,subs="verbatim,quotes,attributes"] ----- - logging.group.tomcat=org.apache.catalina, org.apache.coyote, org.apache.tomcat ----- - -Once defined, you can change the level for all the loggers in the group with a single -line: - -[source,properties,indent=0,subs="verbatim,quotes,attributes"] ----- - logging.level.tomcat=TRACE ----- - -Spring Boot includes the following pre-defined logging groups that can be used -out-of-the-box: - -[cols="1,4"] -|=== -|Name |Loggers - -|web -|`org.springframework.core.codec`, `org.springframework.http`, `org.springframework.web` - -|sql -|`org.springframework.jdbc.core`, `org.hibernate.SQL`, `org.jooq.tools.LoggerListener` - -|=== - - - -[[boot-features-custom-log-configuration]] -=== Custom Log Configuration -The various logging systems can be activated by including the appropriate libraries on -the classpath and can be further customized by providing a suitable configuration file in -the root of the classpath or in a location specified by the following Spring `Environment` -property: `logging.config`. - -You can force Spring Boot to use a particular logging system by using the -`org.springframework.boot.logging.LoggingSystem` system property. The value should be the -fully qualified class name of a `LoggingSystem` implementation. You can also disable -Spring Boot's logging configuration entirely by using a value of `none`. - -NOTE: Since logging is initialized *before* the `ApplicationContext` is created, it is -not possible to control logging from `@PropertySources` in Spring `@Configuration` files. -The only way to change the logging system or disable it entirely is via System properties. - -Depending on your logging system, the following files are loaded: - -|=== -|Logging System |Customization - -|Logback -|`logback-spring.xml`, `logback-spring.groovy`, `logback.xml`, or `logback.groovy` - -|Log4j2 -|`log4j2-spring.xml` or `log4j2.xml` - -|JDK (Java Util Logging) -|`logging.properties` -|=== - -NOTE: When possible, we recommend that you use the `-spring` variants for your logging -configuration (for example, `logback-spring.xml` rather than `logback.xml`). If you use -standard configuration locations, Spring cannot completely control log initialization. - -WARNING: There are known classloading issues with Java Util Logging that cause problems -when running from an 'executable jar'. We recommend that you avoid it when running from -an 'executable jar' if at all possible. - -To help with the customization, some other properties are transferred from the Spring -`Environment` to System properties, as described in the following table: - -|=== -|Spring Environment |System Property |Comments - -|`logging.exception-conversion-word` -|`LOG_EXCEPTION_CONVERSION_WORD` -|The conversion word used when logging exceptions. - -|`logging.file.clean-history-on-start` -|`LOG_FILE_CLEAN_HISTORY_ON_START` -|Whether to clean the archive log files on startup (if LOG_FILE enabled). (Only supported -with the default Logback setup.) - -|`logging.file.name` -|`LOG_FILE` -|If defined, it is used in the default log configuration. - -|`logging.file.max-size` -|`LOG_FILE_MAX_SIZE` -|Maximum log file size (if LOG_FILE enabled). (Only supported with the default Logback -setup.) - -|`logging.file.max-history` -|`LOG_FILE_MAX_HISTORY` -|Maximum number of archive log files to keep (if LOG_FILE enabled). (Only supported with -the default Logback setup.) - -|`logging.file.path` -|`LOG_PATH` -|If defined, it is used in the default log configuration. - -|`logging.file.total-size-cap` -|`LOG_FILE_TOTAL_SIZE_CAP` -|Total size of log backups to be kept (if LOG_FILE enabled). (Only supported with the -default Logback setup.) - -|`logging.pattern.console` -|`CONSOLE_LOG_PATTERN` -|The log pattern to use on the console (stdout). (Only supported with the default Logback -setup.) - -|`logging.pattern.dateformat` -|`LOG_DATEFORMAT_PATTERN` -|Appender pattern for log date format. (Only supported with the default Logback setup.) - -|`logging.pattern.file` -|`FILE_LOG_PATTERN` -|The log pattern to use in a file (if `LOG_FILE` is enabled). (Only supported with the -default Logback setup.) - -|`logging.pattern.level` -|`LOG_LEVEL_PATTERN` -|The format to use when rendering the log level (default `%5p`). (Only supported with the -default Logback setup.) - -|`PID` -|`PID` -|The current process ID (discovered if possible and when not already defined as an OS -environment variable). -|=== - -All the supported logging systems can consult System properties when parsing their -configuration files. See the default configurations in `spring-boot.jar` for examples: - -* {github-code}/spring-boot-project/spring-boot/src/main/resources/org/springframework/boot/logging/logback/defaults.xml[Logback] -* {github-code}/spring-boot-project/spring-boot/src/main/resources/org/springframework/boot/logging/log4j2/log4j2.xml[Log4j 2] -* {github-code}/spring-boot-project/spring-boot/src/main/resources/org/springframework/boot/logging/java/logging-file.properties[Java Util logging] - -[TIP] -==== -If you want to use a placeholder in a logging property, you should use -<> and not -the syntax of the underlying framework. Notably, if you use Logback, you should use `:` -as the delimiter between a property name and its default value and not use `:-`. -==== - -[TIP] -==== - -You can add MDC and other ad-hoc content to log lines by overriding only the -`LOG_LEVEL_PATTERN` (or `logging.pattern.level` with Logback). For example, if you use -`logging.pattern.level=user:%X\{user} %5p`, then the default log format contains an MDC -entry for "user", if it exists, as shown in the following example. - ----- -2015-09-30 12:30:04.031 user:someone INFO 22174 --- [ nio-8080-exec-0] demo.Controller -Handling authenticated request ----- -==== - - - -[[boot-features-logback-extensions]] -=== Logback Extensions -Spring Boot includes a number of extensions to Logback that can help with advanced -configuration. You can use these extensions in your `logback-spring.xml` configuration -file. - -NOTE: Because the standard `logback.xml` configuration file is loaded too early, you -cannot use extensions in it. You need to either use `logback-spring.xml` or define a -`logging.config` property. - -WARNING: The extensions cannot be used with Logback's -https://logback.qos.ch/manual/configuration.html#autoScan[configuration scanning]. If you -attempt to do so, making changes to the configuration file results in an error similar to -one of the following being logged: - ----- -ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProperty], current ElementPath is [[configuration][springProperty]] -ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProfile], current ElementPath is [[configuration][springProfile]] ----- - - - -==== Profile-specific Configuration -The `` tag lets you optionally include or exclude sections of -configuration based on the active Spring profiles. Profile sections are supported -anywhere within the `` element. Use the `name` attribute to specify which -profile accepts the configuration. The `` tag can contain a simple profile -name (for example `staging`) or a profile expression. A profile expression allows for more -complicated profile logic to be expressed, for example -`production & (eu-central | eu-west)`. Check the -{spring-reference}core.html#beans-definition-profiles-java[reference guide] for more -details. The following listing shows three sample profiles: - -[source,xml,indent=0] ----- - - - - - - - - - - - ----- - - - -==== Environment Properties -The `` tag lets you expose properties from the Spring `Environment` for -use within Logback. Doing so can be useful if you want to access values from your -`application.properties` file in your Logback configuration. The tag works in a similar -way to Logback's standard `` tag. However, rather than specifying a direct -`value`, you specify the `source` of the property (from the `Environment`). If you need -to store the property somewhere other than in `local` scope, you can use the `scope` -attribute. If you need a fallback value (in case the property is not set in the -`Environment`), you can use the `defaultValue` attribute. The following example shows how -to expose properties for use within Logback: - -[source,xml,indent=0] ----- - - - ${fluentHost} - ... - ----- - -NOTE: The `source` must be specified in kebab case (such as `my.property-name`). -However, properties can be added to the `Environment` by using the relaxed rules. - - - -[[boot-features-internationalization]] -== Internationalization -Spring Boot supports localized messages so that your application can cater to users -of different language preferences. By default, Spring Boot looks for the presence of -a `messages` resource bundle at the root of the classpath. - -NOTE: The auto-configuration applies when the default properties file for the configured -resource bundle is available (i.e. `messages.properties` by default). If your resource -bundle contains only language-specific properties files, you are required to add the -default. - -The basename of the resource bundle as well as several other attributes can be configured -using the `spring.messages` namespace, as shown in the following example: - -[source,properties,indent=0] ----- - spring.messages.basename=messages,config.i18n.messages - spring.messages.fallback-to-system-locale=false ----- - -TIP: `spring.messages.basename` supports comma-separated list of locations, either a -package qualifier or a resource resolved from the classpath root. - -See {sc-spring-boot-autoconfigure}/context/MessageSourceProperties.{sc-ext}[ -`MessageSourceProperties`] for more supported options. - - - - -[[boot-features-json]] -== JSON -Spring Boot provides integration with three JSON mapping libraries: - -- Gson -- Jackson -- JSON-B - -Jackson is the preferred and default library. - - - -[[boot-features-json-jackson]] -=== Jackson -Auto-configuration for Jackson is provided and Jackson is part of -`spring-boot-starter-json`. When Jackson is on the classpath an `ObjectMapper` -bean is automatically configured. Several configuration properties are provided for -<>. - - - -[[boot-features-json-gson]] -=== Gson -Auto-configuration for Gson is provided. When Gson is on the classpath a `Gson` bean is -automatically configured. Several `+spring.gson.*+` configuration properties are -provided for customizing the configuration. To take more control, one or more -`GsonBuilderCustomizer` beans can be used. - - - -[[boot-features-json-json-b]] -=== JSON-B -Auto-configuration for JSON-B is provided. When the JSON-B API and an implementation are -on the classpath a `Jsonb` bean will be automatically configured. The preferred JSON-B -implementation is Apache Johnzon for which dependency management is provided. - - - -[[boot-features-developing-web-applications]] -== Developing Web Applications -Spring Boot is well suited for web application development. You can create a -self-contained HTTP server by using embedded Tomcat, Jetty, Undertow, or Netty. Most web -applications use the `spring-boot-starter-web` module to get up and running quickly. You -can also choose to build reactive web applications by using the -`spring-boot-starter-webflux` module. - -If you have not yet developed a Spring Boot web application, you can follow the -"Hello World!" example in the -_<>_ section. - - - -[[boot-features-spring-mvc]] -=== The "`Spring Web MVC Framework`" -The {spring-reference}web.html#mvc[Spring Web MVC framework] (often referred to as simply -"`Spring MVC`") is a rich "`model view controller`" web framework. Spring MVC lets you -create special `@Controller` or `@RestController` beans to handle incoming HTTP requests. -Methods in your controller are mapped to HTTP by using `@RequestMapping` annotations. - -The following code shows a typical `@RestController` that serves JSON data: - -[source,java,indent=0] ----- - @RestController - @RequestMapping(value="/users") - public class MyRestController { - - @RequestMapping(value="/\{user}", method=RequestMethod.GET) - public User getUser(@PathVariable Long user) { - // ... - } - - @RequestMapping(value="/\{user}/customers", method=RequestMethod.GET) - List getUserCustomers(@PathVariable Long user) { - // ... - } - - @RequestMapping(value="/\{user}", method=RequestMethod.DELETE) - public User deleteUser(@PathVariable Long user) { - // ... - } - - } ----- - -Spring MVC is part of the core Spring Framework, and detailed information is available in -the {spring-reference}web.html#mvc[reference documentation]. There are also several -guides that cover Spring MVC available at https://spring.io/guides. - - - -[[boot-features-spring-mvc-auto-configuration]] -==== Spring MVC Auto-configuration -Spring Boot provides auto-configuration for Spring MVC that works well with most -applications. - -The auto-configuration adds the following features on top of Spring's defaults: - -* Inclusion of `ContentNegotiatingViewResolver` and `BeanNameViewResolver` beans. -* Support for serving static resources, including support for WebJars (covered -<>)). -* Automatic registration of `Converter`, `GenericConverter`, and `Formatter` beans. -* Support for `HttpMessageConverters` (covered -<>). -* Automatic registration of `MessageCodesResolver` (covered -<>). -* Static `index.html` support. -* Custom `Favicon` support (covered <>). -* Automatic use of a `ConfigurableWebBindingInitializer` bean (covered -<>). - -If you want to keep Spring Boot MVC features and you want to add additional -{spring-reference}web.html#mvc[MVC configuration] (interceptors, formatters, view -controllers, and other features), you can add your own `@Configuration` class of type -`WebMvcConfigurer` but *without* `@EnableWebMvc`. If you wish to provide custom -instances of `RequestMappingHandlerMapping`, `RequestMappingHandlerAdapter`, or -`ExceptionHandlerExceptionResolver`, you can declare a `WebMvcRegistrationsAdapter` -instance to provide such components. - -If you want to take complete control of Spring MVC, you can add your own `@Configuration` -annotated with `@EnableWebMvc`. - - -[[boot-features-spring-mvc-message-converters]] -==== HttpMessageConverters -Spring MVC uses the `HttpMessageConverter` interface to convert HTTP requests and -responses. Sensible defaults are included out of the box. For example, objects can be -automatically converted to JSON (by using the Jackson library) or XML (by using the -Jackson XML extension, if available, or by using JAXB if the Jackson XML extension is not -available). By default, strings are encoded in `UTF-8`. - -If you need to add or customize converters, you can use Spring Boot's -`HttpMessageConverters` class, as shown in the following listing: - -[source,java,indent=0] ----- - import org.springframework.boot.autoconfigure.http.HttpMessageConverters; - import org.springframework.context.annotation.*; - import org.springframework.http.converter.*; - - @Configuration(proxyBeanMethods = false) - public class MyConfiguration { - - @Bean - public HttpMessageConverters customConverters() { - HttpMessageConverter additional = ... - HttpMessageConverter another = ... - return new HttpMessageConverters(additional, another); - } - - } ----- - -Any `HttpMessageConverter` bean that is present in the context is added to the list of -converters. You can also override default converters in the same way. - - - -[[boot-features-json-components]] -==== Custom JSON Serializers and Deserializers -If you use Jackson to serialize and deserialize JSON data, you might want to write your -own `JsonSerializer` and `JsonDeserializer` classes. Custom serializers are usually -https://github.com/FasterXML/jackson-docs/wiki/JacksonHowToCustomSerializers[registered with Jackson through -a module], but Spring Boot provides an alternative `@JsonComponent` annotation that makes -it easier to directly register Spring Beans. - -You can use the `@JsonComponent` annotation directly on `JsonSerializer`, -`JsonDeserializer` or `KeyDeserializer` implementations. You can also use it on classes -that contain serializers/deserializers as inner classes, as shown in the following example: - -[source,java,indent=0] ----- - import java.io.*; - import com.fasterxml.jackson.core.*; - import com.fasterxml.jackson.databind.*; - import org.springframework.boot.jackson.*; - - @JsonComponent - public class Example { - - public static class Serializer extends JsonSerializer { - // ... - } - - public static class Deserializer extends JsonDeserializer { - // ... - } - - } ----- - -All `@JsonComponent` beans in the `ApplicationContext` are automatically registered with -Jackson. Because `@JsonComponent` is meta-annotated with `@Component`, the usual -component-scanning rules apply. - -Spring Boot also provides -{sc-spring-boot}/jackson/JsonObjectSerializer.{sc-ext}[`JsonObjectSerializer`] and -{sc-spring-boot}/jackson/JsonObjectDeserializer.{sc-ext}[`JsonObjectDeserializer`] base -classes that provide useful alternatives to the standard Jackson versions when -serializing objects. See -{dc-spring-boot}/jackson/JsonObjectSerializer.{dc-ext}[`JsonObjectSerializer`] -and {dc-spring-boot}/jackson/JsonObjectDeserializer.{dc-ext}[`JsonObjectDeserializer`] in -the Javadoc for details. - - - -[[boot-features-spring-message-codes]] -==== MessageCodesResolver -Spring MVC has a strategy for generating error codes for rendering error messages from -binding errors: `MessageCodesResolver`. If you set the -`spring.mvc.message-codes-resolver.format` property `PREFIX_ERROR_CODE` or -`POSTFIX_ERROR_CODE`, Spring Boot creates one for you (see the enumeration in -{spring-javadoc}/validation/DefaultMessageCodesResolver.Format.{dc-ext}[`DefaultMessageCodesResolver.Format`]). - - - -[[boot-features-spring-mvc-static-content]] -==== Static Content -By default, Spring Boot serves static content from a directory called `/static` (or -`/public` or `/resources` or `/META-INF/resources`) in the classpath or from the root of -the `ServletContext`. It uses the `ResourceHttpRequestHandler` from Spring MVC so that -you can modify that behavior by adding your own `WebMvcConfigurer` and overriding the -`addResourceHandlers` method. - -In a stand-alone web application, the default servlet from the container is also enabled -and acts as a fallback, serving content from the root of the `ServletContext` if Spring -decides not to handle it. Most of the time, this does not happen (unless you modify the -default MVC configuration), because Spring can always handle requests through the -`DispatcherServlet`. - -By default, resources are mapped on `+/**+`, but you can tune that with the -`spring.mvc.static-path-pattern` property. For instance, relocating all resources to -`/resources/**` can be achieved as follows: - -[source,properties,indent=0,subs="verbatim,quotes,attributes"] ----- - spring.mvc.static-path-pattern=/resources/** ----- - -You can also customize the static resource locations by using the -`spring.resources.static-locations` property (replacing the default values with a list of -directory locations). The root Servlet context path, `"/"`, is automatically added as a -location as well. - -In addition to the "`standard`" static resource locations mentioned earlier, a special -case is made for https://www.webjars.org/[Webjars content]. Any resources with a path in -`+/webjars/**+` are served from jar files if they are packaged in the Webjars format. - -TIP: Do not use the `src/main/webapp` directory if your application is packaged as a jar. -Although this directory is a common standard, it works *only* with war packaging, and it -is silently ignored by most build tools if you generate a jar. - -Spring Boot also supports the advanced resource handling features provided by Spring MVC, -allowing use cases such as cache-busting static resources or using version agnostic URLs -for Webjars. - -To use version agnostic URLs for Webjars, add the `webjars-locator-core` dependency. -Then declare your Webjar. Using jQuery as an example, adding -`"/webjars/jquery/jquery.min.js"` results in -`"/webjars/jquery/x.y.z/jquery.min.js"`. where `x.y.z` is the Webjar version. - -NOTE: If you use JBoss, you need to declare the `webjars-locator-jboss-vfs` -dependency instead of the `webjars-locator-core`. Otherwise, all Webjars resolve as a -`404`. - -To use cache busting, the following configuration configures a cache busting solution for -all static resources, effectively adding a content hash, such as -``, in URLs: - -[source,properties,indent=0,subs="verbatim,quotes,attributes"] ----- - spring.resources.chain.strategy.content.enabled=true - spring.resources.chain.strategy.content.paths=/** ----- - -NOTE: Links to resources are rewritten in templates at runtime, thanks to a -`ResourceUrlEncodingFilter` that is auto-configured for Thymeleaf and FreeMarker. You -should manually declare this filter when using JSPs. Other template engines are currently -not automatically supported but can be with custom template macros/helpers and the use of -the -{spring-javadoc}/web/servlet/resource/ResourceUrlProvider.{dc-ext}[`ResourceUrlProvider`]. - -When loading resources dynamically with, for example, a JavaScript module loader, -renaming files is not an option. That is why other strategies are also supported and can -be combined. A "fixed" strategy adds a static version string in the URL without changing -the file name, as shown in the following example: - -[source,properties,indent=0,subs="verbatim,quotes,attributes"] ----- - spring.resources.chain.strategy.content.enabled=true - spring.resources.chain.strategy.content.paths=/** - spring.resources.chain.strategy.fixed.enabled=true - spring.resources.chain.strategy.fixed.paths=/js/lib/ - spring.resources.chain.strategy.fixed.version=v12 ----- - -With this configuration, JavaScript modules located under `"/js/lib/"` use a fixed -versioning strategy (`"/v12/js/lib/mymodule.js"`), while other resources still use the -content one (``). - -See {sc-spring-boot-autoconfigure}/web/ResourceProperties.{sc-ext}[`ResourceProperties`] -for more supported options. - -[TIP] -==== -This feature has been thoroughly described in a dedicated -https://spring.io/blog/2014/07/24/spring-framework-4-1-handling-static-web-resources[blog -post] and in Spring Framework's -{spring-reference}web.html#mvc-config-static-resources[reference documentation]. -==== - -[[boot-features-spring-mvc-welcome-page]] -==== Welcome Page -Spring Boot supports both static and templated welcome pages. It first looks for an -`index.html` file in the configured static content locations. If one is not found, it -then looks for an `index` template. If either is found, it is automatically used as the -welcome page of the application. - - - -[[boot-features-spring-mvc-favicon]] -==== Custom Favicon -Spring Boot looks for a `favicon.ico` in the configured static content locations and the -root of the classpath (in that order). If such a file is present, it is automatically -used as the favicon of the application. - - -[[boot-features-spring-mvc-pathmatch]] -==== Path Matching and Content Negotiation -Spring MVC can map incoming HTTP requests to handlers by looking at the request path and -matching it to the mappings defined in your application (for example, `@GetMapping` -annotations on Controller methods). - -Spring Boot chooses to disable suffix pattern matching by default, which means that -requests like `"GET /projects/spring-boot.json"` won't be matched to -`@GetMapping("/projects/spring-boot")` mappings. -This is considered as a -{spring-reference}web.html#mvc-ann-requestmapping-suffix-pattern-match[best practice -for Spring MVC applications]. This feature was mainly useful in the past for HTTP -clients which did not send proper "Accept" request headers; we needed to make sure -to send the correct Content Type to the client. Nowadays, Content Negotiation -is much more reliable. - -There are other ways to deal with HTTP clients that don't consistently send proper -"Accept" request headers. Instead of using suffix matching, we can use a query -parameter to ensure that requests like `"GET /projects/spring-boot?format=json"` -will be mapped to `@GetMapping("/projects/spring-boot")`: - -[source,properties,indent=0,subs="verbatim,quotes,attributes"] ----- - spring.mvc.contentnegotiation.favor-parameter=true - - # We can change the parameter name, which is "format" by default: - # spring.mvc.contentnegotiation.parameter-name=myparam - - # We can also register additional file extensions/media types with: - spring.mvc.contentnegotiation.media-types.markdown=text/markdown ----- - -If you understand the caveats and would still like your application to use -suffix pattern matching, the following configuration is required: - -[source,properties,indent=0,subs="verbatim,quotes,attributes"] ----- - spring.mvc.contentnegotiation.favor-path-extension=true - spring.mvc.pathmatch.use-suffix-pattern=true ----- - -Alternatively, rather than open all suffix patterns, it's more secure to just support -registered suffix patterns: - -[source,properties,indent=0,subs="verbatim,quotes,attributes"] ----- - spring.mvc.contentnegotiation.favor-path-extension=true - spring.mvc.pathmatch.use-registered-suffix-pattern=true - - # You can also register additional file extensions/media types with: - # spring.mvc.contentnegotiation.media-types.adoc=text/asciidoc ----- - - - -[[boot-features-spring-mvc-web-binding-initializer]] -==== ConfigurableWebBindingInitializer -Spring MVC uses a `WebBindingInitializer` to initialize a `WebDataBinder` for a -particular request. If you create your own `ConfigurableWebBindingInitializer` `@Bean`, -Spring Boot automatically configures Spring MVC to use it. - - - -[[boot-features-spring-mvc-template-engines]] -==== Template Engines -As well as REST web services, you can also use Spring MVC to serve dynamic HTML content. -Spring MVC supports a variety of templating technologies, including Thymeleaf, -FreeMarker, and JSPs. Also, many other templating engines include their own Spring MVC -integrations. - -Spring Boot includes auto-configuration support for the following templating engines: - - * https://freemarker.apache.org/docs/[FreeMarker] - * http://docs.groovy-lang.org/docs/next/html/documentation/template-engines.html#_the_markuptemplateengine[Groovy] - * https://www.thymeleaf.org[Thymeleaf] - * https://mustache.github.io/[Mustache] - -TIP: If possible, JSPs should be avoided. There are several -<> when using them with embedded -servlet containers. - -When you use one of these templating engines with the default configuration, your -templates are picked up automatically from `src/main/resources/templates`. - -TIP: Depending on how you run your application, IntelliJ IDEA orders the classpath -differently. Running your application in the IDE from its main method results in a -different ordering than when you run your application by using Maven or Gradle or from -its packaged jar. This can cause Spring Boot to fail to find the templates on the -classpath. If you have this problem, you can reorder the classpath in the IDE to place -the module's classes and resources first. Alternatively, you can configure the template -prefix to search every `templates` directory on the classpath, as follows: -`classpath*:/templates/`. - - - -[[boot-features-error-handling]] -==== Error Handling -By default, Spring Boot provides an `/error` mapping that handles all errors in a -sensible way, and it is registered as a "`global`" error page in the servlet container. -For machine clients, it produces a JSON response with details of the error, the HTTP -status, and the exception message. For browser clients, there is a "`whitelabel`" error -view that renders the same data in HTML format (to customize it, add a `View` that -resolves to `error`). To replace the default behavior completely, you can implement -`ErrorController` and register a bean definition of that type or add a bean of type -`ErrorAttributes` to use the existing mechanism but replace the contents. - -TIP: The `BasicErrorController` can be used as a base class for a custom -`ErrorController`. This is particularly useful if you want to add a handler for a new -content type (the default is to handle `text/html` specifically and provide a fallback -for everything else). To do so, extend `BasicErrorController`, add a public method with a -`@RequestMapping` that has a `produces` attribute, and create a bean of your new type. - -You can also define a class annotated with `@ControllerAdvice` to customize the JSON -document to return for a particular controller and/or exception type, as shown in the -following example: - -[source,java,indent=0,subs="verbatim,quotes,attributes"] ----- - @ControllerAdvice(basePackageClasses = AcmeController.class) - public class AcmeControllerAdvice extends ResponseEntityExceptionHandler { - - @ExceptionHandler(YourException.class) - @ResponseBody - ResponseEntity handleControllerException(HttpServletRequest request, Throwable ex) { - HttpStatus status = getStatus(request); - return new ResponseEntity<>(new CustomErrorType(status.value(), ex.getMessage()), status); - } - - private HttpStatus getStatus(HttpServletRequest request) { - Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); - if (statusCode == null) { - return HttpStatus.INTERNAL_SERVER_ERROR; - } - return HttpStatus.valueOf(statusCode); - } - - } ----- - -In the preceding example, if `YourException` is thrown by a controller defined in the -same package as `AcmeController`, a JSON representation of the `CustomErrorType` POJO is -used instead of the `ErrorAttributes` representation. - - - -[[boot-features-error-handling-custom-error-pages]] -===== Custom Error Pages -If you want to display a custom HTML error page for a given status code, you can add a -file to an `/error` folder. Error pages can either be static HTML (that is, added under -any of the static resource folders) or be built by using templates. The name of the file -should be the exact status code or a series mask. - -For example, to map `404` to a static HTML file, your folder structure would be as -follows: - -[source,indent=0,subs="verbatim,quotes,attributes"] ----- - src/ - +- main/ - +- java/ - | + - +- resources/ - +- public/ - +- error/ - | +- 404.html - +- ----- - -To map all `5xx` errors by using a FreeMarker template, your folder structure would be as -follows: - -[source,indent=0,subs="verbatim,quotes,attributes"] ----- - src/ - +- main/ - +- java/ - | + - +- resources/ - +- templates/ - +- error/ - | +- 5xx.ftlh - +- ----- - -For more complex mappings, you can also add beans that implement the `ErrorViewResolver` -interface, as shown in the following example: - -[source,java,indent=0,subs="verbatim,quotes,attributes"] ----- - public class MyErrorViewResolver implements ErrorViewResolver { - - @Override - public ModelAndView resolveErrorView(HttpServletRequest request, - HttpStatus status, Map model) { - // Use the request or status to optionally return a ModelAndView - return ... - } - - } ----- - - -You can also use regular Spring MVC features such as -{spring-reference}web.html#mvc-exceptionhandlers[`@ExceptionHandler` methods] and -{spring-reference}web.html#mvc-ann-controller-advice[`@ControllerAdvice`]. The -`ErrorController` then picks up any unhandled exceptions. - - - -[[boot-features-error-handling-mapping-error-pages-without-mvc]] -===== Mapping Error Pages outside of Spring MVC -For applications that do not use Spring MVC, you can use the `ErrorPageRegistrar` -interface to directly register `ErrorPages`. This abstraction works directly with the -underlying embedded servlet container and works even if you do not have a Spring MVC -`DispatcherServlet`. - - -[source,java,indent=0,subs="verbatim,quotes,attributes"] ----- - @Bean - public ErrorPageRegistrar errorPageRegistrar(){ - return new MyErrorPageRegistrar(); - } - - // ... - - private static class MyErrorPageRegistrar implements ErrorPageRegistrar { - - @Override - public void registerErrorPages(ErrorPageRegistry registry) { - registry.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400")); - } - - } ----- - -NOTE: If you register an `ErrorPage` with a path that ends up being handled by a `Filter` -(as is common with some non-Spring web frameworks, like Jersey and Wicket), then the -`Filter` has to be explicitly registered as an `ERROR` dispatcher, as shown in the -following example: - -[source,java,indent=0,subs="verbatim,quotes,attributes"] ----- - @Bean - public FilterRegistrationBean myFilter() { - FilterRegistrationBean registration = new FilterRegistrationBean(); - registration.setFilter(new MyFilter()); - ... - registration.setDispatcherTypes(EnumSet.allOf(DispatcherType.class)); - return registration; - } ----- - -Note that the default `FilterRegistrationBean` does not include the `ERROR` dispatcher -type. - - - -[[boot-features-error-handling-websphere]] -CAUTION:When deployed to a servlet container, Spring Boot uses its error page filter to -forward a request with an error status to the appropriate error page. The request can only -be forwarded to the correct error page if the response has not already been committed. By -default, WebSphere Application Server 8.0 and later commits the response upon successful -completion of a servlet's service method. You should disable this behavior by setting -`com.ibm.ws.webcontainer.invokeFlushAfterService` to `false`. - - - -[[boot-features-spring-hateoas]] -==== Spring HATEOAS -If you develop a RESTful API that makes use of hypermedia, Spring Boot provides -auto-configuration for Spring HATEOAS that works well with most applications. The -auto-configuration replaces the need to use `@EnableHypermediaSupport` and registers a -number of beans to ease building hypermedia-based applications, including a -`LinkDiscoverers` (for client side support) and an `ObjectMapper` configured to correctly -marshal responses into the desired representation. The `ObjectMapper` is customized by -setting the various `spring.jackson.*` properties or, if one exists, by a -`Jackson2ObjectMapperBuilder` bean. - -You can take control of Spring HATEOAS's configuration by using -`@EnableHypermediaSupport`. Note that doing so disables the `ObjectMapper` customization -described earlier. - - - -[[boot-features-cors]] -==== CORS Support - -https://en.wikipedia.org/wiki/Cross-origin_resource_sharing[Cross-origin resource sharing] -(CORS) is a https://www.w3.org/TR/cors/[W3C specification] implemented by -https://caniuse.com/#feat=cors[most browsers] that lets you specify in a flexible -way what kind of cross-domain requests are authorized, instead of using some less secure -and less powerful approaches such as IFRAME or JSONP. - -As of version 4.2, Spring MVC {spring-reference}web.html#cors[supports CORS]. -Using {spring-reference}web.html#controller-method-cors-configuration[controller method -CORS configuration] with -{spring-javadoc}/web/bind/annotation/CrossOrigin.{dc-ext}[`@CrossOrigin`] -annotations in your Spring Boot application does not require any specific configuration. -{spring-reference}web.html#global-cors-configuration[Global CORS configuration] can be -defined by registering a `WebMvcConfigurer` bean with a customized -`addCorsMappings(CorsRegistry)` method, as shown in the following example: - -[source,java,indent=0] ----- - @Configuration(proxyBeanMethods = false) - public class MyConfiguration { - - @Bean - public WebMvcConfigurer corsConfigurer() { - return new WebMvcConfigurer() { - @Override - public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/api/**"); - } - }; - } - } ----- - - - -[[boot-features-webflux]] -=== The "`Spring WebFlux Framework`" - -Spring WebFlux is the new reactive web framework introduced in Spring Framework 5.0. -Unlike Spring MVC, it does not require the Servlet API, is fully asynchronous and -non-blocking, and implements the https://www.reactive-streams.org/[Reactive Streams] -specification through https://projectreactor.io/[the Reactor project]. - -Spring WebFlux comes in two flavors: functional and annotation-based. The -annotation-based one is quite close to the Spring MVC model, as shown in the -following example: - -[source,java,indent=0] ----- - @RestController - @RequestMapping("/users") - public class MyRestController { - - @GetMapping("/\{user}") - public Mono getUser(@PathVariable Long user) { - // ... - } - - @GetMapping("/\{user}/customers") - public Flux getUserCustomers(@PathVariable Long user) { - // ... - } - - @DeleteMapping("/\{user}") - public Mono deleteUser(@PathVariable Long user) { - // ... - } - - } ----- - -"`WebFlux.fn`", the functional variant, separates the routing configuration from the -actual handling of the requests, as shown in the following example: - -[source,java,indent=0] ----- - @Configuration(proxyBeanMethods = false) - public class RoutingConfiguration { - - @Bean - public RouterFunction monoRouterFunction(UserHandler userHandler) { - return route(GET("/\{user}").and(accept(APPLICATION_JSON)), userHandler::getUser) - .andRoute(GET("/\{user}/customers").and(accept(APPLICATION_JSON)), userHandler::getUserCustomers) - .andRoute(DELETE("/\{user}").and(accept(APPLICATION_JSON)), userHandler::deleteUser); - } - - } - - @Component - public class UserHandler { - - public Mono getUser(ServerRequest request) { - // ... - } - - public Mono getUserCustomers(ServerRequest request) { - // ... - } - - public Mono deleteUser(ServerRequest request) { - // ... - } - } ----- - -WebFlux is part of the Spring Framework and detailed information is available in its -{spring-reference}web-reactive.html#webflux-fn[reference documentation]. - -TIP: You can define as many `RouterFunction` beans as you like to modularize the -definition of the router. Beans can be ordered if you need to apply a precedence. - -To get started, add the `spring-boot-starter-webflux` module to your application. - -NOTE: Adding both `spring-boot-starter-web` and `spring-boot-starter-webflux` modules in -your application results in Spring Boot auto-configuring Spring MVC, not WebFlux. This -behavior has been chosen because many Spring developers add `spring-boot-starter-webflux` -to their Spring MVC application to use the reactive `WebClient`. You can still enforce -your choice by setting the chosen application type to -`SpringApplication.setWebApplicationType(WebApplicationType.REACTIVE)`. - - - -[[boot-features-webflux-auto-configuration]] -==== Spring WebFlux Auto-configuration -Spring Boot provides auto-configuration for Spring WebFlux that works well with most -applications. - -The auto-configuration adds the following features on top of Spring's defaults: - -* Configuring codecs for `HttpMessageReader` and `HttpMessageWriter` instances (described -<>). -* Support for serving static resources, including support for WebJars (described -<>). - -If you want to keep Spring Boot WebFlux features and you want to add additional -{spring-reference}web.html#web-reactive[WebFlux configuration], you can add your own -`@Configuration` class of type `WebFluxConfigurer` but *without* `@EnableWebFlux`. - -If you want to take complete control of Spring WebFlux, you can add your own -`@Configuration` annotated with `@EnableWebFlux`. - - - -[[boot-features-webflux-httpcodecs]] -==== HTTP Codecs with HttpMessageReaders and HttpMessageWriters -Spring WebFlux uses the `HttpMessageReader` and `HttpMessageWriter` interfaces to convert -HTTP requests and responses. They are configured with `CodecConfigurer` to have sensible -defaults by looking at the libraries available in your classpath. - -Spring Boot applies further customization by using `CodecCustomizer` instances. For -example, `spring.jackson.*` configuration keys are applied to the Jackson codec. - -If you need to add or customize codecs, you can create a custom `CodecCustomizer` -component, as shown in the following example: - -[source,java,indent=0] ----- - import org.springframework.boot.web.codec.CodecCustomizer; - - @Configuration(proxyBeanMethods = false) - public class MyConfiguration { - - @Bean - public CodecCustomizer myCodecCustomizer() { - return codecConfigurer -> { - // ... - } - } - - } ----- - -You can also leverage <>. - - - -[[boot-features-webflux-static-content]] -==== Static Content -By default, Spring Boot serves static content from a directory called `/static` (or -`/public` or `/resources` or `/META-INF/resources`) in the classpath. It uses the -`ResourceWebHandler` from Spring WebFlux so that you can modify that behavior by adding -your own `WebFluxConfigurer` and overriding the `addResourceHandlers` method. - -By default, resources are mapped on `+/**+`, but you can tune that by setting the -`spring.webflux.static-path-pattern` property. For instance, relocating all resources to -`/resources/**` can be achieved as follows: - -[source,properties,indent=0,subs="verbatim,quotes,attributes"] ----- - spring.webflux.static-path-pattern=/resources/** ----- - -You can also customize the static resource locations by using -`spring.resources.static-locations`. Doing so replaces the default values with a list of -directory locations. If you do so, the default welcome page detection switches to your -custom locations. So, if there is an `index.html` in any of your locations on startup, it -is the home page of the application. - -In addition to the "`standard`" static resource locations listed earlier, a special case -is made for https://www.webjars.org/[Webjars content]. Any resources with a path in -`+/webjars/**+` are served from jar files if they are packaged in the Webjars format. - -TIP: Spring WebFlux applications do not strictly depend on the Servlet API, so they -cannot be deployed as war files and do not use the `src/main/webapp` directory. - - - -[[boot-features-webflux-template-engines]] -==== Template Engines -As well as REST web services, you can also use Spring WebFlux to serve dynamic HTML -content. Spring WebFlux supports a variety of templating technologies, including -Thymeleaf, FreeMarker, and Mustache. - -Spring Boot includes auto-configuration support for the following templating engines: - - * https://freemarker.apache.org/docs/[FreeMarker] - * https://www.thymeleaf.org[Thymeleaf] - * https://mustache.github.io/[Mustache] - -When you use one of these templating engines with the default configuration, your -templates are picked up automatically from `src/main/resources/templates`. - - - -[[boot-features-webflux-error-handling]] -==== Error Handling - -Spring Boot provides a `WebExceptionHandler` that handles all errors in a sensible way. -Its position in the processing order is immediately before the handlers provided by -WebFlux, which are considered last. For machine clients, it produces a JSON response -with details of the error, the HTTP status, and the exception message. For browser -clients, there is a "`whitelabel`" error handler that renders the same data in HTML -format. You can also provide your own HTML templates to display errors (see the -<>). - -The first step to customizing this feature often involves using the existing mechanism -but replacing or augmenting the error contents. For that, you can add a bean of type -`ErrorAttributes`. - -To change the error handling behavior, you can implement `ErrorWebExceptionHandler` and -register a bean definition of that type. Because a `WebExceptionHandler` is quite -low-level, Spring Boot also provides a convenient `AbstractErrorWebExceptionHandler` to -let you handle errors in a WebFlux functional way, as shown in the following example: - -[source,java,indent=0,subs="verbatim,quotes,attributes"] ----- - public class CustomErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler { - - // Define constructor here - - @Override - protected RouterFunction getRoutingFunction(ErrorAttributes errorAttributes) { - - return RouterFunctions - .route(aPredicate, aHandler) - .andRoute(anotherPredicate, anotherHandler); - } - - } ----- - -For a more complete picture, you can also subclass `DefaultErrorWebExceptionHandler` -directly and override specific methods. - - - -[[boot-features-webflux-error-handling-custom-error-pages]] -===== Custom Error Pages - -If you want to display a custom HTML error page for a given status code, you can add a -file to an `/error` folder. Error pages can either be static HTML (that is, added under -any of the static resource folders) or built with templates. The name of the file should -be the exact status code or a series mask. - -For example, to map `404` to a static HTML file, your folder structure would be as -follows: - -[source,indent=0,subs="verbatim,quotes,attributes"] ----- - src/ - +- main/ - +- java/ - | + - +- resources/ - +- public/ - +- error/ - | +- 404.html - +- ----- - -To map all `5xx` errors by using a Mustache template, your folder structure would be as -follows: - -[source,indent=0,subs="verbatim,quotes,attributes"] ----- - src/ - +- main/ - +- java/ - | + - +- resources/ - +- templates/ - +- error/ - | +- 5xx.mustache - +- ----- - - - -[[boot-features-webflux-web-filters]] -==== Web Filters -Spring WebFlux provides a `WebFilter` interface that can be implemented to filter HTTP -request-response exchanges. `WebFilter` beans found in the application context will -be automatically used to filter each exchange. - -Where the order of the filters is important they can implement `Ordered` or be annotated -with `@Order`. Spring Boot auto-configuration may configure web filters for you. When it -does so, the orders shown in the following table will be used: - -|=== -| Web Filter | Order - -|`MetricsWebFilter` -|`Ordered.HIGHEST_PRECEDENCE + 1` - -|`WebFilterChainProxy` (Spring Security) -|`-100` - -|`HttpTraceWebFilter` -|`Ordered.LOWEST_PRECEDENCE - 10` - -|=== - - - -[[boot-features-jersey]] -=== JAX-RS and Jersey -If you prefer the JAX-RS programming model for REST endpoints, you can use one of the -available implementations instead of Spring MVC. https://jersey.github.io/[Jersey] and -https://cxf.apache.org/[Apache CXF] work quite well out of the box. CXF requires you to -register its `Servlet` or `Filter` as a `@Bean` in your application context. Jersey has -some native Spring support, so we also provide auto-configuration support for it in -Spring Boot, together with a starter. - -To get started with Jersey, include the `spring-boot-starter-jersey` as a dependency -and then you need one `@Bean` of type `ResourceConfig` in which you register all the -endpoints, as shown in the following example: - -[source,java,indent=0,subs="verbatim,quotes,attributes"] ----- - @Component - public class JerseyConfig extends ResourceConfig { - - public JerseyConfig() { - register(Endpoint.class); - } - - } ----- - -WARNING: Jersey's support for scanning executable archives is rather limited. For example, -it cannot scan for endpoints in a package found in a <> or in `WEB-INF/classes` when running an executable war file. -To avoid this limitation, the `packages` method should not be used, and endpoints should -be registered individually by using the `register` method, as shown in the preceding -example. - -For more advanced customizations, you can also register an arbitrary number of beans that -implement `ResourceConfigCustomizer`. - -All the registered endpoints should be `@Components` with HTTP resource annotations -(`@GET` and others), as shown in the following example: - -[source,java,indent=0,subs="verbatim,quotes,attributes"] ----- - @Component - @Path("/hello") - public class Endpoint { - - @GET - public String message() { - return "Hello"; - } - - } ----- - -Since the `Endpoint` is a Spring `@Component`, its lifecycle is managed by Spring and you -can use the `@Autowired` annotation to inject dependencies and use the `@Value` -annotation to inject external configuration. By default, the Jersey servlet is registered -and mapped to `/*`. You can change the mapping by adding `@ApplicationPath` to your -`ResourceConfig`. - -By default, Jersey is set up as a Servlet in a `@Bean` of type `ServletRegistrationBean` -named `jerseyServletRegistration`. By default, the servlet is initialized lazily, but you -can customize that behavior by setting `spring.jersey.servlet.load-on-startup`. You can -disable or override that bean by creating one of your own with the same name. You can -also use a filter instead of a servlet by setting `spring.jersey.type=filter` (in which -case, the `@Bean` to replace or override is `jerseyFilterRegistration`). The filter has -an `@Order`, which you can set with `spring.jersey.filter.order`. Both the servlet and -the filter registrations can be given init parameters by using `spring.jersey.init.*` to -specify a map of properties. - - - -[[boot-features-embedded-container]] -=== Embedded Servlet Container Support -Spring Boot includes support for embedded https://tomcat.apache.org/[Tomcat], -https://www.eclipse.org/jetty/[Jetty], and -https://github.com/undertow-io/undertow[Undertow] servers. Most developers use the -appropriate "`Starter`" to obtain a fully configured instance. By default, the embedded -server listens for HTTP requests on port `8080`. - - - -[[boot-features-embedded-container-servlets-filters-listeners]] -==== Servlets, Filters, and listeners -When using an embedded servlet container, you can register servlets, filters, and all the -listeners (such as `HttpSessionListener`) from the Servlet spec, either by using Spring -beans or by scanning for Servlet components. - - -[[boot-features-embedded-container-servlets-filters-listeners-beans]] -===== Registering Servlets, Filters, and Listeners as Spring Beans -Any `Servlet`, `Filter`, or servlet `*Listener` instance that is a Spring bean is -registered with the embedded container. This can be particularly convenient if you want -to refer to a value from your `application.properties` during configuration. - -By default, if the context contains only a single Servlet, it is mapped to `/`. In the -case of multiple servlet beans, the bean name is used as a path prefix. Filters map to -`+/*+`. - -If convention-based mapping is not flexible enough, you can use the -`ServletRegistrationBean`, `FilterRegistrationBean`, and -`ServletListenerRegistrationBean` classes for complete control. - -Filter beans can be ordered to control their position in the filter chain by using -`@Order` or implemented `Ordered`. It is usually safe to leave Filter beans unordered. -However, if a specific order is required, you should avoid configuring a Filter that reads -the request body at `Ordered.HIGHEST_PRECEDENCE`, since it might go against the character -encoding configuration of your application. If a Servlet filter wraps the request, it -should be configured with an order that is less than or equal to -`OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER`. - -TIP: To see the order of every `Filter` in your application, enable debug level logging -for the `web` <> -(`logging.level.web=debug`). Details of the registered filters, including their order and -URL patterns, will then be logged at startup. - - - -[[boot-features-embedded-container-context-initializer]] -==== Servlet Context Initialization -Embedded servlet containers do not directly execute the Servlet 3.0+ -`javax.servlet.ServletContainerInitializer` interface or Spring's -`org.springframework.web.WebApplicationInitializer` interface. This is an intentional -design decision intended to reduce the risk that third party libraries designed to run -inside a war may break Spring Boot applications. - -If you need to perform servlet context initialization in a Spring Boot application, you -should register a bean that implements the -`org.springframework.boot.web.servlet.ServletContextInitializer` interface. The -single `onStartup` method provides access to the `ServletContext` and, if necessary, can -easily be used as an adapter to an existing `WebApplicationInitializer`. - - - -[[boot-features-embedded-container-servlets-filters-listeners-scanning]] -===== Scanning for Servlets, Filters, and listeners -When using an embedded container, automatic registration of classes annotated with -`@WebServlet`, `@WebFilter`, and `@WebListener` can be enabled by using -`@ServletComponentScan`. - -TIP: `@ServletComponentScan` has no effect in a standalone container, where the -container's built-in discovery mechanisms are used instead. - - - -[[boot-features-embedded-container-application-context]] -==== The ServletWebServerApplicationContext -Under the hood, Spring Boot uses a different type of `ApplicationContext` for embedded -servlet container support. The `ServletWebServerApplicationContext` is a special type of -`WebApplicationContext` that bootstraps itself by searching for a single -`ServletWebServerFactory` bean. Usually a `TomcatServletWebServerFactory`, -`JettyServletWebServerFactory`, or `UndertowServletWebServerFactory` -has been auto-configured. - -NOTE: You usually do not need to be aware of these implementation classes. Most -applications are auto-configured, and the appropriate `ApplicationContext` and -`ServletWebServerFactory` are created on your behalf. - - - -[[boot-features-customizing-embedded-containers]] -==== Customizing Embedded Servlet Containers -Common servlet container settings can be configured by using Spring `Environment` -properties. Usually, you would define the properties in your `application.properties` -file. - -Common server settings include: - -* Network settings: Listen port for incoming HTTP requests (`server.port`), interface -address to bind to `server.address`, and so on. -* Session settings: Whether the session is persistent (`server.servlet.session.persistent`), -session timeout (`server.servlet.session.timeout`), location of session data -(`server.servlet.session.store-dir`), and session-cookie configuration -(`server.servlet.session.cookie.*`). -* Error management: Location of the error page (`server.error.path`) and so on. -* <> -* <> - -Spring Boot tries as much as possible to expose common settings, but this is not always -possible. For those cases, dedicated namespaces offer server-specific customizations (see -`server.tomcat` and `server.undertow`). For instance, -<> can be configured with specific -features of the embedded servlet container. - -TIP: See the -{sc-spring-boot-autoconfigure}/web/ServerProperties.{sc-ext}[`ServerProperties`] class -for a complete list. - - - -[[boot-features-programmatic-embedded-container-customization]] -===== Programmatic Customization -If you need to programmatically configure your embedded servlet container, you can -register a Spring bean that implements the `WebServerFactoryCustomizer` interface. -`WebServerFactoryCustomizer` provides access to the -`ConfigurableServletWebServerFactory`, which includes numerous customization setter -methods. The following example shows programmatically setting the port: - -[source,java,indent=0] ----- - import org.springframework.boot.web.server.WebServerFactoryCustomizer; - import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; - import org.springframework.stereotype.Component; - - @Component - public class CustomizationBean implements WebServerFactoryCustomizer { - - @Override - public void customize(ConfigurableServletWebServerFactory server) { - server.setPort(9000); - } - - } ----- - -NOTE: `TomcatServletWebServerFactory`, `JettyServletWebServerFactory` and `UndertowServletWebServerFactory` -are dedicated variants of `ConfigurableServletWebServerFactory` that have additional customization setter methods -for Tomcat, Jetty and Undertow respectively. - - - -[[boot-features-customizing-configurableservletwebserverfactory-directly]] -===== Customizing ConfigurableServletWebServerFactory Directly -If the preceding customization techniques are too limited, you can register the -`TomcatServletWebServerFactory`, `JettyServletWebServerFactory`, or -`UndertowServletWebServerFactory` bean yourself. - -[source,java,indent=0] ----- - @Bean - public ConfigurableServletWebServerFactory webServerFactory() { - TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(); - factory.setPort(9000); - factory.setSessionTimeout(10, TimeUnit.MINUTES); - factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notfound.html")); - return factory; - } ----- - -Setters are provided for many configuration options. Several protected method "`hooks`" -are also provided should you need to do something more exotic. See the -{dc-spring-boot}/web/servlet/server/ConfigurableServletWebServerFactory.{dc-ext}[source -code documentation] for details. - - - -[[boot-features-jsp-limitations]] -==== JSP Limitations -When running a Spring Boot application that uses an embedded servlet container (and is -packaged as an executable archive), there are some limitations in the JSP support. - -* With Jetty and Tomcat, it should work if you use war packaging. An executable war will - work when launched with `java -jar`, and will also be deployable to any standard - container. JSPs are not supported when using an executable jar. - -* Undertow does not support JSPs. - -* Creating a custom `error.jsp` page does not override the default view for -<>. -<> should be used -instead. - - - -[[boot-features-reactive-server]] -=== Embedded Reactive Server Support -Spring Boot includes support for the following embedded reactive web servers: -Reactor Netty, Tomcat, Jetty, and Undertow. Most developers use the appropriate “Starter” -to obtain a fully configured instance. By default, the embedded server listens for HTTP -requests on port 8080. - - - -[[boot-features-reactive-server-resources]] -=== Reactive Server Resources Configuration -When auto-configuring a Reactor Netty or Jetty server, Spring Boot will create specific -beans that will provide HTTP resources to the server instance: `ReactorResourceFactory` -or `JettyResourceFactory`. - -By default, those resources will be also shared with the Reactor Netty and Jetty clients -for optimal performances, given: - -* the same technology is used for server and client -* the client instance is built using the `WebClient.Builder` bean auto-configured by -Spring Boot - -Developers can override the resource configuration for Jetty and Reactor Netty by providing -a custom `ReactorResourceFactory` or `JettyResourceFactory` bean - this will be applied to -both clients and servers. - -You can learn more about the resource configuration on the client side in the -<>. - - - -[[boot-features-rsocket]] -== RSocket - -https://rsocket.io[RSocket] is a binary protocol for use on byte stream transports. -It enables symmetric interaction models via async message passing over a single connection. - -Spring Framework, with the Spring Messaging module supports RSocket both on the server and -the client side. On the server side, it lets you create special `@Controller` beans -to handle incoming RSocket messages. -Methods in your controller are mapped to RSocket routes by using `@MessageMapping` annotations. - -The following code shows a typical `@Controller`: - -[source,java,indent=0] ----- - @Controller - public class MyRSocketController { - - @MessageMapping("chat.room.{name}") - public Flux enterChatRoom(@DestinationVariable String chatRoom, - Flux messages) { - // ... - } - - @MessageMapping("users.\{user}.info") - Mono getUserInfo(@DestinationVariable String user) { - // ... - } - - } ----- - - - -[[boot-features-rsocket-strategies-auto-configuration]] -=== RSocket Strategies Auto-configuration -Spring Boot auto-configures an `RSocketStrategies` bean that provides all the required -infrastructure for encoding and decoding RSocket payloads. By default, the -auto-configuration will try to configure the following (in order): - -1. https://cbor.io/[CBOR] codecs with Jackson -2. JSON codecs with Jackson - -The `spring-boot-starter-rsocket` Starter provides both dependencies. - -Developers can customize the `RSocketStrategies` component by creating beans that -implement the `RSocketStrategiesCustomizer` interface. Note that their `@Order` is -important, as it determines the order of codecs. - - - -[[boot-features-rsocket-server-auto-configuration]] -=== RSocket server Auto-configuration -Spring Boot provides auto-configuration for RSocket servers. The required dependencies -are provided by the `spring-boot-starter-rsocket`. - -Spring Boot will start an RSocket server as a new embedded server in your application, -or will plug the RSocket infrastructure into an existing reactive Web server. This -depends on the type of application and its configuration. - -In case of a WebFlux application (i.e. of type `WebApplicationType.REACTIVE`), the -RSocket server will be plugged into the existing Web Server only if the following -properties match: - -[source,properties,indent=0,subs="verbatim,quotes,attributes"] ----- - spring.rsocket.server.mapping-path=/rsocket # a mapping path is defined - spring.rsocket.server.transport=websocket # websocket is chosen as a transport - #spring.rsocket.server.port= # no port is defined ----- - -The only other way to create an RSocket server is to start an independent, embedded -RSocket server. Besides the dependency requirements, the only required configuration -is to define a port for that server: - -[source,properties,indent=0,subs="verbatim,quotes,attributes"] ----- - spring.rsocket.server.port=9898 # the only required configuration - spring.rsocket.server.transport=tcp # you're free to configure other properties ----- - - - -[[boot-features-rsocket-messaging]] -=== Spring Messaging RSocket support -Spring Boot will auto-configure the Spring Messaging infrastructure for RSocket. - -An `RSocketStrategies` bean is created to provide encoding and decoding support -for RSocket messages. By default, Spring Boot will try to auto-configure JSON -support with Jackson for `application/json` and `"application/*+json"` media types. -Check out the <> to know more -about customization possibilities. - -Developers can create `RSocketStrategiesCustomizer` beans to add other strategies, -assuming there are `Encoder` and `Decoder` implementations available. - - - -[[boot-features-rsocket-requester]] -=== Calling RSocket Services with `RSocketRequester` - -Once the `RSocket` channel is established between server and client, any party can send or -receive requests to the other. - -As a server, you can get injected an `RSocketRequester` instance on any handler method of -an RSocket `@Controller`. As a client, you need to configure and establish an RSocket -connection first. Spring Boot auto-configures an `RSocketRequester.Builder` for such cases -with the expected codecs. - -The `RSocketRequester.Builder` instance is a prototype bean, meaning each injection point -will provide you with a new instance - this is done on purpose since this builder is stateful -and you shouldn't create requesters with different setups using the same instance. - -The following code shows a typical example: - -[source,java,indent=0] ----- - @Service - public class MyService { - - private final RSocketRequester rsocketRequester; - - public MyService(RSocketRequester.Builder rsocketRequesterBuilder) { - this.rsocketRequester = rsocketRequesterBuilder - .connectTcp("example.org", 9090).block(); - } - - public Mono someRSocketCall(String name) { - return this.requester.route("user").data(name) - .retrieveMono(User.class); - } - - } ----- - - - -[[boot-features-security]] -== Security -If {spring-security}[Spring Security] is on the classpath, then web applications are -secured by default. Spring Boot relies on Spring Security’s content-negotiation strategy -to determine whether to use `httpBasic` or `formLogin`. To add method-level security to a -web application, you can also add `@EnableGlobalMethodSecurity` with your desired -settings. Additional information can be found in the -{spring-security-reference}#jc-method[Spring Security Reference Guide]. - -The default `UserDetailsService` has a single user. The user name is `user`, and the -password is random and is printed at INFO level when the application starts, as shown in -the following example: - -[indent=0] ----- - Using generated security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35 ----- - -NOTE: If you fine-tune your logging configuration, ensure that the -`org.springframework.boot.autoconfigure.security` category is set to log `INFO`-level -messages. Otherwise, the default password is not printed. - -You can change the username and password by providing a `spring.security.user.name` and -`spring.security.user.password`. - -The basic features you get by default in a web application are: - -* A `UserDetailsService` (or `ReactiveUserDetailsService` in case of a WebFlux application) -bean with in-memory store and a single user with a generated password (see -{dc-spring-boot}/autoconfigure/security/SecurityProperties.User.html[`SecurityProperties.User`] -for the properties of the user). -* Form-based login or HTTP Basic security (depending on the `Accept` header in the request) for -the entire application (including actuator endpoints if actuator is on the classpath). -* A `DefaultAuthenticationEventPublisher` for publishing authentication events. - -You can provide a different `AuthenticationEventPublisher` by adding a bean for it. - - - -[[boot-features-security-mvc]] -=== MVC Security -The default security configuration is implemented in `SecurityAutoConfiguration` and -`UserDetailsServiceAutoConfiguration`. `SecurityAutoConfiguration` imports -`SpringBootWebSecurityConfiguration` for web security and -`UserDetailsServiceAutoConfiguration` configures authentication, which is also -relevant in non-web applications. To switch off the default web application security -configuration completely, you can add a bean of type `WebSecurityConfigurerAdapter` (doing -so does not disable the `UserDetailsService` configuration or Actuator's security). - -To also switch off the `UserDetailsService` configuration, you can add a bean of type -`UserDetailsService`, `AuthenticationProvider`, or `AuthenticationManager`. - -Access rules can be overridden by adding a custom `WebSecurityConfigurerAdapter`. Spring -Boot provides convenience methods that can be used to override access rules for actuator -endpoints and static resources. `EndpointRequest` can be used to create a `RequestMatcher` -that is based on the `management.endpoints.web.base-path` property. -`PathRequest` can be used to create a `RequestMatcher` for resources in -commonly used locations. - - - -[[boot-features-security-webflux]] -=== WebFlux Security -Similar to Spring MVC applications, you can secure your WebFlux applications by adding -the `spring-boot-starter-security` dependency. The default security configuration is -implemented in `ReactiveSecurityAutoConfiguration` and -`UserDetailsServiceAutoConfiguration`. `ReactiveSecurityAutoConfiguration` imports -`WebFluxSecurityConfiguration` for web security and `UserDetailsServiceAutoConfiguration` -configures authentication, which is also relevant in non-web applications. To switch off the default web application security -configuration completely, you can add a bean of type `WebFilterChainProxy` (doing so does -not disable the `UserDetailsService` configuration or Actuator's security). - -To also switch off the `UserDetailsService` configuration, you can add a bean of type -`ReactiveUserDetailsService` or `ReactiveAuthenticationManager`. - -Access rules can be configured by adding a custom `SecurityWebFilterChain`. Spring -Boot provides convenience methods that can be used to override access rules for actuator -endpoints and static resources. `EndpointRequest` can be used to create a -`ServerWebExchangeMatcher` that is based on the `management.endpoints.web.base-path` -property. - -`PathRequest` can be used to create a `ServerWebExchangeMatcher` for resources in -commonly used locations. - -For example, you can customize your security configuration by adding something like: - -[source,java,indent=0] ----- -include::{code-examples}/web/security/CustomWebFluxSecurityExample.java[tag=configuration] ----- - - - -[[boot-features-security-oauth2]] -=== OAuth2 -https://oauth.net/2/[OAuth2] is a widely used authorization framework that is supported by -Spring. - - - -[[boot-features-security-oauth2-client]] -==== Client -If you have `spring-security-oauth2-client` on your classpath, you can take advantage of -some auto-configuration to make it easy to set up an OAuth2/Open ID Connect clients. This configuration -makes use of the properties under `OAuth2ClientProperties`. The same properties are applicable to both servlet and reactive applications. - -You can register multiple OAuth2 clients and providers under the -`spring.security.oauth2.client` prefix, as shown in the following example: - -[source,properties,indent=0] ----- - spring.security.oauth2.client.registration.my-client-1.client-id=abcd - spring.security.oauth2.client.registration.my-client-1.client-secret=password - spring.security.oauth2.client.registration.my-client-1.client-name=Client for user scope - spring.security.oauth2.client.registration.my-client-1.provider=my-oauth-provider - spring.security.oauth2.client.registration.my-client-1.scope=user - spring.security.oauth2.client.registration.my-client-1.redirect-uri-template=https://my-redirect-uri.com - spring.security.oauth2.client.registration.my-client-1.client-authentication-method=basic - spring.security.oauth2.client.registration.my-client-1.authorization-grant-type=authorization_code - - spring.security.oauth2.client.registration.my-client-2.client-id=abcd - spring.security.oauth2.client.registration.my-client-2.client-secret=password - spring.security.oauth2.client.registration.my-client-2.client-name=Client for email scope - spring.security.oauth2.client.registration.my-client-2.provider=my-oauth-provider - spring.security.oauth2.client.registration.my-client-2.scope=email - spring.security.oauth2.client.registration.my-client-2.redirect-uri-template=https://my-redirect-uri.com - spring.security.oauth2.client.registration.my-client-2.client-authentication-method=basic - spring.security.oauth2.client.registration.my-client-2.authorization-grant-type=authorization_code - - spring.security.oauth2.client.provider.my-oauth-provider.authorization-uri=https://my-auth-server/oauth/authorize - spring.security.oauth2.client.provider.my-oauth-provider.token-uri=https://my-auth-server/oauth/token - spring.security.oauth2.client.provider.my-oauth-provider.user-info-uri=https://my-auth-server/userinfo - spring.security.oauth2.client.provider.my-oauth-provider.user-info-authentication-method=header - spring.security.oauth2.client.provider.my-oauth-provider.jwk-set-uri=https://my-auth-server/token_keys - spring.security.oauth2.client.provider.my-oauth-provider.user-name-attribute=name ----- - -For OpenID Connect providers that support https://openid.net/specs/openid-connect-discovery-1_0.html[OpenID Connect discovery], -the configuration can be further simplified. The provider needs to be configured with an `issuer-uri` which is the -URI that the it asserts as its Issuer Identifier. For example, if the -`issuer-uri` provided is "https://example.com", then an `OpenID Provider Configuration Request` -will be made to "https://example.com/.well-known/openid-configuration". The result is expected -to be an `OpenID Provider Configuration Response`. The following example shows how an OpenID Connect -Provider can be configured with the `issuer-uri`: - -[source,properties,indent=0] ----- - spring.security.oauth2.client.provider.oidc-provider.issuer-uri=https://dev-123456.oktapreview.com/oauth2/default/ ----- - - - -By default, Spring Security's `OAuth2LoginAuthenticationFilter` only processes URLs -matching `/login/oauth2/code/*`. If you want to customize the `redirect-uri` to -use a different pattern, you need to provide configuration to process that custom pattern. -For example, for servlet applications, you can add your own `WebSecurityConfigurerAdapter` that resembles the -following: - -[source,java,indent=0] ----- -public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests() - .anyRequest().authenticated() - .and() - .oauth2Login() - .redirectionEndpoint() - .baseUri("/custom-callback"); - } -} ----- - - - -[[boot-features-security-oauth2-common-providers]] -===== OAuth2 client registration for common providers -For common OAuth2 and OpenID providers, including Google, Github, Facebook, and Okta, -we provide a set of provider defaults (`google`, `github`, `facebook`, and `okta`, -respectively). - -If you do not need to customize these providers, you can set the `provider` attribute to -the one for which you need to infer defaults. Also, if the key for the client registration matches a -default supported provider, Spring Boot infers that as well. - -In other words, the two configurations in the following example use the Google provider: - -[source,properties,indent=0] ----- - spring.security.oauth2.client.registration.my-client.client-id=abcd - spring.security.oauth2.client.registration.my-client.client-secret=password - spring.security.oauth2.client.registration.my-client.provider=google - - spring.security.oauth2.client.registration.google.client-id=abcd - spring.security.oauth2.client.registration.google.client-secret=password ----- - - - -[[boot-features-security-oauth2-server]] -==== Resource Server -If you have `spring-security-oauth2-resource-server` on your classpath, Spring Boot can -set up an OAuth2 Resource Server. For JWT configuration, a JWK Set URI or OIDC Issuer URI -needs to be specified, as shown in the following examples: - -[source,properties,indent=0] ----- - spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://example.com/oauth2/default/v1/keys ----- - -[source,properties,indent=0] ----- - spring.security.oauth2.resourceserver.jwt.issuer-uri=https://dev-123456.oktapreview.com/oauth2/default/ ----- - -NOTE: If the authorization server does not support a JWK Set URI, you can configure the -resource server with the Public Key used for verifying the signature of the JWT. This can -be done using the `spring.security.oauth2.resourceserver.jwt.public-key-location` property, -where the value needs to point to a file containing the public key in the PEM-encoded x509 -format. - -The same properties are applicable for both servlet and reactive applications. - -Alternatively, you can define your own `JwtDecoder` bean for servlet applications -or a `ReactiveJwtDecoder` for reactive applications. - -In cases where opaque tokens are used instead of JWTs, you can configure the following properties -to validate tokens via introspection: - -[source,properties,indent=0] ----- - spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://example.com/check-token - spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id - spring.security.oauth2.resourceserver.opaquetoken.client-secret-my-client-secret ----- - -Again, the same properties are applicable for both servlet and reactive applications. - -Alternatively, you can define your own `OAuth2TokenIntrospectionClient` bean for servlet applications -or a `ReactiveOAuth2TokenIntrospectionClient` for reactive applications. - -==== Authorization Server -Currently, Spring Security does not provide support for implementing an OAuth 2.0 -Authorization Server. However, this functionality is available from -the https://projects.spring.io/spring-security-oauth/[Spring Security OAuth] project, -which will eventually be superseded by Spring Security completely. Until then, you can -use the `spring-security-oauth2-autoconfigure` module to easily set up an OAuth 2.0 authorization server; -see its https://docs.spring.io/spring-security-oauth2-boot[documentation] for instructions. - - - -[[boot-features-security-actuator]] -=== Actuator Security -For security purposes, all actuators other than `/health` and `/info` are disabled by -default. The `management.endpoints.web.exposure.include` property can be used to enable -the actuators. - -If Spring Security is on the classpath and no other WebSecurityConfigurerAdapter is -present, all actuators other than `/health` and `/info` are secured by Spring Boot -auto-configuration. If you define a custom `WebSecurityConfigurerAdapter`, Spring Boot -auto-configuration will back off and you will be in full control of actuator access rules. - -NOTE: Before setting the `management.endpoints.web.exposure.include`, ensure that the -exposed actuators do not contain sensitive information and/or are secured by placing them -behind a firewall or by something like Spring Security. - - - -[[boot-features-security-csrf]] -==== Cross Site Request Forgery Protection -Since Spring Boot relies on Spring Security's defaults, CSRF protection is turned on by -default. This means that the actuator endpoints that require a `POST` (shutdown and -loggers endpoints), `PUT` or `DELETE` will get a 403 forbidden error when the default -security configuration is in use. - -NOTE: We recommend disabling CSRF protection completely only if you are creating a service -that is used by non-browser clients. - -Additional information about CSRF protection can be found in the -{spring-security-reference}#csrf[Spring Security Reference Guide]. - - - -[[boot-features-sql]] -== Working with SQL Databases -The {spring-framework}[Spring Framework] provides extensive support for working with SQL -databases, from direct JDBC access using `JdbcTemplate` to complete "`object relational -mapping`" technologies such as Hibernate. {spring-data}[Spring Data] provides an -additional level of functionality: creating `Repository` implementations directly from -interfaces and using conventions to generate queries from your method names. - - - -[[boot-features-configure-datasource]] -=== Configure a DataSource -Java's `javax.sql.DataSource` interface provides a standard method of working with -database connections. Traditionally, a 'DataSource' uses a `URL` along with some -credentials to establish a database connection. - -TIP: See <> for more -advanced examples, typically to take full control over the configuration of the -DataSource. - - - -[[boot-features-embedded-database-support]] -==== Embedded Database Support -It is often convenient to develop applications by using an in-memory embedded database. -Obviously, in-memory databases do not provide persistent storage. You need to populate -your database when your application starts and be prepared to throw away data when your -application ends. - -TIP: The "`How-to`" section includes a <>. - -Spring Boot can auto-configure embedded https://www.h2database.com[H2], -http://hsqldb.org/[HSQL], and https://db.apache.org/derby/[Derby] databases. You need not -provide any connection URLs. You need only include a build dependency to the embedded -database that you want to use. - -[NOTE] -==== -If you are using this feature in your tests, you may notice that the same database is -reused by your whole test suite regardless of the number of application contexts that you -use. If you want to make sure that each context has a separate embedded database, you -should set `spring.datasource.generate-unique-name` to `true`. -==== - -For example, the typical POM dependencies would be as follows: - -[source,xml,indent=0] ----- - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.hsqldb - hsqldb - runtime - ----- - -NOTE: You need a dependency on `spring-jdbc` for an embedded database to be -auto-configured. In this example, it is pulled in transitively through -`spring-boot-starter-data-jpa`. - -TIP: If, for whatever reason, you do configure the connection URL for an embedded -database, take care to ensure that the database's automatic shutdown is disabled. If you -use H2, you should use `DB_CLOSE_ON_EXIT=FALSE` to do so. If you use HSQLDB, you should -ensure that `shutdown=true` is not used. Disabling the database's automatic shutdown lets -Spring Boot control when the database is closed, thereby ensuring that it happens once -access to the database is no longer needed. - - - -[[boot-features-connect-to-production-database]] -==== Connection to a Production Database -Production database connections can also be auto-configured by using a pooling -`DataSource`. Spring Boot uses the following algorithm for choosing a specific -implementation: - -. We prefer https://github.com/brettwooldridge/HikariCP[HikariCP] for its performance and -concurrency. If HikariCP is available, we always choose it. -. Otherwise, if the Tomcat pooling `DataSource` is available, we use it. -. If neither HikariCP nor the Tomcat pooling datasource are available and if -https://commons.apache.org/proper/commons-dbcp/[Commons DBCP2] is available, we use it. - -If you use the `spring-boot-starter-jdbc` or `spring-boot-starter-data-jpa` "`starters`", -you automatically get a dependency to `HikariCP`. - -NOTE: You can bypass that algorithm completely and specify the connection pool to use by -setting the `spring.datasource.type` property. This is especially important if you run -your application in a Tomcat container, as `tomcat-jdbc` is provided by default. - -TIP: Additional connection pools can always be configured manually. If you define your -own `DataSource` bean, auto-configuration does not occur. - -DataSource configuration is controlled by external configuration properties in -`+spring.datasource.*+`. For example, you might declare the following section in -`application.properties`: - -[source,properties,indent=0] ----- - spring.datasource.url=jdbc:mysql://localhost/test - spring.datasource.username=dbuser - spring.datasource.password=dbpass - spring.datasource.driver-class-name=com.mysql.jdbc.Driver ----- - -NOTE: You should at least specify the URL by setting the `spring.datasource.url` -property. Otherwise, Spring Boot tries to auto-configure an embedded database. - -TIP: You often do not need to specify the `driver-class-name`, since Spring Boot can -deduce it for most databases from the `url`. - -NOTE: For a pooling `DataSource` to be created, we need to be able to verify that a valid -`Driver` class is available, so we check for that before doing anything. In other words, -if you set `spring.datasource.driver-class-name=com.mysql.jdbc.Driver`, then that class -has to be loadable. - -See -{sc-spring-boot-autoconfigure}/jdbc/DataSourceProperties.{sc-ext}[`DataSourceProperties`] -for more of the supported options. These are the standard options that work regardless of -the actual implementation. It is also possible to fine-tune implementation-specific -settings by using their respective prefix (`+spring.datasource.hikari.*+`, -`+spring.datasource.tomcat.*+`, and `+spring.datasource.dbcp2.*+`). Refer to the -documentation of the connection pool implementation you are using for more details. - -For instance, if you use the -https://tomcat.apache.org/tomcat-8.0-doc/jdbc-pool.html#Common_Attributes[Tomcat -connection pool], you could customize many additional settings, as shown in the following -example: - - -[source,properties,indent=0] ----- - # Number of ms to wait before throwing an exception if no connection is available. - spring.datasource.tomcat.max-wait=10000 - - # Maximum number of active connections that can be allocated from this pool at the same time. - spring.datasource.tomcat.max-active=50 - - # Validate the connection before borrowing it from the pool. - spring.datasource.tomcat.test-on-borrow=true ----- - - - -[[boot-features-connecting-to-a-jndi-datasource]] -==== Connection to a JNDI DataSource -If you deploy your Spring Boot application to an Application Server, you might want to -configure and manage your DataSource by using your Application Server's built-in features -and access it by using JNDI. - -The `spring.datasource.jndi-name` property can be used as an alternative to the -`spring.datasource.url`, `spring.datasource.username`, and `spring.datasource.password` -properties to access the `DataSource` from a specific JNDI location. For example, the -following section in `application.properties` shows how you can access a JBoss AS defined -`DataSource`: - -[source,properties,indent=0] ----- - spring.datasource.jndi-name=java:jboss/datasources/customers ----- - - - -[[boot-features-using-jdbc-template]] -=== Using JdbcTemplate -Spring's `JdbcTemplate` and `NamedParameterJdbcTemplate` classes are auto-configured, and -you can `@Autowire` them directly into your own beans, as shown in the following example: - -[source,java,indent=0] ----- - import org.springframework.beans.factory.annotation.Autowired; - import org.springframework.jdbc.core.JdbcTemplate; - import org.springframework.stereotype.Component; - - @Component - public class MyBean { - - private final JdbcTemplate jdbcTemplate; - - @Autowired - public MyBean(JdbcTemplate jdbcTemplate) { - this.jdbcTemplate = jdbcTemplate; - } - - // ... - - } ----- - -You can customize some properties of the template by using the `spring.jdbc.template.*` -properties, as shown in the following example: - -[source,properties,indent=0] ----- - spring.jdbc.template.max-rows=500 ----- - -NOTE: The `NamedParameterJdbcTemplate` reuses the same `JdbcTemplate` instance behind the -scenes. If more than one `JdbcTemplate` is defined and no primary candidate exists, the -`NamedParameterJdbcTemplate` is not auto-configured. - - - -[[boot-features-jpa-and-spring-data]] -=== JPA and Spring Data JPA -The Java Persistence API is a standard technology that lets you "`map`" objects to -relational databases. The `spring-boot-starter-data-jpa` POM provides a quick way to get -started. It provides the following key dependencies: - -* Hibernate: One of the most popular JPA implementations. -* Spring Data JPA: Makes it easy to implement JPA-based repositories. -* Spring ORMs: Core ORM support from the Spring Framework. - -TIP: We do not go into too many details of JPA or {spring-data}[Spring Data] here. You can -follow the https://spring.io/guides/gs/accessing-data-jpa/["`Accessing Data with JPA`"] -guide from https://spring.io and read the {spring-data-jpa}[Spring Data JPA] and -https://hibernate.org/orm/documentation/[Hibernate] reference documentation. - - - -[[boot-features-entity-classes]] -==== Entity Classes -Traditionally, JPA "`Entity`" classes are specified in a `persistence.xml` file. With -Spring Boot, this file is not necessary and "`Entity Scanning`" is used instead. By -default, all packages below your main configuration class (the one annotated with -`@EnableAutoConfiguration` or `@SpringBootApplication`) are searched. - -Any classes annotated with `@Entity`, `@Embeddable`, or `@MappedSuperclass` are -considered. A typical entity class resembles the following example: - -[source,java,indent=0] ----- - package com.example.myapp.domain; - - import java.io.Serializable; - import javax.persistence.*; - - @Entity - public class City implements Serializable { - - @Id - @GeneratedValue - private Long id; - - @Column(nullable = false) - private String name; - - @Column(nullable = false) - private String state; - - // ... additional members, often include @OneToMany mappings - - protected City() { - // no-args constructor required by JPA spec - // this one is protected since it shouldn't be used directly - } - - public City(String name, String state) { - this.name = name; - this.state = state; - } - - public String getName() { - return this.name; - } - - public String getState() { - return this.state; - } - - // ... etc - - } ----- - -TIP: You can customize entity scanning locations by using the `@EntityScan` annotation. -See the "`<>`" -how-to. - - - -[[boot-features-spring-data-jpa-repositories]] -==== Spring Data JPA Repositories -{spring-data-jpa}[Spring Data JPA] repositories are interfaces that you can define to -access data. JPA queries are created automatically from your method names. For example, a -`CityRepository` interface might declare a `findAllByState(String state)` method to find -all the cities in a given state. - -For more complex queries, you can annotate your method with Spring Data's -{spring-data-javadoc}/repository/Query.html[`Query`] annotation. - -Spring Data repositories usually extend from the -{spring-data-commons-javadoc}/repository/Repository.html[`Repository`] or -{spring-data-commons-javadoc}/repository/CrudRepository.html[`CrudRepository`] -interfaces. If you use auto-configuration, repositories are searched from the package -containing your main configuration class (the one annotated with -`@EnableAutoConfiguration` or `@SpringBootApplication`) down. - -The following example shows a typical Spring Data repository interface definition: - -[source,java,indent=0] ----- - package com.example.myapp.domain; - - import org.springframework.data.domain.*; - import org.springframework.data.repository.*; - - public interface CityRepository extends Repository { - - Page findAll(Pageable pageable); - - City findByNameAndStateAllIgnoringCase(String name, String state); - - } ----- - -Spring Data JPA repositories support three different modes of bootstrapping: default, -deferred, and lazy. To enable deferred or lazy bootstrapping, set the -`spring.data.jpa.repositories.bootstrap-mode` to `deferred` or `lazy` respectively. When -using deferred or lazy bootstrapping, the auto-configured `EntityManagerFactoryBuilder` -will use the context's `AsyncTaskExecutor`, if any, as the bootstrap executor. If more -than one exists, the one named `applicationTaskExecutor` will be used. - -TIP: We have barely scratched the surface of Spring Data JPA. For complete details, see -the https://docs.spring.io/spring-data/jpa/docs/current/reference/html/[Spring Data JPA -reference documentation]. - - - -[[boot-features-creating-and-dropping-jpa-databases]] -==== Creating and Dropping JPA Databases -By default, JPA databases are automatically created *only* if you use an embedded -database (H2, HSQL, or Derby). You can explicitly configure JPA settings by using -`+spring.jpa.*+` properties. For example, to create and drop tables you can add the -following line to your `application.properties`: - -[indent=0] ----- - spring.jpa.hibernate.ddl-auto=create-drop ----- - -NOTE: Hibernate's own internal property name for this (if you happen to remember it -better) is `hibernate.hbm2ddl.auto`. You can set it, along with other Hibernate native -properties, by using `+spring.jpa.properties.*+` (the prefix is stripped before adding -them to the entity manager). The following line shows an example of setting JPA -properties for Hibernate: - -[indent=0] ----- - spring.jpa.properties.hibernate.globally_quoted_identifiers=true ----- - -The line in the preceding example passes a value of `true` for the -`hibernate.globally_quoted_identifiers` property to the Hibernate entity manager. - -By default, the DDL execution (or validation) is deferred until the `ApplicationContext` -has started. There is also a `spring.jpa.generate-ddl` flag, but it is not used if -Hibernate auto-configuration is active, because the `ddl-auto` settings are more -fine-grained. - - - -[[boot-features-jpa-in-web-environment]] -==== Open EntityManager in View -If you are running a web application, Spring Boot by default registers -{spring-javadoc}/orm/jpa/support/OpenEntityManagerInViewInterceptor.{dc-ext}[`OpenEntityManagerInViewInterceptor`] -to apply the "`Open EntityManager in View`" pattern, to allow for lazy loading in web -views. If you do not want this behavior, you should set `spring.jpa.open-in-view` to -`false` in your `application.properties`. - - - -[[boot-features-data-jdbc]] -=== Spring Data JDBC -Spring Data includes repository support for JDBC and will automatically generate SQL for -the methods on `CrudRepository`. For more advanced queries, a `@Query` annotation is -provided. - -Spring Boot will auto-configure Spring Data's JDBC repositories when the necessary -dependencies are on the classpath. They can be added to your project with a single -dependency on `spring-boot-starter-data-jdbc`. If necessary, you can take control of -Spring Data JDBC's configuration by adding the `@EnableJdbcRepositories` annotation or a -`JdbcConfiguration` subclass to your application. - -TIP: For complete details of Spring Data JDBC, please refer to the -https://projects.spring.io/spring-data-jdbc/[reference documentation]. - - - -[[boot-features-sql-h2-console]] -=== Using H2's Web Console -The https://www.h2database.com[H2 database] provides a -https://www.h2database.com/html/quickstart.html#h2_console[browser-based console] that -Spring Boot can auto-configure for you. The console is auto-configured when the following -conditions are met: - -* You are developing a servlet-based web application. -* `com.h2database:h2` is on the classpath. -* You are using <>. - -TIP: If you are not using Spring Boot's developer tools but would still like to make use -of H2's console, you can configure the `spring.h2.console.enabled` property with a value -of `true`. - -NOTE: The H2 console is only intended for use during development, so you should take -care to ensure that `spring.h2.console.enabled` is not set to `true` in production. - - - -[[boot-features-sql-h2-console-custom-path]] -==== Changing the H2 Console's Path -By default, the console is available at `/h2-console`. You can customize the console's -path by using the `spring.h2.console.path` property. - - - -[[boot-features-jooq]] -=== Using jOOQ -jOOQ Object Oriented Querying (https://www.jooq.org/[jOOQ]) is a popular product from -https://www.datageekery.com/[Data Geekery] which generates Java code from your -database and lets you build type-safe SQL queries through its fluent API. Both the -commercial and open source editions can be used with Spring Boot. - - - -==== Code Generation -In order to use jOOQ type-safe queries, you need to generate Java classes from your -database schema. You can follow the instructions in the -{jooq-manual}/#jooq-in-7-steps-step3[jOOQ user manual]. If you use the -`jooq-codegen-maven` plugin and you also use the `spring-boot-starter-parent` -"`parent POM`", you can safely omit the plugin's `` tag. You can also use Spring -Boot-defined version variables (such as `h2.version`) to declare the plugin's database -dependency. The following listing shows an example: - -[source,xml,indent=0] ----- - - org.jooq - jooq-codegen-maven - - ... - - - - com.h2database - h2 - ${h2.version} - - - - - org.h2.Driver - jdbc:h2:~/yourdatabase - - - ... - - - ----- - - - -==== Using DSLContext -The fluent API offered by jOOQ is initiated through the `org.jooq.DSLContext` interface. -Spring Boot auto-configures a `DSLContext` as a Spring Bean and connects it to your -application `DataSource`. To use the `DSLContext`, you can `@Autowire` it, as shown in -the following example: - -[source,java,indent=0] ----- - @Component - public class JooqExample implements CommandLineRunner { - - private final DSLContext create; - - @Autowired - public JooqExample(DSLContext dslContext) { - this.create = dslContext; - } - - } ----- - -TIP: The jOOQ manual tends to use a variable named `create` to hold the `DSLContext`. - -You can then use the `DSLContext` to construct your queries, as shown in the following -example: - -[source,java,indent=0] ----- - public List authorsBornAfter1980() { - return this.create.selectFrom(AUTHOR) - .where(AUTHOR.DATE_OF_BIRTH.greaterThan(new GregorianCalendar(1980, 0, 1))) - .fetch(AUTHOR.DATE_OF_BIRTH); - } ----- - - - -==== jOOQ SQL Dialect -Unless the `spring.jooq.sql-dialect` property has been configured, Spring Boot determines -the SQL dialect to use for your datasource. If Spring Boot could not detect the dialect, -it uses `DEFAULT`. - -NOTE: Spring Boot can only auto-configure dialects supported by the open source version -of jOOQ. - - - -==== Customizing jOOQ -More advanced customizations can be achieved by defining your own `@Bean` definitions, -which is used when the jOOQ `Configuration` is created. You can define beans for the -following jOOQ Types: - -* `ConnectionProvider` -* `ExecutorProvider` -* `TransactionProvider` -* `RecordMapperProvider` -* `RecordUnmapperProvider` -* `RecordListenerProvider` -* `ExecuteListenerProvider` -* `VisitListenerProvider` -* `TransactionListenerProvider` - -You can also create your own `org.jooq.Configuration` `@Bean` if you want to take -complete control of the jOOQ configuration. - - - -[[boot-features-nosql]] -== Working with NoSQL Technologies -Spring Data provides additional projects that help you access a variety of NoSQL -technologies, including: -https://projects.spring.io/spring-data-mongodb/[MongoDB], -https://projects.spring.io/spring-data-neo4j/[Neo4J], -https://github.com/spring-projects/spring-data-elasticsearch/[Elasticsearch], -https://projects.spring.io/spring-data-solr/[Solr], -https://projects.spring.io/spring-data-redis/[Redis], -https://projects.spring.io/spring-data-gemfire/[Gemfire], -https://projects.spring.io/spring-data-cassandra/[Cassandra], -https://projects.spring.io/spring-data-couchbase/[Couchbase] and -https://projects.spring.io/spring-data-ldap/[LDAP]. -Spring Boot provides auto-configuration for Redis, MongoDB, Neo4j, Elasticsearch, Solr -Cassandra, Couchbase, and LDAP. You can make use of the other projects, but you must -configure them yourself. Refer to the appropriate reference documentation at -https://projects.spring.io/spring-data[projects.spring.io/spring-data]. - - - -[[boot-features-redis]] -=== Redis -https://redis.io/[Redis] is a cache, message broker, and richly-featured key-value store. -Spring Boot offers basic auto-configuration for the -https://github.com/lettuce-io/lettuce-core/[Lettuce] and -https://github.com/xetorthio/jedis/[Jedis] client libraries and the abstractions on top -of them provided by https://github.com/spring-projects/spring-data-redis[Spring Data -Redis]. - -There is a `spring-boot-starter-data-redis` "`Starter`" for collecting the dependencies -in a convenient way. By default, it uses -https://github.com/lettuce-io/lettuce-core/[Lettuce]. That starter handles both -traditional and reactive applications. - -TIP: we also provide a `spring-boot-starter-data-redis-reactive` "`Starter`" for -consistency with the other stores with reactive support. - - - -[[boot-features-connecting-to-redis]] -==== Connecting to Redis -You can inject an auto-configured `RedisConnectionFactory`, `StringRedisTemplate`, or -vanilla `RedisTemplate` instance as you would any other Spring Bean. By default, the -instance tries to connect to a Redis server at `localhost:6379`. The following listing -shows an example of such a bean: - -[source,java,indent=0] ----- - @Component - public class MyBean { - - private StringRedisTemplate template; - - @Autowired - public MyBean(StringRedisTemplate template) { - this.template = template; - } - - // ... - - } ----- - -TIP: You can also register an arbitrary number of beans that implement -`LettuceClientConfigurationBuilderCustomizer` for more advanced customizations. If you -use Jedis, `JedisClientConfigurationBuilderCustomizer` is also available. - -If you add your own `@Bean` of any of the auto-configured types, it replaces the default -(except in the case of `RedisTemplate`, when the exclusion is based on the bean name, -`redisTemplate`, not its type). By default, if `commons-pool2` is on the classpath, you -get a pooled connection factory. - - - -[[boot-features-mongodb]] -=== MongoDB -https://www.mongodb.com/[MongoDB] is an open-source NoSQL document database that uses a -JSON-like schema instead of traditional table-based relational data. Spring Boot offers -several conveniences for working with MongoDB, including the -`spring-boot-starter-data-mongodb` and `spring-boot-starter-data-mongodb-reactive` -"`Starters`". - - - -[[boot-features-connecting-to-mongodb]] -==== Connecting to a MongoDB Database -To access Mongo databases, you can inject an auto-configured -`org.springframework.data.mongodb.MongoDbFactory`. By default, the instance tries to -connect to a MongoDB server at `mongodb://localhost/test` The following example shows how -to connect to a MongoDB database: - -[source,java,indent=0] ----- - import org.springframework.data.mongodb.MongoDbFactory; - import com.mongodb.DB; - - @Component - public class MyBean { - - private final MongoDbFactory mongo; - - @Autowired - public MyBean(MongoDbFactory mongo) { - this.mongo = mongo; - } - - // ... - - public void example() { - DB db = mongo.getDb(); - // ... - } - - } ----- - -You can set the `spring.data.mongodb.uri` property to change the URL and configure -additional settings such as the _replica set_, as shown in the following example: - -[source,properties,indent=0] ----- - spring.data.mongodb.uri=mongodb://user:secret@mongo1.example.com:12345,mongo2.example.com:23456/test ----- - -Alternatively, as long as you use Mongo 2.x, you can specify a `host`/`port`. For -example, you might declare the following settings in your `application.properties`: - -[source,properties,indent=0] ----- - spring.data.mongodb.host=mongoserver - spring.data.mongodb.port=27017 ----- - -If you have defined your own `MongoClient`, it will be used to auto-configure a suitable -`MongoDbFactory`. Both `com.mongodb.MongoClient` and `com.mongodb.client.MongoClient` -are supported. - -NOTE: If you use the Mongo 3.0 Java driver, `spring.data.mongodb.host` and -`spring.data.mongodb.port` are not supported. In such cases, `spring.data.mongodb.uri` -should be used to provide all of the configuration. - -TIP: If `spring.data.mongodb.port` is not specified, the default of `27017` is used. You -could delete this line from the example shown earlier. - -TIP: If you do not use Spring Data Mongo, you can inject `com.mongodb.MongoClient` beans -instead of using `MongoDbFactory`. If you want to take complete control of establishing -the MongoDB connection, you can also declare your own `MongoDbFactory` or `MongoClient` -bean. - -NOTE: If you are using the reactive driver, Netty is required for SSL. The -auto-configuration configures this factory automatically if Netty is available and the -factory to use hasn't been customized already. - -[[boot-features-mongo-template]] -==== MongoTemplate -{spring-data-mongo}[Spring Data MongoDB] provides a -{spring-data-mongo-javadoc}/core/MongoTemplate.html[`MongoTemplate`] class that is very -similar in its design to Spring's `JdbcTemplate`. As with `JdbcTemplate`, Spring Boot -auto-configures a bean for you to inject the template, as follows: - -[source,java,indent=0] ----- - import org.springframework.beans.factory.annotation.Autowired; - import org.springframework.data.mongodb.core.MongoTemplate; - import org.springframework.stereotype.Component; - - @Component - public class MyBean { - - private final MongoTemplate mongoTemplate; - - @Autowired - public MyBean(MongoTemplate mongoTemplate) { - this.mongoTemplate = mongoTemplate; - } - - // ... - - } ----- - -See the -https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/MongoOperations.html[`MongoOperations` -Javadoc] for complete details. - - - -[[boot-features-spring-data-mongo-repositories]] -==== Spring Data MongoDB Repositories -Spring Data includes repository support for MongoDB. As with the JPA repositories -discussed earlier, the basic principle is that queries are constructed automatically, -based on method names. - -In fact, both Spring Data JPA and Spring Data MongoDB share the same common -infrastructure. You could take the JPA example from earlier and, assuming that `City` is -now a Mongo data class rather than a JPA `@Entity`, it works in the same way, as shown -in the following example: - -[source,java,indent=0] ----- - package com.example.myapp.domain; - - import org.springframework.data.domain.*; - import org.springframework.data.repository.*; - - public interface CityRepository extends Repository { - - Page findAll(Pageable pageable); - - City findByNameAndStateAllIgnoringCase(String name, String state); - - } ----- - -TIP: You can customize document scanning locations by using the `@EntityScan` annotation. - -TIP: For complete details of Spring Data MongoDB, including its rich object mapping -technologies, refer to its https://projects.spring.io/spring-data-mongodb/[reference -documentation]. - - - -[[boot-features-mongo-embedded]] -==== Embedded Mongo -Spring Boot offers auto-configuration for -https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo[Embedded Mongo]. To use it in -your Spring Boot application, add a dependency on -`de.flapdoodle.embed:de.flapdoodle.embed.mongo`. - -The port that Mongo listens on can be configured by setting the `spring.data.mongodb.port` -property. To use a randomly allocated free port, use a value of 0. The `MongoClient` -created by `MongoAutoConfiguration` is automatically configured to use the randomly -allocated port. - -NOTE: If you do not configure a custom port, the embedded support uses a random port -(rather than 27017) by default. - -If you have SLF4J on the classpath, the output produced by Mongo is automatically routed -to a logger named `org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongo`. - -You can declare your own `IMongodConfig` and `IRuntimeConfig` beans to take control of -the Mongo instance's configuration and logging routing. The download configuration can be -customized by declaring a `DownloadConfigBuilderCustomizer` bean. - - - -[[boot-features-neo4j]] -=== Neo4j -https://neo4j.com/[Neo4j] is an open-source NoSQL graph database that uses a rich data -model of nodes connected by first class relationships, which is better suited for -connected big data than traditional RDBMS approaches. Spring Boot offers several -conveniences for working with Neo4j, including the `spring-boot-starter-data-neo4j` -"`Starter`". - - - -[[boot-features-connecting-to-neo4j]] -==== Connecting to a Neo4j Database -To access a Neo4j server, you can inject an auto-configured -`org.neo4j.ogm.session.Session`. By default, the instance tries to connect to a Neo4j -server at `localhost:7687` using the Bolt protocol. The following example shows how to -inject a Neo4j `Session`: - -[source,java,indent=0] ----- - @Component - public class MyBean { - - private final Session session; - - @Autowired - public MyBean(Session session) { - this.session = session; - } - - // ... - - } ----- - -You can configure the uri and credentials to use by setting the `spring.data.neo4j.*` -properties, as shown in the following example: - -[source,properties,indent=0] ----- - spring.data.neo4j.uri=bolt://my-server:7687 - spring.data.neo4j.username=neo4j - spring.data.neo4j.password=secret ----- - -You can take full control over the session creation by adding a -`org.neo4j.ogm.config.Configuration` `@Bean`. Also, adding a `@Bean` of type -`SessionFactory` disables the auto-configuration and gives you full control. - - - -[[boot-features-connecting-to-neo4j-embedded]] -==== Using the Embedded Mode -If you add `org.neo4j:neo4j-ogm-embedded-driver` to the dependencies of your application, -Spring Boot automatically configures an in-process embedded instance of Neo4j that does -not persist any data when your application shuts down. - -[NOTE] -==== -As the embedded Neo4j OGM driver does not provide the Neo4j kernel itself, you have -to declare `org.neo4j:neo4j` as dependency yourself. Refer to -https://neo4j.com/docs/ogm-manual/current/reference/#reference:getting-started[the -Neo4j OGM documentation] for a list of compatible versions. -==== - -The embedded driver takes precedence over the other drivers when there are multiple -drivers on the classpath. You can explicitly disable the embedded mode by setting -`spring.data.neo4j.embedded.enabled=false`. - -<> -automatically make use of an embedded Neo4j instance if the embedded driver and Neo4j -kernel are on the classpath as described above. - -[NOTE] -==== -You can enable persistence for the embedded mode by providing a path to a database file -in your configuration, e.g. `spring.data.neo4j.uri=file://var/tmp/graph.db`. -==== - - - -[[boot-features-neo4j-ogm-native-types]] -==== Using Native Types -Neo4j-OGM can map some types, like those in `java.time.*`, to `String`-based properties -or to one of the native types that Neo4j provides. For backwards compatibility reasons -the default for Neo4j-OGM is to use a `String`-based representation. To use native types, -add a dependency on either `org.neo4j:neo4j-ogm-bolt-native-types` or -`org.neo4j:neo4j-ogm-embedded-native-types`, and configure the -`spring.data.neo4j.use-native-types` property as shown in the following example: - -[source,properties,indent=0] ----- - spring.data.neo4j.use-native-types=true ----- - - - -[[boot-features-neo4j-ogm-session]] -==== Neo4jSession -By default, if you are running a web application, the session is bound to the thread for -the entire processing of the request (that is, it uses the "Open Session in View" -pattern). If you do not want this behavior, add the following line to your -`application.properties` file: - -[source,properties,indent=0] ----- - spring.data.neo4j.open-in-view=false ----- - - - -[[boot-features-spring-data-neo4j-repositories]] -==== Spring Data Neo4j Repositories -Spring Data includes repository support for Neo4j. - -Spring Data Neo4j shares the common infrastructure with Spring Data JPA as many other -Spring Data modules do. You could take the JPA example from earlier and define -`City` as Neo4j OGM `@NodeEntity` rather than JPA `@Entity` and the repository -abstraction works in the same way, as shown in the following example: - -[source,java,indent=0] ----- - package com.example.myapp.domain; - - import java.util.Optional; - - import org.springframework.data.neo4j.repository.*; - - public interface CityRepository extends Neo4jRepository { - - Optional findOneByNameAndState(String name, String state); - - } ----- - -The `spring-boot-starter-data-neo4j` "`Starter`" enables the repository support as well -as transaction management. You can customize the locations to look for repositories and -entities by using `@EnableNeo4jRepositories` and `@EntityScan` respectively on a -`@Configuration`-bean. - -TIP: For complete details of Spring Data Neo4j, including its object mapping -technologies, refer to the https://projects.spring.io/spring-data-neo4j/[reference -documentation]. - - - -[[boot-features-gemfire]] -=== Gemfire -https://github.com/spring-projects/spring-data-gemfire[Spring Data Gemfire] provides -convenient Spring-friendly tools for accessing the -https://pivotal.io/big-data/pivotal-gemfire#details[Pivotal Gemfire] data management -platform. There is a `spring-boot-starter-data-gemfire` "`Starter`" for collecting the -dependencies in a convenient way. There is currently no auto-configuration support for -Gemfire, but you can enable Spring Data Repositories with a -https://github.com/spring-projects/spring-data-gemfire/blob/master/src/main/java/org/springframework/data/gemfire/repository/config/EnableGemfireRepositories.java[single annotation: `@EnableGemfireRepositories`]. - - - -[[boot-features-solr]] -=== Solr -https://lucene.apache.org/solr/[Apache Solr] is a search engine. Spring Boot offers basic -auto-configuration for the Solr 5 client library and the abstractions on top of it -provided by https://github.com/spring-projects/spring-data-solr[Spring Data Solr]. There -is a `spring-boot-starter-data-solr` "`Starter`" for collecting the dependencies in a -convenient way. - - -[[boot-features-connecting-to-solr]] -==== Connecting to Solr -You can inject an auto-configured `SolrClient` instance as you would any other Spring -bean. By default, the instance tries to connect to a server at -`http://localhost:8983/solr`. The following example shows how to inject a Solr bean: - -[source,java,indent=0] ----- - @Component - public class MyBean { - - private SolrClient solr; - - @Autowired - public MyBean(SolrClient solr) { - this.solr = solr; - } - - // ... - - } ----- - -If you add your own `@Bean` of type `SolrClient`, it replaces the default. - - - -[[boot-features-spring-data-solr-repositories]] -==== Spring Data Solr Repositories -Spring Data includes repository support for Apache Solr. As with the JPA repositories -discussed earlier, the basic principle is that queries are automatically constructed for \ -you based on method names. - -In fact, both Spring Data JPA and Spring Data Solr share the same common infrastructure. -You could take the JPA example from earlier and, assuming that `City` is now a -`@SolrDocument` class rather than a JPA `@Entity`, it works in the same way. - -TIP: For complete details of Spring Data Solr, refer to the -https://projects.spring.io/spring-data-solr/[reference documentation]. - - - -[[boot-features-elasticsearch]] -=== Elasticsearch -https://www.elastic.co/products/elasticsearch[Elasticsearch] is an open source, -distributed, RESTful search and analytics engine. Spring Boot offers basic -auto-configuration for Elasticsearch. - -Spring Boot supports several clients: - -* The official Java "Low Level" and "High Level" REST clients -* The `ReactiveElasticsearchClient` provided by Spring Data Elasticsearch - -The transport client is still available but its support has been deprecated in -https://github.com/spring-projects/spring-data-elasticsearch[Spring Data Elasticsearch] -and Elasticsearch itself. It will be removed in a future release. -Spring Boot provides a dedicated "`Starter`", `spring-boot-starter-data-elasticsearch`. - -The https://github.com/searchbox-io/Jest[Jest] client has been deprecated as well, since -both Elasticsearch and Spring Data Elasticsearch provide official support for REST clients. - -[[boot-features-connecting-to-elasticsearch-rest]] -==== Connecting to Elasticsearch using REST clients -Elasticsearch ships -https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/index.html[two different REST clients] -that you can use to query a cluster: the "Low Level" client and the "High Level" client. - -If you have the `org.elasticsearch.client:elasticsearch-rest-client` dependency on the -classpath, Spring Boot will auto-configure and register a `RestClient` bean that -by default targets `http://localhost:9200`. -You can further tune how `RestClient` is configured, as shown in the following example: - -[source,properties,indent=0] ----- - spring.elasticsearch.rest.uris=https://search.example.com:9200 - spring.elasticsearch.rest.read-timeout=10s - spring.elasticsearch.rest.username=user - spring.elasticsearch.rest.password=secret ----- - -You can also register an arbitrary number of beans that implement -`RestClientBuilderCustomizer` for more advanced customizations. -To take full control over the registration, define a `RestClient` bean. - -If you have the `org.elasticsearch.client:elasticsearch-rest-high-level-client` dependency -on the classpath, Spring Boot will auto-configure a `RestHighLevelClient`, which wraps -any existing `RestClient` bean, reusing its HTTP configuration. - -[[boot-features-connecting-to-elasticsearch-reactive-rest]] -==== Connecting to Elasticsearch using Reactive REST clients -{spring-data-elasticsearch}[Spring Data Elasticsearch] ships `ReactiveElasticsearchClient` -for querying Elasticsearch instances in a reactive fashion. It is built on top of WebFlux's -`WebClient`, so both `spring-boot-starter-elasticsearch` and `spring-boot-starter-webflux` -dependencies are useful to enable this support. - -By default, Spring Boot will auto-configure and register a `ReactiveElasticsearchClient` -bean that targets `http://localhost:9200`. -You can further tune how it is configured, as shown in the following example: - -[source,properties,indent=0] ----- - spring.elasticsearch.reactive.endpoints=search.example.com:9200 - spring.elasticsearch.reactive.use-ssl=true - spring.elasticsearch.reactive.socket-timeout=10s - spring.elasticsearch.reactive.username=user - spring.elasticsearch.reactive.password=secret ----- - -If the configuration properties are not enough and you'd like to fully control the client -configuration, you can register a custom `ClientConfiguration` bean. - -[[boot-features-connecting-to-elasticsearch-jest]] -==== Connecting to Elasticsearch using Jest -Now that Spring Boot supports the official `RestHighLevelClient`, Jest support is -deprecated. - -If you have `Jest` on the classpath, you can inject an auto-configured `JestClient` that -by default targets `http://localhost:9200`. You can further tune how the client is -configured, as shown in the following example: - -[source,properties,indent=0] ----- - spring.elasticsearch.jest.uris=https://search.example.com:9200 - spring.elasticsearch.jest.read-timeout=10000 - spring.elasticsearch.jest.username=user - spring.elasticsearch.jest.password=secret ----- - -You can also register an arbitrary number of beans that implement -`HttpClientConfigBuilderCustomizer` for more advanced customizations. The following -example tunes additional HTTP settings: - -[source,java,indent=0] ----- -include::{code-examples}/elasticsearch/jest/JestClientCustomizationExample.java[tag=customizer] ----- - -To take full control over the registration, define a `JestClient` bean. - - - -[[boot-features-connecting-to-elasticsearch-spring-data]] -==== Connecting to Elasticsearch by Using Spring Data - -To connect to Elasticsearch, a `RestHighLevelClient` bean must be defined, -auto-configured by Spring Boot or manually provided by the application (see previous sections). -With this configuration in place, an -`ElasticsearchRestTemplate` can be injected like any other Spring bean, -as shown in the following example: - -[source,java,indent=0] ----- - @Component - public class MyBean { - - private final ElasticsearchRestTemplate template; - - public MyBean(ElasticsearchRestTemplate template) { - this.template = template; - } - - // ... - - } ----- - -In the presence of `spring-data-elasticsearch` and the required dependencies -for using a `WebClient` (typically `spring-boot-starter-webflux`), Spring Boot can also -auto-configure a -<> -and a `ReactiveElasticsearchTemplate` as beans. They are the reactive equivalent of the -other REST clients. - - -[[boot-features-spring-data-elasticsearch-repositories]] -==== Spring Data Elasticsearch Repositories -Spring Data includes repository support for Elasticsearch. As with the JPA repositories -discussed earlier, the basic principle is that queries are constructed for you -automatically based on method names. - -In fact, both Spring Data JPA and Spring Data Elasticsearch share the same common -infrastructure. You could take the JPA example from earlier and, assuming that `City` is -now an Elasticsearch `@Document` class rather than a JPA `@Entity`, it works in the same -way. - -TIP: For complete details of Spring Data Elasticsearch, refer to the -{spring-data-elasticsearch-reference}[reference documentation]. - -Spring Boot supports both classic and reactive Elasticsearch repositories, using the -`ElasticsearchRestTemplate` or `ReactiveElasticsearchTemplate` beans. Most likely those -beans are auto-configured by Spring Boot given the required dependencies are present. - -If you wish to use your own template for backing the Elasticsearch repositories, you can -add your own `ElasticsearchRestTemplate` or `ElasticsearchOperations` `@Bean`, -as long as it is named `"elasticsearchTemplate"`. Same applies to -`ReactiveElasticsearchTemplate` and `ReactiveElasticsearchOperations`, with the bean -name `"reactiveElasticsearchTemplate"`. - -You can choose to disable the repositories support with the following property: - -[source,properties,indent=0] ----- - spring.data.elasticsearch.repositories.enabled=false ----- - - -[[boot-features-cassandra]] -=== Cassandra -https://cassandra.apache.org/[Cassandra] is an open source, distributed database -management system designed to handle large amounts of data across many commodity servers. -Spring Boot offers auto-configuration for Cassandra and the abstractions on top of it -provided by https://github.com/spring-projects/spring-data-cassandra[Spring Data -Cassandra]. There is a `spring-boot-starter-data-cassandra` "`Starter`" for collecting -the dependencies in a convenient way. - - - -[[boot-features-connecting-to-cassandra]] -==== Connecting to Cassandra -You can inject an auto-configured `CassandraTemplate` or a Cassandra `Session` instance -as you would with any other Spring Bean. The `spring.data.cassandra.*` properties can be -used to customize the connection. Generally, you provide `keyspace-name` and -`contact-points` properties, as shown in the following example: - -[source,properties,indent=0] ----- - spring.data.cassandra.keyspace-name=mykeyspace - spring.data.cassandra.contact-points=cassandrahost1,cassandrahost2 ----- - -You can also register an arbitrary number of beans that implement -`ClusterBuilderCustomizer` for more advanced customizations. - -The following code listing shows how to inject a Cassandra bean: - -[source,java,indent=0] ----- - @Component - public class MyBean { - - private CassandraTemplate template; - - @Autowired - public MyBean(CassandraTemplate template) { - this.template = template; - } - - // ... - - } ----- - -If you add your own `@Bean` of type `CassandraTemplate`, it replaces the default. - - - -[[boot-features-spring-data-cassandra-repositories]] -==== Spring Data Cassandra Repositories -Spring Data includes basic repository support for Cassandra. Currently, this is more -limited than the JPA repositories discussed earlier and needs to annotate finder methods -with `@Query`. - -TIP: For complete details of Spring Data Cassandra, refer to the -https://docs.spring.io/spring-data/cassandra/docs/[reference documentation]. - - - -[[boot-features-couchbase]] -=== Couchbase -https://www.couchbase.com/[Couchbase] is an open-source, distributed, multi-model NoSQL -document-oriented database that is optimized for interactive applications. Spring Boot -offers auto-configuration for Couchbase and the abstractions on top of it provided by -https://github.com/spring-projects/spring-data-couchbase[Spring Data Couchbase]. There are -`spring-boot-starter-data-couchbase` and `spring-boot-starter-data-couchbase-reactive` -"`Starters`" for collecting the dependencies in a convenient way. - - - -[[boot-features-connecting-to-couchbase]] -==== Connecting to Couchbase -You can get a `Bucket` and `Cluster` by adding the Couchbase SDK and some configuration. -The `spring.couchbase.*` properties can be used to customize the connection. Generally, -you provide the bootstrap hosts, bucket name, and password, as shown in the following -example: - -[source,properties,indent=0] ----- - spring.couchbase.bootstrap-hosts=my-host-1,192.168.1.123 - spring.couchbase.bucket.name=my-bucket - spring.couchbase.bucket.password=secret ----- - -[TIP] -==== -You need to provide _at least_ the bootstrap host(s), in which case the bucket name is -`default` and the password is an empty String. Alternatively, you can define your own -`org.springframework.data.couchbase.config.CouchbaseConfigurer` `@Bean` to take control -over the whole configuration. -==== - -It is also possible to customize some of the `CouchbaseEnvironment` settings. For -instance, the following configuration changes the timeout to use to open a new `Bucket` -and enables SSL support: - -[source,properties,indent=0] ----- - spring.couchbase.env.timeouts.connect=3000 - spring.couchbase.env.ssl.key-store=/location/of/keystore.jks - spring.couchbase.env.ssl.key-store-password=secret ----- - -Check the `spring.couchbase.env.*` properties for more details. - - - -[[boot-features-spring-data-couchbase-repositories]] -==== Spring Data Couchbase Repositories -Spring Data includes repository support for Couchbase. For complete details of Spring -Data Couchbase, refer to the -https://docs.spring.io/spring-data/couchbase/docs/current/reference/html/[reference -documentation]. - -You can inject an auto-configured `CouchbaseTemplate` instance as you would with any -other Spring Bean, provided a _default_ `CouchbaseConfigurer` is available (which -happens when you enable Couchbase support, as explained earlier). - -The following examples shows how to inject a Couchbase bean: - -[source,java,indent=0] ----- - @Component - public class MyBean { - - private final CouchbaseTemplate template; - - @Autowired - public MyBean(CouchbaseTemplate template) { - this.template = template; - } - - // ... - - } ----- - -There are a few beans that you can define in your own configuration to override those -provided by the auto-configuration: - -* A `CouchbaseTemplate` `@Bean` with a name of `couchbaseTemplate`. -* An `IndexManager` `@Bean` with a name of `couchbaseIndexManager`. -* A `CustomConversions` `@Bean` with a name of `couchbaseCustomConversions`. - -To avoid hard-coding those names in your own config, you can reuse `BeanNames` provided -by Spring Data Couchbase. For instance, you can customize the converters to use, as -follows: - -[source,java,indent=0] ----- - @Configuration(proxyBeanMethods = false) - public class SomeConfiguration { - - @Bean(BeanNames.COUCHBASE_CUSTOM_CONVERSIONS) - public CustomConversions myCustomConversions() { - return new CustomConversions(...); - } - - // ... - - } ----- - -TIP: If you want to fully bypass the auto-configuration for Spring Data Couchbase, -provide your own implementation of -`org.springframework.data.couchbase.config.AbstractCouchbaseDataConfiguration`. - - - -[[boot-features-ldap]] -=== LDAP -https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol[LDAP] (Lightweight -Directory Access Protocol) is an open, vendor-neutral, industry standard application -protocol for accessing and maintaining distributed directory information services over an -IP network. Spring Boot offers auto-configuration for any compliant LDAP server as well -as support for the embedded in-memory LDAP server from -https://www.ldap.com/unboundid-ldap-sdk-for-java[UnboundID]. - -LDAP abstractions are provided by -https://github.com/spring-projects/spring-data-ldap[Spring Data LDAP]. -There is a `spring-boot-starter-data-ldap` "`Starter`" for collecting the dependencies in -a convenient way. - - - -[[boot-features-ldap-connecting]] -==== Connecting to an LDAP Server -To connect to an LDAP server, make sure you declare a dependency on the -`spring-boot-starter-data-ldap` "`Starter`" or `spring-ldap-core` and then declare the -URLs of your server in your application.properties, as shown in the following example: - -[source,properties,indent=0] ----- - spring.ldap.urls=ldap://myserver:1235 - spring.ldap.username=admin - spring.ldap.password=secret ----- - -If you need to customize connection settings, you can use the `spring.ldap.base` and -`spring.ldap.base-environment` properties. - -An `LdapContextSource` is auto-configured based on these settings. If you need to customize -it, for instance to use a `PooledContextSource`, you can still inject the auto-configured -`LdapContextSource`. Make sure to flag your customized `ContextSource` as `@Primary` so -that the auto-configured `LdapTemplate` uses it. - - - -[[boot-features-ldap-spring-data-repositories]] -==== Spring Data LDAP Repositories -Spring Data includes repository support for LDAP. For complete details of Spring -Data LDAP, refer to the -https://docs.spring.io/spring-data/ldap/docs/1.0.x/reference/html/[reference -documentation]. - -You can also inject an auto-configured `LdapTemplate` instance as you would with any -other Spring Bean, as shown in the following example: - - -[source,java,indent=0] ----- - @Component - public class MyBean { - - private final LdapTemplate template; - - @Autowired - public MyBean(LdapTemplate template) { - this.template = template; - } - - // ... - - } ----- - - - -[[boot-features-ldap-embedded]] -==== Embedded In-memory LDAP Server -For testing purposes, Spring Boot supports auto-configuration of an in-memory LDAP server -from https://www.ldap.com/unboundid-ldap-sdk-for-java[UnboundID]. To configure the server, -add a dependency to `com.unboundid:unboundid-ldapsdk` and declare a `base-dn` property, as -follows: - -[source,properties,indent=0] ----- - spring.ldap.embedded.base-dn=dc=spring,dc=io ----- - -[NOTE] -==== -It is possible to define multiple base-dn values, however, since distinguished names -usually contain commas, they must be defined using the correct notation. - -In yaml files, you can use the yaml list notation: - -[source,yaml,indent=0] ----- - spring.ldap.embedded.base-dn: - - dc=spring,dc=io - - dc=pivotal,dc=io ----- - -In properties files, you must include the index as part of the property name: - -[source,properties,indent=0] ----- - spring.ldap.embedded.base-dn[0]=dc=spring,dc=io - spring.ldap.embedded.base-dn[1]=dc=pivotal,dc=io ----- - -==== - -By default, the server starts on a random port and triggers the regular LDAP support. -There is no need to specify a `spring.ldap.urls` property. - -If there is a `schema.ldif` file on your classpath, it is used to initialize the server. -If you want to load the initialization script from a different resource, you can also use -the `spring.ldap.embedded.ldif` property. - -By default, a standard schema is used to validate `LDIF` files. You can turn off -validation altogether by setting the `spring.ldap.embedded.validation.enabled` property. -If you have custom attributes, you can use `spring.ldap.embedded.validation.schema` to -define your custom attribute types or object classes. - - - -[[boot-features-influxdb]] -=== InfluxDB -https://www.influxdata.com/[InfluxDB] is an open-source time series database optimized -for fast, high-availability storage and retrieval of time series data in fields such as -operations monitoring, application metrics, Internet-of-Things sensor data, and real-time -analytics. - - - -[[boot-features-connecting-to-influxdb]] -==== Connecting to InfluxDB -Spring Boot auto-configures an `InfluxDB` instance, provided the `influxdb-java` client -is on the classpath and the URL of the database is set, as shown in the following -example: - -[source,properties,indent=0] ----- - spring.influx.url=https://172.0.0.1:8086 ----- - -If the connection to InfluxDB requires a user and password, you can set the -`spring.influx.user` and `spring.influx.password` properties accordingly. - -InfluxDB relies on OkHttp. If you need to tune the http client `InfluxDB` uses behind the -scenes, you can register an `InfluxDbOkHttpClientBuilderProvider` bean. - - - -[[boot-features-caching]] -== Caching -The Spring Framework provides support for transparently adding caching to an application. -At its core, the abstraction applies caching to methods, thus reducing the number of -executions based on the information available in the cache. The caching logic is applied -transparently, without any interference to the invoker. Spring Boot auto-configures the -cache infrastructure as long as caching support is enabled via the `@EnableCaching` -annotation. - -NOTE: Check the {spring-reference}integration.html#cache[relevant section] of the Spring -Framework reference for more details. - -In a nutshell, adding caching to an operation of your service is as easy as adding the -relevant annotation to its method, as shown in the following example: - -[source,java,indent=0] ----- - import org.springframework.cache.annotation.Cacheable; - import org.springframework.stereotype.Component; - - @Component - public class MathService { - - @Cacheable("piDecimals") - public int computePiDecimal(int i) { - // ... - } - - } ----- - -This example demonstrates the use of caching on a potentially costly operation. Before -invoking `computePiDecimal`, the abstraction looks for an entry in the `piDecimals` cache -that matches the `i` argument. If an entry is found, the content in the cache is -immediately returned to the caller, and the method is not invoked. Otherwise, the method -is invoked, and the cache is updated before returning the value. - -CAUTION: You can also use the standard JSR-107 (JCache) annotations (such as -`@CacheResult`) transparently. However, we strongly advise you to not mix and match the -Spring Cache and JCache annotations. - -If you do not add any specific cache library, Spring Boot auto-configures a -<> that uses concurrent maps in -memory. When a cache is required (such as `piDecimals` in the preceding example), this -provider creates it for you. The simple provider is not really recommended for -production usage, but it is great for getting started and making sure that you understand -the features. When you have made up your mind about the cache provider to use, please -make sure to read its documentation to figure out how to configure the caches that your -application uses. Nearly all providers require you to explicitly configure every cache -that you use in the application. Some offer a way to customize the default caches defined -by the `spring.cache.cache-names` property. - -TIP: It is also possible to transparently -{spring-reference}integration.html#cache-annotations-put[update] or -{spring-reference}integration.html#cache-annotations-evict[evict] data from the cache. - - - -[[boot-features-caching-provider]] -=== Supported Cache Providers -The cache abstraction does not provide an actual store and relies on abstraction -materialized by the `org.springframework.cache.Cache` and -`org.springframework.cache.CacheManager` interfaces. - -If you have not defined a bean of type `CacheManager` or a `CacheResolver` named -`cacheResolver` (see -{spring-javadoc}/cache/annotation/CachingConfigurer.html[`CachingConfigurer`]), -Spring Boot tries to detect the following providers (in the indicated order): - -. <> -. <> (EhCache 3, Hazelcast, - Infinispan, and others) -. <> -. <> -. <> -. <> -. <> -. <> -. <> - -TIP: It is also possible to _force_ a particular cache provider by setting the -`spring.cache.type` property. Use this property if you need to -<> in certain environment -(such as tests). - -TIP: Use the `spring-boot-starter-cache` "`Starter`" to quickly add basic caching -dependencies. The starter brings in `spring-context-support`. If you add dependencies -manually, you must include `spring-context-support` in order to use the JCache, -EhCache 2.x, or Caffeine support. - -If the `CacheManager` is auto-configured by Spring Boot, you can further tune its -configuration before it is fully initialized by exposing a bean that implements the -`CacheManagerCustomizer` interface. The following example sets a flag to say that null -values should be passed down to the underlying map: - -[source,java,indent=0] ----- - @Bean - public CacheManagerCustomizer cacheManagerCustomizer() { - return new CacheManagerCustomizer() { - @Override - public void customize(ConcurrentMapCacheManager cacheManager) { - cacheManager.setAllowNullValues(false); - } - }; - } ----- - -[NOTE] -==== -In the preceding example, an auto-configured `ConcurrentMapCacheManager` is expected. If -that is not the case (either you provided your own config or a different cache provider -was auto-configured), the customizer is not invoked at all. You can have as many -customizers as you want, and you can also order them by using `@Order` or `Ordered`. -==== - - - -[[boot-features-caching-provider-generic]] -==== Generic -Generic caching is used if the context defines _at least_ one -`org.springframework.cache.Cache` bean. A `CacheManager` wrapping all beans of that type -is created. - - - -[[boot-features-caching-provider-jcache]] -==== JCache (JSR-107) -https://jcp.org/en/jsr/detail?id=107[JCache] is bootstrapped through the presence of a -`javax.cache.spi.CachingProvider` on the classpath (that is, a JSR-107 compliant caching -library exists on the classpath), and the `JCacheCacheManager` is provided by the -`spring-boot-starter-cache` "`Starter`". Various compliant libraries are available, and -Spring Boot provides dependency management for Ehcache 3, Hazelcast, and Infinispan. Any -other compliant library can be added as well. - -It might happen that more than one provider is present, in which case the provider must -be explicitly specified. Even if the JSR-107 standard does not enforce a standardized way -to define the location of the configuration file, Spring Boot does its best to -accommodate setting a cache with implementation details, as shown in the following -example: - -[source,properties,indent=0] ----- - # Only necessary if more than one provider is present - spring.cache.jcache.provider=com.acme.MyCachingProvider - spring.cache.jcache.config=classpath:acme.xml ----- - -NOTE: When a cache library offers both a native implementation and JSR-107 support, -Spring Boot prefers the JSR-107 support, so that the same features are available if you -switch to a different JSR-107 implementation. - -TIP: Spring Boot has <>. If a -single `HazelcastInstance` is available, it is automatically reused for the -`CacheManager` as well, unless the `spring.cache.jcache.config` property is specified. - -There are two ways to customize the underlying `javax.cache.cacheManager`: - -* Caches can be created on startup by setting the `spring.cache.cache-names` property. If -a custom `javax.cache.configuration.Configuration` bean is defined, it is used to -customize them. -* `org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer` beans are -invoked with the reference of the `CacheManager` for full customization. - -TIP: If a standard `javax.cache.CacheManager` bean is defined, it is wrapped -automatically in an `org.springframework.cache.CacheManager` implementation that the -abstraction expects. No further customization is applied to it. - - - -[[boot-features-caching-provider-ehcache2]] -==== EhCache 2.x -https://www.ehcache.org/[EhCache] 2.x is used if a file named `ehcache.xml` can be found at -the root of the classpath. If EhCache 2.x is found, the `EhCacheCacheManager` provided by -the `spring-boot-starter-cache` "`Starter`" is used to bootstrap the cache manager. An -alternate configuration file can be provided as well, as shown in the following example: - -[source,properties,indent=0] ----- - spring.cache.ehcache.config=classpath:config/another-config.xml ----- - - - -[[boot-features-caching-provider-hazelcast]] -==== Hazelcast - -Spring Boot has <>. If a -`HazelcastInstance` has been auto-configured, it is automatically wrapped in a -`CacheManager`. - - - -[[boot-features-caching-provider-infinispan]] -==== Infinispan -https://infinispan.org/[Infinispan] has no default configuration file location, so it must -be specified explicitly. Otherwise, the default bootstrap is used. - -[source,properties,indent=0] ----- - spring.cache.infinispan.config=infinispan.xml ----- - -Caches can be created on startup by setting the `spring.cache.cache-names` property. If a -custom `ConfigurationBuilder` bean is defined, it is used to customize the caches. - -[NOTE] -==== -The support of Infinispan in Spring Boot is restricted to the embedded mode and is quite -basic. If you want more options, you should use the official Infinispan Spring Boot -starter instead. See -https://github.com/infinispan/infinispan-spring-boot[Infinispan's documentation] for more -details. -==== - - -[[boot-features-caching-provider-couchbase]] -==== Couchbase -If the https://www.couchbase.com/[Couchbase] Java client and the `couchbase-spring-cache` -implementation are available and Couchbase is <>, a -`CouchbaseCacheManager` is auto-configured. It is also possible to create additional -caches on startup by setting the `spring.cache.cache-names` property. These caches -operate on the `Bucket` that was auto-configured. You can _also_ create additional caches -on another `Bucket` by using the customizer. Assume you need two caches (`cache1` and -`cache2`) on the "main" `Bucket` and one (`cache3`) cache with a custom time to live of 2 -seconds on the "`another`" `Bucket`. You can create the first two caches through -configuration, as follows: - -[source,properties,indent=0] ----- - spring.cache.cache-names=cache1,cache2 ----- - -Then you can define a `@Configuration` class to configure the extra `Bucket` and the -`cache3` cache, as follows: - - -[source,java,indent=0] ----- - @Configuration(proxyBeanMethods = false) - public class CouchbaseCacheConfiguration { - - private final Cluster cluster; - - public CouchbaseCacheConfiguration(Cluster cluster) { - this.cluster = cluster; - } - - @Bean - public Bucket anotherBucket() { - return this.cluster.openBucket("another", "secret"); - } - - @Bean - public CacheManagerCustomizer cacheManagerCustomizer() { - return c -> { - c.prepareCache("cache3", CacheBuilder.newInstance(anotherBucket()) - .withExpiration(2)); - }; - } - - } ----- - -This sample configuration reuses the `Cluster` that was created through -auto-configuration. - - - -[[boot-features-caching-provider-redis]] -==== Redis -If https://redis.io/[Redis] is available and configured, a `RedisCacheManager` is -auto-configured. It is possible to create additional caches on startup by setting the -`spring.cache.cache-names` property and cache defaults can be configured by using -`spring.cache.redis.*` properties. For instance, the following configuration creates -`cache1` and `cache2` caches with a _time to live_ of 10 minutes: - -[source,properties,indent=0] ----- - spring.cache.cache-names=cache1,cache2 - spring.cache.redis.time-to-live=600000 ----- - -[NOTE] -==== -By default, a key prefix is added so that, if two separate caches use the same -key, Redis does not have overlapping keys and cannot return invalid values. We strongly -recommend keeping this setting enabled if you create your own `RedisCacheManager`. -==== - -TIP: You can take full control of the configuration by adding a `RedisCacheConfiguration` -`@Bean` of your own. This can be useful if you're looking for customizing the -serialization strategy. - - - -[[boot-features-caching-provider-caffeine]] -==== Caffeine -https://github.com/ben-manes/caffeine[Caffeine] is a Java 8 rewrite of Guava's cache that -supersedes support for Guava. If Caffeine is present, a `CaffeineCacheManager` (provided -by the `spring-boot-starter-cache` "`Starter`") is auto-configured. Caches can be created -on startup by setting the `spring.cache.cache-names` property and can be customized by one -of the following (in the indicated order): - -. A cache spec defined by `spring.cache.caffeine.spec` -. A `com.github.benmanes.caffeine.cache.CaffeineSpec` bean is defined -. A `com.github.benmanes.caffeine.cache.Caffeine` bean is defined - -For instance, the following configuration creates `cache1` and `cache2` caches with a -maximum size of 500 and a _time to live_ of 10 minutes - -[source,properties,indent=0] ----- - spring.cache.cache-names=cache1,cache2 - spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s ----- - -If a `com.github.benmanes.caffeine.cache.CacheLoader` bean is defined, it is -automatically associated to the `CaffeineCacheManager`. Since the `CacheLoader` is going -to be associated with _all_ caches managed by the cache manager, it must be defined as -`CacheLoader`. The auto-configuration ignores any other generic type. - - - -[[boot-features-caching-provider-simple]] -==== Simple -If none of the other providers can be found, a simple implementation using a -`ConcurrentHashMap` as the cache store is configured. This is the default if no caching -library is present in your application. By default, caches are created as needed, but you -can restrict the list of available caches by setting the `cache-names` property. For -instance, if you want only `cache1` and `cache2` caches, set the `cache-names` property -as follows: - -[source,properties,indent=0] ----- - spring.cache.cache-names=cache1,cache2 ----- - -If you do so and your application uses a cache not listed, then it fails at runtime when -the cache is needed, but not on startup. This is similar to the way the "real" cache -providers behave if you use an undeclared cache. - - -[[boot-features-caching-provider-none]] -==== None -When `@EnableCaching` is present in your configuration, a suitable cache configuration is -expected as well. If you need to disable caching altogether in certain environments, -force the cache type to `none` to use a no-op implementation, as shown in the following -example: - -[source,properties,indent=0] ----- - spring.cache.type=none ----- - - - -[[boot-features-messaging]] -== Messaging -The Spring Framework provides extensive support for integrating with messaging systems, -from simplified use of the JMS API using `JmsTemplate` to a complete infrastructure to -receive messages asynchronously. Spring AMQP provides a similar feature set for the -Advanced Message Queuing Protocol. Spring Boot also provides auto-configuration -options for `RabbitTemplate` and RabbitMQ. Spring WebSocket natively includes support for -STOMP messaging, and Spring Boot has support for that through starters and a small amount -of auto-configuration. Spring Boot also has support for Apache Kafka. - - - -[[boot-features-jms]] -=== JMS -The `javax.jms.ConnectionFactory` interface provides a standard method of creating a -`javax.jms.Connection` for interacting with a JMS broker. Although Spring needs a -`ConnectionFactory` to work with JMS, you generally need not use it directly yourself and -can instead rely on higher level messaging abstractions. (See the -{spring-reference}integration.html#jms[relevant section] of the Spring Framework -reference documentation for details.) Spring Boot also auto-configures the necessary -infrastructure to send and receive messages. - - - -[[boot-features-activemq]] -==== ActiveMQ Support -When https://activemq.apache.org/[ActiveMQ] is available on the classpath, Spring Boot can -also configure a `ConnectionFactory`. If the broker is present, an embedded broker is -automatically started and configured (provided no broker URL is specified through -configuration). - -NOTE: If you use `spring-boot-starter-activemq`, the necessary dependencies to connect or -embed an ActiveMQ instance are provided, as is the Spring infrastructure to integrate with -JMS. - -ActiveMQ configuration is controlled by external configuration properties in -`+spring.activemq.*+`. For example, you might declare the following section in -`application.properties`: - -[source,properties,indent=0] ----- - spring.activemq.broker-url=tcp://192.168.1.210:9876 - spring.activemq.user=admin - spring.activemq.password=secret ----- - -By default, a `CachingConnectionFactory` wraps the native `ConnectionFactory` with -sensible settings that you can control by external configuration properties in -`+spring.jms.*+`: - -[source,properties,indent=0] ----- - spring.jms.cache.session-cache-size=5 ----- - -If you'd rather use native pooling, you can do so by adding a dependency to -`org.messaginghub:pooled-jms` and configuring the `JmsPoolConnectionFactory` accordingly, -as shown in the following example: - -[source,properties,indent=0] ----- - spring.activemq.pool.enabled=true - spring.activemq.pool.max-connections=50 ----- - -TIP: See -{sc-spring-boot-autoconfigure}/jms/activemq/ActiveMQProperties.{sc-ext}[`ActiveMQProperties`] -for more of the supported options. You can also register an arbitrary number of beans -that implement `ActiveMQConnectionFactoryCustomizer` for more advanced customizations. - -By default, ActiveMQ creates a destination if it does not yet exist so that destinations -are resolved against their provided names. - - - -[[boot-features-artemis]] -==== Artemis Support -Spring Boot can auto-configure a `ConnectionFactory` when it detects that -https://activemq.apache.org/artemis/[Artemis] is available on the classpath. If the broker -is present, an embedded broker is automatically started and configured (unless the mode -property has been explicitly set). The supported modes are `embedded` (to make explicit -that an embedded broker is required and that an error should occur if the broker is not -available on the classpath) and `native` (to connect to a broker using the `netty` -transport protocol). When the latter is configured, Spring Boot configures a -`ConnectionFactory` that connects to a broker running on the local machine with the -default settings. - -NOTE: If you use `spring-boot-starter-artemis`, the necessary dependencies to -connect to an existing Artemis instance are provided, as well as the Spring -infrastructure to integrate with JMS. Adding `org.apache.activemq:artemis-jms-server` to -your application lets you use embedded mode. - -Artemis configuration is controlled by external configuration properties in -`+spring.artemis.*+`. For example, you might declare the following section in -`application.properties`: - -[source,properties,indent=0] ----- - spring.artemis.mode=native - spring.artemis.host=192.168.1.210 - spring.artemis.port=9876 - spring.artemis.user=admin - spring.artemis.password=secret ----- - -When embedding the broker, you can choose if you want to enable persistence and list the -destinations that should be made available. These can be specified as a comma-separated -list to create them with the default options, or you can define bean(s) of type -`org.apache.activemq.artemis.jms.server.config.JMSQueueConfiguration` or -`org.apache.activemq.artemis.jms.server.config.TopicConfiguration`, for advanced queue -and topic configurations, respectively. - -By default, a `CachingConnectionFactory` wraps the native `ConnectionFactory` with -sensible settings that you can control by external configuration properties in -`+spring.jms.*+`: - -[source,properties,indent=0] ----- - spring.jms.cache.session-cache-size=5 ----- - -If you'd rather use native pooling, you can do so by adding a dependency to -`org.messaginghub:pooled-jms` and configuring the `JmsPoolConnectionFactory` accordingly, -as shown in the following example: - -[source,properties,indent=0] ----- - spring.artemis.pool.enabled=true - spring.artemis.pool.max-connections=50 ----- - -See -{sc-spring-boot-autoconfigure}/jms/artemis/ArtemisProperties.{sc-ext}[`ArtemisProperties`] -for more supported options. - -No JNDI lookup is involved, and destinations are resolved against their names, using -either the `name` attribute in the Artemis configuration or the names provided through -configuration. - - - -[[boot-features-jms-jndi]] -==== Using a JNDI ConnectionFactory -If you are running your application in an application server, Spring Boot tries to -locate a JMS `ConnectionFactory` by using JNDI. By default, the `java:/JmsXA` and -`java:/XAConnectionFactory` location are checked. You can use the `spring.jms.jndi-name` -property if you need to specify an alternative location, as shown in the following -example: - -[source,properties,indent=0] ----- - spring.jms.jndi-name=java:/MyConnectionFactory ----- - - - -[[boot-features-using-jms-sending]] -==== Sending a Message -Spring's `JmsTemplate` is auto-configured, and you can autowire it directly into your own -beans, as shown in the following example: - -[source,java,indent=0] ----- - import org.springframework.beans.factory.annotation.Autowired; - import org.springframework.jms.core.JmsTemplate; - import org.springframework.stereotype.Component; - - @Component - public class MyBean { - - private final JmsTemplate jmsTemplate; - - @Autowired - public MyBean(JmsTemplate jmsTemplate) { - this.jmsTemplate = jmsTemplate; - } - - // ... - - } ----- - -NOTE: {spring-javadoc}/jms/core/JmsMessagingTemplate.{dc-ext}[`JmsMessagingTemplate`] can -be injected in a similar manner. If a `DestinationResolver` or a `MessageConverter` bean -is defined, it is associated automatically to the auto-configured `JmsTemplate`. - - -[[boot-features-using-jms-receiving]] -==== Receiving a Message -When the JMS infrastructure is present, any bean can be annotated with `@JmsListener` to -create a listener endpoint. If no `JmsListenerContainerFactory` has been defined, a -default one is configured automatically. If a `DestinationResolver` or a -`MessageConverter` beans is defined, it is associated automatically to the default -factory. - -By default, the default factory is transactional. If you run in an infrastructure where a -`JtaTransactionManager` is present, it is associated to the listener container by default. -If not, the `sessionTransacted` flag is enabled. In that latter scenario, you can -associate your local data store transaction to the processing of an incoming message by -adding `@Transactional` on your listener method (or a delegate thereof). This ensures that -the incoming message is acknowledged, once the local transaction has completed. This also -includes sending response messages that have been performed on the same JMS session. - -The following component creates a listener endpoint on the `someQueue` destination: - -[source,java,indent=0] ----- - @Component - public class MyBean { - - @JmsListener(destination = "someQueue") - public void processMessage(String content) { - // ... - } - - } ----- - -TIP: See {spring-javadoc}/jms/annotation/EnableJms.{dc-ext}[the Javadoc of `@EnableJms`] -for more details. - -If you need to create more `JmsListenerContainerFactory` instances or if you want to -override the default, Spring Boot provides a -`DefaultJmsListenerContainerFactoryConfigurer` that you can use to initialize a -`DefaultJmsListenerContainerFactory` with the same settings as the one that is -auto-configured. - -For instance, the following example exposes another factory that uses a specific -`MessageConverter`: - -[source,java,indent=0] ----- - @Configuration(proxyBeanMethods = false) - static class JmsConfiguration { - - @Bean - public DefaultJmsListenerContainerFactory myFactory( - DefaultJmsListenerContainerFactoryConfigurer configurer) { - DefaultJmsListenerContainerFactory factory = - new DefaultJmsListenerContainerFactory(); - configurer.configure(factory, connectionFactory()); - factory.setMessageConverter(myMessageConverter()); - return factory; - } - - } ----- - -Then you can use the factory in any `@JmsListener`-annotated method as follows: - -[source,java,indent=0] -[subs="verbatim,quotes"] ----- - @Component - public class MyBean { - - @JmsListener(destination = "someQueue", **containerFactory="myFactory"**) - public void processMessage(String content) { - // ... - } - - } ----- - - -[[boot-features-amqp]] -=== AMQP -The Advanced Message Queuing Protocol (AMQP) is a platform-neutral, wire-level protocol -for message-oriented middleware. The Spring AMQP project applies core Spring concepts to -the development of AMQP-based messaging solutions. Spring Boot offers several conveniences -for working with AMQP through RabbitMQ, including the `spring-boot-starter-amqp` -"`Starter`". - - - -[[boot-features-rabbitmq]] -==== RabbitMQ support -https://www.rabbitmq.com/[RabbitMQ] is a lightweight, reliable, scalable, and portable -message broker based on the AMQP protocol. Spring uses `RabbitMQ` to communicate through -the AMQP protocol. - -RabbitMQ configuration is controlled by external configuration properties in -`+spring.rabbitmq.*+`. For example, you might declare the following section in -`application.properties`: - -[source,properties,indent=0] ----- - spring.rabbitmq.host=localhost - spring.rabbitmq.port=5672 - spring.rabbitmq.username=admin - spring.rabbitmq.password=secret ----- - -If a `ConnectionNameStrategy` bean exists in the context, it will be automatically used to -name connections created by the auto-configured `ConnectionFactory`. See -{sc-spring-boot-autoconfigure}/amqp/RabbitProperties.{sc-ext}[`RabbitProperties`] for more -of the supported options. - -TIP: See -https://spring.io/blog/2010/06/14/understanding-amqp-the-protocol-used-by-rabbitmq/[Understanding -AMQP, the protocol used by RabbitMQ] for more details. - - - -[[boot-features-using-amqp-sending]] -==== Sending a Message -Spring's `AmqpTemplate` and `AmqpAdmin` are auto-configured, and you can autowire them -directly into your own beans, as shown in the following example: - -[source,java,indent=0] ----- - import org.springframework.amqp.core.AmqpAdmin; - import org.springframework.amqp.core.AmqpTemplate; - import org.springframework.beans.factory.annotation.Autowired; - import org.springframework.stereotype.Component; - - @Component - public class MyBean { - - private final AmqpAdmin amqpAdmin; - private final AmqpTemplate amqpTemplate; - - @Autowired - public MyBean(AmqpAdmin amqpAdmin, AmqpTemplate amqpTemplate) { - this.amqpAdmin = amqpAdmin; - this.amqpTemplate = amqpTemplate; - } - - // ... - - } ----- - -NOTE: {spring-amqp-javadoc}/rabbit/core/RabbitMessagingTemplate.{dc-ext}[`RabbitMessagingTemplate`] -can be injected in a similar manner. If a `MessageConverter` bean is defined, it is -associated automatically to the auto-configured `AmqpTemplate`. - -If necessary, any `org.springframework.amqp.core.Queue` that is defined as a bean is -automatically used to declare a corresponding queue on the RabbitMQ instance. - -To retry operations, you can enable retries on the `AmqpTemplate` (for example, in the -event that the broker connection is lost): - -[source,properties,indent=0] ----- - spring.rabbitmq.template.retry.enabled=true - spring.rabbitmq.template.retry.initial-interval=2s ----- - -Retries are disabled by default. You can also customize the `RetryTemplate` -programmatically by declaring a `RabbitRetryTemplateCustomizer` bean. - - - -[[boot-features-using-amqp-receiving]] -==== Receiving a Message -When the Rabbit infrastructure is present, any bean can be annotated with -`@RabbitListener` to create a listener endpoint. If no `RabbitListenerContainerFactory` -has been defined, a default `SimpleRabbitListenerContainerFactory` is automatically -configured and you can switch to a direct container using the -`spring.rabbitmq.listener.type` property. If a `MessageConverter` or a `MessageRecoverer` -bean is defined, it is automatically associated with the default factory. - -The following sample component creates a listener endpoint on the `someQueue` queue: - -[source,java,indent=0] ----- - @Component - public class MyBean { - - @RabbitListener(queues = "someQueue") - public void processMessage(String content) { - // ... - } - - } ----- - -TIP: See {spring-amqp-javadoc}/rabbit/annotation/EnableRabbit.{dc-ext}[the Javadoc of -`@EnableRabbit`] for more details. - -If you need to create more `RabbitListenerContainerFactory` instances or if you want to -override the default, Spring Boot provides a -`SimpleRabbitListenerContainerFactoryConfigurer` and a -`DirectRabbitListenerContainerFactoryConfigurer` that you can use to initialize a -`SimpleRabbitListenerContainerFactory` and a `DirectRabbitListenerContainerFactory` with -the same settings as the factories used by the auto-configuration. - -TIP: It does not matter which container type you chose. Those two beans are exposed by -the auto-configuration. - -For instance, the following configuration class exposes another factory that uses a -specific `MessageConverter`: - -[source,java,indent=0] ----- - @Configuration(proxyBeanMethods = false) - static class RabbitConfiguration { - - @Bean - public SimpleRabbitListenerContainerFactory myFactory( - SimpleRabbitListenerContainerFactoryConfigurer configurer) { - SimpleRabbitListenerContainerFactory factory = - new SimpleRabbitListenerContainerFactory(); - configurer.configure(factory, connectionFactory); - factory.setMessageConverter(myMessageConverter()); - return factory; - } - - } ----- - -Then you can use the factory in any `@RabbitListener`-annotated method, as follows: - -[source,java,indent=0] -[subs="verbatim,quotes"] ----- - @Component - public class MyBean { - - @RabbitListener(queues = "someQueue", **containerFactory="myFactory"**) - public void processMessage(String content) { - // ... - } - - } ----- - -You can enable retries to handle situations where your listener throws an exception. By -default, `RejectAndDontRequeueRecoverer` is used, but you can define a `MessageRecoverer` -of your own. When retries are exhausted, the message is rejected and either dropped or -routed to a dead-letter exchange if the broker is configured to do so. By default, -retries are disabled. You can also customize the `RetryTemplate` programmatically by -declaring a `RabbitRetryTemplateCustomizer` bean. - -IMPORTANT: By default, if retries are disabled and the listener throws an exception, the -delivery is retried indefinitely. You can modify this behavior in two ways: Set the -`defaultRequeueRejected` property to `false` so that zero re-deliveries are attempted or -throw an `AmqpRejectAndDontRequeueException` to signal the message should be rejected. -The latter is the mechanism used when retries are enabled and the maximum number of -delivery attempts is reached. - - - -[[boot-features-kafka]] -=== Apache Kafka Support -https://kafka.apache.org/[Apache Kafka] is supported by providing auto-configuration of -the `spring-kafka` project. - -Kafka configuration is controlled by external configuration properties in -`spring.kafka.*`. For example, you might declare the following section in -`application.properties`: - -[source,properties,indent=0] ----- - spring.kafka.bootstrap-servers=localhost:9092 - spring.kafka.consumer.group-id=myGroup ----- - -TIP: To create a topic on startup, add a bean of type `NewTopic`. If the topic already -exists, the bean is ignored. - -See {sc-spring-boot-autoconfigure}/kafka/KafkaProperties.{sc-ext}[`KafkaProperties`] -for more supported options. - - - -[[boot-features-kafka-sending-a-message]] -==== Sending a Message -Spring's `KafkaTemplate` is auto-configured, and you can autowire it directly in your own -beans, as shown in the following example: - -[source,java,indent=0] ----- -@Component -public class MyBean { - - private final KafkaTemplate kafkaTemplate; - - @Autowired - public MyBean(KafkaTemplate kafkaTemplate) { - this.kafkaTemplate = kafkaTemplate; - } - - // ... - -} ----- - -NOTE: If the property `spring.kafka.producer.transaction-id-prefix` is defined, a -`KafkaTransactionManager` is automatically configured. Also, if a `RecordMessageConverter` -bean is defined, it is automatically associated to the auto-configured `KafkaTemplate`. - - -[[boot-features-kafka-receiving-a-message]] -==== Receiving a Message -When the Apache Kafka infrastructure is present, any bean can be annotated with -`@KafkaListener` to create a listener endpoint. If no `KafkaListenerContainerFactory` has -been defined, a default one is automatically configured with keys defined in -`spring.kafka.listener.*`. - -The following component creates a listener endpoint on the `someTopic` topic: - -[source,java,indent=0] ----- - @Component - public class MyBean { - - @KafkaListener(topics = "someTopic") - public void processMessage(String content) { - // ... - } - - } ----- - -If a `KafkaTransactionManager` bean is defined, it is automatically associated to the -container factory. Similarly, if a `ErrorHandler`, `AfterRollbackProcessor` or -`ConsumerAwareRebalanceListener` bean is defined, it is automatically associated to the -default factory. - -Depending on the listener type, a `RecordMessageConverter` or `BatchMessageConverter` bean -is associated to the default factory. If only a `RecordMessageConverter` bean is present -for a batch listener, it is wrapped in a `BatchMessageConverter`. - -TIP: A custom `ChainedKafkaTransactionManager` must be marked `@Primary` as it usually -references the auto-configured `KafkaTransactionManager` bean. - - - -[[boot-features-kafka-streams]] -==== Kafka Streams -Spring for Apache Kafka provides a factory bean to create a `StreamsBuilder` object and -manage the lifecycle of its streams. Spring Boot auto-configures the required -`KafkaStreamsConfiguration` bean as long as `kafka-streams` is on the classpath and Kafka -Streams is enabled via the `@EnableKafkaStreams` annotation. - -Enabling Kafka Streams means that the application id and bootstrap servers must be set. -The former can be configured using `spring.kafka.streams.application-id`, defaulting to -`spring.application.name` if not set. The latter can be set globally or -specifically overridden just for streams. - -Several additional properties are available using dedicated properties; other arbitrary -Kafka properties can be set using the `spring.kafka.streams.properties` namespace. See -also <> for more information. - -To use the factory bean, simply wire `StreamsBuilder` into your `@Bean` as shown in the -following example: - -[source,java,indent=0] ----- -include::{code-examples}/kafka/KafkaStreamsBeanExample.java[tag=configuration] ----- - -By default, the streams managed by the `StreamBuilder` object it creates are started -automatically. You can customize this behaviour using the -`spring.kafka.streams.auto-startup` property. - - - -[[boot-features-kafka-extra-props]] -==== Additional Kafka Properties -The properties supported by auto configuration are shown in -<>. Note that, for the most part, these properties -(hyphenated or camelCase) map directly to the Apache Kafka dotted properties. Refer to the -Apache Kafka documentation for details. - -The first few of these properties apply to all components (producers, consumers, admins, -and streams) but can be -specified at the component level if you wish to use different values. -Apache Kafka designates properties with an importance of HIGH, MEDIUM, or LOW. Spring Boot -auto-configuration supports all HIGH importance properties, some selected MEDIUM and LOW -properties, and any properties that do not have a default value. - -Only a subset of the properties supported by Kafka are available directly through the -`KafkaProperties` class. If you wish to configure the producer or consumer with additional -properties that are not directly supported, use the following properties: - -[source,properties,indent=0] ----- - spring.kafka.properties.prop.one=first - spring.kafka.admin.properties.prop.two=second - spring.kafka.consumer.properties.prop.three=third - spring.kafka.producer.properties.prop.four=fourth - spring.kafka.streams.properties.prop.five=fifth ----- - -This sets the common `prop.one` Kafka property to `first` (applies to producers, -consumers and admins), the `prop.two` admin property to `second`, the `prop.three` -consumer property to `third`, the `prop.four` producer property to `fourth` and the -`prop.five` streams property to `fifth`. - -You can also configure the Spring Kafka `JsonDeserializer` as follows: - -[source,properties,indent=0] ----- -spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.JsonDeserializer -spring.kafka.consumer.properties.spring.json.value.default.type=com.example.Invoice -spring.kafka.consumer.properties.spring.json.trusted.packages=com.example,org.acme ----- - -Similarly, you can disable the `JsonSerializer` default behavior of sending type -information in headers: - -[source,properties,indent=0] ----- -spring.kafka.producer.value-serializer=org.springframework.kafka.support.serializer.JsonSerializer -spring.kafka.producer.properties.spring.json.add.type.headers=false ----- - -IMPORTANT: Properties set in this way override any configuration item that Spring Boot -explicitly supports. - -[[boot-features-resttemplate]] -== Calling REST Services with `RestTemplate` -If you need to call remote REST services from your application, you can use the Spring -Framework's {spring-javadoc}/web/client/RestTemplate.html[`RestTemplate`] class. Since -`RestTemplate` instances often need to be customized before being used, Spring Boot does -not provide any single auto-configured `RestTemplate` bean. It does, however, -auto-configure a `RestTemplateBuilder`, which can be used to create `RestTemplate` -instances when needed. The auto-configured `RestTemplateBuilder` ensures that sensible -`HttpMessageConverters` are applied to `RestTemplate` instances. - -The following code shows a typical example: - -[source,java,indent=0] ----- - @Service - public class MyService { - - private final RestTemplate restTemplate; - - public MyService(RestTemplateBuilder restTemplateBuilder) { - this.restTemplate = restTemplateBuilder.build(); - } - - public Details someRestCall(String name) { - return this.restTemplate.getForObject("/{name}/details", Details.class, name); - } - - } ----- - -TIP: `RestTemplateBuilder` includes a number of useful methods that can be used to -quickly configure a `RestTemplate`. For example, to add BASIC auth support, you can use -`builder.basicAuthentication("user", "password").build()`. - - - -[[boot-features-resttemplate-customization]] -=== RestTemplate Customization -There are three main approaches to `RestTemplate` customization, depending on how broadly -you want the customizations to apply. - -To make the scope of any customizations as narrow as possible, inject the auto-configured -`RestTemplateBuilder` and then call its methods as required. Each method call returns a -new `RestTemplateBuilder` instance, so the customizations only affect this use of the -builder. - -To make an application-wide, additive customization, use a `RestTemplateCustomizer` bean. -All such beans are automatically registered with the auto-configured `RestTemplateBuilder` -and are applied to any templates that are built with it. - -The following example shows a customizer that configures the use of a proxy for all hosts -except `192.168.0.5`: - -[source,java,indent=0] ----- -include::{code-examples}/web/client/RestTemplateProxyCustomizationExample.java[tag=customizer] ----- - -Finally, the most extreme (and rarely used) option is to create your own -`RestTemplateBuilder` bean. Doing so switches off the auto-configuration of a -`RestTemplateBuilder` and prevents any `RestTemplateCustomizer` beans from being used. - - - -[[boot-features-webclient]] -== Calling REST Services with `WebClient` -If you have Spring WebFlux on your classpath, you can also choose to use `WebClient` to -call remote REST services. Compared to `RestTemplate`, this client has a more functional -feel and is fully reactive. You can learn more about the `WebClient` in the dedicated -{spring-reference}web-reactive.html#webflux-client[section in the Spring Framework docs]. - -Spring Boot creates and pre-configures a `WebClient.Builder` for you; it is strongly -advised to inject it in your components and use it to create `WebClient` instances. -Spring Boot is configuring that builder to share HTTP resources, reflect codecs -setup in the same fashion as the server ones (see -<>), and more. - -The following code shows a typical example: - -[source,java,indent=0] ----- - @Service - public class MyService { - - private final WebClient webClient; - - public MyService(WebClient.Builder webClientBuilder) { - this.webClient = webClientBuilder.baseUrl("https://example.org").build(); - } - - public Mono
someRestCall(String name) { - return this.webClient.get().uri("/{name}/details", name) - .retrieve().bodyToMono(Details.class); - } - - } ----- - - - -[[boot-features-webclient-runtime]] -=== WebClient Runtime -Spring Boot will auto-detect which `ClientHttpConnector` to use to drive `WebClient`, -depending on the libraries available on the application classpath. For now, Reactor -Netty and Jetty RS client are supported. - -The `spring-boot-starter-webflux` starter depends on `io.projectreactor.netty:reactor-netty` -by default, which brings both server and client implementations. If you choose to use Jetty -as a reactive server instead, you should add a dependency on the Jetty Reactive HTTP -client library, `org.eclipse.jetty:jetty-reactive-httpclient`. Using the same technology -for server and client has it advantages, as it will automatically share HTTP resources -between client and server. - -Developers can override the resource configuration for Jetty and Reactor Netty by providing -a custom `ReactorResourceFactory` or `JettyResourceFactory` bean - this will be applied to -both clients and servers. - -If you wish to override that choice for the client, you can define your own -`ClientHttpConnector` bean and have full control over the client configuration. - -You can learn more about the -{spring-reference}web-reactive.html#webflux-client-builder[`WebClient` configuration -options in the Spring Framework reference documentation]. - - - -[[boot-features-webclient-customization]] -=== WebClient Customization -There are three main approaches to `WebClient` customization, depending on how broadly you -want the customizations to apply. - -To make the scope of any customizations as narrow as possible, inject the auto-configured -`WebClient.Builder` and then call its methods as required. `WebClient.Builder` instances -are stateful: Any change on the builder is reflected in all clients subsequently created -with it. If you want to create several clients with the same builder, you can also -consider cloning the builder with `WebClient.Builder other = builder.clone();`. - -To make an application-wide, additive customization to all `WebClient.Builder` instances, -you can declare `WebClientCustomizer` beans and change the `WebClient.Builder` locally at -the point of injection. - -Finally, you can fall back to the original API and use `WebClient.create()`. In that case, -no auto-configuration or `WebClientCustomizer` is applied. - - - -[[boot-features-validation]] -== Validation -The method validation feature supported by Bean Validation 1.1 is automatically enabled -as long as a JSR-303 implementation (such as Hibernate validator) is on the classpath. -This lets bean methods be annotated with `javax.validation` constraints on their -parameters and/or on their return value. Target classes with such annotated methods need -to be annotated with the `@Validated` annotation at the type level for their methods to -be searched for inline constraint annotations. - -For instance, the following service triggers the validation of the first argument, making -sure its size is between 8 and 10: - -[source,java,indent=0] ----- - @Service - @Validated - public class MyBean { - - public Archive findByCodeAndAuthor(@Size(min = 8, max = 10) String code, - Author author) { - ... - } - - } ----- - - - -[[boot-features-email]] -== Sending Email -The Spring Framework provides an easy abstraction for sending email by using the -`JavaMailSender` interface, and Spring Boot provides auto-configuration for it as well as -a starter module. - -TIP: See the {spring-reference}integration.html#mail[reference documentation] for a -detailed explanation of how you can use `JavaMailSender`. - -If `spring.mail.host` and the relevant libraries (as defined by -`spring-boot-starter-mail`) are available, a default `JavaMailSender` is created if none -exists. The sender can be further customized by configuration items from the -`spring.mail` namespace. See -{sc-spring-boot-autoconfigure}/mail/MailProperties.{sc-ext}[`MailProperties`] for more -details. - -In particular, certain default timeout values are infinite, and you may want to change -that to avoid having a thread blocked by an unresponsive mail server, as shown in the -following example: - -[source,properties,indent=0] ----- - spring.mail.properties.mail.smtp.connectiontimeout=5000 - spring.mail.properties.mail.smtp.timeout=3000 - spring.mail.properties.mail.smtp.writetimeout=5000 ----- - -It is also possible to configure a `JavaMailSender` with an existing `Session` from JNDI: - -[source,properties,indent=0] ----- - spring.mail.jndi-name=mail/Session ----- - -When a `jndi-name` is set, it takes precedence over all other Session-related settings. - - - -[[boot-features-jta]] -== Distributed Transactions with JTA -Spring Boot supports distributed JTA transactions across multiple XA resources by using -either an https://www.atomikos.com/[Atomikos] or https://github.com/bitronix/btm[Bitronix] -embedded transaction manager. JTA transactions are also supported when deploying to a -suitable Java EE Application Server. - -When a JTA environment is detected, Spring's `JtaTransactionManager` is used to manage -transactions. Auto-configured JMS, DataSource, and JPA beans are upgraded to support XA -transactions. You can use standard Spring idioms, such as `@Transactional`, to participate -in a distributed transaction. If you are within a JTA environment and still want to use -local transactions, you can set the `spring.jta.enabled` property to `false` to disable -the JTA auto-configuration. - - - -[[boot-features-jta-atomikos]] -=== Using an Atomikos Transaction Manager -https://www.atomikos.com/[Atomikos] is a popular open source transaction manager which can -be embedded into your Spring Boot application. You can use the -`spring-boot-starter-jta-atomikos` Starter to pull in the appropriate Atomikos libraries. -Spring Boot auto-configures Atomikos and ensures that appropriate `depends-on` settings -are applied to your Spring beans for correct startup and shutdown ordering. - -By default, Atomikos transaction logs are written to a `transaction-logs` directory in -your application's home directory (the directory in which your application jar file -resides). You can customize the location of this directory by setting a -`spring.jta.log-dir` property in your `application.properties` file. Properties starting -with `spring.jta.atomikos.properties` can also be used to customize the Atomikos -`UserTransactionServiceImp`. See the -{dc-spring-boot}/jta/atomikos/AtomikosProperties.{dc-ext}[`AtomikosProperties` Javadoc] -for complete details. - -NOTE: To ensure that multiple transaction managers can safely coordinate the same -resource managers, each Atomikos instance must be configured with a unique ID. By default, -this ID is the IP address of the machine on which Atomikos is running. To ensure -uniqueness in production, you should configure the `spring.jta.transaction-manager-id` -property with a different value for each instance of your application. - - - -[[boot-features-jta-bitronix]] -=== Using a Bitronix Transaction Manager -https://github.com/bitronix/btm[Bitronix] is a popular open-source JTA transaction -manager implementation. You can use the `spring-boot-starter-jta-bitronix` starter to add -the appropriate Bitronix dependencies to your project. As with Atomikos, Spring Boot -automatically configures Bitronix and post-processes your beans to ensure that startup and -shutdown ordering is correct. - -By default, Bitronix transaction log files (`part1.btm` and `part2.btm`) are written to -a `transaction-logs` directory in your application home directory. You can customize the -location of this directory by setting the `spring.jta.log-dir` property. Properties -starting with `spring.jta.bitronix.properties` are also bound to the -`bitronix.tm.Configuration` bean, allowing for complete customization. See the -https://github.com/bitronix/btm/wiki/Transaction-manager-configuration[Bitronix -documentation] for details. - -NOTE: To ensure that multiple transaction managers can safely coordinate the same -resource managers, each Bitronix instance must be configured with a unique ID. By default, -this ID is the IP address of the machine on which Bitronix is running. To ensure -uniqueness in production, you should configure the `spring.jta.transaction-manager-id` -property with a different value for each instance of your application. - - - -[[boot-features-jta-javaee]] -=== Using a Java EE Managed Transaction Manager -If you package your Spring Boot application as a `war` or `ear` file and deploy it to a -Java EE application server, you can use your application server's built-in transaction -manager. Spring Boot tries to auto-configure a transaction manager by looking at common -JNDI locations (`java:comp/UserTransaction`, `java:comp/TransactionManager`, and so on). -If you use a transaction service provided by your application server, you generally also -want to ensure that all resources are managed by the server and exposed over JNDI. Spring -Boot tries to auto-configure JMS by looking for a `ConnectionFactory` at the JNDI path -(`java:/JmsXA` or `java:/XAConnectionFactory`), and you can use the -<> -to configure your `DataSource`. - - - -[[boot-features-jta-mixed-jms]] -=== Mixing XA and Non-XA JMS Connections -When using JTA, the primary JMS `ConnectionFactory` bean is XA-aware and participates -in distributed transactions. In some situations, you might want to process certain JMS -messages by using a non-XA `ConnectionFactory`. For example, your JMS processing logic -might take longer than the XA timeout. - -If you want to use a non-XA `ConnectionFactory`, you can inject the -`nonXaJmsConnectionFactory` bean rather than the `@Primary` `jmsConnectionFactory` bean. -For consistency, the `jmsConnectionFactory` bean is also provided by using the bean alias -`xaJmsConnectionFactory`. - -The following example shows how to inject `ConnectionFactory` instances: - -[source,java,indent=0,subs="verbatim,quotes,attributes"] ----- - // Inject the primary (XA aware) ConnectionFactory - @Autowired - private ConnectionFactory defaultConnectionFactory; - - // Inject the XA aware ConnectionFactory (uses the alias and injects the same as above) - @Autowired - @Qualifier("xaJmsConnectionFactory") - private ConnectionFactory xaConnectionFactory; - - // Inject the non-XA aware ConnectionFactory - @Autowired - @Qualifier("nonXaJmsConnectionFactory") - private ConnectionFactory nonXaConnectionFactory; ----- - - - -[[boot-features-jta-supporting-alternative-embedded]] -=== Supporting an Alternative Embedded Transaction Manager -The {sc-spring-boot}/jms/XAConnectionFactoryWrapper.{sc-ext}[`XAConnectionFactoryWrapper`] -and {sc-spring-boot}/jdbc/XADataSourceWrapper.{sc-ext}[`XADataSourceWrapper`] interfaces -can be used to support alternative embedded transaction managers. The interfaces are -responsible for wrapping `XAConnectionFactory` and `XADataSource` beans and exposing them -as regular `ConnectionFactory` and `DataSource` beans, which transparently enroll in the -distributed transaction. DataSource and JMS auto-configuration use JTA variants, provided -you have a `JtaTransactionManager` bean and appropriate XA wrapper beans registered -within your `ApplicationContext`. - -The {sc-spring-boot}/jta/bitronix/BitronixXAConnectionFactoryWrapper.{sc-ext}[BitronixXAConnectionFactoryWrapper] -and {sc-spring-boot}/jta/bitronix/BitronixXADataSourceWrapper.{sc-ext}[BitronixXADataSourceWrapper] -provide good examples of how to write XA wrappers. - - - -[[boot-features-hazelcast]] -== Hazelcast - -If https://hazelcast.com/[Hazelcast] is on the classpath and a suitable configuration is -found, Spring Boot auto-configures a `HazelcastInstance` that you can inject in your -application. - -If you define a `com.hazelcast.config.Config` bean, Spring Boot uses that. If your -configuration defines an instance name, Spring Boot tries to locate an existing instance -rather than creating a new one. - -You could also specify the Hazelcast configuration file to use through configuration, as -shown in the following example: - -[source,properties,indent=0] ----- - spring.hazelcast.config=classpath:config/my-hazelcast.xml ----- - -Otherwise, Spring Boot tries to find the Hazelcast configuration from the default -locations: `hazelcast.xml` in the working directory or at the root of the classpath, or -a `.yaml` counterpart in the same locations. We also check if the `hazelcast.config` -system property is set. See the -https://docs.hazelcast.org/docs/latest/manual/html-single/[Hazelcast documentation] for -more details. - -If `hazelcast-client` is present on the classpath, Spring Boot first attempts to create a -client by checking the following configuration options: - -* The presence of a `com.hazelcast.client.config.ClientConfig` bean. -* A configuration file defined by the `spring.hazelcast.config` property. -* The presence of the `hazelcast.client.config` system property. -* A `hazelcast-client.xml` in the working directory or at the root of the classpath. -* A `hazelcast-client.yaml` in the working directory or at the root of the classpath. - -NOTE: Spring Boot also has -<>. If -caching is enabled, the `HazelcastInstance` is automatically wrapped in a `CacheManager` -implementation. - - - -[[boot-features-quartz]] -== Quartz Scheduler -Spring Boot offers several conveniences for working with the -https://www.quartz-scheduler.org/[Quartz scheduler], including the -`spring-boot-starter-quartz` "`Starter`". If Quartz is available, a `Scheduler` is -auto-configured (through the `SchedulerFactoryBean` abstraction). - -Beans of the following types are automatically picked up and associated with the -`Scheduler`: - -* `JobDetail`: defines a particular Job. `JobDetail` instances can be built with the -`JobBuilder` API. -* `Calendar`. -* `Trigger`: defines when a particular job is triggered. - -By default, an in-memory `JobStore` is used. However, it is possible to configure a -JDBC-based store if a `DataSource` bean is available in your application and if the -`spring.quartz.job-store-type` property is configured accordingly, as shown in the -following example: - -[source,properties,indent=0] ----- - spring.quartz.job-store-type=jdbc ----- - -When the JDBC store is used, the schema can be initialized on startup, as shown in the -following example: - -[source,properties,indent=0] ----- - spring.quartz.jdbc.initialize-schema=always ----- - -WARNING: By default, the database is detected and initialized by using the standard scripts -provided with the Quartz library. These scripts drop existing tables, deleting all triggers -on every restart. It is also possible to provide a custom script by setting the -`spring.quartz.jdbc.schema` property. - -To have Quartz use a `DataSource` other than the application's main `DataSource`, declare -a `DataSource` bean, annotating its `@Bean` method with `@QuartzDataSource`. Doing so -ensures that the Quartz-specific `DataSource` is used by both the `SchedulerFactoryBean` -and for schema initialization. - -By default, jobs created by configuration will not overwrite already registered jobs that -have been read from a persistent job store. To enable overwriting existing job definitions -set the `spring.quartz.overwrite-existing-jobs` property. - -Quartz Scheduler configuration can be customized using `spring.quartz` properties and -`SchedulerFactoryBeanCustomizer` beans, which allow programmatic `SchedulerFactoryBean` -customization. Advanced Quartz configuration properties can be customized using -`spring.quartz.properties.*`. - -NOTE: In particular, an `Executor` bean is not associated with the scheduler as Quartz -offers a way to configure the scheduler via `spring.quartz.properties`. If you need -to customize the task executor, consider implementing `SchedulerFactoryBeanCustomizer`. - -Jobs can define setters to inject data map properties. Regular beans can also be injected -in a similar manner, as shown in the following example: - -[source,java,indent=0] ----- - public class SampleJob extends QuartzJobBean { - - private MyService myService; - - private String name; - - // Inject "MyService" bean - public void setMyService(MyService myService) { ... } - - // Inject the "name" job data property - public void setName(String name) { ... } - - @Override - protected void executeInternal(JobExecutionContext context) - throws JobExecutionException { - ... - } - - } ----- - - - -[[boot-features-task-execution-scheduling]] -== Task Execution and Scheduling -In the absence of an `Executor` bean in the context, Spring Boot auto-configures a -`ThreadPoolTaskExecutor` with sensible defaults that can be automatically associated to -asynchronous task execution (`@EnableAsync`) and Spring MVC asynchronous request -processing. - -[TIP] -==== -If you have defined a custom `Executor` in the context, regular task execution (i.e. -`@EnableAsync`) will use it transparently but the Spring MVC support will not be -configured as it requires an `AsyncTaskExecutor` implementation (named -`applicationTaskExecutor`). Depending on your target arrangement, you could change your -`Executor` into a `ThreadPoolTaskExecutor` or define both a `ThreadPoolTaskExecutor` and -an `AsyncConfigurer` wrapping your custom `Executor`. - -The auto-configured `TaskExecutorBuilder` allows you to easily create instances that -reproduce what the auto-configuration does by default. -==== - -The thread pool uses 8 core threads that can grow and shrink according to the load. Those -default settings can be fine-tuned using the `spring.task.execution` namespace as shown in -the following example: - -[source,properties,indent=0] ----- - spring.task.execution.pool.max-threads=16 - spring.task.execution.pool.queue-capacity=100 - spring.task.execution.pool.keep-alive=10s ----- - -This changes the thread pool to use a bounded queue so that when the queue is full (100 -tasks), the thread pool increases to maximum 16 threads. Shrinking of the pool is more -aggressive as threads are reclaimed when they are idle for 10 seconds (rather than -60 seconds by default). - -A `ThreadPoolTaskScheduler` can also be auto-configured if need to be associated to -scheduled task execution (`@EnableScheduling`). The thread pool uses one thread by default -and those settings can be fine-tuned using the `spring.task.scheduling` namespace. - -Both a `TaskExecutorBuilder` bean and a `TaskSchedulerBuilder` bean are made available in -the context if a custom executor or scheduler needs to be created. - - - -[[boot-features-integration]] -== Spring Integration -Spring Boot offers several conveniences for working with {spring-integration}[Spring -Integration], including the `spring-boot-starter-integration` "`Starter`". Spring -Integration provides abstractions over messaging and also other transports such as HTTP, -TCP, and others. If Spring Integration is available on your classpath, it is initialized -through the `@EnableIntegration` annotation. - -Spring Boot also configures some features that are triggered by the presence of additional -Spring Integration modules. If `spring-integration-jmx` is also on the classpath, -message processing statistics are published over JMX . If `spring-integration-jdbc` is -available, the default database schema can be created on startup, as shown in the -following line: - -[source,properties,indent=0] ----- - spring.integration.jdbc.initialize-schema=always ----- - -See the -{sc-spring-boot-autoconfigure}/integration/IntegrationAutoConfiguration.{sc-ext}[`IntegrationAutoConfiguration`] -and {sc-spring-boot-autoconfigure}/integration/IntegrationProperties.{sc-ext}[`IntegrationProperties`] -classes for more details. - -By default, if a Micrometer `meterRegistry` bean is present, Spring Integration metrics -will be managed by Micrometer. If you wish to use legacy Spring Integration metrics, add -a `DefaultMetricsFactory` bean to the application context. - - - -[[boot-features-session]] -== Spring Session -Spring Boot provides {spring-session}[Spring Session] auto-configuration for a wide range -of data stores. When building a Servlet web application, the following stores can be -auto-configured: - -* JDBC -* Redis -* Hazelcast -* MongoDB - -When building a reactive web application, the following stores can be auto-configured: - -* Redis -* MongoDB - -If a single Spring Session module is present on the classpath, Spring Boot uses that store -implementation automatically. If you have more than one implementation, you must choose -the {sc-spring-boot-autoconfigure}/session/StoreType.{sc-ext}[`StoreType`] that you wish -to use to store the sessions. For instance, to use JDBC as the back-end store, you can -configure your application as follows: - -[source,properties,indent=0] ----- - spring.session.store-type=jdbc ----- - -TIP: You can disable Spring Session by setting the `store-type` to `none`. - -Each store has specific additional settings. For instance, it is possible to customize -the name of the table for the JDBC store, as shown in the following example: - -[source,properties,indent=0] ----- - spring.session.jdbc.table-name=SESSIONS ----- - -For setting the timeout of the session you can use the `spring.session.timeout` property. -If that property is not set, the auto-configuration falls back to the value of -`server.servlet.session.timeout`. - -[[boot-features-jmx]] -== Monitoring and Management over JMX -Java Management Extensions (JMX) provide a standard mechanism to monitor and manage -applications. Spring Boot exposes the most suitable `MBeanServer` as a bean with an ID of -`mbeanServer`. Any of your beans that are annotated with Spring JMX annotations ( -`@ManagedResource`, `@ManagedAttribute`, or `@ManagedOperation`) are exposed to it. - -If your platform provides a standard `MBeanServer`, Spring Boot will use that and default -to the VM `MBeanServer` if necessary. If all that fails, a new `MBeanServer` will be -created. - -See the -{sc-spring-boot-autoconfigure}/jmx/JmxAutoConfiguration.{sc-ext}[`JmxAutoConfiguration`] -class for more details. - - - -[[boot-features-testing]] -== Testing -Spring Boot provides a number of utilities and annotations to help when testing your -application. Test support is provided by two modules: `spring-boot-test` contains core -items, and `spring-boot-test-autoconfigure` supports auto-configuration for tests. - -Most developers use the `spring-boot-starter-test` "`Starter`", which imports both Spring -Boot test modules as well as JUnit Jupiter, AssertJ, Hamcrest, and a number of other -useful libraries. - -[TIP] -==== -The starter also brings the vintage engine so that you can run both JUnit 4 and JUnit 5 -tests. If you have migrated your tests to JUnit 5, you should exclude JUnit 4 support, as -shown in the following example: - -[source,xml,indent=0,subs="verbatim,quotes,attributes"] ----- - - org.springframework.boot - spring-boot-starter-test - test - - - org.junit.vintage - junit-vintage-engine - - - ----- -==== - - - -[[boot-features-test-scope-dependencies]] -=== Test Scope Dependencies -The `spring-boot-starter-test` "`Starter`" (in the `test` `scope`) contains -the following provided libraries: - -* https://junit.org/junit5[JUnit 5] (including the vintage engine for backward -compatibility with JUnit 4: The de-facto standard for unit testing Java applications. -* {spring-reference}testing.html#integration-testing[Spring Test] & Spring Boot Test: -Utilities and integration test support for Spring Boot applications. -* https://joel-costigliola.github.io/assertj/[AssertJ]: A fluent assertion library. -* https://github.com/hamcrest/JavaHamcrest[Hamcrest]: A library of matcher objects (also -known as constraints or predicates). -* https://mockito.github.io[Mockito]: A Java mocking framework. -* https://github.com/skyscreamer/JSONassert[JSONassert]: An assertion library for JSON. -* https://github.com/jayway/JsonPath[JsonPath]: XPath for JSON. - -We generally find these common libraries to be useful when writing tests. If these -libraries do not suit your needs, you can add additional test dependencies of your own. - - - -[[boot-features-testing-spring-applications]] -=== Testing Spring Applications -One of the major advantages of dependency injection is that it should make your code -easier to unit test. You can instantiate objects by using the `new` operator without -even involving Spring. You can also use _mock objects_ instead of real dependencies. - -Often, you need to move beyond unit testing and start integration testing (with -a Spring `ApplicationContext`). It is useful to be able to perform integration testing -without requiring deployment of your application or needing to connect to other -infrastructure. - -The Spring Framework includes a dedicated test module for such integration testing. You -can declare a dependency directly to `org.springframework:spring-test` or use the -`spring-boot-starter-test` "`Starter`" to pull it in transitively. - -If you have not used the `spring-test` module before, you should start by reading the -{spring-reference}testing.html#testing[relevant section] of the Spring Framework -reference documentation. - - - -[[boot-features-testing-spring-boot-applications]] -=== Testing Spring Boot Applications -A Spring Boot application is a Spring `ApplicationContext`, so nothing very special has -to be done to test it beyond what you would normally do with a vanilla Spring context. - -NOTE: External properties, logging, and other features of Spring Boot are installed in the -context by default only if you use `SpringApplication` to create it. - -Spring Boot provides a `@SpringBootTest` annotation, which can be used as an alternative -to the standard `spring-test` `@ContextConfiguration` annotation when you need Spring -Boot features. The annotation works by -<>. In addition to -`@SpringBootTest` a number of other annotations are also provided for -<> of an application. - -TIP: If you are using JUnit 4, don't forget to also add `@RunWith(SpringRunner.class)` to -your test, otherwise the annotations will be ignored. If you are using JUnit 5, there's no -need to add the equivalent `@RunWith(SpringExtension.class)` as `@SpringBootTest` and -the other `@…Test` annotations are already annotated with it. - -By default, `@SpringBootTest` will not start a server. You can use the `webEnvironment` -attribute of `@SpringBootTest` to further refine how your tests run: - -* `MOCK`(Default) : Loads a web `ApplicationContext` and provides a mock web -environment. Embedded servers are not started when using this annotation. If a web -environment is not available on your classpath, this mode transparently falls back to -creating a regular non-web `ApplicationContext`. It can be used in conjunction with -<> for mock-based testing of your -web application. -* `RANDOM_PORT`: Loads a `WebServerApplicationContext` and provides a real web -environment. Embedded servers are started and listen on a random port. -* `DEFINED_PORT`: Loads a `WebServerApplicationContext` and provides a real web -environment. Embedded servers are started and listen on a defined port (from your -`application.properties`) or on the default port of `8080`. -* `NONE`: Loads an `ApplicationContext` by using `SpringApplication` but does not provide -_any_ web environment (mock or otherwise). - -NOTE: If your test is `@Transactional`, it rolls back the transaction at the end of each -test method by default. However, as using this arrangement with either `RANDOM_PORT` or -`DEFINED_PORT` implicitly provides a real servlet environment, the HTTP client and server -run in separate threads and, thus, in separate transactions. Any transaction initiated on -the server does not roll back in this case. - -NOTE: `@SpringBootTest` with `webEnvironment = WebEnvironment.RANDOM_PORT` will also -start the management server on a separate random port if your application uses a different -port for the management server. - - - -[[boot-features-testing-spring-boot-applications-detecting-web-app-type]] -==== Detecting Web Application Type -If Spring MVC is available, a regular MVC-based application context is configured. If you -have only Spring WebFlux, we'll detect that and configure a WebFlux-based application -context instead. - -If both are present, Spring MVC takes precedence. If you want to test a reactive web -application in this scenario, you must set the `spring.main.web-application-type` -property: - -[source,java,indent=0] ----- - @SpringBootTest(properties = "spring.main.web-application-type=reactive") - class MyWebFluxTests { ... } ----- - - - -[[boot-features-testing-spring-boot-applications-detecting-config]] -==== Detecting Test Configuration -If you are familiar with the Spring Test Framework, you may be used to using -`@ContextConfiguration(classes=...)` in order to specify which Spring `@Configuration` to -load. Alternatively, you might have often used nested `@Configuration` classes within -your test. - -When testing Spring Boot applications, this is often not required. Spring Boot's `@*Test` -annotations search for your primary configuration automatically whenever you do not -explicitly define one. - -The search algorithm works up from the package that contains the test until it finds a -class annotated with `@SpringBootApplication` or `@SpringBootConfiguration`. As long as -you <> in a sensible way, your -main configuration is usually found. - -[NOTE] -==== -If you use a -<>, you should avoid adding -configuration settings that are specific to a particular area on the -<>. - -The underlying component scan configuration of `@SpringBootApplication` defines exclude -filters that are used to make sure slicing works as expected. If you are using an explicit -`@ComponentScan` directive on your `@SpringBootApplication`-annotated class, be aware that -those filters will be disabled. If you are using slicing, you should define them again. -==== - -If you want to customize the primary configuration, you can use a nested -`@TestConfiguration` class. Unlike a nested `@Configuration` class, which would be used -instead of your application's primary configuration, a nested `@TestConfiguration` class -is used in addition to your application's primary configuration. - -NOTE: Spring's test framework caches application contexts between tests. Therefore, as -long as your tests share the same configuration (no matter how it is discovered), the -potentially time-consuming process of loading the context happens only once. - - - -[[boot-features-testing-spring-boot-applications-excluding-config]] -==== Excluding Test Configuration -If your application uses component scanning (for example, if you use -`@SpringBootApplication` or `@ComponentScan`), you may find top-level configuration -classes that you created only for specific tests accidentally get picked up everywhere. - -As we <>, `@TestConfiguration` can be used on an inner class of a test to customize the -primary configuration. When placed on a top-level class, `@TestConfiguration` indicates -that classes in `src/test/java` should not be picked up by scanning. You can then import -that class explicitly where it is required, as shown in the following example: - -[source,java,indent=0] ----- - @SpringBootTest - @Import(MyTestsConfiguration.class) - class MyTests { - - @Test - void exampleTest() { - ... - } - - } ----- - -NOTE: If you directly use `@ComponentScan` (that is, not through -`@SpringBootApplication`) you need to register the `TypeExcludeFilter` with it. See -{dc-spring-boot}/context/TypeExcludeFilter.{dc-ext}[the Javadoc] for details. - - - -[[boot-features-testing-spring-boot-application-arguments]] -==== Using Application Arguments -If your application expects <>, you can -have `@SpringBootTest` inject them using the `args` attribute. - -[source,java,indent=0] ----- -include::{code-examples}/test/context/ApplicationArgumentsExampleTests.java[tag=example] ----- - - - -[[boot-features-testing-spring-boot-applications-testing-with-mock-environment]] -==== Testing with a mock environment -By default, `@SpringBootTest` does not start the server. If you have web endpoints that -you want to test against this mock environment, you can additionally configure -{spring-reference}/testing.html#spring-mvc-test-framework[`MockMvc`] as shown in the -following example: - -[source,java,indent=0] ----- -include::{code-examples}/test/web/MockMvcExampleTests.java[tag=test-mock-mvc] ----- - -TIP: If you want to focus only on the web layer and not start a complete -`ApplicationContext`, consider -<>. - -Alternatively, you can configure a -{spring-reference}testing.html#webtestclient-tests[`WebTestClient`] as shown in the -following example: - -[source,java,indent=0] ----- -include::{code-examples}/test/web/MockWebTestClientExampleTests.java[tag=test-mock-web-test-client] ----- - - - -[[boot-features-testing-spring-boot-applications-testing-with-running-server]] -==== Testing with a running server -If you need to start a full running server, we recommend that you use random ports. -If you use `@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)`, an -available port is picked at random each time your test runs. - -The `@LocalServerPort` annotation can be used to -<> into your test. -For convenience, tests that need to make REST calls to the started server can -additionally `@Autowire` a -{spring-reference}testing.html#webtestclient-tests[`WebTestClient`], which resolves -relative links to the running server and comes with a dedicated API for verifying -responses, as shown in the following example: - -[source,java,indent=0] ----- -include::{code-examples}/test/web/RandomPortWebTestClientExampleTests.java[tag=test-random-port] ----- - -This setup requires `spring-webflux` on the classpath. If you can't or won't add webflux, -Spring Boot also provides a `TestRestTemplate` facility: - -[source,java,indent=0] ----- -include::{code-examples}/test/web/RandomPortTestRestTemplateExampleTests.java[tag=test-random-port] ----- - - - -[[boot-features-testing-spring-boot-applications-jmx]] -==== Using JMX -As the test context framework caches context, JMX is disabled by default to prevent -identical components to register on the same domain. If such test needs access to an -`MBeanServer`, consider marking it dirty as well: - -[source,java,indent=0] ----- -include::{test-examples}/jmx/SampleJmxTests.java[tag=test] ----- - - - -[[boot-features-testing-spring-boot-applications-mocking-beans]] -==== Mocking and Spying Beans -When running tests, it is sometimes necessary to mock certain components within your -application context. For example, you may have a facade over some remote service that is -unavailable during development. Mocking can also be useful when you want to simulate -failures that might be hard to trigger in a real environment. - -Spring Boot includes a `@MockBean` annotation that can be used to define a Mockito mock -for a bean inside your `ApplicationContext`. You can use the annotation to add new beans -or replace a single existing bean definition. The annotation can be used directly on test -classes, on fields within your test, or on `@Configuration` classes and fields. When used -on a field, the instance of the created mock is also injected. Mock beans are -automatically reset after each test method. - -[NOTE] -==== -If your test uses one of Spring Boot's test annotations (such as `@SpringBootTest`), this -feature is automatically enabled. To use this feature with a different -arrangement, a listener must be explicitly added, as shown in the following example: - -[source,java,indent=0] ----- - @TestExecutionListeners(MockitoTestExecutionListener.class) ----- - -==== - -The following example replaces an existing `RemoteService` bean with a mock -implementation: - -[source,java,indent=0] ----- - import org.junit.jupiter.api.Test; - import org.springframework.beans.factory.annotation.*; - import org.springframework.boot.test.context.*; - import org.springframework.boot.test.mock.mockito.*; - - import static org.assertj.core.api.Assertions.*; - import static org.mockito.BDDMockito.*; - - @SpringBootTest - class MyTests { - - @MockBean - private RemoteService remoteService; - - @Autowired - private Reverser reverser; - - @Test - void exampleTest() { - // RemoteService has been injected into the reverser bean - given(this.remoteService.someCall()).willReturn("mock"); - String reverse = reverser.reverseSomeCall(); - assertThat(reverse).isEqualTo("kcom"); - } - - } ----- - -NOTE: `@MockBean` cannot be used to mock the behavior of a bean that's exercised during -application context refresh. By the time the test is executed, the application context refresh -has completed and it is too late to configure the mocked behavior. We recommend using a `@Bean` -method to create and configure the mock in this situation. - -Additionally, you can use `@SpyBean` to wrap any existing bean with a Mockito `spy`. See -the {dc-spring-boot-test}/mock/mockito/SpyBean.{dc-ext}[Javadoc] for full details. - -NOTE: While Spring's test framework caches application contexts between tests and reuses -a context for tests sharing the same configuration, the use of `@MockBean` or `@SpyBean` -influences the cache key, which will most likely increase the number of contexts. - -TIP: If you are using `@SpyBean` to spy on a bean with `@Cacheable` methods that refer -to parameters by name, your application must be compiled with `-parameters`. This -ensures that the parameter names are available to the caching infrastructure once the -bean has been spied upon. - - - -[[boot-features-testing-spring-boot-applications-testing-autoconfigured-tests]] -==== Auto-configured Tests -Spring Boot's auto-configuration system works well for applications but can sometimes be -a little too much for tests. It often helps to load only the parts of the configuration -that are required to test a "`slice`" of your application. For example, you might want to -test that Spring MVC controllers are mapping URLs correctly, and you do not want to -involve database calls in those tests, or you might want to test JPA entities, and you -are not interested in the web layer when those tests run. - -The `spring-boot-test-autoconfigure` module includes a number of annotations that can be -used to automatically configure such "`slices`". Each of them works in a similar way, -providing a `@...Test` annotation that loads the `ApplicationContext` and one or -more `@AutoConfigure...` annotations that can be used to customize auto-configuration -settings. - -NOTE: Each slice restricts component scan to appropriate components and loads a very -restricted set of auto-configuration classes. If you need to exclude one of them, -most `@...Test` annotations provide an `excludeAutoConfiguration` attribute. -Alternatively, you can use `@ImportAutoConfiguration#exclude`. - -NOTE: Including multiple "`slices`" by using several `@...Test` annotations in one test is -not supported. If you need multiple "`slices`", pick one of the `@...Test` annotations -and include the `@AutoConfigure...` annotations of the other "`slices`" by hand. - -TIP: It is also possible to use the `@AutoConfigure...` annotations with the standard -`@SpringBootTest` annotation. You can use this combination if you are not interested in -"`slicing`" your application but you want some of the auto-configured test beans. - - - -[[boot-features-testing-spring-boot-applications-testing-autoconfigured-json-tests]] -==== Auto-configured JSON Tests -To test that object JSON serialization and deserialization is working as expected, you can -use the `@JsonTest` annotation. `@JsonTest` auto-configures the available supported JSON -mapper, which can be one of the following libraries: - -* Jackson `ObjectMapper`, any `@JsonComponent` beans and any Jackson ``Module``s -* `Gson` -* `Jsonb` - -TIP: A list of the auto-configurations that are enabled by `@JsonTest` can be -<>. - -If you need to configure elements of the auto-configuration, you can use the -`@AutoConfigureJsonTesters` annotation. - -Spring Boot includes AssertJ-based helpers that work with the JSONAssert and JsonPath -libraries to check that JSON appears as expected. The `JacksonTester`, `GsonTester`, -`JsonbTester`, and `BasicJsonTester` classes can be used for Jackson, Gson, Jsonb, and -Strings respectively. Any helper fields on the test class can be `@Autowired` when using -`@JsonTest`. The following example shows a test class for Jackson: - -[source,java,indent=0] ----- - import org.junit.jupiter.api.Test; - import org.springframework.beans.factory.annotation.*; - import org.springframework.boot.test.autoconfigure.json.*; - import org.springframework.boot.test.context.*; - import org.springframework.boot.test.json.*; - - import static org.assertj.core.api.Assertions.*; - - @JsonTest - class MyJsonTests { - - @Autowired - private JacksonTester json; - - @Test - void testSerialize() throws Exception { - VehicleDetails details = new VehicleDetails("Honda", "Civic"); - // Assert against a `.json` file in the same package as the test - assertThat(this.json.write(details)).isEqualToJson("expected.json"); - // Or use JSON path based assertions - assertThat(this.json.write(details)).hasJsonPathStringValue("@.make"); - assertThat(this.json.write(details)).extractingJsonPathStringValue("@.make") - .isEqualTo("Honda"); - } - - @Test - void testDeserialize() throws Exception { - String content = "{\"make\":\"Ford\",\"model\":\"Focus\"}"; - assertThat(this.json.parse(content)) - .isEqualTo(new VehicleDetails("Ford", "Focus")); - assertThat(this.json.parseObject(content).getMake()).isEqualTo("Ford"); - } - - } ----- - -NOTE: JSON helper classes can also be used directly in standard unit tests. To do so, -call the `initFields` method of the helper in your `@Before` method if you do not use -`@JsonTest`. - -If you're using Spring Boot's AssertJ-based helpers to assert on a number value -at a given JSON path, you might not be able to use `isEqualTo` depending on the type. -Instead, you can use AssertJ's `satisfies` to assert that the value matches the given -condition. For instance, the following example asserts that the actual number is a float -value close to `0.15` within an offset of `0.01`. - -[source,java,indent=0] ----- -assertThat(json.write(message)) - .extractingJsonPathNumberValue("@.test.numberValue") - .satisfies((number) -> assertThat(number.floatValue()).isCloseTo(0.15f, within(0.01f))); ----- - - - -[[boot-features-testing-spring-boot-applications-testing-autoconfigured-mvc-tests]] -==== Auto-configured Spring MVC Tests -To test whether Spring MVC controllers are working as expected, use the `@WebMvcTest` -annotation. `@WebMvcTest` auto-configures the Spring MVC infrastructure and limits -scanned beans to `@Controller`, `@ControllerAdvice`, `@JsonComponent`, `Converter`, -`GenericConverter`, `Filter`, `WebMvcConfigurer`, and `HandlerMethodArgumentResolver`. -Regular `@Component` beans are not scanned when using this annotation. - -TIP: A list of the auto-configuration settings that are enabled by `@WebMvcTest` can be -<>. - -TIP: If you need to register extra components, such as the Jackson `Module`, you can -import additional configuration classes by using `@Import` on your test. - -Often, `@WebMvcTest` is limited to a single controller and is used in combination with -`@MockBean` to provide mock implementations for required collaborators. - -`@WebMvcTest` also auto-configures `MockMvc`. Mock MVC offers a powerful way to quickly -test MVC controllers without needing to start a full HTTP server. - -TIP: You can also auto-configure `MockMvc` in a non-`@WebMvcTest` (such as -`@SpringBootTest`) by annotating it with `@AutoConfigureMockMvc`. The following example -uses `MockMvc`: - -[source,java,indent=0] ----- - import org.junit.jupiter.api.*; - import org.springframework.beans.factory.annotation.*; - import org.springframework.boot.test.autoconfigure.web.servlet.*; - import org.springframework.boot.test.mock.mockito.*; - - import static org.assertj.core.api.Assertions.*; - import static org.mockito.BDDMockito.*; - import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; - import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - - @WebMvcTest(UserVehicleController.class) - class MyControllerTests { - - @Autowired - private MockMvc mvc; - - @MockBean - private UserVehicleService userVehicleService; - - @Test - void testExample() throws Exception { - given(this.userVehicleService.getVehicleDetails("sboot")) - .willReturn(new VehicleDetails("Honda", "Civic")); - this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)) - .andExpect(status().isOk()).andExpect(content().string("Honda Civic")); - } - - } ----- - -TIP: If you need to configure elements of the auto-configuration (for example, when -servlet filters should be applied) you can use attributes in the `@AutoConfigureMockMvc` -annotation. - -If you use HtmlUnit or Selenium, auto-configuration also provides an HTMLUnit `WebClient` -bean and/or a `WebDriver` bean. The following example uses HtmlUnit: - - -[source,java,indent=0] ----- - import com.gargoylesoftware.htmlunit.*; - import org.junit.jupiter.api.*; - import org.springframework.beans.factory.annotation.*; - import org.springframework.boot.test.autoconfigure.web.servlet.*; - import org.springframework.boot.test.mock.mockito.*; - - import static org.assertj.core.api.Assertions.*; - import static org.mockito.BDDMockito.*; - - @WebMvcTest(UserVehicleController.class) - class MyHtmlUnitTests { - - @Autowired - private WebClient webClient; - - @MockBean - private UserVehicleService userVehicleService; - - @Test - void testExample() throws Exception { - given(this.userVehicleService.getVehicleDetails("sboot")) - .willReturn(new VehicleDetails("Honda", "Civic")); - HtmlPage page = this.webClient.getPage("/sboot/vehicle.html"); - assertThat(page.getBody().getTextContent()).isEqualTo("Honda Civic"); - } - - } ----- - -NOTE: By default, Spring Boot puts `WebDriver` beans in a special "`scope`" to ensure -that the driver exits after each test and that a new instance is injected. If you do -not want this behavior, you can add `@Scope("singleton")` to your `WebDriver` `@Bean` -definition. - -WARNING: The `webDriver` scope created by Spring Boot will replace any user defined scope -of the same name. If you define your own `webDriver` scope you may find it stops working -when you use `@WebMvcTest`. - -If you have Spring Security on the classpath, `@WebMvcTest` will also scan `WebSecurityConfigurer` -beans. Instead of disabling security completely for such tests, you can use Spring Security's test support. -More details on how to use Spring Security's `MockMvc` support can be found in -this _<>_ how-to section. - -TIP: Sometimes writing Spring MVC tests is not enough; Spring Boot can help you run -<>. - - - -[[boot-features-testing-spring-boot-applications-testing-autoconfigured-webflux-tests]] -==== Auto-configured Spring WebFlux Tests -To test that {spring-reference}/web-reactive.html[Spring WebFlux] controllers are -working as expected, you can use the `@WebFluxTest` annotation. `@WebFluxTest` -auto-configures the Spring WebFlux infrastructure and limits scanned beans to -`@Controller`, `@ControllerAdvice`, `@JsonComponent`, `Converter`, `GenericConverter`, and -`WebFluxConfigurer`. Regular `@Component` beans are not scanned when the `@WebFluxTest` -annotation is used. - -TIP: A list of the auto-configurations that are enabled by `@WebFluxTest` can be -<>. - -TIP: If you need to register extra components, such as Jackson `Module`, you can import -additional configuration classes using `@Import` on your test. - -Often, `@WebFluxTest` is limited to a single controller and used in combination with the -`@MockBean` annotation to provide mock implementations for required collaborators. - -`@WebFluxTest` also auto-configures -{spring-reference}testing.html#webtestclient[`WebTestClient`], which offers -a powerful way to quickly test WebFlux controllers without needing to start a full HTTP -server. - -TIP: You can also auto-configure `WebTestClient` in a non-`@WebFluxTest` (such as -`@SpringBootTest`) by annotating it with `@AutoConfigureWebTestClient`. The following -example shows a class that uses both `@WebFluxTest` and a `WebTestClient`: - -[source,java,indent=0] ----- - import org.junit.jupiter.api.Test; - - import org.springframework.beans.factory.annotation.Autowired; - import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; - import org.springframework.http.MediaType; - import org.springframework.test.web.reactive.server.WebTestClient; - - @WebFluxTest(UserVehicleController.class) - class MyControllerTests { - - @Autowired - private WebTestClient webClient; - - @MockBean - private UserVehicleService userVehicleService; - - @Test - void testExample() throws Exception { - given(this.userVehicleService.getVehicleDetails("sboot")) - .willReturn(new VehicleDetails("Honda", "Civic")); - this.webClient.get().uri("/sboot/vehicle").accept(MediaType.TEXT_PLAIN) - .exchange() - .expectStatus().isOk() - .expectBody(String.class).isEqualTo("Honda Civic"); - } - - } ----- - -TIP: This setup is only supported by WebFlux applications as using `WebTestClient` in a -mocked web application only works with WebFlux at the moment. - -NOTE: `@WebFluxTest` cannot detect routes registered via the functional web framework. For -testing `RouterFunction` beans in the context, consider importing your `RouterFunction` -yourself via `@Import` or using `@SpringBootTest`. - -NOTE: `@WebFluxTest` cannot detect custom security configuration registered via a `@Bean` -of type `SecurityWebFilterChain`. To include that in your test, you will need to import -the configuration that registers the bean via `@Import` or use `@SpringBootTest`. - -TIP: Sometimes writing Spring WebFlux tests is not enough; Spring Boot can help you run -<>. - - - -[[boot-features-testing-spring-boot-applications-testing-autoconfigured-jpa-test]] -==== Auto-configured Data JPA Tests -You can use the `@DataJpaTest` annotation to test JPA applications. By default, it scans -for `@Entity` classes and configures Spring Data JPA repositories. If an embedded database -is available on the classpath, it configures one as well. Regular `@Component` beans are -not loaded into the `ApplicationContext`. - -TIP: A list of the auto-configuration settings that are enabled by `@DataJpaTest` can be -<>. - -By default, data JPA tests are transactional and roll back at the end of each test. See -the {spring-reference}testing.html#testcontext-tx-enabling-transactions[relevant section] -in the Spring Framework Reference Documentation for more details. If that is not what you -want, you can disable transaction management for a test or for the whole class as -follows: - -[source,java,indent=0] ----- - import org.junit.jupiter.api.Test; - import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; - import org.springframework.transaction.annotation.Propagation; - import org.springframework.transaction.annotation.Transactional; - - @DataJpaTest - @Transactional(propagation = Propagation.NOT_SUPPORTED) - class ExampleNonTransactionalTests { - - } ----- - -Data JPA tests may also inject a -{sc-spring-boot-test-autoconfigure}/orm/jpa/TestEntityManager.{sc-ext}[`TestEntityManager`] -bean, which provides an alternative to the standard JPA `EntityManager` that is -specifically designed for tests. If you want to use `TestEntityManager` outside of -`@DataJpaTest` instances, you can also use the `@AutoConfigureTestEntityManager` -annotation. A `JdbcTemplate` is also available if you need that. The following example -shows the `@DataJpaTest` annotation in use: - -[source,java,indent=0] ----- - import org.junit.jupiter.api.Test; - import org.springframework.boot.test.autoconfigure.orm.jpa.*; - - import static org.assertj.core.api.Assertions.*; - - @DataJpaTest - class ExampleRepositoryTests { - - @Autowired - private TestEntityManager entityManager; - - @Autowired - private UserRepository repository; - - @Test - void testExample() throws Exception { - this.entityManager.persist(new User("sboot", "1234")); - User user = this.repository.findByUsername("sboot"); - assertThat(user.getUsername()).isEqualTo("sboot"); - assertThat(user.getVin()).isEqualTo("1234"); - } - - } ----- - -In-memory embedded databases generally work well for tests, since they are fast and do -not require any installation. If, however, you prefer to run tests against a real -database you can use the `@AutoConfigureTestDatabase` annotation, as shown in the -following example: - -[source,java,indent=0] ----- - @DataJpaTest - @AutoConfigureTestDatabase(replace=Replace.NONE) - class ExampleRepositoryTests { - - // ... - - } ----- - - - -[[boot-features-testing-spring-boot-applications-testing-autoconfigured-jdbc-test]] -==== Auto-configured JDBC Tests -`@JdbcTest` is similar to `@DataJpaTest` but is for tests that only require a -`DataSource` and do not use Spring Data JDBC. By default, it configures an in-memory -embedded database and a `JdbcTemplate`. Regular `@Component` beans are not loaded into -the `ApplicationContext`. - -TIP: A list of the auto-configurations that are enabled by `@JdbcTest` can be -<>. - -By default, JDBC tests are transactional and roll back at the end of each test. See the -{spring-reference}testing.html#testcontext-tx-enabling-transactions[relevant section] in -the Spring Framework Reference Documentation for more details. If that is not what you -want, you can disable transaction management for a test or for the whole class, as -follows: - -[source,java,indent=0] ----- - import org.junit.jupiter.api.Test; - import org.springframework.boot.test.autoconfigure.jdbc.JdbcTest; - import org.springframework.transaction.annotation.Propagation; - import org.springframework.transaction.annotation.Transactional; - - @JdbcTest - @Transactional(propagation = Propagation.NOT_SUPPORTED) - class ExampleNonTransactionalTests { - - } ----- - -If you prefer your test to run against a real database, you can use the -`@AutoConfigureTestDatabase` annotation in the same way as for `DataJpaTest`. (See -"<>".) - - - -[[boot-features-testing-spring-boot-applications-testing-autoconfigured-data-jdbc-test]] -==== Auto-configured Data JDBC Tests -`@DataJdbcTest` is similar to `@JdbcTest` but is for tests that use Spring Data JDBC -repositories. By default, it configures an in-memory embedded database, a `JdbcTemplate`, -and Spring Data JDBC repositories. Regular `@Component` beans are not loaded into -the `ApplicationContext`. - -TIP: A list of the auto-configurations that are enabled by `@DataJdbcTest` can be -<>. - -By default, Data JDBC tests are transactional and roll back at the end of each test. See -the {spring-reference}testing.html#testcontext-tx-enabling-transactions[relevant section] -in the Spring Framework Reference Documentation for more details. If that is not what you -want, you can disable transaction management for a test or for the whole test class as -<>. - -If you prefer your test to run against a real database, you can use the -`@AutoConfigureTestDatabase` annotation in the same way as for `DataJpaTest`. (See -"<>".) - - - -[[boot-features-testing-spring-boot-applications-testing-autoconfigured-jooq-test]] -==== Auto-configured jOOQ Tests -You can use `@JooqTest` in a similar fashion as `@JdbcTest` but for jOOQ-related tests. -As jOOQ relies heavily on a Java-based schema that corresponds with the database schema, -the existing `DataSource` is used. If you want to replace it with an in-memory database, -you can use `@AutoConfigureTestDatabase` to override those settings. (For more about using -jOOQ with Spring Boot, see "<>", earlier in this chapter.) Regular -`@Component` beans are not loaded into the `ApplicationContext`. - -TIP: A list of the auto-configurations that are enabled by `@JooqTest` can be -<>. - -`@JooqTest` configures a `DSLContext`. Regular `@Component` beans are not loaded into the -`ApplicationContext`. The following example shows the `@JooqTest` annotation in use: - -[source,java,indent=0] ----- - import org.jooq.DSLContext; - import org.junit.jupiter.api.Test; - import org.springframework.boot.test.autoconfigure.jooq.JooqTest; - - @JooqTest - class ExampleJooqTests { - - @Autowired - private DSLContext dslContext; - } ----- - -JOOQ tests are transactional and roll back at the end of each test by default. If that is -not what you want, you can disable transaction management for a test or for the whole -test class as -<>. - - - - -[[boot-features-testing-spring-boot-applications-testing-autoconfigured-mongo-test]] -==== Auto-configured Data MongoDB Tests -You can use `@DataMongoTest` to test MongoDB applications. By default, it configures an -in-memory embedded MongoDB (if available), configures a `MongoTemplate`, scans for -`@Document` classes, and configures Spring Data MongoDB repositories. Regular -`@Component` beans are not loaded into the `ApplicationContext`. (For more about using -MongoDB with Spring Boot, see "<>", earlier in this chapter.) - -TIP: A list of the auto-configuration settings that are enabled by `@DataMongoTest` can be -<>. - -The following class shows the `@DataMongoTest` annotation in use: - -[source,java,indent=0] ----- - import org.springframework.beans.factory.annotation.Autowired; - import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest; - import org.springframework.data.mongodb.core.MongoTemplate; - - @DataMongoTest - class ExampleDataMongoTests { - - @Autowired - private MongoTemplate mongoTemplate; - - // - } ----- - -In-memory embedded MongoDB generally works well for tests, since it is fast and does not -require any developer installation. If, however, you prefer to run tests against a real -MongoDB server, you should exclude the embedded MongoDB auto-configuration, as shown in -the following example: - -[source,java,indent=0] ----- - import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration; - import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest; - - @DataMongoTest(excludeAutoConfiguration = EmbeddedMongoAutoConfiguration.class) - class ExampleDataMongoNonEmbeddedTests { - - } ----- - - - - -[[boot-features-testing-spring-boot-applications-testing-autoconfigured-neo4j-test]] -==== Auto-configured Data Neo4j Tests -You can use `@DataNeo4jTest` to test Neo4j applications. By default, it uses an in-memory -embedded Neo4j (if the embedded driver is available), scans for `@NodeEntity` classes, and -configures Spring Data Neo4j repositories. Regular `@Component` beans are not loaded into -the `ApplicationContext`. (For more about using Neo4J with Spring Boot, see -"<>", earlier in this chapter.) - -TIP: A list of the auto-configuration settings that are enabled by `@DataNeo4jTest` can be -<>. - -The following example shows a typical setup for using Neo4J tests in Spring Boot: - -[source,java,indent=0] ----- - import org.springframework.beans.factory.annotation.Autowired; - import org.springframework.boot.test.autoconfigure.data.neo4j.DataNeo4jTest; - - @DataNeo4jTest - class ExampleDataNeo4jTests { - - @Autowired - private YourRepository repository; - - // - } ----- - -By default, Data Neo4j tests are transactional and roll back at the end of each test. -See the {spring-reference}testing.html#testcontext-tx-enabling-transactions[relevant -section] in the Spring Framework Reference Documentation for more details. If that is not -what you want, you can disable transaction management for a test or for the whole class, -as follows: - -[source,java,indent=0] ----- - import org.springframework.boot.test.autoconfigure.data.neo4j.DataNeo4jTest; - import org.springframework.transaction.annotation.Propagation; - import org.springframework.transaction.annotation.Transactional; - - @DataNeo4jTest - @Transactional(propagation = Propagation.NOT_SUPPORTED) - class ExampleNonTransactionalTests { - - } ----- - - - - -[[boot-features-testing-spring-boot-applications-testing-autoconfigured-redis-test]] -==== Auto-configured Data Redis Tests -You can use `@DataRedisTest` to test Redis applications. By default, it scans for -`@RedisHash` classes and configures Spring Data Redis repositories. Regular `@Component` -beans are not loaded into the `ApplicationContext`. (For more about using Redis with -Spring Boot, see "<>", earlier in this chapter.) - -TIP: A list of the auto-configuration settings that are enabled by `@DataRedisTest` can be -<>. - -The following example shows the `@DataRedisTest` annotation in use: - -[source,java,indent=0] ----- - import org.springframework.beans.factory.annotation.Autowired; - import org.springframework.boot.test.autoconfigure.data.redis.DataRedisTest; - - @DataRedisTest - class ExampleDataRedisTests { - - @Autowired - private YourRepository repository; - - // - } ----- - - - -[[boot-features-testing-spring-boot-applications-testing-autoconfigured-ldap-test]] -==== Auto-configured Data LDAP Tests -You can use `@DataLdapTest` to test LDAP applications. By default, it configures an -in-memory embedded LDAP (if available), configures an `LdapTemplate`, scans for `@Entry` -classes, and configures Spring Data LDAP repositories. Regular `@Component` beans are not -loaded into the `ApplicationContext`. (For more about using LDAP with -Spring Boot, see "<>", earlier in this chapter.) - -TIP: A list of the auto-configuration settings that are enabled by `@DataLdapTest` can be -<>. - -The following example shows the `@DataLdapTest` annotation in use: - -[source,java,indent=0] ----- - import org.springframework.beans.factory.annotation.Autowired; - import org.springframework.boot.test.autoconfigure.data.ldap.DataLdapTest; - import org.springframework.ldap.core.LdapTemplate; - - @DataLdapTest - class ExampleDataLdapTests { - - @Autowired - private LdapTemplate ldapTemplate; - - // - } ----- - -In-memory embedded LDAP generally works well for tests, since it is fast and does not -require any developer installation. If, however, you prefer to run tests against a real -LDAP server, you should exclude the embedded LDAP auto-configuration, as shown in the -following example: - -[source,java,indent=0] ----- - import org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration; - import org.springframework.boot.test.autoconfigure.data.ldap.DataLdapTest; - - @DataLdapTest(excludeAutoConfiguration = EmbeddedLdapAutoConfiguration.class) - class ExampleDataLdapNonEmbeddedTests { - - } ----- - - - -[[boot-features-testing-spring-boot-applications-testing-autoconfigured-rest-client]] -==== Auto-configured REST Clients -You can use the `@RestClientTest` annotation to test REST clients. By default, it -auto-configures Jackson, GSON, and Jsonb support, configures a `RestTemplateBuilder`, and -adds support for `MockRestServiceServer`. Regular `@Component` beans are not loaded into -the `ApplicationContext`. - -TIP: A list of the auto-configuration settings that are enabled by `@RestClientTest` can -be <>. - -The specific beans that you want to test should be specified by using the `value` or -`components` attribute of `@RestClientTest`, as shown in the following example: - -[source,java,indent=0] ----- - @RestClientTest(RemoteVehicleDetailsService.class) - class ExampleRestClientTest { - - @Autowired - private RemoteVehicleDetailsService service; - - @Autowired - private MockRestServiceServer server; - - @Test - void getVehicleDetailsWhenResultIsSuccessShouldReturnDetails() - throws Exception { - this.server.expect(requestTo("/greet/details")) - .andRespond(withSuccess("hello", MediaType.TEXT_PLAIN)); - String greeting = this.service.callRestService(); - assertThat(greeting).isEqualTo("hello"); - } - - } ----- - - - -[[boot-features-testing-spring-boot-applications-testing-autoconfigured-rest-docs]] -==== Auto-configured Spring REST Docs Tests -You can use the `@AutoConfigureRestDocs` annotation to use {spring-rest-docs}[Spring REST -Docs] in your tests with Mock MVC, REST Assured, or WebTestClient. It removes the need for -the JUnit extension in Spring REST Docs. - -`@AutoConfigureRestDocs` can be used to override the default output directory -(`target/generated-snippets` if you are using Maven or `build/generated-snippets` if you -are using Gradle). It can also be used to configure the host, scheme, and port that -appears in any documented URIs. - - - -[[boot-features-testing-spring-boot-applications-testing-autoconfigured-rest-docs-mock-mvc]] -===== Auto-configured Spring REST Docs Tests with Mock MVC -`@AutoConfigureRestDocs` customizes the `MockMvc` bean to use Spring REST Docs. You can -inject it by using `@Autowired` and use it in your tests as you normally would when using -Mock MVC and Spring REST Docs, as shown in the following example: - -[source,java,indent=0] ----- - import org.junit.jupiter.api.Test; - - import org.springframework.beans.factory.annotation.Autowired; - import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; - import org.springframework.http.MediaType; - import org.springframework.test.web.servlet.MockMvc; - - import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; - import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; - import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - - @WebMvcTest(UserController.class) - @AutoConfigureRestDocs - class UserDocumentationTests { - - @Autowired - private MockMvc mvc; - - @Test - void listUsers() throws Exception { - this.mvc.perform(get("/users").accept(MediaType.TEXT_PLAIN)) - .andExpect(status().isOk()) - .andDo(document("list-users")); - } - - } ----- - -If you require more control over Spring REST Docs configuration than offered by the -attributes of `@AutoConfigureRestDocs`, you can use a -`RestDocsMockMvcConfigurationCustomizer` bean, as shown in the following example: - -[source,java,indent=0] ----- - @TestConfiguration - static class CustomizationConfiguration - implements RestDocsMockMvcConfigurationCustomizer { - - @Override - public void customize(MockMvcRestDocumentationConfigurer configurer) { - configurer.snippets().withTemplateFormat(TemplateFormats.markdown()); - } - - } ----- - -If you want to make use of Spring REST Docs support for a parameterized output directory, -you can create a `RestDocumentationResultHandler` bean. The auto-configuration calls -`alwaysDo` with this result handler, thereby causing each `MockMvc` call to automatically -generate the default snippets. The following example shows a -`RestDocumentationResultHandler` being defined: - -[source,java,indent=0] ----- - @TestConfiguration - static class ResultHandlerConfiguration { - - @Bean - public RestDocumentationResultHandler restDocumentation() { - return MockMvcRestDocumentation.document("{method-name}"); - } - - } ----- - - - -[[boot-features-testing-spring-boot-applications-testing-autoconfigured-rest-docs-web-test-client]] -===== Auto-configured Spring REST Docs Tests with WebTestClient -`@AutoConfigureRestDocs` can also be used with `WebTestClient`. You can inject it by using -`@Autowired` and use it in your tests as you normally would when using `@WebFluxTest` and -Spring REST Docs, as shown in the following example: - -[source,java,indent=0] ----- -include::{code-examples}/test/autoconfigure/restdocs/webclient/UsersDocumentationTests.java[tag=source] ----- - -If you require more control over Spring REST Docs configuration than offered by the -attributes of `@AutoConfigureRestDocs`, you can use a -`RestDocsWebTestClientConfigurationCustomizer` bean, as shown in the following example: - -[source,java,indent=0] ----- -include::{code-examples}/test/autoconfigure/restdocs/webclient/AdvancedConfigurationExample.java[tag=configuration] ----- - - - -[[boot-features-testing-spring-boot-applications-testing-autoconfigured-rest-docs-rest-assured]] -===== Auto-configured Spring REST Docs Tests with REST Assured -`@AutoConfigureRestDocs` makes a `RequestSpecification` bean, preconfigured to use Spring -REST Docs, available to your tests. You can inject it by using `@Autowired` and use it in -your tests as you normally would when using REST Assured and Spring REST Docs, as shown -in the following example: - -[source,java,indent=0] ----- -include::{code-examples}/test/autoconfigure/restdocs/restassured/UserDocumentationTests.java[tag=source] ----- - -If you require more control over Spring REST Docs configuration than offered by the -attributes of `@AutoConfigureRestDocs`, a `RestDocsRestAssuredConfigurationCustomizer` -bean can be used, as shown in the following example: - -[source,java,indent=0] ----- -include::{code-examples}/test/autoconfigure/restdocs/restassured/AdvancedConfigurationExample.java[tag=configuration] ----- - - - -[[boot-features-testing-spring-boot-applications-testing-auto-configured-additional-auto-config]] -==== Additional Auto-configuration and Slicing -Each slice provides one or more `@AutoConfigure...` annotations that namely defines the -auto-configurations that should be included as part of a slice. Additional -auto-configurations can be added by creating a custom `@AutoConfigure...` annotation or -simply by adding `@ImportAutoConfiguration` to the test as shown in the following example: - -[source,java,indent=0] ----- - @JdbcTest - @ImportAutoConfiguration(IntegrationAutoConfiguration.class) - class ExampleJdbcTests { - - } ----- - -NOTE: Make sure to not use the regular `@Import` annotation to import auto-configurations -as they are handled in a specific way by Spring Boot. - - - -[[boot-features-testing-spring-boot-applications-testing-user-configuration]] -==== User Configuration and Slicing -If you <> in a sensible way, your -`@SpringBootApplication` class is -<> as -the configuration of your tests. - -It then becomes important not to litter the application's main class with configuration -settings that are specific to a particular area of its functionality. - -Assume that you are using Spring Batch and you rely on the auto-configuration for it. -You could define your `@SpringBootApplication` as follows: - -[source,java,indent=0] ----- - @SpringBootApplication - @EnableBatchProcessing - public class SampleApplication { ... } ----- - -Because this class is the source configuration for the test, any slice test actually -tries to start Spring Batch, which is definitely not what you want to do. A recommended -approach is to move that area-specific configuration to a separate `@Configuration` class -at the same level as your application, as shown in the following example: - -[source,java,indent=0] ----- - @Configuration(proxyBeanMethods = false) - @EnableBatchProcessing - public class BatchConfiguration { ... } ----- - -NOTE: Depending on the complexity of your application, you may either have a single -`@Configuration` class for your customizations or one class per domain area. The latter -approach lets you enable it in one of your tests, if necessary, with the `@Import` -annotation. - -Test slices exclude `@Configuration` classes from scanning. For example, for a `@WebMvcTest`, -the following configuration will not include the given `WebMvcConfigurer` bean in the application -context loaded by the test slice: - -[source,java,indent=0] ----- - @Configuration - public class WebConfiguration { - @Bean - public WebMvcConfigurer testConfigurer() { - return new WebMvcConfigurer() { - ... - }; - } - } ----- - -The configuration below will, however, cause the custom `WebMvcConfigurer` to be loaded -by the test slice. - -[source,java,indent=0] ----- - @Component - public class TestWebMvcConfigurer implements WebMvcConfigurer { - ... - } ----- - -Another source of confusion is classpath scanning. Assume that, while you structured your -code in a sensible way, you need to scan an additional package. Your application may -resemble the following code: - -[source,java,indent=0] ----- - @SpringBootApplication - @ComponentScan({ "com.example.app", "org.acme.another" }) - public class SampleApplication { ... } ----- - -Doing so effectively overrides the default component scan directive with the side effect -of scanning those two packages regardless of the slice that you chose. For instance, a -`@DataJpaTest` seems to suddenly scan components and user configurations of your -application. Again, moving the custom directive to a separate class is a good way to fix -this issue. - -TIP: If this is not an option for you, you can create a `@SpringBootConfiguration` -somewhere in the hierarchy of your test so that it is used instead. Alternatively, you -can specify a source for your test, which disables the behavior of finding a default one. - - - -[[boot-features-testing-spring-boot-applications-with-spock]] -==== Using Spock to Test Spring Boot Applications -If you wish to use Spock to test a Spring Boot application, you should add a dependency -on Spock's `spock-spring` module to your application's build. `spock-spring` integrates -Spring's test framework into Spock. It is recommended that you use Spock 1.2 or later to -benefit from a number of improvements to Spock's Spring Framework and Spring Boot -integration. See http://spockframework.org/spock/docs/1.2/modules.html#_spring_module[the -documentation for Spock's Spring module] for further details. - - - -[[boot-features-test-utilities]] -=== Test Utilities -A few test utility classes that are generally useful when testing your application are -packaged as part of `spring-boot`. - - - -[[boot-features-configfileapplicationcontextinitializer-test-utility]] -==== ConfigFileApplicationContextInitializer -`ConfigFileApplicationContextInitializer` is an `ApplicationContextInitializer` that you -can apply to your tests to load Spring Boot `application.properties` files. You can use -it when you do not need the full set of features provided by `@SpringBootTest`, as shown -in the following example: - -[source,java,indent=0] ----- - @ContextConfiguration(classes = Config.class, - initializers = ConfigFileApplicationContextInitializer.class) ----- - -NOTE: Using `ConfigFileApplicationContextInitializer` alone does not provide support for -`@Value("${...}")` injection. Its only job is to ensure that `application.properties` -files are loaded into Spring's `Environment`. For `@Value` support, you need to either -additionally configure a `PropertySourcesPlaceholderConfigurer` or use `@SpringBootTest`, -which auto-configures one for you. - - - -[[boot-features-test-property-values]] -==== TestPropertyValues -`TestPropertyValues` lets you quickly add properties to a -`ConfigurableEnvironment` or `ConfigurableApplicationContext`. You can call it with -`key=value` strings, as follows: - -[source,java,indent=0] ----- - TestPropertyValues.of("org=Spring", "name=Boot").applyTo(env); ----- - - - -[[boot-features-output-capture-test-utility]] -==== OutputCapture -`OutputCapture` is a JUnit `Extension` that you can use to capture `System.out` and -`System.err` output. To use with {@link ExtendWith @ExtendWith}, you can inject -`CapturedOutput` as an argument to your test class constructor or test method as follows: - -[source,java,indent=0] ----- - import org.junit.jupiter.api.Test; - import org.junit.jupiter.api.extension.ExtendWith; - - import org.springframework.boot.test.system.CapturedOutput; - import org.springframework.boot.test.system.OutputCaptureExtension; - - import static org.assertj.core.api.Assertions.assertThat; - - @ExtendWith(OutputCaptureExtension.class) - class MyTest { - - @Test - void testName(CapturedOutput output) { - System.out.println("Hello World!"); - assertThat(output).contains("World")); - } - - } ----- - -[[boot-features-rest-templates-test-utility]] -==== TestRestTemplate - -TIP: Spring Framework 5.0 provides a new `WebTestClient` that works for -<> and both -<>. It provides a fluent API for assertions, -unlike `TestRestTemplate`. - - -`TestRestTemplate` is a convenience alternative to Spring's `RestTemplate` that is useful -in integration tests. You can get a vanilla template or one that sends Basic HTTP -authentication (with a username and password). In either case, the template behaves in a -test-friendly way by not throwing exceptions on server-side errors. It is recommended, -but not mandatory, to use the Apache HTTP Client (version 4.3.2 or better). If you have -that on your classpath, the `TestRestTemplate` responds by configuring the client -appropriately. If you do use Apache's HTTP client, some additional test-friendly features -are enabled: - -* Redirects are not followed (so you can assert the response location). -* Cookies are ignored (so the template is stateless). - -`TestRestTemplate` can be instantiated directly in your integration tests, as shown in -the following example: - -[source,java,indent=0] ----- - public class MyTest { - - private TestRestTemplate template = new TestRestTemplate(); - - @Test - public void testRequest() throws Exception { - HttpHeaders headers = this.template.getForEntity( - "https://myhost.example.com/example", String.class).getHeaders(); - assertThat(headers.getLocation()).hasHost("other.example.com"); - } - - } ----- - -Alternatively, if you use the `@SpringBootTest` annotation with -`WebEnvironment.RANDOM_PORT` or `WebEnvironment.DEFINED_PORT`, you can inject a -fully configured `TestRestTemplate` and start using it. If necessary, additional -customizations can be applied through the `RestTemplateBuilder` bean. Any URLs that do -not specify a host and port automatically connect to the embedded server, as shown in the -following example: - -[source,java,indent=0] ----- -include::{test-examples}/web/client/SampleWebClientTests.java[tag=test] ----- - - - -[[boot-features-websockets]] -== WebSockets -Spring Boot provides WebSockets auto-configuration for embedded Tomcat, Jetty, and -Undertow. If you deploy a war file to a standalone container, Spring Boot assumes that the -container is responsible for the configuration of its WebSocket support. - -Spring Framework provides {spring-reference}web.html#websocket[rich WebSocket support] -for MVC web applications that can be easily accessed through the -`spring-boot-starter-websocket` module. - -WebSocket support is also available for -{spring-reference}web-reactive.html#webflux-websocket[reactive web applications] and -requires to include the WebSocket API alongside `spring-boot-starter-webflux`: - -[source,xml,indent=0,subs="verbatim,quotes,attributes"] ----- - - javax.websocket - javax.websocket-api - ----- - - - -[[boot-features-webservices]] -== Web Services -Spring Boot provides Web Services auto-configuration so that all you must do is define -your `Endpoints`. - -The {spring-webservices-reference}[Spring Web Services features] can be easily accessed -with the `spring-boot-starter-webservices` module. - -`SimpleWsdl11Definition` and `SimpleXsdSchema` beans can be automatically created for -your WSDLs and XSDs respectively. To do so, configure their location, as shown in the -following example: - - -[source,properties,indent=0] ----- - spring.webservices.wsdl-locations=classpath:/wsdl ----- - - - -[[boot-features-webservices-template]] -=== Calling Web Services with `WebServiceTemplate` -If you need to call remote Web services from your application, you can use the -{spring-webservices-reference}#client-web-service-template[`WebServiceTemplate`] class. -Since `WebServiceTemplate` instances often need to be customized before being used, Spring -Boot does not provide any single auto-configured `WebServiceTemplate` bean. It does, -however, auto-configure a `WebServiceTemplateBuilder`, which can be used to create -`WebServiceTemplate` instances when needed. - -The following code shows a typical example: - -[source,java,indent=0] ----- - @Service - public class MyService { - - private final WebServiceTemplate webServiceTemplate; - - public MyService(WebServiceTemplateBuilder webServiceTemplateBuilder) { - this.webServiceTemplate = webServiceTemplateBuilder.build(); - } - - public DetailsResp someWsCall(DetailsReq detailsReq) { - return (DetailsResp) this.webServiceTemplate.marshalSendAndReceive(detailsReq, new SoapActionCallback(ACTION)); - - } - - } ----- - -By default, `WebServiceTemplateBuilder` detects a suitable HTTP-based -`WebServiceMessageSender` using the available HTTP client libraries on the classpath. You -can also customize read and connection timeouts as follows: - -[source,java,indent=0] ----- - @Bean - public WebServiceTemplate webServiceTemplate(WebServiceTemplateBuilder builder) { - return builder.messageSenders(new HttpWebServiceMessageSenderBuilder() - .setConnectTimeout(5000).setReadTimeout(2000).build()).build(); - } ----- - - - -[[boot-features-developing-auto-configuration]] -== Creating Your Own Auto-configuration -If you work in a company that develops shared libraries, or if you work on an open-source -or commercial library, you might want to develop your own auto-configuration. -Auto-configuration classes can be bundled in external jars and still be picked-up by -Spring Boot. - -Auto-configuration can be associated to a "`starter`" that provides the auto-configuration -code as well as the typical libraries that you would use with it. We first cover what -you need to know to build your own auto-configuration and then we move on to the -<>. - -TIP: A https://github.com/snicoll-demos/spring-boot-master-auto-configuration[demo -project] is available to showcase how you can create a starter step-by-step. - - - -[[boot-features-understanding-auto-configured-beans]] -=== Understanding Auto-configured Beans -Under the hood, auto-configuration is implemented with standard `@Configuration` classes. -Additional `@Conditional` annotations are used to constrain when the auto-configuration -should apply. Usually, auto-configuration classes use `@ConditionalOnClass` and -`@ConditionalOnMissingBean` annotations. This ensures that auto-configuration applies -only when relevant classes are found and when you have not declared your own -`@Configuration`. - -You can browse the source code of {sc-spring-boot-autoconfigure}[`spring-boot-autoconfigure`] -to see the `@Configuration` classes that Spring provides (see the -{github-code}/spring-boot-project/spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories[`META-INF/spring.factories`] -file). - - - -[[boot-features-locating-auto-configuration-candidates]] -=== Locating Auto-configuration Candidates -Spring Boot checks for the presence of a `META-INF/spring.factories` file within your -published jar. The file should list your configuration classes under the -`EnableAutoConfiguration` key, as shown in the following example: - -[indent=0] ----- - org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ - com.mycorp.libx.autoconfigure.LibXAutoConfiguration,\ - com.mycorp.libx.autoconfigure.LibXWebAutoConfiguration ----- - -[NOTE] -==== -Auto-configurations must be loaded that way _only_. Make sure that they are defined in -a specific package space and that they are never the target of component scanning. -Furthermore, auto-configuration classes should not enable component scanning to find -additional components. Specific ``@Import``s should be used instead. -==== - -You can use the -{sc-spring-boot-autoconfigure}/AutoConfigureAfter.{sc-ext}[`@AutoConfigureAfter`] or -{sc-spring-boot-autoconfigure}/AutoConfigureBefore.{sc-ext}[`@AutoConfigureBefore`] -annotations if your configuration needs to be applied in a specific order. For example, -if you provide web-specific configuration, your class may need to be applied after -`WebMvcAutoConfiguration`. - -If you want to order certain auto-configurations that should not have any direct -knowledge of each other, you can also use `@AutoConfigureOrder`. That annotation has the -same semantic as the regular `@Order` annotation but provides a dedicated order for -auto-configuration classes. - - - -[[boot-features-condition-annotations]] -=== Condition Annotations -You almost always want to include one or more `@Conditional` annotations on your -auto-configuration class. The `@ConditionalOnMissingBean` annotation is one common -example that is used to allow developers to override auto-configuration if they are -not happy with your defaults. - -Spring Boot includes a number of `@Conditional` annotations that you can reuse in your -own code by annotating `@Configuration` classes or individual `@Bean` methods. These -annotations include: - -* <> -* <> -* <> -* <> -* <> -* <> - - -[[boot-features-class-conditions]] -==== Class Conditions -The `@ConditionalOnClass` and `@ConditionalOnMissingClass` annotations let -`@Configuration` classes be included based on the presence or absence of specific classes. -Due to the fact that annotation metadata is parsed by using https://asm.ow2.org/[ASM], you -can use the `value` attribute to refer to the real class, even though that class might not -actually appear on the running application classpath. You can also use the `name` -attribute if you prefer to specify the class name by using a `String` value. - -This mechanism does not apply the same way to `@Bean` methods where typically the return -type is the target of the condition: before the condition on the method applies, the JVM -will have loaded the class and potentially processed method references which will fail if -the class is not present. - -To handle this scenario, a separate `@Configuration` class can be used to isolate the -condition, as shown in the following example: - -[source,java,indent=0] ----- - @Configuration(proxyBeanMethods = false) - // Some conditions - public class MyAutoConfiguration { - - // Auto-configured beans - - @Configuration(proxyBeanMethods = false) - @ConditionalOnClass(EmbeddedAcmeService.class) - static class EmbeddedConfiguration { - - @Bean - @ConditionalOnMissingBean - public EmbeddedAcmeService embeddedAcmeService() { ... } - - } - - } ----- - -[TIP] -==== -If you use `@ConditionalOnClass` or `@ConditionalOnMissingClass` as a part of a -meta-annotation to compose your own composed annotations, you must use `name` as referring -to the class in such a case is not handled. -==== - - - -[[boot-features-bean-conditions]] -==== Bean Conditions -The `@ConditionalOnBean` and `@ConditionalOnMissingBean` annotations let a bean be -included based on the presence or absence of specific beans. You can use the `value` -attribute to specify beans by type or `name` to specify beans by name. The `search` -attribute lets you limit the `ApplicationContext` hierarchy that should be considered -when searching for beans. - -When placed on a `@Bean` method, the target type defaults to the return type of the -method, as shown in the following example: - -[source,java,indent=0] ----- - @Configuration(proxyBeanMethods = false) - public class MyAutoConfiguration { - - @Bean - @ConditionalOnMissingBean - public MyService myService() { ... } - - } ----- - -In the preceding example, the `myService` bean is going to be created if no bean of type -`MyService` is already contained in the `ApplicationContext`. - -TIP: You need to be very careful about the order in which bean definitions are added, as -these conditions are evaluated based on what has been processed so far. For this reason, -we recommend using only `@ConditionalOnBean` and `@ConditionalOnMissingBean` annotations -on auto-configuration classes (since these are guaranteed to load after any user-defined -bean definitions have been added). - -NOTE: `@ConditionalOnBean` and `@ConditionalOnMissingBean` do not prevent `@Configuration` -classes from being created. The only difference between using these conditions at the class level -and marking each contained `@Bean` method with the annotation is that the former prevents -registration of the `@Configuration` class as a bean if the condition does not match. - - - -[[boot-features-property-conditions]] -==== Property Conditions -The `@ConditionalOnProperty` annotation lets configuration be included based on a Spring -Environment property. Use the `prefix` and `name` attributes to specify the property that -should be checked. By default, any property that exists and is not equal to `false` is -matched. You can also create more advanced checks by using the `havingValue` and -`matchIfMissing` attributes. - - - -[[boot-features-resource-conditions]] -==== Resource Conditions -The `@ConditionalOnResource` annotation lets configuration be included only when a -specific resource is present. Resources can be specified by using the usual Spring -conventions, as shown in the following example: `file:/home/user/test.dat`. - - - -[[boot-features-web-application-conditions]] -==== Web Application Conditions -The `@ConditionalOnWebApplication` and `@ConditionalOnNotWebApplication` annotations let -configuration be included depending on whether the application is a "`web application`". -A web application is any application that uses a Spring `WebApplicationContext`, -defines a `session` scope, or has a `StandardServletEnvironment`. - - - -[[boot-features-spel-conditions]] -==== SpEL Expression Conditions -The `@ConditionalOnExpression` annotation lets configuration be included based on the -result of a {spring-reference}core.html#expressions[SpEL expression]. - - - -[[boot-features-test-autoconfig]] -=== Testing your Auto-configuration -An auto-configuration can be affected by many factors: user configuration (`@Bean` -definition and `Environment` customization), condition evaluation (presence of a -particular library), and others. Concretely, each test should create a well defined -`ApplicationContext` that represents a combination of those customizations. -`ApplicationContextRunner` provides a great way to achieve that. - -`ApplicationContextRunner` is usually defined as a field of the test class to gather the -base, common configuration. The following example makes sure that -`UserServiceAutoConfiguration` is always invoked: - -[source,java,indent=0] ----- -include::{test-examples}/autoconfigure/UserServiceAutoConfigurationTests.java[tag=runner] ----- - -TIP: If multiple auto-configurations have to be defined, there is no need to order their -declarations as they are invoked in the exact same order as when running the -application. - -Each test can use the runner to represent a particular use case. For instance, the sample -below invokes a user configuration (`UserConfiguration`) and checks that the -auto-configuration backs off properly. Invoking `run` provides a callback context that can -be used with `Assert4J`. - -[source,java,indent=0] ----- -include::{test-examples}/autoconfigure/UserServiceAutoConfigurationTests.java[tag=test-user-config] ----- - -It is also possible to easily customize the `Environment`, as shown in the following -example: - -[source,java,indent=0] ----- -include::{test-examples}/autoconfigure/UserServiceAutoConfigurationTests.java[tag=test-env] ----- - -The runner can also be used to display the `ConditionEvaluationReport`. The report can be printed -at `INFO` or `DEBUG` level. The following example shows how to use the `ConditionEvaluationReportLoggingListener` -to print the report in auto-configuration tests. - -[source,java,indent=0] ----- - @Test - public void autoConfigTest { - ConditionEvaluationReportLoggingListener initializer = new ConditionEvaluationReportLoggingListener( - LogLevel.INFO); - ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withInitializer(initializer).run((context) -> { - // Do something... - }); - } ----- - - - -==== Simulating a Web Context -If you need to test an auto-configuration that only operates in a Servlet or Reactive web -application context, use the `WebApplicationContextRunner` or -`ReactiveWebApplicationContextRunner` respectively. - - - -==== Overriding the Classpath -It is also possible to test what happens when a particular class and/or package is not -present at runtime. Spring Boot ships with a `FilteredClassLoader` that can easily be used -by the runner. In the following example, we assert that if `UserService` is not present, the -auto-configuration is properly disabled: - -[source,java,indent=0] ----- -include::{test-examples}/autoconfigure/UserServiceAutoConfigurationTests.java[tag=test-classloader] ----- - - - -[[boot-features-custom-starter]] -=== Creating Your Own Starter -A full Spring Boot starter for a library may contain the following components: - -* The `autoconfigure` module that contains the auto-configuration code. -* The `starter` module that provides a dependency to the `autoconfigure` module as well -as the library and any additional dependencies that are typically useful. In a nutshell, -adding the starter should provide everything needed to start using that library. - -TIP: You may combine the auto-configuration code and the dependency management in a -single module if you do not need to separate those two concerns. - - - -[[boot-features-custom-starter-naming]] -==== Naming -You should make sure to provide a proper namespace for your starter. Do not start your -module names with `spring-boot`, even if you use a different Maven `groupId`. We may -offer official support for the thing you auto-configure in the future. - -As a rule of thumb, you should name a combined module after the starter. For example, -assume that you are creating a starter for "acme" and that you name the auto-configure -module `acme-spring-boot-autoconfigure` and the starter `acme-spring-boot-starter`. If -you only have one module that combines the two, name it `acme-spring-boot-starter`. - -Also, if your starter provides configuration keys, use a unique namespace for them. In -particular, do not include your keys in the namespaces that Spring Boot uses (such as -`server`, `management`, `spring`, and so on). If you use the same namespace, we may modify -these namespaces in the future in ways that break your modules. - -Make sure to -<> so that IDE assistance is available for your keys as well. You may want to -review the generated meta-data (`META-INF/spring-configuration-metadata.json`) to make -sure your keys are properly documented. - - - -[[boot-features-custom-starter-module-autoconfigure]] -==== `autoconfigure` Module -The `autoconfigure` module contains everything that is necessary to get started with the -library. It may also contain configuration key definitions (such as -`@ConfigurationProperties`) and any callback interface that can be used to further -customize how the components are initialized. - -TIP: You should mark the dependencies to the library as optional so that you can include -the `autoconfigure` module in your projects more easily. If you do it that way, the -library is not provided and, by default, Spring Boot backs off. - -Spring Boot uses an annotation processor to collect the conditions on auto-configurations -in a metadata file (`META-INF/spring-autoconfigure-metadata.properties`). If that file is -present, it is used to eagerly filter auto-configurations that do not match, which will -improve startup time. It is recommended to add the following dependency in a module that -contains auto-configurations: - -[source,xml,indent=0,subs="verbatim,quotes,attributes"] ----- - - org.springframework.boot - spring-boot-autoconfigure-processor - true - ----- - -With Gradle 4.5 and earlier, the dependency should be declared in the `compileOnly` -configuration, as shown in the following example: - -[source,groovy,indent=0,subs="verbatim,quotes,attributes"] ----- - dependencies { - compileOnly "org.springframework.boot:spring-boot-autoconfigure-processor" - } ----- - -With Gradle 4.6 and later, the dependency should be declared in the `annotationProcessor` -configuration, as shown in the following example: - -[source,groovy,indent=0,subs="verbatim,quotes,attributes"] ----- - dependencies { - annotationProcessor "org.springframework.boot:spring-boot-autoconfigure-processor" - } ----- - - - -[[boot-features-custom-starter-module-starter]] -==== Starter Module -The starter is really an empty jar. Its only purpose is to provide the necessary -dependencies to work with the library. You can think of it as an opinionated view of what -is required to get started. - -Do not make assumptions about the project in which your starter is added. If the library -you are auto-configuring typically requires other starters, mention them as well. -Providing a proper set of _default_ dependencies may be hard if the number of optional -dependencies is high, as you should avoid including dependencies that are unnecessary for -a typical usage of the library. In other words, you should not include optional -dependencies. - -NOTE: Either way, your starter must reference the core Spring Boot starter -(`spring-boot-starter`) directly or indirectly (i.e. no need to add it if your starter -relies on another starter). If a project is created with only your custom starter, Spring -Boot's core features will be honoured by the presence of the core starter. - - - -[[boot-features-kotlin]] -== Kotlin support -https://kotlinlang.org[Kotlin] is a statically-typed language targeting the JVM (and other -platforms) which allows writing concise and elegant code while providing -{kotlin-documentation}java-interop.html[interoperability] with existing libraries written -in Java. - -Spring Boot provides Kotlin support by leveraging the support in other Spring projects -such as Spring Framework, Spring Data, and Reactor. See the -{spring-reference}languages.html#kotlin[Spring Framework Kotlin support documentation] -for more information. - -The easiest way to start with Spring Boot and Kotlin is to follow -https://spring.io/guides/tutorials/spring-boot-kotlin/[this comprehensive tutorial]. You -can create new Kotlin projects via -https://start.spring.io/#!language=kotlin[start.spring.io]. Feel free to join the #spring -channel of https://slack.kotlinlang.org/[Kotlin Slack] or ask a question with the `spring` -and `kotlin` tags on https://stackoverflow.com/questions/tagged/spring+kotlin[Stack -Overflow] if you need support. - - - -[[boot-features-kotlin-requirements]] -=== Requirements -Spring Boot supports Kotlin 1.3.x. To use Kotlin, `org.jetbrains.kotlin:kotlin-stdlib` and -`org.jetbrains.kotlin:kotlin-reflect` must be present on the classpath. The -`kotlin-stdlib` variants `kotlin-stdlib-jdk7` and `kotlin-stdlib-jdk8` can also be used. - -Since https://discuss.kotlinlang.org/t/classes-final-by-default/166[Kotlin classes are -final by default], you are likely to want to configure -{kotlin-documentation}compiler-plugins.html#spring-support[kotlin-spring] -plugin in order to automatically open Spring-annotated classes so that they can be -proxied. - -https://github.com/FasterXML/jackson-module-kotlin[Jackson's Kotlin module] is required -for serializing / deserializing JSON data in Kotlin. It is automatically registered when -found on the classpath. A warning message is logged if Jackson and Kotlin are present but -the Jackson Kotlin module is not. - -TIP: These dependencies and plugins are provided by default if one bootstraps a Kotlin -project on https://start.spring.io/#!language=kotlin[start.spring.io]. - - - -[[boot-features-kotlin-null-safety]] -=== Null-safety -One of Kotlin's key features is {kotlin-documentation}null-safety.html[null-safety]. It -deals with `null` values at compile time rather than deferring the problem to runtime and -encountering a `NullPointerException`. This helps to eliminate a common source of bugs -without paying the cost of wrappers like `Optional`. Kotlin also allows using functional -constructs with nullable values as described in this -https://www.baeldung.com/kotlin-null-safety[comprehensive guide to null-safety in Kotlin]. - -Although Java does not allow one to express null-safety in its type system, Spring -Framework, Spring Data, and Reactor now provide null-safety of their API via -tooling-friendly annotations. By default, types from Java APIs used in Kotlin are -recognized as -{kotlin-documentation}java-interop.html#null-safety-and-platform-types[platform types] -for which null-checks are relaxed. -{kotlin-documentation}java-interop.html#jsr-305-support[Kotlin's support for JSR 305 -annotations] combined with nullability annotations provide null-safety for the related -Spring API in Kotlin. - -The JSR 305 checks can be configured by adding the `-Xjsr305` compiler flag with the -following options: `-Xjsr305={strict|warn|ignore}`. The default behavior is the same as -`-Xjsr305=warn`. The `strict` value is required to have null-safety taken in account in -Kotlin types inferred from Spring API but should be used with the knowledge that Spring -API nullability declaration could evolve even between minor releases and more checks may -be added in the future). - -WARNING: Generic type arguments, varargs and array elements nullability are not yet -supported. See https://jira.spring.io/browse/SPR-15942[SPR-15942] for up-to-date -information. Also be aware that Spring Boot's own API is {github-issues}10712[not yet -annotated]. - - - -[[boot-features-kotlin-api]] -=== Kotlin API - - - -[[boot-features-kotlin-api-runapplication]] -==== runApplication -Spring Boot provides an idiomatic way to run an application with -`runApplication(*args)` as shown in the following example: - -[source,kotlin,indent=0] ----- -import org.springframework.boot.autoconfigure.SpringBootApplication -import org.springframework.boot.runApplication - -@SpringBootApplication -class MyApplication - -fun main(args: Array) { - runApplication(*args) -} ----- - -This is a drop-in replacement for -`SpringApplication.run(MyApplication::class.java, *args)`. It also allows customization -of the application as shown in the following example: - -[source,kotlin,indent=0] ----- -runApplication(*args) { - setBannerMode(OFF) -} ----- - - - -[[boot-features-kotlin-api-extensions]] -==== Extensions -Kotlin {kotlin-documentation}extensions.html[extensions] provide the ability -to extend existing classes with additional functionality. The Spring Boot Kotlin API makes -use of these extensions to add new Kotlin specific conveniences to existing APIs. - -`TestRestTemplate` extensions, similar to those provided by Spring Framework for -`RestOperations` in Spring Framework, are provided. Among other things, the extensions -make it possible to take advantage of Kotlin reified type parameters. - - - -[[boot-features-kotlin-dependency-management]] -=== Dependency management -In order to avoid mixing different versions of Kotlin dependencies on the classpath, -Spring Boot imports the Kotlin BOM. - -With Maven, the Kotlin version can be customized via the `kotlin.version` property and -plugin management is provided for `kotlin-maven-plugin`. With Gradle, the Spring Boot -plugin automatically aligns the `kotlin.version` with the version of the Kotlin plugin. - - - -[[boot-features-kotlin-configuration-properties]] -=== `@ConfigurationProperties` -`@ConfigurationProperties` supports classes with immutable `val` properties as shown in -the following example: - -[source,kotlin,indent=0] ----- -@ConfigurationProperties("example.kotlin") -data class KotlinExampleProperties( - val name: String, - val description: String, - val myService: MyService -) - -data class MyService( - val apiToken: String, - val uri: URI -) ----- - -TIP: To generate <> using the annotation processor, {kotlin-documentation}kapt.html[`kapt` should -be configured] with the `spring-boot-configuration-processor` dependency. Note that some -features (such as detecting the default value or deperecated items) are not working due -to limitations in the model kapt provides. - - -[[boot-features-kotlin-testing]] -=== Testing -While it is possible to use JUnit 4 to test Kotlin code, JUnit 5 is recommended. JUnit 5 -enables a test class to be instantiated once and reused for all of the class's tests. This -makes it possible to use `@BeforeClass` and `@AfterClass` annotations on non-static -methods, which is a good fit for Kotlin. - -JUnit 5 is the default and the vintage engine is provided for backward compatibility with -JUnit 4. If you don't use it, exclude `org.junit.vintange:junit-vintage-engine`. See the -{junit5-documentation}/#dependency-metadata-junit-jupiter-samples[JUnit 5 documentation] -for more details. You also need to -{junit5-documentation}/#writing-tests-test-instance-lifecycle-changing-default[switch test -instance lifecycle to "per-class"]. - -To mock Kotlin classes, https://mockk.io/[MockK] is recommended. If you need the `Mockk` -equivalent of the Mockito specific -<>, you can use https://github.com/Ninja-Squad/springmockk[SpringMockK] which -provides similar `@MockkBean` and `@SpykBean` annotations. - - - -[[boot-features-kotlin-resources]] -=== Resources - - - -[[boot-features-kotlin-resources-further-reading]] -==== Further reading -* {kotlin-documentation}[Kotlin language reference] -* https://slack.kotlinlang.org/[Kotlin Slack] (with a dedicated #spring channel) -* https://stackoverflow.com/questions/tagged/spring+kotlin[Stackoverflow with `spring` and `kotlin` tags] -* https://try.kotlinlang.org/[Try Kotlin in your browser] -* https://blog.jetbrains.com/kotlin/[Kotlin blog] -* https://kotlin.link/[Awesome Kotlin] -* https://spring.io/guides/tutorials/spring-boot-kotlin/[Tutorial: building web applications with Spring Boot and Kotlin] -* https://spring.io/blog/2016/02/15/developing-spring-boot-applications-with-kotlin[Developing Spring Boot applications with Kotlin] -* https://spring.io/blog/2016/03/20/a-geospatial-messenger-with-kotlin-spring-boot-and-postgresql[A Geospatial Messenger with Kotlin, Spring Boot and PostgreSQL] -* https://spring.io/blog/2017/01/04/introducing-kotlin-support-in-spring-framework-5-0[Introducing Kotlin support in Spring Framework 5.0] -* https://spring.io/blog/2017/08/01/spring-framework-5-kotlin-apis-the-functional-way[Spring Framework 5 Kotlin APIs, the functional way] - - - -[[boot-features-kotlin-resources-examples]] -==== Examples - -* https://github.com/sdeleuze/spring-boot-kotlin-demo[spring-boot-kotlin-demo]: regular Spring Boot + Spring Data JPA project -* https://github.com/mixitconf/mixit[mixit]: Spring Boot 2 + WebFlux + Reactive Spring Data MongoDB -* https://github.com/sdeleuze/spring-kotlin-fullstack[spring-kotlin-fullstack]: WebFlux Kotlin fullstack example with Kotlin2js for frontend instead of JavaScript or TypeScript -* https://github.com/spring-petclinic/spring-petclinic-kotlin[spring-petclinic-kotlin]: Kotlin version of the Spring PetClinic Sample Application -* https://github.com/sdeleuze/spring-kotlin-deepdive[spring-kotlin-deepdive]: a step by step migration for Boot 1.0 + Java to Boot 2.0 + Kotlin - - - -[[boot-features-whats-next]] +[[features-whats-next]] == What to Read Next -If you want to learn more about any of the classes discussed in this section, you can -check out the {dc-root}[Spring Boot API documentation] or you can browse the +If you want to learn more about any of the classes discussed in this section, you can browse the {github-code}[source code directly]. If you have specific questions, take a look at the <> section. -If you are comfortable with Spring Boot's core features, you can continue on and read -about <>. +If you are comfortable with {project-full-name}'s core features, you can continue on and read +about ... diff --git a/docs/src/main/asciidoc/using.adoc b/docs/src/main/asciidoc/using.adoc index 113f1153c6..81ba85c51e 100644 --- a/docs/src/main/asciidoc/using.adoc +++ b/docs/src/main/asciidoc/using.adoc @@ -1,1152 +1,269 @@ -[[using-boot]] -= Using Spring Boot +[[using]] += Using Spring Cloud Contract include::_attributes.adoc[] -This section goes into more detail about how you should use Spring Boot. It covers topics -such as build systems, auto-configuration, and how to run your applications. We also -cover some Spring Boot best practices. Although there is nothing particularly special -about Spring Boot (it is just another library that you can consume), there are a few -recommendations that, when followed, make your development process a little easier. +This section goes into more detail about how you should use {project-full-name}. It covers topics +such as description of flows of how to work with {{project-full-name}}. We also +cover some {{project-full-name}} best practices. -If you are starting out with Spring Boot, you should probably read the +If you are starting out with {project-full-name}, you should probably read the _<>_ guide before diving into this section. +[[flows-provider-nexus]] +== Provider contract testing with stubs in Nexus / Artifactory +You can check the <> link to see the provider contract testing with stubs in Nexus / Artifactory flow. -[[using-boot-build-systems]] -== Build Systems -It is strongly recommended that you choose a build system that supports -<> and that can consume -artifacts published to the "`Maven Central`" repository. We would recommend that you -choose Maven or Gradle. It is possible to get Spring Boot to work with other build -systems (Ant, for example), but they are not particularly well supported. +You can also check the https://cloud-samples.spring.io/spring-cloud-contract-samples/tutorials/contracts_on_the_producer_side.html[workshop page] for a step by step instruction on how to do this flow. +[[flows-provider-git]] +== Provider contract testing with stubs in Git +[[flows-cdc-contracts-producer]] +== Consumer Driven Contracts with contracts on the producer side -[[using-boot-dependency-management]] -=== Dependency Management -Each release of Spring Boot provides a curated list of dependencies that it supports. In -practice, you do not need to provide a version for any of these dependencies in your -build configuration, as Spring Boot manages that for you. When you upgrade Spring -Boot itself, these dependencies are upgraded as well in a consistent way. +You can check the <> link to see the Consumer Driven Contracts with contracts on the producer side flow. -NOTE: You can still specify a version and override Spring Boot's recommendations if you -need to do so. +[[flows-cdc-contracts-external]] +== Consumer Driven Contracts with contracts in external repo -The curated list contains all the spring modules that you can use with Spring Boot as -well as a refined list of third party libraries. The list is available as a standard -<> -that can be used with both <> and -<>. +In this flow, we will perform Consumer Driven Contract testing. The contract definitions will be stored in a separate repository. -WARNING: Each release of Spring Boot is associated with a base version of the Spring -Framework. We **highly** recommend that you not specify its version. +You can check the https://cloud-samples.spring.io/spring-cloud-contract-samples/tutorials/contracts_on_the_producer_side.html[workshop page] for a step by step instruction on how to do this flow. +Prerequisites: +* Git repository that +** will contain all the contract defintiions for each producer +** can package the contract definitions in a JAR +** for each contract producer contains a way (e.g. `pom.xml`) to install stubs locally via the Spring Cloud Contract Plugin (SCC Plugin) +** for more information please visit the <> where we describe how to set up such a repository +** for an example of such a project you can {samples_code}/beer_contracts[check the samples] +* Consumer code that has Spring Cloud Contract Stub Runner setup +** for an example of such a project you can {samples_code}/consumer[check the samples] +* Producer code that has Spring Cloud Contract setup together with a plugin +** for an example of such a project you can {samples_code}/producer_with_external_contracts[check the samples] -[[using-boot-maven]] -=== Maven -Maven users can inherit from the `spring-boot-starter-parent` project to obtain sensible -defaults. The parent project provides the following features: +At a high level the flow looks as follows: -* Java 1.8 as the default compiler level. -* UTF-8 source encoding. -* A <>, inherited from -the spring-boot-dependencies pom, that manages the versions of common dependencies. This -dependency management lets you omit tags for those dependencies when used in -your own pom. -* An execution of the {spring-boot-maven-plugin-site}/repackage-mojo.html[`repackage` -goal] with a `repackage` execution id. -* Sensible -https://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html[resource -filtering]. -* Sensible plugin configuration (https://www.mojohaus.org/exec-maven-plugin/[exec plugin], -https://github.com/ktoso/maven-git-commit-id-plugin[Git commit ID], and -https://maven.apache.org/plugins/maven-shade-plugin/[shade]). -* Sensible resource filtering for `application.properties` and `application.yml` -including profile-specific files (for example, `application-dev.properties` and -`application-dev.yml`) +* Consumer works with the contract definitions from the separate repository +* Once the consumer's work is done, a branch with working code is done on the consumer side and a pull request is made to the separate repository with contract definitions +* Producer takes over the pull request to the separate repository with contract definitions and installs the JAR with all contracts locally +* Producer generates tests from the locally stored JAR and writes the missing implementation to make the tests pass +* Once the producer's work is done, the pull request to the repository with contract definitions is merged. +* After the CI tool builds the repository with contract definitions and the JAR with contract definitions gets uploaded to Nexus / Artifactory, the producer can merge their branch +* Finally the consumer can switch to working online to fetch stubs of the producer from a remote location and the branch can be merged to master -Note that, since the `application.properties` and `application.yml` files accept Spring -style placeholders (`${...}`), the Maven filtering is changed to use `@..@` placeholders. -(You can override that by setting a Maven property called `resource.delimiter`.) +[[flows-cdc-contracts-external-consumer]] +=== Consumer Flow +As a consumer +* write a test that would send a request to the producer +** the test will fail due to no server being present +* clone the repository with contract definitions +* set up the your requirements as contract under the folder with your consumer name as a subfolder of the producer. E.g. for a producer `producer` and consumer `consumer` the contracts would be stored under `src/main/resources/contracts/producer/consumer/`) +* once the contracts are defined, install the producer stubs to your local storage e.g. ++ +``` +$ cd src/main/resource/contracts/producer +$ ./mvnw clean install +``` +* setup Spring Cloud Contract (SCC) Stub Runner in your tests +** to fetch the producer stubs from your local storage +** to work in the `stubs per consumer` mode (this enables Consumer Driven Contracts mode) +* SCC Stub Runner will +** fetch the producer stubs +** run an in memory HTTP server stub with the producer stubs +* Now your test communicates with the HTTP server stub and your tests pass +* Create a pull request to the repository with contract definitions, with the new contracts for the producer +* Branch your consumer code, until the producer team has merged their code -[[using-boot-maven-parent-pom]] -==== Inheriting the Starter Parent -To configure your project to inherit from the `spring-boot-starter-parent`, set the -`parent` as follows: - -[source,xml,indent=0,subs="verbatim,quotes,attributes"] +[plantuml, flow-overview-consumer-cdc-external-consumer, png] ---- - - - org.springframework.boot - spring-boot-starter-parent - {spring-boot-version} - +"Consumer"->"Repo\nwith\ncontracts": clone +"Repo\nwith\ncontracts"->"Repo\nwith\ncontracts\nclone": cloned +"Consumer"->"Repo\nwith\ncontracts\nclone": create contract\ndefinitions of\nthe [Producer] +"Repo\nwith\ncontracts\nclone"->"Local storage": install [Producer]\nstubs locally +"Consumer"->"Consumer\nBuild": run tests +"Consumer\nBuild"->"SCC\nStub Runner": Run [Producer] stubs +"SCC\nStub Runner"->"Local storage": fetch [Producer] stubs +"SCC\nStub Runner"->"Producer stub": stub is running +"Consumer\nBuild"->"Producer stub": send a request\nin the tests +"Producer stub"->"Consumer\nBuild": send a response +"Consumer\nBuild"->"Consumer": the tests are passing +"Consumer"->"Repo\nwith\ncontracts\nclone": send a pull request +"Repo\nwith\ncontracts\nclone"->"Repo\nwith\ncontracts": pull request sent +"Consumer"->"Consumer": branch the code ---- -NOTE: You should need to specify only the Spring Boot version number on this dependency. -If you import additional starters, you can safely omit the version number. - -With that setup, you can also override individual dependencies by overriding a property -in your own project. For instance, to upgrade to another Spring Data release train, you -would add the following to your `pom.xml`: - -[source,xml,indent=0,subs="verbatim,quotes,attributes"] ----- - - Fowler-SR2 - ----- - -TIP: Check the -{github-code}/spring-boot-project/spring-boot-dependencies/pom.xml[`spring-boot-dependencies` pom] -for a list of supported properties. - - - -[[using-boot-maven-without-a-parent]] -==== Using Spring Boot without the Parent POM -Not everyone likes inheriting from the `spring-boot-starter-parent` POM. You may have -your own corporate standard parent that you need to use or you may prefer to explicitly -declare all your Maven configuration. - -If you do not want to use the `spring-boot-starter-parent`, you can still keep the -benefit of the dependency management (but not the plugin management) by using a -`scope=import` dependency, as follows: - -[source,xml,indent=0,subs="verbatim,quotes,attributes"] ----- - - - - - org.springframework.boot - spring-boot-dependencies - {spring-boot-version} - pom - import - - - ----- - -The preceding sample setup does not let you override individual dependencies by using a -property, as explained above. To achieve the same result, you need to add an entry in the -`dependencyManagement` of your project **before** the `spring-boot-dependencies` entry. -For instance, to upgrade to another Spring Data release train, you could add the -following element to your `pom.xml`: - -[source,xml,indent=0,subs="verbatim,quotes,attributes"] ----- - - - - - org.springframework.data - spring-data-releasetrain - Fowler-SR2 - pom - import - - - org.springframework.boot - spring-boot-dependencies - {spring-boot-version} - pom - import - - - ----- - -NOTE: In the preceding example, we specify a _BOM_, but any dependency type can be -overridden in the same way. - - - -[[using-boot-maven-plugin]] -==== Using the Spring Boot Maven Plugin -Spring Boot includes a <> that can package the project as an executable jar. Add the plugin to your -`` section if you want to use it, as shown in the following example: - -[source,xml,indent=0,subs="verbatim,quotes,attributes"] ----- - - - - org.springframework.boot - spring-boot-maven-plugin - - - ----- - -NOTE: If you use the Spring Boot starter parent pom, you need to add only the plugin. -There is no need to configure it unless you want to change the settings defined in the -parent. - - - -[[using-boot-gradle]] -=== Gradle -To learn about using Spring Boot with Gradle, please refer to the documentation for -Spring Boot's Gradle plugin: - -* Reference ({spring-boot-gradle-plugin}/reference/html[HTML] and -{spring-boot-gradle-plugin}/reference/pdf/spring-boot-gradle-plugin-reference.pdf[PDF]) -* {spring-boot-gradle-plugin}/api[API] - -[[using-boot-ant]] -=== Ant -It is possible to build a Spring Boot project using Apache Ant+Ivy. The -`spring-boot-antlib` "`AntLib`" module is also available to help Ant create executable -jars. - -To declare dependencies, a typical `ivy.xml` file looks something like the following -example: - -[source,xml,indent=0] ----- - - - - - - - - - - ----- - -A typical `build.xml` looks like the following example: - -[source,xml,indent=0,subs="verbatim,quotes,attributes"] ----- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ----- - -TIP: If you do not want to use the `spring-boot-antlib` module, see the -_<>_ "`How-to`" . - - - -[[using-boot-starter]] -=== Starters -Starters are a set of convenient dependency descriptors that you can include in your -application. You get a one-stop shop for all the Spring and related technologies that you -need without having to hunt through sample code and copy-paste loads of dependency -descriptors. For example, if you want to get started using Spring and JPA for database -access, include the `spring-boot-starter-data-jpa` dependency in your project. - -The starters contain a lot of the dependencies that you need to get a project up and -running quickly and with a consistent, supported set of managed transitive dependencies. - -.What's in a name -**** -All **official** starters follow a similar naming pattern; `+spring-boot-starter-*+`, -where `+*+` is a particular type of application. This naming structure is intended to -help when you need to find a starter. The Maven integration in many IDEs lets you -search dependencies by name. For example, with the appropriate Eclipse or STS plugin -installed, you can press `ctrl-space` in the POM editor and type -"`spring-boot-starter`" for a complete list. - -As explained in the "`<>`" section, third party starters should not start with `spring-boot`, as it -is reserved for official Spring Boot artifacts. Rather, a third-party starter typically -starts with the name of the project. For example, a third-party starter project called -`thirdpartyproject` would typically be named `thirdpartyproject-spring-boot-starter`. -**** - -The following application starters are provided by Spring Boot under the -`org.springframework.boot` group: - -.Spring Boot application starters -include::{generated-resources-root}/application-starters.adoc[] - -In addition to the application starters, the following starters can be used to add -_<>_ features: - -.Spring Boot production starters -include::{generated-resources-root}/production-starters.adoc[] - -Finally, Spring Boot also includes the following starters that can be used if you want to -exclude or swap specific technical facets: - -.Spring Boot technical starters -include::{generated-resources-root}/technical-starters.adoc[] - -TIP: For a list of additional community contributed starters, see the -{github-master-code}/spring-boot-project/spring-boot-starters/README.adoc[README file] in -the `spring-boot-starters` module on GitHub. - - - -[[using-boot-structuring-your-code]] -== Structuring Your Code -Spring Boot does not require any specific code layout to work. However, there are some -best practices that help. - - - -[[using-boot-using-the-default-package]] -=== Using the "`default`" Package -When a class does not include a `package` declaration, it is considered to be in the -"`default package`". The use of the "`default package`" is generally discouraged and -should be avoided. It can cause particular problems for Spring Boot applications that use -the `@ComponentScan`, `@ConfigurationPropertiesScan`, `@EntityScan`, or `@SpringBootApplication` -annotations, since every class from every jar is read. - -TIP: We recommend that you follow Java's recommended package naming conventions and use a -reversed domain name (for example, `com.example.project`). - - - -[[using-boot-locating-the-main-class]] -=== Locating the Main Application Class -We generally recommend that you locate your main application class in a root package -above other classes. The <> is often placed on your main class, and it -implicitly defines a base "`search package`" for certain items. For example, if you are -writing a JPA application, the package of the `@SpringBootApplication` annotated class -is used to search for `@Entity` items. Using a root package also allows component -scan to apply only on your project. - -TIP: If you don't want to use `@SpringBootApplication`, the `@EnableAutoConfiguration` -`@ComponentScan`, and `@ConfigurationPropertiesScan` annotations that it imports defines -that behaviour so you can also use those instead. - -The following listing shows a typical layout: - -[indent=0] ----- - com - +- example - +- myapplication - +- Application.java - | - +- customer - | +- Customer.java - | +- CustomerController.java - | +- CustomerService.java - | +- CustomerRepository.java - | - +- order - +- Order.java - +- OrderController.java - +- OrderService.java - +- OrderRepository.java ----- - -The `Application.java` file would declare the `main` method, along with the basic -`@SpringBootApplication`, as follows: - -[source,java,indent=0] ----- - package com.example.myapplication; - - import org.springframework.boot.SpringApplication; - import org.springframework.boot.autoconfigure.SpringBootApplication; - - @SpringBootApplication - public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - - } ----- - - - -[[using-boot-configuration-classes]] -== Configuration Classes -Spring Boot favors Java-based configuration. Although it is possible to use -`SpringApplication` with XML sources, we generally recommend that your primary source be -a single `@Configuration` class. Usually the class that defines the `main` method is a -good candidate as the primary `@Configuration`. - -TIP: Many Spring configuration examples have been published on the Internet that use XML -configuration. If possible, always try to use the equivalent Java-based configuration. -Searching for `+Enable*+` annotations can be a good starting point. - - - -[[using-boot-importing-configuration]] -=== Importing Additional Configuration Classes -You need not put all your `@Configuration` into a single class. The `@Import` annotation -can be used to import additional configuration classes. Alternatively, you can use -`@ComponentScan` to automatically pick up all Spring components, including -`@Configuration` classes. - - - -[[using-boot-importing-xml-configuration]] -=== Importing XML Configuration -If you absolutely must use XML based configuration, we recommend that you still start -with a `@Configuration` class. You can then use an `@ImportResource` annotation to load -XML configuration files. - - - -[[using-boot-auto-configuration]] -== Auto-configuration -Spring Boot auto-configuration attempts to automatically configure your Spring -application based on the jar dependencies that you have added. For example, if `HSQLDB` -is on your classpath, and you have not manually configured any database connection beans, -then Spring Boot auto-configures an in-memory database. - -You need to opt-in to auto-configuration by adding the `@EnableAutoConfiguration` or -`@SpringBootApplication` annotations to one of your `@Configuration` classes. - -TIP: You should only ever add one `@SpringBootApplication` or `@EnableAutoConfiguration` -annotation. We generally recommend that you add one or the other to your primary -`@Configuration` class only. - - - -[[using-boot-replacing-auto-configuration]] -=== Gradually Replacing Auto-configuration -Auto-configuration is non-invasive. At any point, you can start to define your own -configuration to replace specific parts of the auto-configuration. For example, if you -add your own `DataSource` bean, the default embedded database support backs away. - -If you need to find out what auto-configuration is currently being applied, and why, -start your application with the `--debug` switch. Doing so enables debug logs for a -selection of core loggers and logs a conditions report to the console. - - - -[[using-boot-disabling-specific-auto-configuration]] -=== Disabling Specific Auto-configuration Classes -If you find that specific auto-configuration classes that you do not want are being -applied, you can use the exclude attribute of `@EnableAutoConfiguration` to disable them, -as shown in the following example: - -[source,java,indent=0] ----- - import org.springframework.boot.autoconfigure.*; - import org.springframework.boot.autoconfigure.jdbc.*; - import org.springframework.context.annotation.*; - - @Configuration(proxyBeanMethods = false) - @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) - public class MyConfiguration { - } ----- - -If the class is not on the classpath, you can use the `excludeName` attribute of the -annotation and specify the fully qualified name instead. Finally, you can also control -the list of auto-configuration classes to exclude by using the -`spring.autoconfigure.exclude` property. - -TIP: You can define exclusions both at the annotation level and by using the property. - -[[using-boot-spring-beans-and-dependency-injection]] -== Spring Beans and Dependency Injection -You are free to use any of the standard Spring Framework techniques to define your beans -and their injected dependencies. For simplicity, we often find that using -`@ComponentScan` (to find your beans) and using `@Autowired` (to do constructor -injection) works well. - -If you structure your code as suggested above (locating your application class in a root -package), you can add `@ComponentScan` without any arguments. All of your application -components (`@Component`, `@Service`, `@Repository`, `@Controller` etc.) are -automatically registered as Spring Beans. - -The following example shows a `@Service` Bean that uses constructor injection to obtain a -required `RiskAssessor` bean: - -[source,java,indent=0] ----- - package com.example.service; - - import org.springframework.beans.factory.annotation.Autowired; - import org.springframework.stereotype.Service; - - @Service - public class DatabaseAccountService implements AccountService { - - private final RiskAssessor riskAssessor; - - @Autowired - public DatabaseAccountService(RiskAssessor riskAssessor) { - this.riskAssessor = riskAssessor; - } - - // ... - - } ----- - -If a bean has one constructor, you can omit the `@Autowired`, as shown in the following -example: - -[source,java,indent=0] ----- - @Service - public class DatabaseAccountService implements AccountService { - - private final RiskAssessor riskAssessor; - - public DatabaseAccountService(RiskAssessor riskAssessor) { - this.riskAssessor = riskAssessor; - } - - // ... - - } ----- - -TIP: Notice how using constructor injection lets the `riskAssessor` field be marked as -`final`, indicating that it cannot be subsequently changed. - - - -[[using-boot-using-springbootapplication-annotation]] -== Using the @SpringBootApplication Annotation -Many Spring Boot developers like their apps to use auto-configuration, component scan and -be able to define extra configuration on their "application class". A single -`@SpringBootApplication` annotation can be used to enable those three features, that is: - -* `@EnableAutoConfiguration`: enable <> -* `@ComponentScan`: enable `@Component` scan on the package where the application is -located (see <>) -* `@ConfigurationPropertiesScan`: enable `@ConfigurationProperties` scan on the package -where the application is located (see <>) -* `@Configuration`: allow to register extra beans in the context or import additional -configuration classes - - -[source,java,indent=0] ----- - package com.example.myapplication; - - import org.springframework.boot.SpringApplication; - import org.springframework.boot.autoconfigure.SpringBootApplication; - - @SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan @ConfigurationPropertiesScan - public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - - } ----- - -NOTE: `@SpringBootApplication` also provides aliases to customize the attributes of -`@EnableAutoConfiguration` and `@ComponentScan`. - -[NOTE] -==== -None of these features are mandatory and you may choose to replace this single annotation -by any of the features that it enables. For instance, you may not want to use component -scan or configuration properties scan in your application: - -[source,java,indent=0] ----- - package com.example.myapplication; - - import org.springframework.boot.SpringApplication; - import org.springframework.context.annotation.ComponentScan - import org.springframework.context.annotation.Configuration; - import org.springframework.context.annotation.Import; - - @Configuration(proxyBeanMethods = false) - @EnableAutoConfiguration - @Import({ MyConfig.class, MyAnotherConfig.class }) - public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - - } ----- - -In this example, `Application` is just like any other Spring Boot application except that -`@Component`-annotated classes and `@ConfigurationProperties`-annotated classes are not detected -automatically and the user-defined beans are imported explicitly (see `@Import`). -==== - - - -[[using-boot-running-your-application]] -== Running Your Application -One of the biggest advantages of packaging your application as a jar and using an -embedded HTTP server is that you can run your application as you would any other. -Debugging Spring Boot applications is also easy. You do not need any special IDE plugins -or extensions. - -NOTE: This section only covers jar based packaging. If you choose to package your -application as a war file, you should refer to your server and IDE documentation. - - - -[[using-boot-running-from-an-ide]] -=== Running from an IDE -You can run a Spring Boot application from your IDE as a simple Java application. -However, you first need to import your project. Import steps vary depending on your IDE -and build system. Most IDEs can import Maven projects directly. For example, Eclipse -users can select `Import...` -> `Existing Maven Projects` from the `File` menu. - -If you cannot directly import your project into your IDE, you may be able to generate IDE -metadata by using a build plugin. Maven includes plugins for -https://maven.apache.org/plugins/maven-eclipse-plugin/[Eclipse] and -https://maven.apache.org/plugins/maven-idea-plugin/[IDEA]. Gradle offers plugins for -{gradle-user-guide}/userguide.html[various IDEs]. - -TIP: If you accidentally run a web application twice, you see a "`Port already in use`" -error. STS users can use the `Relaunch` button rather than the `Run` button to ensure -that any existing instance is closed. - - - -[[using-boot-running-as-a-packaged-application]] -=== Running as a Packaged Application -If you use the Spring Boot Maven or Gradle plugins to create an executable jar, you can -run your application using `java -jar`, as shown in the following example: - -[indent=0,subs="attributes"] ----- - $ java -jar target/myapplication-0.0.1-SNAPSHOT.jar ----- - -It is also possible to run a packaged application with remote debugging support enabled. -Doing so lets you attach a debugger to your packaged application, as shown in the -following example: - -[indent=0,subs="attributes"] ----- - $ java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n \ - -jar target/myapplication-0.0.1-SNAPSHOT.jar ----- - - - -[[using-boot-running-with-the-maven-plugin]] -=== Using the Maven Plugin -The Spring Boot Maven plugin includes a `run` goal that can be used to quickly compile -and run your application. Applications run in an exploded form, as they do in your IDE. -The following example shows a typical Maven command to run a Spring Boot application: - -[indent=0,subs="attributes"] ----- - $ mvn spring-boot:run ----- - -You might also want to use the `MAVEN_OPTS` operating system environment variable, as -shown in the following example: - -[indent=0,subs="attributes"] ----- - $ export MAVEN_OPTS=-Xmx1024m ----- - - - -[[using-boot-running-with-the-gradle-plugin]] -=== Using the Gradle Plugin -The Spring Boot Gradle plugin also includes a `bootRun` task that can be used to run your -application in an exploded form. The `bootRun` task is added whenever you apply the -`org.springframework.boot` and `java` plugins and is shown in the following example: - -[indent=0,subs="attributes"] ----- - $ gradle bootRun ----- - -You might also want to use the `JAVA_OPTS` operating system environment variable, as -shown in the following example: - -[indent=0,subs="attributes"] ----- - $ export JAVA_OPTS=-Xmx1024m ----- - - - -[[using-boot-hot-swapping]] -=== Hot Swapping -Since Spring Boot applications are just plain Java applications, JVM hot-swapping should -work out of the box. JVM hot swapping is somewhat limited with the bytecode that it can -replace. For a more complete solution, -https://zeroturnaround.com/software/jrebel/[JRebel] can be used. - -The -`spring-boot-devtools` module also includes support for quick application restarts. -See the <> section later in this chapter and the -<> for details. - - - -[[using-boot-devtools]] -== Developer Tools -Spring Boot includes an additional set of tools that can make the application -development experience a little more pleasant. The `spring-boot-devtools` module can be -included in any project to provide additional development-time features. To include -devtools support, add the module dependency to your build, as shown in the following -listings for Maven and Gradle: - +[[flows-cdc-contracts-external-producer]] +=== Producer Flow + +As a producer + +* take over the pull request to the repository with contract definitions. You can do it from the command line ++ +```bash +$ git checkout -b the_branch_with_pull_request master +git pull https://github.com/user_id/project_name.git the_branch_with_pull_request +``` +* Install the contract definitions e.g. +```bash +$ ./mvnw clean install +``` +* Setup your plugin to fetch the contract definitions from a JAR instead of from `src/test/resources/contracts` ++ +[source,xml,indent=0,subs="verbatim,attributes",role="primary"] .Maven -[source,xml,indent=0,subs="verbatim,quotes,attributes"] ---- - - - org.springframework.boot - spring-boot-devtools - true - - + + org.springframework.cloud + spring-cloud-contract-maven-plugin + ${spring-cloud-contract.version} + true + + + + com.example + beer-contracts + + + LOCAL + + + ---- - ++ +[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] .Gradle -[source,groovy,indent=0,subs="attributes"] ---- - configurations { - developmentOnly - runtimeClasspath { - extendsFrom developmentOnly - } +contracts { + // We want to use the JAR with contracts with the following coordinates + // group id `com.example`, artifact id `beer-contracts`, LATEST version and NO classifier + contractDependency { + stringNotation = 'com.example:beer-contracts:+:' } - dependencies { - developmentOnly("org.springframework.boot:spring-boot-devtools") + // The JAR with contracts should be taken from Maven local + contractsMode = "LOCAL" + // Additional configuration +} +---- +* Run the build, generate tests and stubs ++ +[source,bash,indent=0,subs="verbatim,attributes",role="primary"] +.Maven +---- +./mvnw clean install +---- ++ +[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] +.Gradle +---- +./gradlew clean build +---- +* Write the missing implementation, make the tests pass +* Once done +** merge the pull request to the repository with contract definitions +** you can do it from the command line ++ +```bash +$ git commit -am "Finished the implementation to make the contract tests pass" +$ git checkout master +$ git merge --no-ff the_branch_with_pull_request +$ git push origin master +``` +* Now, the CI system will build the project with contract definitions and upload the JAR with contract definitions to Nexus / Artifactory +* The producer can switch to working remotely +** Setup the plugin so that the contract definitions are no longer taken from the local storage but from a remote location ++ +[source,xml,indent=0,subs="verbatim,attributes",role="primary"] +.Maven +---- + + org.springframework.cloud + spring-cloud-contract-maven-plugin + ${spring-cloud-contract.version} + true + + + + com.example + beer-contracts + + + REMOTE + + + +---- ++ +[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] +.Gradle +---- +contracts { + // We want to use the JAR with contracts with the following coordinates + // group id `com.example`, artifact id `beer-contracts`, LATEST version and NO classifier + contractDependency { + stringNotation = 'com.example:beer-contracts:+:' } + // The JAR with contracts should be taken from a remote location + contractsMode = "REMOTE" + // Additional configuration +} +---- +** merge the producer code with the new implementation +* Now, the CI system will build the project, generate tests, stubs, stub JAR and upload the artifact with the application and the stubs to Nexus / Artifactory + +[plantuml, flow-overview-consumer-cdc-external-producer, png] +---- +"Producer"->"Repo\nwith\ncontracts": take over the pull request +"Producer"->"Repo\nwith\ncontracts": install the contract\ndefinitions JAR +"Repo\nwith\ncontracts"->"Local storage": install the\ncontract definitions\nJAR locally +"Local storage"->"Repo\nwith\ncontracts": contract definitions\nJAR installed +"Producer"->"Producer\nBuild": run build +"Producer\nBuild"->"SCC\nPlugin": generate tests,\nstubs\nand stub jar +"SCC\nPlugin"->"Local storage": fetch the contract definitions +"Local storage"->"SCC\nPlugin": contract definitions found +"SCC\nPlugin"->"SCC\nPlugin": generate tests +"Producer\nBuild"->"Producer\nBuild": run the\ngenerated tests +"Producer\nBuild"->"Producer": the tests failed to pass +"Producer"->"Producer": write the missing implementation +"Producer"->"Producer\nBuild": run the build again +"Producer\nBuild"->"Producer\nBuild": fetch the contract definitions\nrun the generated tests +"Producer\nBuild"->"Producer": the tests passed +"Producer"->"Repo\nwith\ncontracts": merge the pull request +"Repo\nwith\ncontracts"->"CI": build and upload the\ncontract definitions artifact +"CI"->"Nexus / Artifactory": upload the\ncontract definitions +"Producer"->"Producer": setup the SCC Plugin\nto work remotely +"Producer"->"Producer": merge the code\nwith the implementation +"Producer"->"CI": build and upload\nthe artifacts +"CI"->"Producer\nBuild\non CI": generate tests,\nstubs\nand stub jar +"Producer\nBuild\non CI"->"SCC\nPlugin": generate tests,\nstubs\nand stub jar +"SCC\nPlugin"->"Nexus / Artifactory": fetch the contract definitions +"Nexus / Artifactory"->"SCC\nPlugin": contract definitions found +"SCC\nPlugin"->"SCC\nPlugin": generate tests +"Producer\nBuild\non CI"->"CI": the build passed +"Producer\nBuild\non CI"->"Nexus / Artifactory": upload the application JAR\nand the stubs jar ---- -NOTE: Developer tools are automatically disabled when running a fully packaged -application. If your application is launched from `java -jar` or if it is started from a -special classloader, then it is considered a "`production application`". If that does not -apply to you (i.e. if you run your application from a container), consider excluding -devtools or set the `-Dspring.devtools.restart.enabled=false` system property. +[[flows-cdc-contracts-stubs-git]] +== Consumer Driven Contracts with contracts and stubs in git -TIP: Flagging the dependency as optional in Maven or using a custom `developmentOnly` -configuration in Gradle (as shown above) is a best practice that prevents devtools from -being transitively applied to other modules that use your project. +[[flows-provider-non-spring]] +== Provider contract testing with stubs in artifactory for a non Spring application -TIP: Repackaged archives do not contain devtools by default. If you want to use a -<>, you need to disable the -`excludeDevtools` build property to include it. The property is supported with both the -Maven and Gradle plugins. +[[flows-provider-non-jvm]] +== Provider contract testing with stubs in artifactory in non JVM world +[[flows-provider-rest-docs]] +== Provider contract testing with REST Docs and stubs in Artifactory -[[using-boot-devtools-property-defaults]] -=== Property Defaults -Several of the libraries supported by Spring Boot use caches to improve performance. For -example, <> cache compiled templates to avoid repeatedly parsing template files. Also, -Spring MVC can add HTTP caching headers to responses when serving static resources. - -While caching is very beneficial in production, it can be counter-productive during -development, preventing you from seeing the changes you just made in your application. -For this reason, spring-boot-devtools disables the caching options by default. - -Cache options are usually configured by settings in your `application.properties` file. -For example, Thymeleaf offers the `spring.thymeleaf.cache` property. Rather than needing -to set these properties manually, the `spring-boot-devtools` module automatically applies -sensible development-time configuration. - -Because you need more information about web requests while developing Spring MVC and -Spring WebFlux applications, developer tools will enable `DEBUG` logging for the `web` -logging group. This will give you information about the incoming request, which handler is -processing it, the response outcome, etc. If you wish to log all request details -(including potentially sensitive information), you can turn on the -`spring.http.log-request-details` configuration property. - -NOTE: If you don't want property defaults to be applied you can set -`spring.devtools.add-properties` to `false` in your `application.properties`. - -TIP: For a complete list of the properties that are applied by the devtools, see -{sc-spring-boot-devtools}/env/DevToolsPropertyDefaultsPostProcessor.{sc-ext}[DevToolsPropertyDefaultsPostProcessor]. - - - -[[using-boot-devtools-restart]] -=== Automatic Restart -Applications that use `spring-boot-devtools` automatically restart whenever files on the -classpath change. This can be a useful feature when working in an IDE, as it gives a very -fast feedback loop for code changes. By default, any entry on the classpath that points -to a folder is monitored for changes. Note that certain resources, such as static assets -and view templates, <>. - -.Triggering a restart -**** -As DevTools monitors classpath resources, the only way to trigger a restart is to update -the classpath. The way in which you cause the classpath to be updated depends on the IDE -that you are using. In Eclipse, saving a modified file causes the classpath to be updated -and triggers a restart. In IntelliJ IDEA, building the project -(`Build +->+ Build Project`) has the same effect. -**** - -[NOTE] -==== -As long as forking is enabled, you can also start your application by using the supported -build plugins (Maven and Gradle), since DevTools needs an isolated application -classloader to operate properly. By default, the Gradle and Maven plugins fork the -application process. - -==== - -TIP: Automatic restart works very well when used with LiveReload. -<> for details. If you use -JRebel, automatic restarts are disabled in favor of dynamic class reloading. Other -devtools features (such as LiveReload and property overrides) can still be used. - -NOTE: DevTools relies on the application context's shutdown hook to close it during a -restart. It does not work correctly if you have disabled the shutdown hook -(`SpringApplication.setRegisterShutdownHook(false)`). - -NOTE: When deciding if an entry on the classpath should trigger a restart when it -changes, DevTools automatically ignores projects named `spring-boot`, -`spring-boot-devtools`, `spring-boot-autoconfigure`, `spring-boot-actuator`, and -`spring-boot-starter`. - -NOTE: DevTools needs to customize the `ResourceLoader` used by the `ApplicationContext`. -If your application provides one already, it is going to be wrapped. Direct override of -the `getResource` method on the `ApplicationContext` is not supported. - -[[using-spring-boot-restart-vs-reload]] -.Restart vs Reload -**** -The restart technology provided by Spring Boot works by using two classloaders. Classes -that do not change (for example, those from third-party jars) are loaded into a _base_ -classloader. Classes that you are actively developing are loaded into a _restart_ -classloader. When the application is restarted, the _restart_ classloader is thrown away -and a new one is created. This approach means that application restarts are typically -much faster than "`cold starts`", since the _base_ classloader is already available and -populated. - -If you find that restarts are not quick enough for your applications or you encounter -classloading issues, you could consider reloading technologies such as -https://zeroturnaround.com/software/jrebel/[JRebel] from ZeroTurnaround. These work by -rewriting classes as they are loaded to make them more amenable to reloading. -**** - -[[using-boot-devtools-restart-logging-condition-delta]] -==== Logging changes in condition evaluation -By default, each time your application restarts, a report showing the condition evaluation -delta is logged. The report shows the changes to your application's auto-configuration as -you make changes such as adding or removing beans and setting configuration properties. - -To disable the logging of the report, set the following property: - -[indent=0] ----- - spring.devtools.restart.log-condition-evaluation-delta=false ----- - - -[[using-boot-devtools-restart-exclude]] -==== Excluding Resources -Certain resources do not necessarily need to trigger a restart when they are changed. For -example, Thymeleaf templates can be edited in-place. By default, changing resources -in `/META-INF/maven`, `/META-INF/resources`, `/resources`, `/static`, `/public`, or -`/templates` does not trigger a restart but does trigger a -<>. If you want to customize these -exclusions, you can use the `spring.devtools.restart.exclude` property. For example, to -exclude only `/static` and `/public` you would set the following property: - -[indent=0] ----- - spring.devtools.restart.exclude=static/**,public/** ----- - -TIP: If you want to keep those defaults and _add_ additional exclusions, use the -`spring.devtools.restart.additional-exclude` property instead. - - -[[using-boot-devtools-restart-additional-paths]] -==== Watching Additional Paths -You may want your application to be restarted or reloaded when you make changes to files -that are not on the classpath. To do so, use the -`spring.devtools.restart.additional-paths` property to configure additional paths to -watch for changes. You can use the `spring.devtools.restart.exclude` property -<> to control whether changes -beneath the additional paths trigger a full restart or a -<>. - - - -[[using-boot-devtools-restart-disable]] -==== Disabling Restart -If you do not want to use the restart feature, you can disable it by using the -`spring.devtools.restart.enabled` property. In most cases, you can set this property in -your `application.properties` (doing so still initializes the restart classloader, but it -does not watch for file changes). - -If you need to _completely_ disable restart support (for example, because it does not work -with a specific library), you need to set the `spring.devtools.restart.enabled` `System` -property to `false` before calling `SpringApplication.run(...)`, as shown in the -following example: - -[source,java,indent=0] ----- - public static void main(String[] args) { - System.setProperty("spring.devtools.restart.enabled", "false"); - SpringApplication.run(MyApp.class, args); - } ----- - - - -[[using-boot-devtools-restart-triggerfile]] -==== Using a Trigger File -If you work with an IDE that continuously compiles changed files, you might prefer to -trigger restarts only at specific times. To do so, you can use a "`trigger file`", which -is a special file that must be modified when you want to actually trigger a restart -check. Changing the file only triggers the check and the restart only occurs if -Devtools has detected it has to do something. The trigger file can be updated manually or -with an IDE plugin. - -To use a trigger file, set the `spring.devtools.restart.trigger-file` property to the -path of your trigger file. - -TIP: You might want to set `spring.devtools.restart.trigger-file` as a -<>, so that all your projects behave -in the same way. - - - -[[using-boot-devtools-customizing-classload]] -==== Customizing the Restart Classloader -As described earlier in the <> section, restart -functionality is implemented by using two classloaders. For most applications, this -approach works well. However, it can sometimes cause classloading issues. - -By default, any open project in your IDE is loaded with the "`restart`" classloader, and -any regular `.jar` file is loaded with the "`base`" classloader. If you work on a -multi-module project, and not every module is imported into your IDE, you may need to -customize things. To do so, you can create a `META-INF/spring-devtools.properties` file. - -The `spring-devtools.properties` file can contain properties prefixed with -`restart.exclude` and `restart.include`. The `include` elements are items that should be -pulled up into the "`restart`" classloader, and the `exclude` elements are items that -should be pushed down into the "`base`" classloader. The value of the property is a regex -pattern that is applied to the classpath, as shown in the following example: - -[source,properties,indent=0] ----- - restart.exclude.companycommonlibs=/mycorp-common-[\\w\\d-\.]+\.jar - restart.include.projectcommon=/mycorp-myproj-[\\w\\d-\.]+\.jar ----- - -NOTE: All property keys must be unique. As long as a property starts with -`restart.include.` or `restart.exclude.` it is considered. - -TIP: All `META-INF/spring-devtools.properties` from the classpath are loaded. You can -package files inside your project, or in the libraries that the project consumes. - - - -[[using-boot-devtools-known-restart-limitations]] -==== Known Limitations -Restart functionality does not work well with objects that are deserialized by using a -standard `ObjectInputStream`. If you need to deserialize data, you may need to use -Spring's `ConfigurableObjectInputStream` in combination with -`Thread.currentThread().getContextClassLoader()`. - -Unfortunately, several third-party libraries deserialize without considering the context -classloader. If you find such a problem, you need to request a fix with the original -authors. - - - -[[using-boot-devtools-livereload]] -=== LiveReload -The `spring-boot-devtools` module includes an embedded LiveReload server that can be used -to trigger a browser refresh when a resource is changed. LiveReload browser extensions -are freely available for Chrome, Firefox and Safari from -http://livereload.com/extensions/[livereload.com]. - -If you do not want to start the LiveReload server when your application runs, you can set -the `spring.devtools.livereload.enabled` property to `false`. - -NOTE: You can only run one LiveReload server at a time. Before starting your application, -ensure that no other LiveReload servers are running. If you start multiple applications -from your IDE, only the first has LiveReload support. - - - -[[using-boot-devtools-globalsettings]] -=== Global Settings -You can configure global devtools settings by adding a file named -`.spring-boot-devtools.properties` to your `$HOME` folder (note that the filename starts -with "`.`"). Any properties added to this file apply to _all_ Spring Boot applications on -your machine that use devtools. For example, to configure restart to always use a -<>, you would add the following -property: - -.~/.spring-boot-devtools.properties -[source,properties,indent=0] ----- - spring.devtools.reload.trigger-file=.reloadtrigger ----- - -NOTE: Profiles activated in `.spring-boot-devtools.properties` will not affect the -loading of <>. - - - -[[using-boot-devtools-remote]] -=== Remote Applications -The Spring Boot developer tools are not limited to local development. You can also -use several features when running applications remotely. Remote support is opt-in. To -enable it, you need to make sure that `devtools` is included in the repackaged archive, -as shown in the following listing: - -[source,xml,indent=0,subs="verbatim,quotes,attributes"] ----- - - - - org.springframework.boot - spring-boot-maven-plugin - - false - - - - ----- - -Then you need to set a `spring.devtools.remote.secret` property, as shown in the -following example: - -[source,properties,indent=0] ----- - spring.devtools.remote.secret=mysecret ----- - -WARNING: Enabling `spring-boot-devtools` on a remote application is a security risk. You -should never enable support on a production deployment. - -Remote devtools support is provided in two parts: a server-side endpoint that accepts -connections and a client application that you run in your IDE. The server component is -automatically enabled when the `spring.devtools.remote.secret` property is set. The -client component must be launched manually. - - - -==== Running the Remote Client Application -The remote client application is designed to be run from within your IDE. You need to run -`org.springframework.boot.devtools.RemoteSpringApplication` with the same classpath as -the remote project that you connect to. The application's single required argument is the -remote URL to which it connects. - -For example, if you are using Eclipse or STS and you have a project named `my-app` that -you have deployed to Cloud Foundry, you would do the following: - -* Select `Run Configurations...` from the `Run` menu. -* Create a new `Java Application` "`launch configuration`". -* Browse for the `my-app` project. -* Use `org.springframework.boot.devtools.RemoteSpringApplication` as the main class. -* Add `+++https://myapp.cfapps.io+++` to the `Program arguments` (or whatever your remote -URL is). - -A running remote client might resemble the following listing: - -[indent=0,subs="attributes"] ----- - . ____ _ __ _ _ - /\\ / ___'_ __ _ _(_)_ __ __ _ ___ _ \ \ \ \ - ( ( )\___ | '_ | '_| | '_ \/ _` | | _ \___ _ __ ___| |_ ___ \ \ \ \ - \\/ ___)| |_)| | | | | || (_| []::::::[] / -_) ' \/ _ \ _/ -_) ) ) ) ) - ' |____| .__|_| |_|_| |_\__, | |_|_\___|_|_|_\___/\__\___|/ / / / - =========|_|==============|___/===================================/_/_/_/ - :: Spring Boot Remote :: {spring-boot-version} - - 2015-06-10 18:25:06.632 INFO 14938 --- [ main] o.s.b.devtools.RemoteSpringApplication : Starting RemoteSpringApplication on pwmbp with PID 14938 (/Users/pwebb/projects/spring-boot/code/spring-boot-devtools/target/classes started by pwebb in /Users/pwebb/projects/spring-boot/code/spring-boot-samples/spring-boot-sample-devtools) - 2015-06-10 18:25:06.671 INFO 14938 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2a17b7b6: startup date [Wed Jun 10 18:25:06 PDT 2015]; root of context hierarchy - 2015-06-10 18:25:07.043 WARN 14938 --- [ main] o.s.b.d.r.c.RemoteClientConfiguration : The connection to http://localhost:8080 is insecure. You should use a URL starting with 'https://'. - 2015-06-10 18:25:07.074 INFO 14938 --- [ main] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729 - 2015-06-10 18:25:07.130 INFO 14938 --- [ main] o.s.b.devtools.RemoteSpringApplication : Started RemoteSpringApplication in 0.74 seconds (JVM running for 1.105) ----- - -NOTE: Because the remote client is using the same classpath as the real application it -can directly read application properties. This is how the `spring.devtools.remote.secret` -property is read and passed to the server for authentication. - -TIP: It is always advisable to use `https://` as the connection protocol, so that traffic -is encrypted and passwords cannot be intercepted. - -TIP: If you need to use a proxy to access the remote application, configure the -`spring.devtools.remote.proxy.host` and `spring.devtools.remote.proxy.port` properties. - - - -[[using-boot-devtools-remote-update]] -==== Remote Update -The remote client monitors your application classpath for changes in the same way as the -<>. Any updated resource is pushed to the -remote application and (_if required_) triggers a restart. This can be helpful if you -iterate on a feature that uses a cloud service that you do not have locally. Generally, -remote updates and restarts are much quicker than a full rebuild and deploy cycle. - -NOTE: Files are only monitored when the remote client is running. If you change a file -before starting the remote client, it is not pushed to the remote server. - - - -[[using-boot-packaging-for-production]] -== Packaging Your Application for Production -Executable jars can be used for production deployment. As they are self-contained, they -are also ideally suited for cloud-based deployment. - -For additional "`production ready`" features, such as health, auditing, and metric REST -or JMX end-points, consider adding `spring-boot-actuator`. See -_<>_ for details. - - - -[[using-boot-whats-next]] +[[using-whats-next]] == What to Read Next -You should now understand how you can use Spring Boot and some best practices that you +You should now understand how you can use {project-full-name} and some best practices that you should follow. You can now go on to learn about specific -_<>_ in depth, or you could -skip ahead and read about the "`<>`" aspects of Spring Boot. +_<>_ in depth, or you could +skip ahead and read about the ... From a725e8a76f8ed165bda018debdd1eb73124956c3 Mon Sep 17 00:00:00 2001 From: Marcin Grzejszczak Date: Wed, 24 Jul 2019 11:25:43 +0200 Subject: [PATCH 10/18] WIP --- docs/src/main/asciidoc/getting-started.adoc | 36 ++-- docs/src/main/asciidoc/index.htmladoc | 6 +- docs/src/main/asciidoc/index.htmlpdfadoc | 4 +- docs/src/main/asciidoc/index.htmlsingleadoc | 4 +- docs/src/main/asciidoc/using.adoc | 176 +++++++++++++++++++- 5 files changed, 198 insertions(+), 28 deletions(-) diff --git a/docs/src/main/asciidoc/getting-started.adoc b/docs/src/main/asciidoc/getting-started.adoc index 845c181903..3176d9aa4d 100644 --- a/docs/src/main/asciidoc/getting-started.adoc +++ b/docs/src/main/asciidoc/getting-started.adoc @@ -18,7 +18,7 @@ Spring Cloud Contract moves TDD to the level of software architecture. It allows Before becoming Spring Cloud Contract, this project was called https://github.com/Codearte/accurest[Accurest]. It was created by https://twitter.com/mgrzejszczak[Marcin Grzejszczak] and https://twitter.com/jkubrynski[Jakub Kubrynski] -from (https://github.com/Codearte[Codearte]. +from (https://github.com/Codearte[Codearte]). The `0.1.0` release took place on 26 Jan 2015 and it became stable with `1.0.0` release on 29 Feb 2016. @@ -141,12 +141,12 @@ You can find a somewhat longer tour "API Producer"->"API Producer": define contracts "API Producer"->"Build": run build "Build"->"SCC Plugin": generate \ntests, stubs and stubs \nartifact (e.g. stubs-jar) -"Build"->"Nexus / Artifactory": upload contracts \nand stubs and the project arifact +"Build"->"Stub Storage": upload contracts \nand stubs and the project arifact "Build"->"API Producer": Build successful "API Consumer"->"API Consumer": add SCC Stub Runner \ndependency "API Consumer"->"API Consumer": write a SCC Stub Runner \nbased contract test -"SCC Stub Runner"->"Nexus / Artifactory": test asks for [API Producer] stubs -"Nexus / Artifactory"->"SCC Stub Runner": fetch the [API Producer] stubs +"SCC Stub Runner"->"Stub Storage": test asks for [API Producer] stubs +"Stub Storage"->"SCC Stub Runner": fetch the [API Producer] stubs "SCC Stub Runner"->"SCC Stub Runner": run in memory\n HTTP server stubs "API Consumer"->"SCC Stub Runner": send a request \nto the HTTP server stub "SCC Stub Runner"->"API Consumer": communication is correct @@ -264,6 +264,8 @@ This brief tour walks through using Spring Cloud Contract: You can find an even more brief tour <>. +For the sake of this example the `Stub Storage` will be Nexus / Artifactory. + image::getting-started-three-second.png[Getting started first application] [[getting-started-first-application-producer]] @@ -604,11 +606,19 @@ Assume that `Loan Issuance` is a client to the `Fraud Detection` server. In the sprint, we must develop a new feature: if a client wants to borrow too much money, then we mark the client as a fraud. -Technical remark - Fraud Detection has an `artifact-id` of `http-server`, while Loan -Issuance has an artifact-id of `http-client`, and both have a `group-id` of `com.example`. +Technical remarks -Social remark - both client and server development teams need to communicate directly and -discuss changes while going through the process. CDC is all about communication. +* Fraud Detection has an `artifact-id` of `http-server`, +* Loan +Issuance has an artifact-id of `http-client` +* both have a `group-id` of `com.example` +* For the sake of this example the `Stub Storage` will be Nexus / Artifactory + +Social remarks + +* both client and server development teams need to communicate directly and +discuss changes while going through the process +* CDC is all about communication. The https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-server[server side code is available here] and https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-client[the @@ -920,7 +930,7 @@ Let's look at the Fraud Detection flow: "Fraud\nDetection\nBuild"->"Fraud\nDetection": all the tests passed! "Fraud\nDetection"->"Fraud\nDetection": commit and push changes "Fraud\nDetection"->"CI": commit pushed!\nTriggers the build -"CI"->"Nexus / Artifactory": build successful,\nupload artifacts +"CI"->"Stub Storage": build successful,\nupload artifacts ---- *Take over the pull request.* @@ -1059,10 +1069,10 @@ As a developer of the Loan Issuance service (a consumer of the Fraud Detection s [plantuml, getting-started-cdc-client, png] ---- "Loan\nIssuance"->"Loan\nIssuance": merge the\nfeature branch\nto master branch -"Loan\nIssuance"->"Loan\nIssuance": setup SCC Stub Runner\nto fetch stubs\nfrom Nexus / Artifactory -"Loan\nIssuance"->"LI\nSCC\nStub Runner": start stubs\nof FD from\nNexus / Artifactory -"LI\nSCC\nStub Runner"->"Nexus / Artifactory": find stubs of [FD] -"Nexus / Artifactory"->"LI\nSCC\nStub Runner": stubs of [FD] found +"Loan\nIssuance"->"Loan\nIssuance": setup SCC Stub Runner\nto fetch stubs\nfrom Stub Storage +"Loan\nIssuance"->"LI\nSCC\nStub Runner": start stubs\nof FD from\nStub Storage +"LI\nSCC\nStub Runner"->"Stub Storage": find stubs of [FD] +"Stub Storage"->"LI\nSCC\nStub Runner": stubs of [FD] found "LI\nSCC\nStub Runner"->"FD stub": run stubs of [FD] "FD stub"->"LI\nSCC\nStub Runner": [FD] stub is running "LI\nSCC\nStub Runner"->"Loan\nIssuance": stubs running and ready for the test diff --git a/docs/src/main/asciidoc/index.htmladoc b/docs/src/main/asciidoc/index.htmladoc index 795c5a05af..8e7c3bcbd1 100644 --- a/docs/src/main/asciidoc/index.htmladoc +++ b/docs/src/main/asciidoc/index.htmladoc @@ -8,9 +8,9 @@ The reference documentation consists of the following sections: [horizontal] <> :: Legal information. <> :: About the Documentation, Getting Help, First Steps, and more. -<> :: Introducing Spring Cloud Contract, System Requirements, Developing Your First Spring Cloud Contract based Application -<> :: Build Systems, Structuring Your Code, Configuration, Spring Beans and Dependency Injection, and more. -<> :: Profiles, Logging, Security, Caching, Spring Integration, Testing, and more. +<> :: Introducing {project-full-name}, System Requirements, Developing Your First {project-full-name} based Application +<> :: Build Systems, Structuring Your Code, Configuration, Spring Beans and Dependency Injection, and more. +<> :: Profiles, Logging, Security, Caching, Spring Integration, Testing, and more. <> :: Monitoring, Metrics, Auditing, and more. <> :: Maven Plugin, Gradle Plugin. <> :: Application Development, Configuration, Embedded Servers, Data Access, and many more. diff --git a/docs/src/main/asciidoc/index.htmlpdfadoc b/docs/src/main/asciidoc/index.htmlpdfadoc index 7f92b081e8..5e8932ca92 100644 --- a/docs/src/main/asciidoc/index.htmlpdfadoc +++ b/docs/src/main/asciidoc/index.htmlpdfadoc @@ -7,8 +7,8 @@ include::_attributes.adoc[] include::legal.adoc[leveloffset=+1] include::documentation-overview.adoc[leveloffset=+1] include::getting-started.adoc[leveloffset=+1] -include::using-spring-cloud-contract.adoc[leveloffset=+1] -include::spring-cloud-contract-features.adoc[leveloffset=+1] +include::using.adoc[leveloffset=+1] +include::project-features.adoc[leveloffset=+1] include::build-tool-plugins.adoc[leveloffset=+1] include::howto.adoc[leveloffset=+1] include::appendix.adoc[leveloffset=+1] \ No newline at end of file diff --git a/docs/src/main/asciidoc/index.htmlsingleadoc b/docs/src/main/asciidoc/index.htmlsingleadoc index 7f92b081e8..5e8932ca92 100644 --- a/docs/src/main/asciidoc/index.htmlsingleadoc +++ b/docs/src/main/asciidoc/index.htmlsingleadoc @@ -7,8 +7,8 @@ include::_attributes.adoc[] include::legal.adoc[leveloffset=+1] include::documentation-overview.adoc[leveloffset=+1] include::getting-started.adoc[leveloffset=+1] -include::using-spring-cloud-contract.adoc[leveloffset=+1] -include::spring-cloud-contract-features.adoc[leveloffset=+1] +include::using.adoc[leveloffset=+1] +include::project-features.adoc[leveloffset=+1] include::build-tool-plugins.adoc[leveloffset=+1] include::howto.adoc[leveloffset=+1] include::appendix.adoc[leveloffset=+1] \ No newline at end of file diff --git a/docs/src/main/asciidoc/using.adoc b/docs/src/main/asciidoc/using.adoc index 81ba85c51e..8aac5d4a88 100644 --- a/docs/src/main/asciidoc/using.adoc +++ b/docs/src/main/asciidoc/using.adoc @@ -20,6 +20,149 @@ You can also check the https://cloud-samples.spring.io/spring-cloud-contract-sam [[flows-provider-git]] == Provider contract testing with stubs in Git +In this flow, we will perform the provider contract testing (producer has no knowledge of how consumers use their API). The stubs will be uploaded to a separate repository (they will not be uploaded to Artifactory / Nexus). + +Prerequisites: + +* Git repository that +** will contain all the stubs for each producer +** for an example of such a project you can check the samples +{samples_code}/contract_git[check the samples ] or {samples_code}/contract_git[check the samples here] +** as a result of pushing stubs there, the repository will have the following structure ++ +``` +$ tree . +└── META-INF +   └── folder.with.group.id.as.its.name +   └── folder-with-artifact-id +   └── folder-with-version +   ├── contractA.groovy +   ├── contractB.yml +   └── contractC.groovy + +``` +* Consumer code that has Spring Cloud Contract Stub Runner setup +** for an example of such a project you can {samples_code}/consumer[check the samples] and search for a `BeerControllerGitTest` test +* Producer code that has Spring Cloud Contract setup together with a plugin +** for an example of such a project you can {samples_code}/producer_with_empty_git[check the samples] + +[[flows-provider-git-flow]] +=== The flow + +The flow looks exactly as the one presented in he <> section, but the `Stub Storage` implementation will be a git repository. + +You can read more about setting up git repository as a git storage and setting consumer and producer side in the <> of the documentation. + +[[flows-provider-git-consumer]] +=== Consumer setup + +In order to fetch the stubs from a git repository instead of Nexus / Artifactory, you need to use the `git` protocol in the URL of the `repositoryRoot` property in Stub Runner. Below you have an example of how to set it up. + +[source,java,indent=0,subs="verbatim,attributes",role="primary"] +.Annotation +---- +@AutoConfigureStubRunner( +stubsMode = StubRunnerProperties.StubsMode.REMOTE, + repositoryRoot = "git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git", + ids = "com.example:artifact-id:0.0.1") +---- + +[source,java,indent=0,subs="verbatim,attributes",role="secondary"] +.JUnit 4 Rule +---- +@Rule + public StubRunnerRule rule = new StubRunnerRule() + .downloadStub("com.example","artifact-id", "0.0.1") + .repoRoot("git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git") + .stubsMode(StubRunnerProperties.StubsMode.REMOTE); +---- + +[source,java,indent=0,subs="verbatim,attributes",role="secondary"] +.JUnit 5 Extension +---- +@Rule + public StubRunnerExtension stubRunnerExtension = new StubRunnerExtension() + .downloadStub("com.example","artifact-id", "0.0.1") + .repoRoot("git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git") + .stubsMode(StubRunnerProperties.StubsMode.REMOTE); +---- + +[[flows-provider-git-producer]] +=== Producer setup + +In order to push the stubs to a git repository instead of Nexus / Artifactory, you need to use the `git` protocol in the URL of the plugin setup. Also you need to explicitly tell the plugin to push the stubs at the end of the build process. + +==== +[source,xml,indent=0,role="primary"] +.maven +---- + + org.springframework.cloud + spring-cloud-contract-maven-plugin + ${spring-cloud-contract.version} + true + + + + + git://git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git + + + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + + REMOTE + + + + package + + + pushStubsToScm + + + + +---- + +[source,groovy,indent=0,role="secondary"] +.gradle +---- +contracts { + // We want to pick contracts from a Git repository + contractDependency { + stringNotation = "${project.group}:${project.name}:${project.version}" + } + /* + We reuse the contract dependency section to set up the path + to the folder that contains the contract definitions. In our case the + path will be /groupId/artifactId/version/contracts + */ + contractRepository { + repositoryUrl = "git://git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git" + } + // The mode can't be classpath + contractsMode = "REMOTE" + // Base class mappings etc. +} + +/* +In this scenario we want to publish stubs to SCM whenever +the `publish` task is executed +*/ +publish.dependsOn("publishStubsToScm") +---- +==== + +You can read more about setting up git repository as a git storage in the <> of the documentation. + [[flows-cdc-contracts-producer]] == Consumer Driven Contracts with contracts on the producer side @@ -35,7 +178,7 @@ You can check the https://cloud-samples.spring.io/spring-cloud-contract-samples/ Prerequisites: * Git repository that -** will contain all the contract defintiions for each producer +** will contain all the contract definitions for each producer ** can package the contract definitions in a JAR ** for each contract producer contains a way (e.g. `pom.xml`) to install stubs locally via the Spring Cloud Contract Plugin (SCC Plugin) ** for more information please visit the <> where we describe how to set up such a repository @@ -44,6 +187,7 @@ Prerequisites: ** for an example of such a project you can {samples_code}/consumer[check the samples] * Producer code that has Spring Cloud Contract setup together with a plugin ** for an example of such a project you can {samples_code}/producer_with_external_contracts[check the samples] +* The `Stub Storage` will be Nexus / Artifactory At a high level the flow looks as follows: @@ -235,27 +379,43 @@ contracts { "Producer\nBuild"->"Producer": the tests passed "Producer"->"Repo\nwith\ncontracts": merge the pull request "Repo\nwith\ncontracts"->"CI": build and upload the\ncontract definitions artifact -"CI"->"Nexus / Artifactory": upload the\ncontract definitions +"CI"->"Stub Storage": upload the\ncontract definitions "Producer"->"Producer": setup the SCC Plugin\nto work remotely "Producer"->"Producer": merge the code\nwith the implementation "Producer"->"CI": build and upload\nthe artifacts "CI"->"Producer\nBuild\non CI": generate tests,\nstubs\nand stub jar "Producer\nBuild\non CI"->"SCC\nPlugin": generate tests,\nstubs\nand stub jar -"SCC\nPlugin"->"Nexus / Artifactory": fetch the contract definitions -"Nexus / Artifactory"->"SCC\nPlugin": contract definitions found +"SCC\nPlugin"->"Stub Storage": fetch the contract definitions +"Stub Storage"->"SCC\nPlugin": contract definitions found "SCC\nPlugin"->"SCC\nPlugin": generate tests "Producer\nBuild\non CI"->"CI": the build passed -"Producer\nBuild\non CI"->"Nexus / Artifactory": upload the application JAR\nand the stubs jar +"Producer\nBuild\non CI"->"Stub Storage": upload the application JAR\nand the stubs jar ---- [[flows-cdc-contracts-stubs-git]] -== Consumer Driven Contracts with contracts and stubs in git +== Consumer Driven Contracts with contracts on the producer side, pushed to git + +You can check the <> link to see the Consumer Driven Contracts with contracts on the producer side flow. + +The Stub Storage implementation would be the git repository. We describe its setup in the <> section. + +You can read more about setting up git repository as a git storage and setting consumer and producer side in the <> of the documentation. [[flows-provider-non-spring]] -== Provider contract testing with stubs in artifactory for a non Spring application +== Provider contract testing with stubs in Artifactory for a non Spring application + +[[flows-provider-non-spring-flow]] +=== The flow + +You can check the <> link to see the provider contract testing with stubs in Nexus / Artifactory flow. + +[[flows-provider-non-spring-consumer]] +=== Consumer setup + +For the consumer side, it's enough to use a JUnit rule. [[flows-provider-non-jvm]] -== Provider contract testing with stubs in artifactory in non JVM world +== Provider contract testing with stubs in Artifactory in non JVM world [[flows-provider-rest-docs]] == Provider contract testing with REST Docs and stubs in Artifactory From 48ea06b66a6a4a783fbd51ecaed7b5ad38b1b631 Mon Sep 17 00:00:00 2001 From: Marcin Grzejszczak Date: Wed, 24 Jul 2019 13:16:29 +0200 Subject: [PATCH 11/18] Added flows --- docs/src/main/asciidoc/using.adoc | 358 +++++++++++++++++++++++++++++- 1 file changed, 355 insertions(+), 3 deletions(-) diff --git a/docs/src/main/asciidoc/using.adoc b/docs/src/main/asciidoc/using.adoc index 8aac5d4a88..07ddd2d03e 100644 --- a/docs/src/main/asciidoc/using.adoc +++ b/docs/src/main/asciidoc/using.adoc @@ -412,14 +412,366 @@ You can check the < ctx.result("Hello World")); + } + + public Javalin run(int port) { + return registerGet(start(port)); + } + +} +---- + +Setup the plugin to use the `EXPLICIT` mode (i.e. to send out requests to a real port). + +==== +[source,xml,indent=0,role="primary"] +.maven +---- + + org.springframework.cloud + spring-cloud-contract-maven-plugin + ${spring-cloud-contract.version} + true + + com.example.demo.BaseClass + + EXPLICIT + + +---- + +[source,groovy,indent=0,role="secondary"] +.gradle +---- +contracts { + // This will setup the EXPLICIT mode for the tests + testMode = "EXPLICIT" + baseClassForTests = "com.example.demo.BaseClass" +} +---- +==== + +The base class could look like this + +[source,java,indent=0] +---- +import io.javalin.Javalin; +import io.restassured.RestAssured; +import org.junit.After; +import org.junit.Before; +import org.springframework.util.SocketUtils; + +public class BaseClass { + + Javalin app; + + @Before + public void setup() { + // pick a random port + int port = SocketUtils.findAvailableTcpPort(); + // start the application at a random port + this.app = start(port); + // tell Rest Assured where the started application is + RestAssured.baseURI = "http://localhost:" + port; + } + + @After + public void close() { + // stop the server after each test + this.app.stop(); + } + + private Javalin start(int port) { + // reuse the production logic to start a server + return new DemoApplication().run(port); + } +} +---- + +With such a setup + +* we've setup the Spring Cloud Contract plugin that it uses the `EXPLICIT` mode to send real requests instead of mocked ones +* we've defined a base class that +** starts the HTTP server on a random port for each test +** sets Rest Assured to send requests to that port +** closes the HTTP server after each test [[flows-provider-non-jvm]] == Provider contract testing with stubs in Artifactory in non JVM world -[[flows-provider-rest-docs]] -== Provider contract testing with REST Docs and stubs in Artifactory +In this flow we assume that +* the API Producer and API Consumer are non JVM applications. +* the contract definitions are written in YAML +* the Stub Storage is Artifactory / Nexus +* Spring Cloud Contract Docker (SCC Docker) and Spring Cloud Contract Stub Runner Docker (SCC Stub Runner Docker) images will be used + +You can read more about how to use Spring Cloud Contract with Docker <>. + +Over https://spring.io/blog/2018/02/13/spring-cloud-contract-in-a-polyglot-world[here] you can read a blog post about how to use Spring Cloud Contract in a polyglot world. + +https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs/[Here] you can find a sample of a NodeJS application using Spring Cloud Contract both as a producer and a consumer. + +[[flows-provider-non-jvm-producer]] +=== Producer Flow + +At a high level the producer + +* writes contract definitions e.g. in YAML +* sets up the build tool to +** start the application with mocked services on a given port X +** in case when mocking is not possible you can setup the infrastructure and define tests in a stateful way +** run the Spring Cloud Contract Docker image and pass the port of a running application as an environment variable +* The SCC Docker image +** generates the tests from the attached volume +** runs the tests against the running application +** upon test completion, stubs will get uploaded to a Stub Storage (e.g. Artifactory, Git) + +[plantuml, flows-provider-non-jvm-producer, png] +---- +"API Producer"->"API Producer": write contract definitions +"API Producer"->"API Producer": (preferable) prepare a way\nto run the app\nwith mocked services +"API Producer"->"API Producer\nbuild": run the build +"API Producer\nbuild"->"API Producer\nrunning app": run the app\non port X\nwith mocked services +"API Producer\nbuild"->"SCC Docker": attach contract definitions\nas a volume +"API Producer\nbuild"->"SCC Docker": set environment variables\ne.g. app running on port X +"API Producer\nbuild"->"SCC Docker": run the contract tests +"SCC Docker"->"SCC Docker\nimage": run the contract tests +"SCC Docker\nimage"->"SCC Docker\nimage": pick the contract definitions\nfrom volume +"SCC Docker\nimage"->"SCC Docker\nimage": generate contract tests +"SCC Docker\nimage"->"SCC Docker\nimage": run the tests\nagainst app running\non port X +"SCC Docker\nimage"->"SCC Docker\nimage": the tests are passing! +"SCC Docker\nimage"->"Stub Storage": upload the stubs +"SCC Docker\nimage"->"SCC Docker": build successful +"SCC Docker"->"API Producer\nbuild": build successful +"API Producer\nbuild"->"API Producer": build successful +---- + +[[flows-provider-non-jvm-consumer]] +=== Consumer Flow + +At a high level the consumer + +* sets up the build tool to +** start the Spring Cloud Contract Stub Runner Docker image and start the stubs +*** the environment variables passed will configure +**** the stubs to fetch +**** location of the repositories +*** to use the local storage you can also attach it as a volume +*** the ports at which the stubs are running need to be exposed +** run your application tests against the running stubs + +[plantuml, flows-provider-non-jvm-consumer, png] +---- +"API Consumer"->"API Consumer\nbuild": run the build +"API Consumer\nbuild"->"SCC\nStub Runner\nDocker": set environment variables\ne.g. stub X running on port Y +"SCC\nStub Runner\nDocker"->"SCC\nStub Runner\nDocker\nimage": fetch and run\nthe stubs +"SCC\nStub Runner\nDocker\nimage"->"Stub Storage": fetch the stubs of X +"Stub Storage"->"SCC\nStub Runner\nDocker\nimage": stubs found +"SCC\nStub Runner\nDocker\nimage"->"X Stub": run the stub of X +"X Stub"->"SCC\nStub Runner\nDocker\nimage": stub is running\non port Y +"SCC\nStub Runner\nDocker\nimage"->"SCC\nStub Runner\nDocker": stubs running and\nready for tests +"API Consumer\nbuild"->"API Consumer\nbuild": run tests against X stub +"API Consumer\nbuild"->"X Stub": send a request +"X Stub"->"API Consumer\nbuild": response received +"API Consumer\nbuild"->"API Consumer": build successful +---- + +[[flows-provider-rest-docs]] +== Provider contract testing with REST Docs and stubs in Nexus / Artifactory + +In this flow, we will not use a Spring Cloud Contract Plugin to generate tests and stubs. We will write https://spring.io/projects/spring-restdocs[Spring RESTDocs] and from them we will automatically generate stubs. Finally, we will setup our builds to package the stubs and upload them to the Stub Storage - in our case Nexus / Artifactory. + +You can also check the https://cloud-samples.spring.io/spring-cloud-contract-samples/tutorials/rest_docs.html[workshop page] for a step by step instruction on how to do this flow. + +[[flows-provider-rest-docs-producer]] +=== Producer flow + +As a producer + +* we write RESTDocs tests of our API +* we add Spring Cloud Contract Stub Runner starter to our build (`spring-cloud-starter-contract-stub-runner`) ++ +==== +[source,xml,indent=0,role="primary"] +.maven +---- + + + org.springframework.cloud + spring-cloud-starter-contract-stub-runner + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + +---- + +[source,groovy,indent=0,role="secondary"] +.gradle +---- +dependencies { + testImplementation 'org.springframework.cloud:spring-cloud-starter-contract-stub-runner' +} + +dependencyManagement { + imports { + mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" + } +} +---- +==== +* we setup the build tool to package our stubs ++ +==== +[source,xml,indent=0,role="primary"] +.maven +---- + + + + org.apache.maven.plugins + maven-assembly-plugin + + + stub + prepare-package + + single + + false + + true + + ${basedir}/src/assembly/stub.xml + + + + + + + + + + stubs + + jar + + false + + + ${project.build.directory}/generated-snippets/stubs + META-INF/${project.groupId}/${project.artifactId}/${project.version}/mappings + + **/* + + + + +---- + +[source,groovy,indent=0,role="secondary"] +.gradle +---- +task stubsJar(type: Jar) { + classifier = "stubs" + into("META-INF/${project.group}/${project.name}/${project.version}/mappings") { + include('**/*.*') + from("${project.buildDir}/generated-snippets/stubs") + } +} +// we need the tests to pass to build the stub jar +stubsJar.dependsOn(test) +bootJar.dependsOn(stubsJar) +---- +==== +* now, when we run the tests, stubs will be automatically published and packaged + +[plantuml, flows-provider-rest-docs-producer, png] +---- +"API Producer"->"API Producer": write RESTDocs tests +"API Producer"->"API Producer": add the stub runner\nstarter dependency +"API Producer"->"API Producer": setup the build tool to package\nthe generated stubs +"API Producer"->"API Producer\nbuild": run the build +"API Producer\nbuild"->"RESTDocs": generate HTTP snippets +"RESTDocs"->"Spring Cloud\nContract": generate HTTP stubs +"RESTDocs"->"Spring Cloud\nContract": (optional) generate\ncontract DSLs +"Spring Cloud\nContract"->"RESTDocs": files generated +"RESTDocs"->"API Producer\nbuild": snippets generated +"API Producer\nbuild"->"API Producer\nbuild": tests passed +"API Producer\nbuild"->"API Producer\nbuild": generate stubs jar +"API Producer\nbuild"->"Stub Storage": upload JAR with the application +"API Producer\nbuild"->"Stub Storage": upload JAR with the stubs +"Stub Storage"->"API Producer\nbuild": JARs uploaded +"API Producer\nbuild"->"API Producer": build successful +---- + +[[flows-provider-rest-docs-consumer]] +=== Consumer flow + +Since the consumer flow isn't affected by the tool used to generate the stubs, you can check the <> link to see the consumer side of the provider contract testing with stubs in Nexus / Artifactory flow. [[using-whats-next]] == What to Read Next From 66a71e72a4990db709dbe3a6a737b79a7aa27b2b Mon Sep 17 00:00:00 2001 From: Marcin Grzejszczak Date: Wed, 24 Jul 2019 13:58:20 +0200 Subject: [PATCH 12/18] WIP: --- README.adoc | 16 +- .../main/asciidoc/_verifier_how_it_works.adoc | 6 +- .../main/asciidoc/_verifier_introduction.adoc | 4 +- docs/src/main/asciidoc/docker-project.adoc | 2 + .../main/asciidoc/documentation-overview.adoc | 73 ++--- docs/src/main/asciidoc/gradle-project.adoc | 26 +- docs/src/main/asciidoc/howto.adoc | 49 ++- docs/src/main/asciidoc/index.htmladoc | 3 +- docs/src/main/asciidoc/maven-project.adoc | 282 +----------------- 9 files changed, 88 insertions(+), 373 deletions(-) diff --git a/README.adoc b/README.adoc index 3bc6dfc1bc..dc5a173a58 100644 --- a/README.adoc +++ b/README.adoc @@ -59,7 +59,7 @@ The `0.1.0` release took place on 26 Jan 2015 and it became stable with `1.0.0` Assume that we have a system consisting of multiple microservices: -image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/docs/src/main/asciidoc/images/Deps.png[Microservices Architecture] +image::{github-raw}/docs/src/main/asciidoc/images/Deps.png[Microservices Architecture] ==== Testing issues @@ -106,7 +106,7 @@ To solve the aforementioned issues, Spring Cloud Contract was created. The main whole world of microservices. If you work on stubs, then the only applications you need are those that your application directly uses. -image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/docs/src/main/asciidoc/images/Stubs2.png[Stubbed Services] +image::{github-raw}/docs/src/main/asciidoc/images/Stubs2.png[Stubbed Services] Spring Cloud Contract gives you the certainty that the stubs that you use were created by the service that you're calling. Also, if you can use them, it means that they @@ -243,9 +243,7 @@ Stub Runner` properties, as shown in the following example: + [source,yaml,indent=0] ---- -stubrunner: - ids: 'com.example:http-server-dsl:+:stubs:8080' - repositoryRoot: https://repo.spring.io/libs-snapshot +Unresolved directive in _verifier_how_it_works.adoc - include::{github-raw}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ---- Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, @@ -552,9 +550,7 @@ Runner` properties, as shown in the following example: + [source,yaml,indent=0] ---- -stubrunner: - ids: 'com.example:http-server-dsl:+:stubs:8080' - repositoryRoot: https://repo.spring.io/libs-snapshot +Unresolved directive in _verifier_how_it_works.adoc - include::{github-raw}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ---- Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, @@ -1083,9 +1079,7 @@ achieving the same thing by changing the properties. [source,yaml,indent=0] ---- -stubrunner: - ids: 'com.example:http-server-dsl:+:stubs:8080' - repositoryRoot: https://repo.spring.io/libs-snapshot +Unresolved directive in _verifier_how_it_works.adoc - include::{github-raw}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ---- That's it! diff --git a/docs/src/main/asciidoc/_verifier_how_it_works.adoc b/docs/src/main/asciidoc/_verifier_how_it_works.adoc index eeff07d9c6..ca5b39e898 100644 --- a/docs/src/main/asciidoc/_verifier_how_it_works.adoc +++ b/docs/src/main/asciidoc/_verifier_how_it_works.adoc @@ -110,7 +110,7 @@ Stub Runner` properties, as shown in the following example: + [source,yaml,indent=0] ---- -include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] +include::{github-raw}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ---- Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, @@ -417,7 +417,7 @@ Runner` properties, as shown in the following example: + [source,yaml,indent=0] ---- -include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] +include::{github-raw}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ---- Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, @@ -946,7 +946,7 @@ achieving the same thing by changing the properties. [source,yaml,indent=0] ---- -include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] +include::{github-raw}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ---- That's it! \ No newline at end of file diff --git a/docs/src/main/asciidoc/_verifier_introduction.adoc b/docs/src/main/asciidoc/_verifier_introduction.adoc index 466d8ad150..75bf483d32 100644 --- a/docs/src/main/asciidoc/_verifier_introduction.adoc +++ b/docs/src/main/asciidoc/_verifier_introduction.adoc @@ -14,7 +14,7 @@ The `0.1.0` release took place on 26 Jan 2015 and it became stable with `1.0.0` Assume that we have a system consisting of multiple microservices: -image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/docs/src/main/asciidoc/images/Deps.png[Microservices Architecture] +image::{github-raw}/docs/src/main/asciidoc/images/Deps.png[Microservices Architecture] ==== Testing issues @@ -61,7 +61,7 @@ To solve the aforementioned issues, Spring Cloud Contract was created. The main whole world of microservices. If you work on stubs, then the only applications you need are those that your application directly uses. -image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/docs/src/main/asciidoc/images/Stubs2.png[Stubbed Services] +image::{github-raw}/docs/src/main/asciidoc/images/Stubs2.png[Stubbed Services] Spring Cloud Contract gives you the certainty that the stubs that you use were created by the service that you're calling. Also, if you can use them, it means that they diff --git a/docs/src/main/asciidoc/docker-project.adoc b/docs/src/main/asciidoc/docker-project.adoc index 4eca6a5220..2547579835 100644 --- a/docs/src/main/asciidoc/docker-project.adoc +++ b/docs/src/main/asciidoc/docker-project.adoc @@ -1,4 +1,5 @@ = Docker Project +include::_attributes.adoc[] We're publishing a `springcloud/spring-cloud-contract` Docker image that contains a project that will generate tests and execute them in `EXPLICIT` mode @@ -177,4 +178,5 @@ will be executed against the running application under http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/ . The stubs will be here http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar. +// TODO: Fix the link To see how the client side looks like check out the <> section. diff --git a/docs/src/main/asciidoc/documentation-overview.adoc b/docs/src/main/asciidoc/documentation-overview.adoc index 81fc6b99bb..05741c891d 100644 --- a/docs/src/main/asciidoc/documentation-overview.adoc +++ b/docs/src/main/asciidoc/documentation-overview.adoc @@ -60,73 +60,34 @@ If you are getting started with {project-full-name} or 'Spring' in general, star Ready to actually start using {project-full-name}? <>: -* *Build systems:* -<> | -<> | -<> | -<> -* *Best practices:* -<> | -<> | -<> | -<> -* *Running your code:* -<> | -<> | -<> | -<> -* *Packaging your app:* -<> -* *{project-full-name} CLI:* -<<{project-name}-cli.adoc#cli, Using the CLI>> +* *Provider contract testing:* + +** <> +** <> +** <> +** <> +** <> + +* *Consumer-Driven contract testing:* +** <> +** <> +** <> == Learning about {project-full-name} Features Need more details about {project-full-name}'s core features? -<<{project-name}-features.adoc#contract-features, The following content is for you>>: +<>: * *Core Features:* <<{project-name}-features.adoc#contract-features-spring-application, SpringApplication>> | <<{project-name}-features.adoc#contract-features-external-config, External Configuration>> | <<{project-name}-features.adoc#contract-features-profiles, Profiles>> | <<{project-name}-features.adoc#contract-features-logging, Logging>> -* *Web Applications:* -<<{project-name}-features.adoc#contract-features-spring-mvc, MVC>> | -<<{project-name}-features.adoc#contract-features-embedded-container, Embedded Containers>> -* *Working with data:* -<<{project-name}-features.adoc#contract-features-sql, SQL>> | -<<{project-name}-features.adoc#contract-features-nosql, NO-SQL>> -* *Messaging:* -<<{project-name}-features.adoc#contract-features-messaging, Overview>> | -<<{project-name}-features.adoc#contract-features-jms, JMS>> -* *Testing:* -<<{project-name}-features.adoc#contract-features-testing, Overview>> | -<<{project-name}-features.adoc#contract-features-testing-{project-name}-applications, Boot -Applications>> | -<<{project-name}-features.adoc#contract-features-test-utilities, Utils>> -* *Extending:* -<<{project-name}-features.adoc#contract-features-developing-auto-configuration, Auto-configuration>> | -<<{project-name}-features.adoc#contract-features-condition-annotations, @Conditions>> - - - -== Moving to Production -When you are ready to push your {project-full-name} application to production, we have -<> that you might like: - -* *Management endpoints:* -<> | -<> -* *Connection options:* -<> | -<> -* *Monitoring:* -<> | -<> | -<> | -<> +* *Build tools:* +link:maven-project.html[Maven] | +link:gradle-project.html[Gradle] | +link:docker-project.html[Docker] diff --git a/docs/src/main/asciidoc/gradle-project.adoc b/docs/src/main/asciidoc/gradle-project.adoc index 8d03c5b3e8..75b89045fa 100644 --- a/docs/src/main/asciidoc/gradle-project.adoc +++ b/docs/src/main/asciidoc/gradle-project.adoc @@ -1,23 +1,5 @@ -:branch: master -:core_path: ../../.. -:plugins_path: ../../../spring-cloud-contract-tools -:converters_path: {plugins_path}/spring-cloud-contract-converters -:verifier_root_path: {core_path}/spring-cloud-contract-verifier -:contract_spec_path: {core_path}/specs/spring-cloud-contract-spec-java -:contract_spec_tests_path: {core_path}/specs/spring-cloud-contract-spec -:samples_path: {core_path}/samples -:verifier_core_path: {verifier_root_path} -:stubrunner_core_path: {core_path}/spring-cloud-contract-stub-runner -:standalone_samples_path: {samples_path}/standalone/dsl -:standalone_messaging_samples_path: {samples_path}/standalone/messaging -:standalone_pact_path: {samples_path}/standalone/pact -:standalone_restdocs_path: {samples_path}/standalone/restdocs -:tests_path: {core_path}/tests -:samples_branch: 2.2.x -:samples_url: https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/{samples_branch} -:introduction_url: ${core_path}/../../ - = Gradle Project +include::_attributes.adoc[] To learn how to set up the Gradle project for Spring Cloud Contract Verifier, read the following sections: @@ -73,10 +55,10 @@ dependencyManagement { } dependencies { - testCompile 'org.codehaus.groovy:groovy-all:2.4.6' + testCompile "org.codehaus.groovy:groovy-all:${groovyVersion}" // example with adding Spock core and Spock Spring - testCompile 'org.spockframework:spock-core:1.0-groovy-2.4' - testCompile 'org.spockframework:spock-spring:1.0-groovy-2.4' + testCompile "org.spockframework:spock-core:${spockVersion}" + testCompile "org.spockframework:spock-spring:${spockVersion}" testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier' } ---- diff --git a/docs/src/main/asciidoc/howto.adoc b/docs/src/main/asciidoc/howto.adoc index 1e31e36b0f..bea57644cd 100644 --- a/docs/src/main/asciidoc/howto.adoc +++ b/docs/src/main/asciidoc/howto.adoc @@ -1001,4 +1001,51 @@ task convertContracts(type: JavaExec) { test.dependsOn("convertContracts") ---- -==== \ No newline at end of file +==== + +[[how-to-work-with-transitivie]] +== How can I work with transitive dependencies? + +The Spring Cloud Contract plugins add the tasks that create the stubs jar for you. One +problem that arises is that, when reusing the stubs, you can mistakenly import all of +that stub's dependencies. When building a Maven artifact, even though you have a couple +of different jars, all of them share one pom: + +[source,bash,indent=0] +---- +├── producer-0.0.1.BUILD-20160903.075506-1-stubs.jar +├── producer-0.0.1.BUILD-20160903.075506-1-stubs.jar.sha1 +├── producer-0.0.1.BUILD-20160903.075655-2-stubs.jar +├── producer-0.0.1.BUILD-20160903.075655-2-stubs.jar.sha1 +├── producer-0.0.1.BUILD-SNAPSHOT.jar +├── producer-0.0.1.BUILD-SNAPSHOT.pom +├── producer-0.0.1.BUILD-SNAPSHOT-stubs.jar +├── ... +└── ... +---- + +There are three possibilities of working with those dependencies so as not to have any +issues with transitive dependencies: + +* Mark all application dependencies as optional +* Create a separate artifactid for the stubs +* Exclude dependencies on the consumer side + +[[how-to-work-with-transitivie-optional]] +=== Mark all application dependencies as optional + +If, in the `producer` application, you mark all of your dependencies as optional, +when you include the `producer` stubs in another application (or when that +dependency gets downloaded by Stub Runner) then, since all of the dependencies are +optional, they will not get downloaded. + +[[how-to-work-with-transitivie-separate]] +=== Create a separate `artifactid` for the stubs + +If you create a separate `artifactid`, then you can set it up in whatever way you wish. +For example, you might decide to have no dependencies at all. + +[[how-to-work-with-transitivie-exclude]] +=== Exclude dependencies on the consumer side + +As a consumer, if you add the stub dependency to your classpath, you can explicitly exclude the unwanted dependencies. \ No newline at end of file diff --git a/docs/src/main/asciidoc/index.htmladoc b/docs/src/main/asciidoc/index.htmladoc index 8e7c3bcbd1..cc009df9f7 100644 --- a/docs/src/main/asciidoc/index.htmladoc +++ b/docs/src/main/asciidoc/index.htmladoc @@ -2,6 +2,7 @@ = Spring Cloud Contract Reference Documentation Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak, Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer, Jay Bryant :docinfo: shared +include::_attributes.adoc[] The reference documentation consists of the following sections: @@ -9,7 +10,7 @@ The reference documentation consists of the following sections: <> :: Legal information. <> :: About the Documentation, Getting Help, First Steps, and more. <> :: Introducing {project-full-name}, System Requirements, Developing Your First {project-full-name} based Application -<> :: Build Systems, Structuring Your Code, Configuration, Spring Beans and Dependency Injection, and more. +<> :: {project-full-name} usage examples and workflows <> :: Profiles, Logging, Security, Caching, Spring Integration, Testing, and more. <> :: Monitoring, Metrics, Auditing, and more. <> :: Maven Plugin, Gradle Plugin. diff --git a/docs/src/main/asciidoc/maven-project.adoc b/docs/src/main/asciidoc/maven-project.adoc index 5b21e7c4ad..ffc5e36735 100644 --- a/docs/src/main/asciidoc/maven-project.adoc +++ b/docs/src/main/asciidoc/maven-project.adoc @@ -1,23 +1,5 @@ -:branch: master -:core_path: ../../.. -:plugins_path: ../../../spring-cloud-contract-tools -:converters_path: {plugins_path}/spring-cloud-contract-converters -:verifier_root_path: {core_path}/spring-cloud-contract-verifier -:contract_spec_path: {core_path}/specs/spring-cloud-contract-spec-java -:contract_spec_tests_path: {core_path}/specs/spring-cloud-contract-spec -:samples_path: {core_path}/samples -:verifier_core_path: {verifier_root_path} -:stubrunner_core_path: {core_path}/spring-cloud-contract-stub-runner -:standalone_samples_path: {samples_path}/standalone/dsl -:standalone_messaging_samples_path: {samples_path}/standalone/messaging -:standalone_pact_path: {samples_path}/standalone/pact -:standalone_restdocs_path: {samples_path}/standalone/restdocs -:tests_path: {core_path}/tests -:samples_branch: 2.2.x -:samples_url: https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/{samples_branch} -:introduction_url: ${core_path}/../../ - = Maven Project +include::_attributes.adoc[] To learn how to set up the Maven project for Spring Cloud Contract Verifier, read the following sections: @@ -53,8 +35,8 @@ include::{standalone_samples_path}/http-server/pom.xml[tags=contract_maven_plugi ---- You can read more in the -https://cloud.spring.io/spring-cloud-static/spring-cloud-contract/2.0.0.RELEASE/spring-cloud-contract-maven-plugin/[Spring -Cloud Contract Maven Plugin Documentation (example for `2.0.0.RELEASE` version)]. +spring-cloud-contract-maven-plugin/index.html[Spring +Cloud Contract Maven Plugin Documentation. [[maven-rest-assured]] == Maven and Rest Assured 2.0 @@ -469,7 +451,7 @@ or an environment variable. If you see the following exception while using STS: -image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/docs/src/main/asciidoc/images/sts_exception.png[STS Exception] +image::{github-raw}/docs/src/main/asciidoc/images/sts_exception.png[STS Exception] When you click on the error marker you should see something like this: @@ -544,258 +526,4 @@ Surefire plugin setup, like in the following example: [source,xml,indent=0] ---- include::{samples_url}/producer_with_spock/pom.xml[tags=spock-surefire-setup,indent=0] ----- - -= Stubs and Transitive Dependencies - -The Maven and Gradle plugin that add the tasks that create the stubs jar for you. One -problem that arises is that, when reusing the stubs, you can mistakenly import all of -that stub's dependencies. When building a Maven artifact, even though you have a couple -of different jars, all of them share one pom: - -[source,bash,indent=0] ----- -├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar -├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar.sha1 -├── github-webhook-0.0.1.BUILD-20160903.075655-2-stubs.jar -├── github-webhook-0.0.1.BUILD-20160903.075655-2-stubs.jar.sha1 -├── github-webhook-0.0.1.BUILD-SNAPSHOT.jar -├── github-webhook-0.0.1.BUILD-SNAPSHOT.pom -├── github-webhook-0.0.1.BUILD-SNAPSHOT-stubs.jar -├── ... -└── ... ----- - -There are three possibilities of working with those dependencies so as not to have any -issues with transitive dependencies: - -* Mark all application dependencies as optional -* Create a separate artifactid for the stubs -* Exclude dependencies on the consumer side - -*Mark all application dependencies as optional* - -If, in the `github-webhook` application, you mark all of your dependencies as optional, -when you include the `github-webhook` stubs in another application (or when that -dependency gets downloaded by Stub Runner) then, since all of the dependencies are -optional, they will not get downloaded. - -*Create a separate `artifactid` for the stubs* - -If you create a separate `artifactid`, then you can set it up in whatever way you wish. -For example, you might decide to have no dependencies at all. - -*Exclude dependencies on the consumer side* - -As a consumer, if you add the stub dependency to your classpath, you can explicitly -exclude the unwanted dependencies. - -= Scenarios - -You can handle scenarios with Spring Cloud Contract Verifier. All you need to do is to -stick to the proper naming convention while creating your contracts. The convention -requires including an order number followed by an underscore. This will work regardles - of whether you're working with YAML or Groovy. Example: - -[source,indent=0] ----- -my_contracts_dir\ - scenario1\ - 1_login.groovy - 2_showCart.groovy - 3_logout.groovy ----- - -Such a tree causes Spring Cloud Contract Verifier to generate WireMock's scenario with a -name of `scenario1` and the three following steps: - -. login marked as `Started` pointing to... -. showCart marked as `Step1` pointing to... -. logout marked as `Step2` which will close the scenario. - -More details about WireMock scenarios can be found at -https://wiremock.org/docs/stateful-behaviour/[https://wiremock.org/docs/stateful-behaviour/] - -Spring Cloud Contract Verifier also generates tests with a guaranteed order of execution. - -[[docker-project]] -= Docker Project - -We're publishing a `springcloud/spring-cloud-contract` Docker image -that contains a project that will generate tests and execute them in `EXPLICIT` mode -against a running application. - -TIP: The `EXPLICIT` mode means that the tests generated from contracts will send -real requests and not the mocked ones. - -== Short intro to Maven, JARs and Binary storage - -Since the Docker image can be used by non JVM projects, it's good to -explain the basic terms behind Spring Cloud Contract packaging defaults. - -Part of the following definitions were taken from the https://maven.apache.org/glossary.html[Maven Glossary] - -- `Project`: Maven thinks in terms of projects. Everything that you -will build are projects. Those projects follow a well defined -“Project Object Model”. Projects can depend on other projects, -in which case the latter are called “dependencies”. A project may -consistent of several subprojects, however these subprojects are still -treated equally as projects. -- `Artifact`: An artifact is something that is either produced or used -by a project. Examples of artifacts produced by Maven for a project -include: JARs, source and binary distributions. Each artifact -is uniquely identified by a group id and an artifact ID which is -unique within a group. -- `JAR`: JAR stands for Java ARchive. It's a format based on -the ZIP file format. Spring Cloud Contract packages the contracts and generated -stubs in a JAR file. -- `GroupId`: A group ID is a universally unique identifier for a project. -While this is often just the project name (eg. commons-collections), -it is helpful to use a fully-qualified package name to distinguish it -from other projects with a similar name (eg. org.apache.maven). -Typically, when published to the Artifact Manager, the `GroupId` will get -slash separated and form part of the URL. E.g. for group id `com.example` -and artifact id `application` would be `/com/example/application/`. -- `Classifier`: The Maven dependency notation looks as follows: -`groupId:artifactId:version:classifier`. The classifier is additional suffix -passed to the dependency. E.g. `stubs`, `sources`. The same dependency -e.g. `com.example:application` can produce multiple artifacts that -differ from each other with the classifier. -- `Artifact manager`: When you generate binaries / sources / packages, you would -like them to be available for others to download / reference or reuse. In case -of the JVM world those artifacts would be JARs, for Ruby these are gems -and for Docker those would be Docker images. You can store those artifacts -in a manager. Examples of such managers can be https://jfrog.com/artifactory/[Artifactory] -or https://www.sonatype.org/nexus/[Nexus]. - -== How it works - -The image searches for contracts under the `/contracts` folder. -The output from running the tests will be available under -`/spring-cloud-contract/build` folder (it's useful for debugging -purposes). - -It's enough for you to mount your contracts, pass the environment variables - and the image will: - -- generate the contract tests -- execute the tests against the provided URL -- generate the https://github.com/tomakehurst/wiremock[WireMock] stubs -- (optional - turned on by default) publish the stubs to a Artifact Manager - -=== Environment Variables - -The Docker image requires some environment variables to point to -your running application, to the Artifact manager instance etc. - -- `PROJECT_GROUP` - your project's group id. Defaults to `com.example` -- `PROJECT_VERSION` - your project's version. Defaults to `0.0.1-SNAPSHOT` -- `PROJECT_NAME` - artifact id. Defaults to `example` -- `PRODUCER_STUBS_CLASSIFIER` - archive classifier used for generated producer stubs, defaults to `stubs`. -- `REPO_WITH_BINARIES_URL` - URL of your Artifact Manager. Defaults to `http://localhost:8081/artifactory/libs-release-local` -which is the default URL of https://jfrog.com/artifactory/[Artifactory] running locally -- `REPO_WITH_BINARIES_USERNAME` - (optional) username when the Artifact Manager is secured, defaults to `admin`. -- `REPO_WITH_BINARIES_PASSWORD` - (optional) password when the Artifact Manager is secured, defaults to `password`. -- `PUBLISH_ARTIFACTS` - if set to `true` then will publish artifact to binary storage. Defaults to `true`. - -These environment variables are used when contracts lay in an external repository. To enable -this feature you must set the `EXTERNAL_CONTRACTS_ARTIFACT_ID` environment variable. - -- `EXTERNAL_CONTRACTS_GROUP_ID` - group id of the project with contracts. Defaults to `com.example` -- `EXTERNAL_CONTRACTS_ARTIFACT_ID`- artifact id of the project with contracts. -- `EXTERNAL_CONTRACTS_CLASSIFIER`- classifier of the project with contracts. Empty by default -- `EXTERNAL_CONTRACTS_VERSION` - version of the project with contracts. Defaults to `+`, equivalent to picking the latest -- `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL` - URL of your Artifact Manager. Defaults to value of `REPO_WITH_BINARIES_URL` env var. -If that's not set, defaults to `http://localhost:8081/artifactory/libs-release-local` -which is the default URL of https://jfrog.com/artifactory/[Artifactory] running locally -- `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_USERNAME` - (optional) username if the `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL` -requires authentication, defaults to `REPO_WITH_BINARIES_USERNAME`. If that's not set defaults to `admin`. -- `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_PASSWORD` - (optional) password if the `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL` -requires authentication, defaults to `REPO_WITH_BINARIES_PASSWORD`. If that's not set defaults to `password`. -- `EXTERNAL_CONTRACTS_PATH` - path to contracts for the given project, inside the project with contracts. -Defaults to slash separated `EXTERNAL_CONTRACTS_GROUP_ID` concatenated with `/` and `EXTERNAL_CONTRACTS_ARTIFACT_ID`. E.g. -for group id `foo.bar` and artifact id `baz`, would result in `foo/bar/baz` contracts path. -- `EXTERNAL_CONTRACTS_WORK_OFFLINE` - if set to `true` then will retrieve artifact with contracts -from the container's `.m2`. Mount your local `.m2` as a volume available at the container's `/root/.m2` path. -You must not set both `EXTERNAL_CONTRACTS_WORK_OFFLINE` and `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL`. - - -These environment variables are used when tests are executed: - -- `APPLICATION_BASE_URL` - url against which tests should be executed. -Remember that it has to be accessible from the Docker container (e.g. `localhost` -will not work) -- `APPLICATION_USERNAME` - (optional) username for basic authentication to your application -- `APPLICATION_PASSWORD` - (optional) password for basic authentication to your application - -== Example of usage - -Let's take a look at a simple MVC application - -```bash -$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs -$ cd bookstore -``` - -The contracts are available under `/contracts` folder. - -[[docker-server-side]] -== Server side (nodejs) - -Since we want to run tests, we could just execute: - -```bash -$ npm test -``` - -however, for learning purposes, let's split it into pieces: - -```bash -# Stop docker infra (nodejs, artifactory) -$ ./stop_infra.sh -# Start docker infra (nodejs, artifactory) -$ ./setup_infra.sh - -# Kill & Run app -$ pkill -f "node app" -$ nohup node app & - -# Prepare environment variables -$ SC_CONTRACT_DOCKER_VERSION="..." -$ APP_IP="192.168.0.100" -$ APP_PORT="3000" -$ ARTIFACTORY_PORT="8081" -$ APPLICATION_BASE_URL="http://${APP_IP}:${APP_PORT}" -$ ARTIFACTORY_URL="http://${APP_IP}:${ARTIFACTORY_PORT}/artifactory/libs-release-local" -$ CURRENT_DIR="$( pwd )" -$ CURRENT_FOLDER_NAME=${PWD##*/} -$ PROJECT_VERSION="0.0.1.RELEASE" - -# Execute contract tests -$ docker run --rm -e "APPLICATION_BASE_URL=${APPLICATION_BASE_URL}" -e "PUBLISH_ARTIFACTS=true" -e "PROJECT_NAME=${CURRENT_FOLDER_NAME}" -e "REPO_WITH_BINARIES_URL=${ARTIFACTORY_URL}" -e "PROJECT_VERSION=${PROJECT_VERSION}" -v "${CURRENT_DIR}/contracts/:/contracts:ro" -v "${CURRENT_DIR}/node_modules/spring-cloud-contract/output:/spring-cloud-contract-output/" springcloud/spring-cloud-contract:"${SC_CONTRACT_DOCKER_VERSION}" - -# Kill app -$ pkill -f "node app" -``` - -What will happen is that via bash scripts: - -- infrastructure will be set up (MongoDb, Artifactory). -In real life scenario you would just run the NodeJS application -with mocked database. In this example we want to show how we can -benefit from Spring Cloud Contract in no time. -- due to those constraints the contracts also represent the -stateful situation -** first request is a `POST` that causes data to get inserted to the database -** second request is a `GET` that returns a list of data with 1 previously inserted element -- the NodeJS application will be started (on port `3000`) -- contract tests will be generated via Docker and tests -will be executed against the running application -** the contracts will be taken from `/contracts` folder. -** the output of the test execution is available under -`node_modules/spring-cloud-contract/output`. -- the stubs will be uploaded to Artifactory. You can check them out -under http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/ . -The stubs will be here http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar. - -To see how the client side looks like check out the <> section. +---- \ No newline at end of file From 3d89adcf8825b86b3b4e7b4befd45e5f7147053b Mon Sep 17 00:00:00 2001 From: Marcin Grzejszczak Date: Thu, 25 Jul 2019 14:40:21 +0200 Subject: [PATCH 13/18] Working docs --- README.adoc | 1539 +---------------- docs/src/main/asciidoc/README.adoc | 38 +- docs/src/main/asciidoc/_attributes.adoc | 3 +- ...ow_it_works.adoc => _getting-started.adoc} | 539 ++++-- docs/src/main/asciidoc/_links.adoc | 11 - ...t.adoc => _project-features-contract.adoc} | 1054 ++--------- .../asciidoc/_project-features-flows.adoc | 417 +++++ .../asciidoc/_project-features-messaging.adoc | 922 ++++++++++ .../_project-features-stubrunner.adoc | 255 ++- .../asciidoc/_project-features-wiremock.adoc | 175 ++ .../_spring-cloud-contract-verifier.adoc | 13 - .../main/asciidoc/_spring-cloud-wiremock.adoc | 422 ----- .../main/asciidoc/_verifier_introduction.adoc | 120 -- .../main/asciidoc/_verifier_messaging.adoc | 195 --- docs/src/main/asciidoc/_verifier_setup.adoc | 7 - .../main/asciidoc/_verifier_stubrunner.adoc | 182 -- .../asciidoc/_verifier_stubrunner_msg.adoc | 75 - docs/src/main/asciidoc/advanced.adoc | 373 ++++ docs/src/main/asciidoc/docker-project.adoc | 89 +- .../main/asciidoc/documentation-overview.adoc | 26 +- docs/src/main/asciidoc/getting-started.adoc | 1137 +----------- docs/src/main/asciidoc/howto.adoc | 280 ++- docs/src/main/asciidoc/index.htmladoc | 8 +- docs/src/main/asciidoc/index.htmlpdfadoc | 4 +- docs/src/main/asciidoc/index.htmlsingleadoc | 4 +- docs/src/main/asciidoc/project-features.adoc | 21 +- .../spec/internal/RegexCreatingProperty.java | 2 + .../junit/StubRunnerRuleJUnitTest.java | 2 +- .../builder/ContractHttpDocsSpec.groovy | 16 + .../src/test/resources/yml/contract.yml | 2 +- .../README.adoc | 125 -- .../README.adoc | 123 -- .../README.adoc | 138 -- .../README.adoc | 160 -- 34 files changed, 3000 insertions(+), 5477 deletions(-) rename docs/src/main/asciidoc/{_verifier_how_it_works.adoc => _getting-started.adoc} (69%) delete mode 100644 docs/src/main/asciidoc/_links.adoc rename docs/src/main/asciidoc/{_verifier_contract.adoc => _project-features-contract.adoc} (60%) create mode 100644 docs/src/main/asciidoc/_project-features-flows.adoc create mode 100644 docs/src/main/asciidoc/_project-features-messaging.adoc rename spring-cloud-contract-stub-runner/README.adoc => docs/src/main/asciidoc/_project-features-stubrunner.adoc (70%) create mode 100644 docs/src/main/asciidoc/_project-features-wiremock.adoc delete mode 100644 docs/src/main/asciidoc/_spring-cloud-contract-verifier.adoc delete mode 100644 docs/src/main/asciidoc/_spring-cloud-wiremock.adoc delete mode 100644 docs/src/main/asciidoc/_verifier_introduction.adoc delete mode 100644 docs/src/main/asciidoc/_verifier_messaging.adoc delete mode 100644 docs/src/main/asciidoc/_verifier_setup.adoc delete mode 100644 docs/src/main/asciidoc/_verifier_stubrunner.adoc delete mode 100644 docs/src/main/asciidoc/_verifier_stubrunner_msg.adoc create mode 100644 docs/src/main/asciidoc/advanced.adoc delete mode 100644 tests/spring-cloud-contract-stub-runner-amqp/README.adoc delete mode 100644 tests/spring-cloud-contract-stub-runner-camel/README.adoc delete mode 100644 tests/spring-cloud-contract-stub-runner-integration/README.adoc delete mode 100644 tests/spring-cloud-contract-stub-runner-stream/README.adoc diff --git a/README.adoc b/README.adoc index dc5a173a58..33f0acfdfc 100644 --- a/README.adoc +++ b/README.adoc @@ -4,29 +4,6 @@ Manual changes to this file will be lost when it is generated again. Edit the files in the src/main/asciidoc/ directory instead. //// -:branch: master -image::https://badges.gitter.im/Join%20Chat.svg[Gitter, link="https://gitter.im/spring-cloud/spring-cloud-contract?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge"] -image::https://codecov.io/gh/spring-cloud/spring-cloud-contract/branch/{branch}/graph/badge.svg["codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-contract"] -image::https://circleci.com/gh/spring-cloud/spring-cloud-contract.svg?style=svg["CircleCI", link="https://circleci.com/gh/spring-cloud/spring-cloud-contract"] -:branch: master -:core_path: ../../.. -:plugins_path: ../../../spring-cloud-contract-tools -:converters_path: {plugins_path}/spring-cloud-contract-converters -:verifier_root_path: {core_path}/spring-cloud-contract-verifier -:contract_spec_path: {core_path}/specs/spring-cloud-contract-spec-java -:contract_spec_tests_path: {core_path}/specs/spring-cloud-contract-spec -:samples_path: {core_path}/samples -:verifier_core_path: {verifier_root_path} -:stubrunner_core_path: {core_path}/spring-cloud-contract-stub-runner -:standalone_samples_path: {samples_path}/standalone/dsl -:standalone_messaging_samples_path: {samples_path}/standalone/messaging -:standalone_pact_path: {samples_path}/standalone/pact -:standalone_restdocs_path: {samples_path}/standalone/restdocs -:tests_path: {core_path}/tests -:samples_branch: 2.2.x -:samples_url: https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/{samples_branch} -:introduction_url: ${core_path}/../../ - == Spring Cloud Contract You always need confidence when pushing new features into a new application or service in @@ -41,1521 +18,9 @@ If you prefer to learn about the project by doing some tutorials, you can check workshops under https://cloud-samples.spring.io/spring-cloud-contract-samples/workshops.html[this link]. -=== Spring Cloud Contract Verifier +== Project page -== Spring Cloud Contract Introduction - -Spring Cloud Contract moves TDD to the level of software architecture. It allows to perform consumer, consumer-driven and producer-driven contract testing. - -=== History - -Before becoming Spring Cloud Contract, this project was called https://github.com/Codearte/accurest[Accurest]. -It was created by https://twitter.com/mgrzejszczak[Marcin Grzejszczak] and https://twitter.com/jkubrynski[Jakub Kubrynski] -from (https://github.com/Codearte[Codearte]. - -The `0.1.0` release took place on 26 Jan 2015 and it became stable with `1.0.0` release on 29 Feb 2016. - -=== Why a Contract Verifier? - -Assume that we have a system consisting of multiple microservices: - -image::{github-raw}/docs/src/main/asciidoc/images/Deps.png[Microservices Architecture] - -==== Testing issues - -If we wanted to test the application in top left corner to determine whether it can -communicate with other services, we could do one of two things: - -- Deploy all microservices and perform end-to-end tests. -- Mock other microservices in unit/integration tests. - -Both have their advantages but also a lot of disadvantages. - -*Deploy all microservices and perform end to end tests* - - -Advantages: - -- Simulates production. -- Tests real communication between services. - -Disadvantages: - -- To test one microservice, we have to deploy 6 microservices, a couple of databases, -etc. -- The environment where the tests run is locked for a single suite of tests (nobody else -would be able to run the tests in the meantime). -- They take a long time to run. -- The feedback comes very late in the process. -- They are extremely hard to debug. - -*Mock other microservices in unit/integration tests* - -Advantages: - -- They provide very fast feedback. -- They have no infrastructure requirements. - -Disadvantages: - -- The implementor of the service creates stubs that might have nothing to do with -reality. -- You can go to production with passing tests and failing production. - -To solve the aforementioned issues, Spring Cloud Contract was created. The main idea is to give you very fast feedback, without the need to set up the -whole world of microservices. If you work on stubs, then the only applications you need -are those that your application directly uses. - -image::{github-raw}/docs/src/main/asciidoc/images/Stubs2.png[Stubbed Services] - -Spring Cloud Contract gives you the certainty that the stubs that you use were -created by the service that you're calling. Also, if you can use them, it means that they -were tested against the producer's side. In short, you can trust those stubs. - -=== Purposes - -The main purposes of Spring Cloud Contract are: - -- To ensure that Http / Messaging stubs (used when developing the client) do exactly -what the actual server-side implementation does. -- To promote ATDD (acceptance test driven developement) method and Microservices architectural style. -- To provide a way to publish changes in contracts that are immediately visible on both -sides. -- To generate boilerplate test code to be used on the server side. - -By default Spring Cloud Contract integrates with http://wiremock.org[Wiremock] as the HTTP server stub. - -IMPORTANT: Spring Cloud Contract's purpose is NOT to start writing business -features in the contracts. Assume that we have a business use case of fraud check. If a -user can be a fraud for 100 different reasons, we would assume that you would create 2 -contracts, one for the positive case and one for the negative case. Contract tests are -used to test contracts between applications and not to simulate full behavior. - -=== How It Works - -This section explores how Spring Cloud Contract. - -[[spring-cloud-contract-verifier-intro-three-second-tour]] -==== A Three-second Tour - -This very brief tour walks through using Spring Cloud Contract: - -* <> -* <> - -You can find a somewhat longer tour -<>. - -[plantuml, three-second, png] ----- -"API Producer"->"API Producer": add Spring Cloud \nContract (SCC) plugin -"API Producer"->"API Producer": add SCC Verifier dependency -"API Producer"->"API Producer": define contracts -"API Producer"->"Build": run build -"Build"->"SCC Plugin": generate \ntests, stubs and stubs \nartifact (e.g. stubs-jar) -"Build"->"Nexus / Artifactory": upload contracts \nand stubs and the project arifact -"Build"->"API Producer": Build successful -"API Consumer"->"API Consumer": add SCC Stub Runner \ndependency -"API Consumer"->"API Consumer": write a SCC Stub Runner \nbased contract test -"SCC Stub Runner"->"Nexus / Artifactory": test asks for [API Producer] stubs -"Nexus / Artifactory"->"SCC Stub Runner": fetch the [API Producer] stubs -"SCC Stub Runner"->"SCC Stub Runner": run in memory\n HTTP server stubs -"API Consumer"->"SCC Stub Runner": send a request \nto the HTTP server stub -"SCC Stub Runner"->"API Consumer": communication is correct ----- - -[[spring-cloud-contract-verifier-intro-three-second-tour-producer]] -===== On the Producer Side - -To start working with Spring Cloud Contract, add files with `REST`/messaging contracts -expressed in either Groovy DSL or YAML to the contracts directory, which is set by the -`contractsDslDir` property. By default, it is `$rootDir/src/test/resources/contracts`. - -Then add the Spring Cloud Contract Verifier dependency and plugin to your build file, as -shown in the following example: - -[source,xml,indent=0] ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] ----- - -The following listing shows how to add the plugin, which should go in the build/plugins -portion of the file: - -[source,xml,indent=0] ----- - - org.springframework.cloud - spring-cloud-contract-maven-plugin - ${spring-cloud-contract.version} - true - ----- - -Running `./mvnw clean install` automatically generates tests that verify the application -compliance with the added contracts. By default, the tests get generated under -`org.springframework.cloud.contract.verifier.tests.`. - -As the implementation of the functionalities described by the contracts is not yet -present, the tests fail. - -To make them pass, you must add the correct implementation of either handling HTTP -requests or messages. Also, you must add a correct base test class for auto-generated -tests to the project. This class is extended by all the auto-generated tests, and it -should contain all the setup necessary to run them (for example `RestAssuredMockMvc` -controller setup or messaging test setup). - -Once the implementation and the test base class are in place, the tests pass, and both the -application and the stub artifacts are built and installed in the local Maven repository. -The changes can now be merged, and both the application and the stub artifacts may be -published in an online repository. - -[[spring-cloud-contract-verifier-intro-three-second-tour-consumer]] -===== On the Consumer Side - -`Spring Cloud Contract Stub Runner` can be used in the integration tests to get a running -WireMock instance or messaging route that simulates the actual service. - -To do so, add the dependency to `Spring Cloud Contract Stub Runner`, as shown in the -following example: - -[source,xml,indent=0] ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] ----- - -You can get the Producer-side stubs installed in your Maven repository in either of two -ways: - -* By checking out the Producer side repository and adding contracts and generating the stubs -by running the following commands: -+ -[source,bash,indent=0] ----- -$ cd local-http-server-repo -$ ./mvnw clean install -DskipTests ----- -TIP: The tests are being skipped because the Producer-side contract implementation is not -in place yet, so the automatically-generated contract tests fail. -* By getting already-existing producer service stubs from a remote repository. To do so, -pass the stub artifact IDs and artifact repository URL as `Spring Cloud Contract -Stub Runner` properties, as shown in the following example: -+ -[source,yaml,indent=0] ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{github-raw}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ----- - -Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, -provide the `group-id` and `artifact-id` values for `Spring Cloud Contract Stub Runner` to -run the collaborators' stubs for you, as shown in the following example: - -[source,java, indent=0] ----- -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment=WebEnvironment.NONE) -@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"}, - stubsMode = StubRunnerProperties.StubsMode.LOCAL) -public class LoanApplicationServiceTests { ----- - -TIP: Use the `REMOTE` `stubsMode` when downloading stubs from an online repository and -`LOCAL` for offline work. - -Now, in your integration test, you can receive stubbed versions of HTTP responses or -messages that are expected to be emitted by the collaborator service. - -[[spring-cloud-contract-verifier-intro-three-minute-tour]] -==== A Three-minute Tour - -This brief tour walks through using Spring Cloud Contract: - -* <> -* <> - -You can find an even more brief tour -<>. - -[[spring-cloud-contract-verifier-intro-three-minute-tour-producer]] -===== On the Producer Side - -To start working with `Spring Cloud Contract`, add files with `REST/` messaging contracts -expressed in either Groovy DSL or YAML to the contracts directory, which is set by the -`contractsDslDir` property. By default, it is `$rootDir/src/test/resources/contracts`. - -For the HTTP stubs, a contract defines what kind of response should be returned for a -given request (taking into account the HTTP methods, URLs, headers, status codes, and so -on). The following example shows how an HTTP stub contract: - -==== -[source,groovy,indent=0,role="primary"] -.groovy ----- -package contracts - -org.springframework.cloud.contract.spec.Contract.make { - request { - method 'PUT' - url '/fraudcheck' - body([ - "client.id": $(regex('[0-9]{10}')), - loanAmount: 99999 - ]) - headers { - contentType('application/json') - } - } - response { - status OK() - body([ - fraudCheckStatus: "FRAUD", - "rejection.reason": "Amount too high" - ]) - headers { - contentType('application/json') - } - } -} ----- - -[source,yaml,indent=0,role="secondary"] -.yaml ----- -request: - method: PUT - url: /fraudcheck - body: - "client.id": 1234567890 - loanAmount: 99999 - headers: - Content-Type: application/json - matchers: - body: - - path: $.['client.id'] - type: by_regex - value: "[0-9]{10}" -response: - status: 200 - body: - fraudCheckStatus: "FRAUD" - "rejection.reason": "Amount too high" - headers: - Content-Type: application/json;charset=UTF-8 ----- -==== - -In the case of messaging, you can define: - -* The input and the output messages can be defined (taking into account from and where it -was sent, the message body, and the header). -* The methods that should be called after the message is received. -* The methods that, when called, should trigger a message. - -The following example shows a Camel messaging contract: - -==== -[source,groovy,indent=0,role="primary"] -.groovy ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_no_output_dsl] ----- - -[source,yaml,indent=0,role="secondary"] -.yaml ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{verifier_core_path}/src/test/resources/yml/contract_message_scenario3.yml[indent=0] ----- -==== - - -Then you can add Spring Cloud Contract Verifier dependency and plugin to your build file, -as shown in the following example: - -[source,xml,indent=0] ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] ----- - -The following listing shows how to add the plugin, which should go in the build/plugins -portion of the file: - -[source,xml,indent=0] ----- - - org.springframework.cloud - spring-cloud-contract-maven-plugin - ${spring-cloud-contract.version} - true - ----- - -Running `./mvnw clean install` automatically generates tests that verify the application -compliance with the added contracts. By default, the generated tests are under -`org.springframework.cloud.contract.verifier.tests.`. - -The following example shows a sample auto-generated test for an HTTP contract: - -[source,java,indent=0] ----- -@Test -public void validate_shouldMarkClientAsFraud() throws Exception { - // given: - MockMvcRequestSpecification request = given() - .header("Content-Type", "application/vnd.fraud.v1+json") - .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}"); - - // when: - ResponseOptions response = given().spec(request) - .put("/fraudcheck"); - - // then: - assertThat(response.statusCode()).isEqualTo(200); - assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*"); - // and: - DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); - assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}"); - assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high"); -} ----- - -The preceding example uses Spring's `MockMvc` to run the tests. This is the default test -mode for HTTP contracts. However, JAX-RS client and explicit HTTP invocations can also be -used. (To do so, change the `testMode` property of the plugin to `JAX-RS` or `EXPLICIT`, -respectively.) - -Since 2.1.0, it is also possible to use `RestAssuredWebTestClient`with Spring's reactive `WebTestClient` -run under the hood. This is particularly recommended while working with Reactive, `Web-Flux`-based applications. -In order to use `WebTestClient` set `testMode` to `WEBTESTCLIENT`. - -Here is an example of a test generated in `WEBTESTCLIENT` test mode: - -[source,java,indent=0] ----- -@Test - public void validate_shouldRejectABeerIfTooYoung() throws Exception { - // given: - WebTestClientRequestSpecification request = given() - .header("Content-Type", "application/json") - .body("{\"age\":10}"); - - // when: - WebTestClientResponse response = given().spec(request) - .post("/check"); - - // then: - assertThat(response.statusCode()).isEqualTo(200); - assertThat(response.header("Content-Type")).matches("application/json.*"); - // and: - DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); - assertThatJson(parsedJson).field("['status']").isEqualTo("NOT_OK"); - } ----- - -Apart from the default JUnit 4, you can instead use JUnit 5 or Spock tests, by setting the plugin -`testFramework` property to either `JUNIT5` or `Spock`. - -TIP: You can now also generate WireMock scenarios based on the contracts, by including an -order number followed by an underscore at the beginning of the contract file names. - -The following example shows an auto-generated test in Spock for a messaging stub contract: - -[source,groovy,indent=0] ----- -given: - ContractVerifierMessage inputMessage = contractVerifierMessaging.create( - \'\'\'{"bookName":"foo"}\'\'\', - ['sample': 'header'] - ) - -when: - contractVerifierMessaging.send(inputMessage, 'jms:delete') - -then: - noExceptionThrown() - bookWasDeleted() ----- - -As the implementation of the functionalities described by the contracts is not yet -present, the tests fail. - -To make them pass, you must add the correct implementation of handling either HTTP -requests or messages. Also, you must add a correct base test class for auto-generated -tests to the project. This class is extended by all the auto-generated tests and should -contain all the setup necessary to run them (for example, `RestAssuredMockMvc` controller -setup or messaging test setup). - -Once the implementation and the test base class are in place, the tests pass, and both the -application and the stub artifacts are built and installed in the local Maven repository. -Information about installing the stubs jar to the local repository appears in the logs, as -shown in the following example: - -[source,bash,indent=0] ----- - [INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server --- - [INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar - [INFO] - [INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server --- - [INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar - [INFO] - [INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server --- - [INFO] - [INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server --- - [INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar - [INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom - [INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar ----- - -You can now merge the changes and publish both the application and the stub artifacts -in an online repository. - -*Docker Project* - -In order to enable working with contracts while creating applications in non-JVM -technologies, the `springcloud/spring-cloud-contract` Docker image has been created. It -contains a project that automatically generates tests for HTTP contracts and executes them -in `EXPLICIT` test mode. Then, if the tests pass, it generates Wiremock stubs and, -optionally, publishes them to an artifact manager. In order to use the image, you can -mount the contracts into the `/contracts` directory and set a few environment variables. -// TODO: We should answer the obvious question: Which environment variables? - -[[spring-cloud-contract-verifier-intro-three-minute-tour-consumer]] -===== On the Consumer Side - -`Spring Cloud Contract Stub Runner` can be used in the integration tests to get a running -WireMock instance or messaging route that simulates the actual service. - -To get started, add the dependency to `Spring Cloud Contract Stub Runner`: - -[source,xml,indent=0] ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] ----- - -You can get the Producer-side stubs installed in your Maven repository in either of two -ways: - -* By checking out the Producer side repository and adding contracts and generating the -stubs by running the following commands: -+ -[source,bash,indent=0] ----- -$ cd local-http-server-repo -$ ./mvnw clean install -DskipTests ----- -NOTE: The tests are skipped because the Producer-side contract implementation is not yet -in place, so the automatically-generated contract tests fail. -* Getting already existing producer service stubs from a remote repository. To do so, -pass the stub artifact IDs and artifact repository URl as `Spring Cloud Contract Stub -Runner` properties, as shown in the following example: -+ -[source,yaml,indent=0] ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{github-raw}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ----- - -Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, -provide the `group-id` and `artifact-id` for `Spring Cloud Contract Stub Runner` to run -the collaborators' stubs for you, as shown in the following example: - -[source,java, indent=0] ----- -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment=WebEnvironment.NONE) -@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"}, - stubsMode = StubRunnerProperties.StubsMode.LOCAL) -public class LoanApplicationServiceTests { ----- - -TIP: Use the `REMOTE` `stubsMode` when downloading stubs from an online repository and -`LOCAL` for offline work. - -In your integration test, you can receive stubbed versions of HTTP responses or messages -that are expected to be emitted by the collaborator service. You can see entries similar -to the following in the build logs: - -[source,bash,indent=0] ----- -2016-07-19 14:22:25.403 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Desired version is + - will try to resolve the latest version -2016-07-19 14:22:25.438 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved version is 0.0.1-SNAPSHOT -2016-07-19 14:22:25.439 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories [] -2016-07-19 14:22:25.451 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar -2016-07-19 14:22:25.465 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar] -2016-07-19 14:22:25.475 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265] -2016-07-19 14:22:27.737 INFO 41050 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}] ----- - -==== Defining the Contract - -As consumers of services, we need to define what exactly we want to achieve. We need to -formulate our expectations. That is why we write contracts. - -Assume that you want to send a request containing the ID of a client company and the -amount it wants to borrow from us. You also want to send it to the /fraudcheck url via -the PUT method. - -==== -[source,groovy,indent=0,role="primary"] -.groovy ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[] ----- - -[source,yaml,indent=0,role="secondary"] -.yaml ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/yml/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.yml[] ----- -==== - -==== Client Side - -Spring Cloud Contract generates stubs, which you can use during client-side testing. -You get a running WireMock instance/Messaging route that simulates the service. -You would like to feed that instance with a proper stub definition. - -At some point in time, you need to send a request to the Fraud Detection service. - -[source,groovy,indent=0] ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/src/main/java/com/example/loan/LoanApplicationService.java[tags=client_call_server,indent=0] ----- - -Annotate your test class with `@AutoConfigureStubRunner`. In the annotation provide the group id and artifact id for the Stub Runner to download stubs of your collaborators. - -[source,groovy,indent=0] ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=autoconfigure_stubrunner,indent=0] ----- - -After that, during the tests, Spring Cloud Contract automatically finds the stubs -(simulating the real service) in the Maven repository and exposes them on a configured -(or random) port. - -==== Server Side - -Since you are developing your stub, you need to be sure that it actually resembles your -concrete implementation. You cannot have a situation where your stub acts in one way and -your application behaves in a different way, especially in production. - -To ensure that your application behaves the way you define in your stub, tests are -generated from the stub you provide. - -The autogenerated test looks, more or less, like this: - -[source,java,indent=0] ----- -@Test -public void validate_shouldMarkClientAsFraud() throws Exception { - // given: - MockMvcRequestSpecification request = given() - .header("Content-Type", "application/vnd.fraud.v1+json") - .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}"); - - // when: - ResponseOptions response = given().spec(request) - .put("/fraudcheck"); - - // then: - assertThat(response.statusCode()).isEqualTo(200); - assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*"); - // and: - DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); - assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}"); - assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high"); -} ----- - -=== Step-by-step Guide to Consumer Driven Contracts (CDC) - -Consider an example of Fraud Detection and the Loan Issuance process. The business -scenario is such that we want to issue loans to people but do not want them to steal from -us. The current implementation of our system grants loans to everybody. - -Assume that `Loan Issuance` is a client to the `Fraud Detection` server. In the current -sprint, we must develop a new feature: if a client wants to borrow too much money, then -we mark the client as a fraud. - -Technical remark - Fraud Detection has an `artifact-id` of `http-server`, while Loan -Issuance has an artifact-id of `http-client`, and both have a `group-id` of `com.example`. - -Social remark - both client and server development teams need to communicate directly and -discuss changes while going through the process. CDC is all about communication. - -The https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-server[server -side code is available here] and https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-client[the -client code here]. - -TIP: In this case, the producer owns the contracts. Physically, all the contract are -in the producer's repository. - -==== Technical note - -If using the *SNAPSHOT* / *Milestone* / *Release Candidate* versions please add the -following section to your build: - -[source,xml,indent=0,subs="verbatim,attributes",role="primary"] -.Maven ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=repos,indent=0] ----- - -[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] -.Gradle ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/build.gradle[tags=deps_repos,indent=0] ----- - -==== Consumer side (Loan Issuance) - -As a developer of the Loan Issuance service (a consumer of the Fraud Detection server), you might do the following steps: - -. Start doing TDD by writing a test for your feature. -. Write the missing implementation. -. Clone the Fraud Detection service repository locally. -. Define the contract locally in the repo of Fraud Detection service. -. Add the Spring Cloud Contract Verifier plugin. -. Run the integration tests. -. File a pull request. -. Create an initial implementation. -. Take over the pull request. -. Write the missing implementation. -. Deploy your app. -. Work online. - -*Start doing TDD by writing a test for your feature.* - -[source,groovy,indent=0] ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=client_tdd,indent=0] ----- - -Assume that you have written a test of your new feature. If a loan application for a big -amount is received, the system should reject that loan application with some description. - -*Write the missing implementation.* - -At some point in time, you need to send a request to the Fraud Detection service. Assume -that you need to send the request containing the ID of the client and the amount the -client wants to borrow. You want to send it to the `/fraudcheck` url via the `PUT` method. - -[source,groovy,indent=0] ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/src/main/java/com/example/loan/LoanApplicationService.java[tags=client_call_server,indent=0] ----- - -For simplicity, the port of the Fraud Detection service is set to `8080`, and the -application runs on `8090`. - -If you start the test at this point, it breaks, because no service currently runs on port -`8080`. - -*Clone the Fraud Detection service repository locally.* - -You can start by playing around with the server side contract. To do so, you must first -clone it. - -[source,bash,indent=0] ----- -$ git clone https://your-git-server.com/server-side.git local-http-server-repo ----- - -*Define the contract locally in the repo of Fraud Detection service.* - -As a consumer, you need to define what exactly you want to achieve. You need to formulate -your expectations. To do so, write the following contract: - -IMPORTANT: Place the contract under `src/test/resources/contracts/fraud` folder. The `fraud` folder -is important because the producer's test base class name references that folder. - -==== -[source,groovy,indent=0,role="primary"] -.groovy ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[] ----- - -[source,yaml,indent=0,role="secondary"] -.yaml ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/yml/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.yml[] ----- -==== - -The YML contract is quite straight-forward. However when you take a look at the Contract -written using a statically typed Groovy DSL - you might wonder what the -`value(client(...), server(...))` parts are. By using this notation, Spring Cloud -Contract lets you define parts of a JSON block, a URL, etc., which are dynamic. In case -of an identifier or a timestamp, you need not hardcode a value. You want to allow some -different ranges of values. To enable ranges of values, you can set regular expressions -matching those values for the consumer side. You can provide the body by means of either -a map notation or String with interpolations. -Consult the <> section for more information. We highly recommend using the map notation! - -TIP: You must understand the map notation in order to set up contracts. Please read the -https://groovy-lang.org/json.html[Groovy docs regarding JSON]. - -The previously shown contract is an agreement between two sides that: - -- if an HTTP request is sent with all of -** a `PUT` method on the `/fraudcheck` endpoint, -** a JSON body with a `client.id` that matches the regular expression `[0-9]{10}` and -`loanAmount` equal to `99999`, -** and a `Content-Type` header with a value of `application/vnd.fraud.v1+json`, -- then an HTTP response is sent to the consumer that -** has status `200`, -** contains a JSON body with the `fraudCheckStatus` field containing a value `FRAUD` and -the `rejectionReason` field having value `Amount too high`, -** and a `Content-Type` header with a value of `application/vnd.fraud.v1+json`. - -Once you are ready to check the API in practice in the integration tests, you need to -install the stubs locally. - -*Add the Spring Cloud Contract Verifier plugin.* - -We can add either a Maven or a Gradle plugin. In this example, you see how to add Maven. -First, add the `Spring Cloud Contract` BOM. - -[source,xml,indent=0] ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_bom,indent=0] ----- - -Next, add the `Spring Cloud Contract Verifier` Maven plugin - -[source,xml,indent=0] ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0] ----- - -Since the plugin was added, you get the `Spring Cloud Contract Verifier` features which, -from the provided contracts: - -- generate and run tests -- produce and install stubs - -You do not want to generate tests since you, as the consumer, want only to play with the -stubs. You need to skip the test generation and execution. When you execute: - -[source,bash,indent=0] ----- -$ cd local-http-server-repo -$ ./mvnw clean install -DskipTests ----- - -In the logs, you see something like this: - -[source,bash,indent=0] ----- -[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server --- -[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar -[INFO] -[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server --- -[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar -[INFO] -[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server --- -[INFO] -[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server --- -[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar -[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom -[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar ----- - -The following line is extremely important: - -[source,bash,indent=0] ----- -[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar ----- - -It confirms that the stubs of the `http-server` have been installed in the local -repository. - -*Run the integration tests.* - -In order to profit from the Spring Cloud Contract Stub Runner functionality of automatic -stub downloading, you must do the following in your consumer side project (`Loan -Application service`): - -Add the `Spring Cloud Contract` BOM: - -[source,xml,indent=0] ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=contract_bom,indent=0] ----- - -Add the dependency to `Spring Cloud Contract Stub Runner`: - -[source,xml,indent=0] ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] ----- - -Annotate your test class with `@AutoConfigureStubRunner`. In the annotation, provide the -`group-id` and `artifact-id` for the Stub Runner to download the stubs of your -collaborators. (Optional step) Because you're playing with the collaborators offline, you -can also provide the offline work switch (`StubRunnerProperties.StubsMode.LOCAL`). - -[source,groovy,indent=0] ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=autoconfigure_stubrunner,indent=0] ----- - -Now, when you run your tests, you see something like this: - -[source,bash,indent=0] ----- -2016-07-19 14:22:25.403 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Desired version is + - will try to resolve the latest version -2016-07-19 14:22:25.438 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved version is 0.0.1-SNAPSHOT -2016-07-19 14:22:25.439 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories [] -2016-07-19 14:22:25.451 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar -2016-07-19 14:22:25.465 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar] -2016-07-19 14:22:25.475 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265] -2016-07-19 14:22:27.737 INFO 41050 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}] ----- - -This output means that Stub Runner has found your stubs and started a server for your app -with group id `com.example`, artifact id `http-server` with version `0.0.1-SNAPSHOT` of -the stubs and with `stubs` classifier on port `8080`. - -*File a pull request.* - -What you have done until now is an iterative process. You can play around with the -contract, install it locally, and work on the consumer side until the contract works as -you wish. - -Once you are satisfied with the results and the test passes, publish a pull request to -the server side. Currently, the consumer side work is done. - -==== Producer side (Fraud Detection server) - -As a developer of the Fraud Detection server (a server to the Loan Issuance service): - -*Create an initial implementation.* - -As a reminder, you can see the initial implementation here: - -[source,java,indent=0] ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=server_api,indent=0] -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=initial_impl,indent=0] -} ----- - -*Take over the pull request.* - -[source,bash,indent=0] ----- -$ git checkout -b contract-change-pr master -$ git pull https://your-git-server.com/server-side-fork.git contract-change-pr ----- - -You must add the dependencies needed by the autogenerated tests: - -[source,xml,indent=0] ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] ----- - -In the configuration of the Maven plugin, pass the `packageWithBaseClasses` property - -[source,xml,indent=0] ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0] ----- - -IMPORTANT: This example uses "convention based" naming by setting the -`packageWithBaseClasses` property. Doing so means that the two last packages combine to -make the name of the base test class. In our case, the contracts were placed under -`src/test/resources/contracts/fraud`. Since you do not have two packages starting from -the `contracts` folder, pick only one, which should be `fraud`. Add the `Base` suffix and -capitalize `fraud`. That gives you the `FraudBase` test class name. - -All the generated tests extend that class. Over there, you can set up your Spring Context -or whatever is necessary. In this case, use https://github.com/rest-assured/rest-assured[Rest Assured MVC] to -start the server side `FraudDetectionController`. - -[source,java,indent=0] ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/src/test/java/com/example/fraud/FraudBase.java[] ----- - -Now, if you run the `./mvnw clean install`, you get something like this: - -[source,bash,indent=0] ----- -Results : - -Tests in error: - ContractVerifierTest.validate_shouldMarkClientAsFraud:32 » IllegalState Parsed... ----- - -This error occurs because you have a new contract from which a test was generated and it -failed since you have not implemented the feature. The auto-generated test would look -like this: - -[source,java,indent=0] ----- -@Test -public void validate_shouldMarkClientAsFraud() throws Exception { - // given: - MockMvcRequestSpecification request = given() - .header("Content-Type", "application/vnd.fraud.v1+json") - .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}"); - - // when: - ResponseOptions response = given().spec(request) - .put("/fraudcheck"); - - // then: - assertThat(response.statusCode()).isEqualTo(200); - assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*"); - // and: - DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); - assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}"); - assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high"); -} ----- - -If you used the Groovy DSL, you can see, all the `producer()` parts of the Contract that were present in the -`value(consumer(...), producer(...))` blocks got injected into the test. -In case of using YAML, the same applied for the `matchers` sections of the `response`. - -Note that, on the producer side, you are also doing TDD. The expectations are expressed -in the form of a test. This test sends a request to our own application with the URL, -headers, and body defined in the contract. It also is expecting precisely defined values -in the response. In other words, you have the `red` part of `red`, `green`, and -`refactor`. It is time to convert the `red` into the `green`. - -*Write the missing implementation.* - -Because you know the expected input and expected output, you can write the missing -implementation: - -[source,java,indent=0] ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=server_api,indent=0] -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=new_impl,indent=0] -Unresolved directive in _verifier_how_it_works.adoc - include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=initial_impl,indent=0] -} ----- - -When you execute `./mvnw clean install` again, the tests pass. Since the `Spring Cloud -Contract Verifier` plugin adds the tests to the `generated-test-sources`, you can -actually run those tests from your IDE. - -*Deploy your app.* - -Once you finish your work, you can deploy your change. First, merge the branch: - -[source,bash,indent=0] ----- -$ git checkout master -$ git merge --no-ff contract-change-pr -$ git push origin master ----- - -Your CI might run something like `./mvnw clean deploy`, which would publish both the -application and the stub artifacts. - -==== Consumer Side (Loan Issuance) Final Step - -As a developer of the Loan Issuance service (a consumer of the Fraud Detection server): - -*Merge branch to master.* - -[source,bash,indent=0] ----- -$ git checkout master -$ git merge --no-ff contract-change-pr ----- - -*Work online.* - -Now you can disable the offline work for Spring Cloud Contract Stub Runner and indicate -where the repository with your stubs is located. At this moment the stubs of the server -side are automatically downloaded from Nexus/Artifactory. You can set the value of -`stubsMode` to `REMOTE`. The following code shows an example of -achieving the same thing by changing the properties. - -[source,yaml,indent=0] ----- -Unresolved directive in _verifier_how_it_works.adoc - include::{github-raw}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ----- - -That's it! - -=== Dependencies - -The best way to add dependencies is to use the proper `starter` dependency. - -For `stub-runner`, use `spring-cloud-starter-stub-runner`. When you use a plugin, add -`spring-cloud-starter-contract-verifier`. - -=== Additional Links - -Here are some resources related to Spring Cloud Contract Verifier and Stub Runner. Note -that some may be outdated, because the Spring Cloud Contract Verifier project is under -constant development. - -==== Spring Cloud Contract video - -You can check out the video from the Warsaw JUG about Spring Cloud Contract: - -video::sAAklvxmPmk[youtube,start=538,width=640,height=480] - -==== Readings - -- https://www.slideshare.net/MarcinGrzejszczak/stick-to-the-rules-consumer-driven-contracts-201507-confitura[Slides from Marcin Grzejszczak's talk about Accurest] -- https://toomuchcoding.com/blog/categories/accurest/[Accurest related articles from Marcin Grzejszczak's blog] -- https://toomuchcoding.com/blog/categories/spring-cloud-contract/[Spring Cloud Contract related articles from Marcin Grzejszczak's blog] -- https://groovy-lang.org/json.html[Groovy docs regarding JSON] - -=== Samples - -You can find some samples at -https://github.com/spring-cloud-samples/spring-cloud-contract-samples[samples]. - -== Links - -The following links may be helpful when working with Spring Cloud Contract: - -* https://github.com/spring-cloud/spring-cloud-contract/[Spring Cloud Contract Github -Repository] -* https://github.com/spring-cloud-samples/spring-cloud-contract-samples/[Spring Cloud -Contract Samples] -* https://gitter.im/spring-cloud/spring-cloud-contract[Spring Cloud Contract Gitter] -* https://www.youtube.com/watch?v=sAAklvxmPmk[Spring Cloud Contract WJUG Presentation by -Marcin Grzejszczak] - -=== Spring Cloud Contract WireMock - -:core_path: ../../.. -:doc_samples: {core_path}/samples/wiremock-jetty -:wiremock_tests: {core_path}/spring-cloud-contract-wiremock - -== Spring Cloud Contract WireMock - -The Spring Cloud Contract WireMock modules let you use https://github.com/tomakehurst/wiremock[WireMock] in a -Spring Boot application. Check out the -https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples[samples] -for more details. - -If you have a Spring Boot application that uses Tomcat as an embedded server (which is -the default with `spring-boot-starter-web`), you can add -`spring-cloud-starter-contract-stub-runner` to your classpath and add `@AutoConfigureWireMock` in -order to be able to use Wiremock in your tests. Wiremock runs as a stub server and you -can register stub behavior using a Java API or via static JSON declarations as part of -your test. The following code shows an example: - -[source,java,indent=0] ----- -Unresolved directive in _spring-cloud-wiremock.adoc - include::{doc_samples}/src/test/java/com/example/WiremockForDocsTests.java[tags=wiremock_test1] -Unresolved directive in _spring-cloud-wiremock.adoc - include::{doc_samples}/src/test/java/com/example/WiremockForDocsTests.java[tags=wiremock_test2] ----- - -To start the stub server on a different port use (for example), -`@AutoConfigureWireMock(port=9999)`. For a random port, use a value of `0`. The stub -server port can be bound in the test application context with the "wiremock.server.port" -property. Using `@AutoConfigureWireMock` adds a bean of type `WiremockConfiguration` to -your test application context, where it will be cached in between methods and classes -having the same context, the same as for Spring integration tests. Also you can inject a bean of type `WireMockServer` into your test. - -=== Registering Stubs Automatically - -If you use `@AutoConfigureWireMock`, it registers WireMock JSON stubs from the file -system or classpath (by default, from `file:src/test/resources/mappings`). You can -customize the locations using the `stubs` attribute in the annotation, which can be an -Ant-style resource pattern or a directory. In the case of a directory, `**/*.json` is -appended. The following code shows an example: - ----- -@RunWith(SpringRunner.class) -@SpringBootTest -@AutoConfigureWireMock(stubs="classpath:/stubs") -public class WiremockImportApplicationTests { - - @Autowired - private Service service; - - @Test - public void contextLoads() throws Exception { - assertThat(this.service.go()).isEqualTo("Hello World!"); - } - -} ----- - -NOTE: Actually, WireMock always loads mappings from `src/test/resources/mappings` *as -well as* the custom locations in the stubs attribute. To change this behavior, you can -also specify a files root as described in the next section of this document. - -If you're using Spring Cloud Contract's default stub jars, then your -stubs are stored under `/META-INF/group-id/artifact-id/versions/mappings/` folder. If you want to register all stubs from that location, from all embedded JARs, then it's enough to use the following syntax. - -[source,java,indent=0] ----- -Unresolved directive in _spring-cloud-wiremock.adoc - include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockFilesApplicationWithUrlResourceTests.java[tags=load_all_stubs] ----- - -=== Using Files to Specify the Stub Bodies - -WireMock can read response bodies from files on the classpath or the file system. In that -case, you can see in the JSON DSL that the response has a `bodyFileName` instead of a -(literal) `body`. The files are resolved relative to a root directory (by default, -`src/test/resources/\__files`). To customize this location you can set the `files` -attribute in the `@AutoConfigureWireMock` annotation to the location of the parent -directory (in other words, `__files` is a subdirectory). You can use Spring resource -notation to refer to `file:...` or `classpath:...` locations. Generic URLs are not -supported. A list of values can be given, in which case WireMock resolves the first file -that exists when it needs to find a response body. - -NOTE: When you configure the `files` root, it also affects the -automatic loading of stubs, because they come from the root location -in a subdirectory called "mappings". The value of `files` has no -effect on the stubs loaded explicitly from the `stubs` attribute. - -=== Alternative: Using JUnit Rules - -For a more conventional WireMock experience, you can use JUnit `@Rules` to start and stop -the server. To do so, use the `WireMockSpring` convenience class to obtain an `Options` -instance, as shown in the following example: - -[source,java,indent=0] ----- -Unresolved directive in _spring-cloud-wiremock.adoc - include::{doc_samples}/src/test/java/com/example/WiremockForDocsClassRuleTests.java[tags=wiremock_test1] -Unresolved directive in _spring-cloud-wiremock.adoc - include::{doc_samples}/src/test/java/com/example/WiremockForDocsClassRuleTests.java[tags=wiremock_test2] ----- - -The `@ClassRule` means that the server shuts down after all the methods in this class -have been run. - -=== Relaxed SSL Validation for Rest Template - -WireMock lets you stub a "secure" server with an "https" URL protocol. If your -application wants to contact that stub server in an integration test, it will find that -the SSL certificates are not valid (the usual problem with self-installed certificates). -The best option is often to re-configure the client to use "http". If that's not an -option, you can ask Spring to configure an HTTP client that ignores SSL validation errors -(do so only for tests, of course). - -To make this work with minimum fuss, you need to be using the Spring Boot -`RestTemplateBuilder` in your app, as shown in the following example: - -[source,java,indent=0] ----- - @Bean - public RestTemplate restTemplate(RestTemplateBuilder builder) { - return builder.build(); - } ----- - -You need `RestTemplateBuilder` because the builder is passed through callbacks to -initialize it, so the SSL validation can be set up in the client at that point. This -happens automatically in your test if you are using the `@AutoConfigureWireMock` -annotation or the stub runner. If you use the JUnit `@Rule` approach, you need to add the -`@AutoConfigureHttpClient` annotation as well, as shown in the following example: - -[source,java,indent=0] ----- -@RunWith(SpringRunner.class) -@SpringBootTest("app.baseUrl=https://localhost:6443") -@AutoConfigureHttpClient -public class WiremockHttpsServerApplicationTests { - - @ClassRule - public static WireMockClassRule wiremock = new WireMockClassRule( - WireMockSpring.options().httpsPort(6443)); -... -} ----- - -If you are using `spring-boot-starter-test`, you have the Apache HTTP client on the -classpath and it is selected by the `RestTemplateBuilder` and configured to ignore SSL -errors. If you use the default `java.net` client, you do not need the annotation (but it -won't do any harm). There is no support currently for other clients, but it may be added -in future releases. - -To disable the custom `RestTemplateBuilder`, set the `wiremock.rest-template-ssl-enabled` -property to `false`. - -=== WireMock and Spring MVC Mocks - -Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into -a Spring `MockRestServiceServer`. The following code shows an example: - -[source,java,indent=0] ----- -Unresolved directive in _spring-cloud-wiremock.adoc - include::{doc_samples}/src/test/java/com/example/WiremockForDocsMockServerApplicationTests.java[tags=wiremock_test] ----- - -The `baseUrl` value is prepended to all mock calls, and the `stubs()` method takes a stub -path resource pattern as an argument. In the preceding example, the stub defined at -`/stubs/resource.json` is loaded into the mock server. If the `RestTemplate` is asked to -visit `https://example.org/`, it gets the responses as being declared at that URL. More -than one stub pattern can be specified, and each one can be a directory (for a recursive -list of all ".json"), a fixed filename (as in the example above), or an Ant-style -pattern. The JSON format is the normal WireMock format, which you can read about in the -https://wiremock.org/docs/stubbing/[WireMock website]. - -Currently, the Spring Cloud Contract Verifier supports Tomcat, Jetty, and Undertow as -Spring Boot embedded servers, and Wiremock itself has "native" support for a particular -version of Jetty (currently 9.2). To use the native Jetty, you need to add the native -Wiremock dependencies and exclude the Spring Boot container (if there is one). - -=== Customization of WireMock configuration - -You can register a bean of `org.springframework.cloud.contract.wiremock.WireMockConfigurationCustomizer` type -in order to customize the WireMock configuration (e.g. add custom transformers). -Example: - -[source,java,indent=0] ----- -Unresolved directive in _spring-cloud-wiremock.adoc - include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockConfigurationCustomizerTests.java[tags=customizer_1] -// perform your customization here -Unresolved directive in _spring-cloud-wiremock.adoc - include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockConfigurationCustomizerTests.java[tags=customizer_2] ----- - -=== Generating Stubs using REST Docs - -https://projects.spring.io/spring-restdocs[Spring REST Docs] can be used to generate -documentation (for example in Asciidoctor format) for an HTTP API with Spring MockMvc -or `WebTestClient` or Rest Assured. At the same time that you generate documentation for your API, you can also -generate WireMock stubs by using Spring Cloud Contract WireMock. To do so, write your -normal REST Docs test cases and use `@AutoConfigureRestDocs` to have stubs be -automatically generated in the REST Docs output directory. - -[plantuml, rest-docs, png] ----- -"API Producer"->"API Producer": add Spring Cloud Contract (SCC) \nStub Runner dependency -"API Producer"->"API Producer": setup stub jar assembly -"API Producer"->"API Producer": write and setup REST Docs tests -"API Producer"->"Build": run build -"Build"->"REST Docs": generate API \ndocumentation -"REST Docs"->"SCC": generate stubs from the \nREST Docs tests -"REST Docs"->"SCC": generate contracts from the \nREST Docs tests -"Build"->"Build": assemble stubs jar with \nstubs and contracts -"Build"->"Nexus / Artifactory": upload contracts \nand stubs and the project arifact -"Build"->"API Producer": Build successful -"API Consumer"->"API Consumer": add SCC Stub Runner \ndependency -"API Consumer"->"API Consumer": write a SCC Stub Runner \nbased contract test -"SCC Stub Runner"->"Nexus / Artifactory": test asks for [API Producer] stubs -"Nexus / Artifactory"->"SCC Stub Runner": fetch the [API Producer] stubs -"SCC Stub Runner"->"SCC Stub Runner": run in memory\n HTTP server stubs -"API Consumer"->"SCC Stub Runner": send a request \nto the HTTP server stub -"SCC Stub Runner"->"API Consumer": communication is correct ----- - -The following code shows an -example using `MockMvc`: - -[source,java,indent=0] ----- -@RunWith(SpringRunner.class) -@SpringBootTest -@AutoConfigureRestDocs(outputDir = "target/snippets") -@AutoConfigureMockMvc -public class ApplicationTests { - - @Autowired - private MockMvc mockMvc; - - @Test - public void contextLoads() throws Exception { - mockMvc.perform(get("/resource")) - .andExpect(content().string("Hello World")) - .andDo(document("resource")); - } -} ----- - -This test generates a WireMock stub at "target/snippets/stubs/resource.json". It matches -all GET requests to the "/resource" path. The same example with `WebTestClient` (used -for testing Spring WebFlux applications) would look like this: - -[source,java,indent=0] ----- -@RunWith(SpringRunner.class) -@SpringBootTest -@AutoConfigureRestDocs(outputDir = "target/snippets") -@AutoConfigureWebTestClient -public class ApplicationTests { - - @Autowired - private WebTestClient client; - - @Test - public void contextLoads() throws Exception { - client.get().uri("/resource").exchange() - .expectBody(String.class).isEqualTo("Hello World") - .consumeWith(document("resource")); - } -} ----- - -Without any additional configuration, these tests create a stub with a request matcher -for the HTTP method and all headers except "host" and "content-length". To match the -request more precisely (for example, to match the body of a POST or PUT), we need to -explicitly create a request matcher. Doing so has two effects: - -* Creating a stub that matches only in the way you specify. -* Asserting that the request in the test case also matches the same conditions. - -The main entry point for this feature is `WireMockRestDocs.verify()`, which can be used -as a substitute for the `document()` convenience method, as shown in the following -example: - -[source,java,indent=0] - -import static org.springframework.cloud.contract.wiremock.restdocs.WireMockRestDocs.verify; - ----- -@RunWith(SpringRunner.class) -@SpringBootTest -@AutoConfigureRestDocs(outputDir = "target/snippets") -@AutoConfigureMockMvc -public class ApplicationTests { - - @Autowired - private MockMvc mockMvc; - - @Test - public void contextLoads() throws Exception { - mockMvc.perform(post("/resource") - .content("{\"id\":\"123456\",\"message\":\"Hello World\"}")) - .andExpect(status().isOk()) - .andDo(verify().jsonPath("$.id") - .stub("resource")); - } -} ----- - -This contract specifies that any valid POST with an "id" field receives the response -defined in this test. You can chain together calls to `.jsonPath()` to add additional -matchers. If JSON Path is unfamiliar, The https://github.com/jayway/JsonPath[JayWay -documentation] can help you get up to speed. The `WebTestClient` version of this test -has a similar `verify()` static helper that you insert in the same place. - -Instead of the `jsonPath` and `contentType` convenience methods, you can also use the -WireMock APIs to verify that the request matches the created stub, as shown in the -following example: - -[source,java,indent=0] ----- - @Test - public void contextLoads() throws Exception { - mockMvc.perform(post("/resource") - .content("{\"id\":\"123456\",\"message\":\"Hello World\"}")) - .andExpect(status().isOk()) - .andDo(verify() - .wiremock(WireMock.post( - urlPathEquals("/resource")) - .withRequestBody(matchingJsonPath("$.id")) - .stub("post-resource")); - } ----- - -The WireMock API is rich. You can match headers, query parameters, and request body by -regex as well as by JSON path. These features can be used to create stubs with a wider -range of parameters. The above example generates a stub resembling the following example: - -.post-resource.json -[source,json] ----- -{ - "request" : { - "url" : "/resource", - "method" : "POST", - "bodyPatterns" : [ { - "matchesJsonPath" : "$.id" - }] - }, - "response" : { - "status" : 200, - "body" : "Hello World", - "headers" : { - "X-Application-Context" : "application:-1", - "Content-Type" : "text/plain" - } - } -} ----- - -NOTE: You can use either the `wiremock()` method or the `jsonPath()` and `contentType()` -methods to create request matchers, but you can't use both approaches. - -On the consumer side, you can make the `resource.json` generated earlier in this section -available on the classpath (by -<= 20)]', byType()) - } - } -} ----- - -The generated document (formatted in Asciidoc in this case) contains a formatted -contract. The location of this file would be `index/dsl-contract.adoc`. - -== Documentation - -You can read more about Spring Cloud Contract Verifier by reading the -{documentation_url}[docs] +You can read more about Spring Cloud Contract by going to https://spring.io/projects/spring-cloud-contract[the project page] == Contributing diff --git a/docs/src/main/asciidoc/README.adoc b/docs/src/main/asciidoc/README.adoc index 2c6fded0b4..0286658de7 100644 --- a/docs/src/main/asciidoc/README.adoc +++ b/docs/src/main/asciidoc/README.adoc @@ -1,26 +1,3 @@ -:branch: master -image::https://badges.gitter.im/Join%20Chat.svg[Gitter, link="https://gitter.im/spring-cloud/spring-cloud-contract?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge"] -image::https://codecov.io/gh/spring-cloud/spring-cloud-contract/branch/{branch}/graph/badge.svg["codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-contract"] -image::https://circleci.com/gh/spring-cloud/spring-cloud-contract.svg?style=svg["CircleCI", link="https://circleci.com/gh/spring-cloud/spring-cloud-contract"] -:branch: master -:core_path: ../../.. -:plugins_path: ../../../spring-cloud-contract-tools -:converters_path: {plugins_path}/spring-cloud-contract-converters -:verifier_root_path: {core_path}/spring-cloud-contract-verifier -:contract_spec_path: {core_path}/specs/spring-cloud-contract-spec-java -:contract_spec_tests_path: {core_path}/specs/spring-cloud-contract-spec -:samples_path: {core_path}/samples -:verifier_core_path: {verifier_root_path} -:stubrunner_core_path: {core_path}/spring-cloud-contract-stub-runner -:standalone_samples_path: {samples_path}/standalone/dsl -:standalone_messaging_samples_path: {samples_path}/standalone/messaging -:standalone_pact_path: {samples_path}/standalone/pact -:standalone_restdocs_path: {samples_path}/standalone/restdocs -:tests_path: {core_path}/tests -:samples_branch: 2.2.x -:samples_url: https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/{samples_branch} -:introduction_url: ${core_path}/../../ - == Spring Cloud Contract You always need confidence when pushing new features into a new application or service in @@ -35,20 +12,9 @@ If you prefer to learn about the project by doing some tutorials, you can check workshops under https://cloud-samples.spring.io/spring-cloud-contract-samples/workshops.html[this link]. -=== Spring Cloud Contract Verifier +== Project page -include::_verifier_introduction.adoc[] - -include::_links.adoc[] - -=== Spring Cloud Contract WireMock - -include::_spring-cloud-wiremock.adoc[] - -== Documentation - -You can read more about Spring Cloud Contract Verifier by reading the -{documentation_url}[docs] +You can read more about Spring Cloud Contract by going to https://spring.io/projects/spring-cloud-contract[the project page] == Contributing diff --git a/docs/src/main/asciidoc/_attributes.adoc b/docs/src/main/asciidoc/_attributes.adoc index 4560b15951..868f5ebdea 100644 --- a/docs/src/main/asciidoc/_attributes.adoc +++ b/docs/src/main/asciidoc/_attributes.adoc @@ -32,5 +32,6 @@ :samples_branch: 2.2.x :samples_url: https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/{samples_branch} :samples_code: https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/ - +:doc_samples: {core_path}/samples/wiremock-jetty +:wiremock_tests: {core_path}/spring-cloud-contract-wiremock :introduction_url: {core_path} \ No newline at end of file diff --git a/docs/src/main/asciidoc/_verifier_how_it_works.adoc b/docs/src/main/asciidoc/_getting-started.adoc similarity index 69% rename from docs/src/main/asciidoc/_verifier_how_it_works.adoc rename to docs/src/main/asciidoc/_getting-started.adoc index ca5b39e898..50ed913b7c 100644 --- a/docs/src/main/asciidoc/_verifier_how_it_works.adoc +++ b/docs/src/main/asciidoc/_getting-started.adoc @@ -1,38 +1,157 @@ -=== How It Works +include::_attributes.adoc[] -This section explores how Spring Cloud Contract. +If you are getting started with {project-full-name}, or "`Spring`" in general, start by reading +this section. It answers the basic "`what?`", "`how?`" and "`why?`" questions. It +includes an introduction to {project-full-name}, along with installation instructions. We then +walk you through building your first {project-full-name} application, discussing some core +principles as we go. -[[spring-cloud-contract-verifier-intro-three-second-tour]] -==== A Three-second Tour +[[getting-started-introducing-spring-cloud-contract]] +== Introducing Spring Cloud Contract + +Spring Cloud Contract moves TDD to the level of software architecture. It allows to perform consumer, consumer-driven and producer-driven contract testing. + +[[getting-started-introducing-spring-cloud-contract-history]] +=== History + +Before becoming Spring Cloud Contract, this project was called https://github.com/Codearte/accurest[Accurest]. +It was created by https://twitter.com/mgrzejszczak[Marcin Grzejszczak] and https://twitter.com/jkubrynski[Jakub Kubrynski] +from (https://github.com/Codearte[Codearte]). + +The `0.1.0` release took place on 26 Jan 2015 and it became stable with `1.0.0` release on 29 Feb 2016. + +[[getting-started-introducing-spring-cloud-contract-why]] +==== Why would you need it? + +Assume that we have a system consisting of multiple microservices: + +image::images/Deps.png[Microservices Architecture] + +[[getting-started-introducing-spring-cloud-contract-testing-issues]] +==== Testing issues + +If we wanted to test the application in top left corner to determine whether it can +communicate with other services, we could do one of two things: + +- Deploy all microservices and perform end-to-end tests. +- Mock other microservices in unit/integration tests. + +Both have their advantages but also a lot of disadvantages. + +*Deploy all microservices and perform end to end tests* + +Advantages: + +- Simulates production. +- Tests real communication between services. + +Disadvantages: + +- To test one microservice, we have to deploy 6 microservices, a couple of databases, +etc. +- The environment where the tests run is locked for a single suite of tests (nobody else +would be able to run the tests in the meantime). +- They take a long time to run. +- The feedback comes very late in the process. +- They are extremely hard to debug. + +*Mock other microservices in unit/integration tests* + +Advantages: + +- They provide very fast feedback. +- They have no infrastructure requirements. + +Disadvantages: + +- The implementor of the service creates stubs that might have nothing to do with +reality. +- You can go to production with passing tests and failing production. + +To solve the aforementioned issues, Spring Cloud Contract was created. The main idea is to give you very fast feedback, without the need to set up the +whole world of microservices. If you work on stubs, then the only applications you need +are those that your application directly uses. + +image::images/Stubs2.png[Stubbed Services] + +Spring Cloud Contract gives you the certainty that the stubs that you use were +created by the service that you're calling. Also, if you can use them, it means that they +were tested against the producer's side. In short, you can trust those stubs. + +[[getting-started-introducing-spring-cloud-contract-purposes]] +=== Purposes + +The main purposes of Spring Cloud Contract are: + +- To ensure that HTTP / Messaging stubs (used when developing the client) do exactly +what the actual server-side implementation does. +- To promote ATDD (acceptance test driven developement) method and Microservices architectural style. +- To provide a way to publish changes in contracts that are immediately visible on both sides. +- To generate boilerplate test code to be used on the server side. + +By default Spring Cloud Contract integrates with http://wiremock.org[Wiremock] as the HTTP server stub. + +IMPORTANT: Spring Cloud Contract's purpose is NOT to start writing business +features in the contracts. Assume that we have a business use case of fraud check. If a +user can be a fraud for 100 different reasons, we would assume that you would create 2 +contracts, one for the positive case and one for the negative case. Contract tests are +used to test contracts between applications and not to simulate full behavior. + +[[getting-started-what-is-a-contract]] +=== What is a contract? + +As consumers of services, we need to define what exactly we want to achieve. We need to +formulate our expectations. That is why we write contracts. In other words a contract is an agreement on how the API / message communication should look like. Let's look at the following example + +Assume that you want to send a request containing the ID of a client company and the +amount it wants to borrow from us. You also want to send it to the /fraudcheck url via +the PUT method. + +==== +[source,groovy,indent=0,role="primary"] +.groovy +---- +include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[] +---- + +[source,yaml,indent=0,role="secondary"] +.yaml +---- +include::{introduction_url}/samples/standalone/yml/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.yml[] +---- +==== + +[[getting-started-three-second-tour]] +== A Three-second Tour This very brief tour walks through using Spring Cloud Contract: -* <> -* <> +* <> +* <> You can find a somewhat longer tour -<>. +<>. -[plantuml, three-second, png] +[plantuml, getting-started-three-second, png] ---- "API Producer"->"API Producer": add Spring Cloud \nContract (SCC) plugin "API Producer"->"API Producer": add SCC Verifier dependency "API Producer"->"API Producer": define contracts "API Producer"->"Build": run build "Build"->"SCC Plugin": generate \ntests, stubs and stubs \nartifact (e.g. stubs-jar) -"Build"->"Nexus / Artifactory": upload contracts \nand stubs and the project arifact +"Build"->"Stub Storage": upload contracts \nand stubs and the project arifact "Build"->"API Producer": Build successful "API Consumer"->"API Consumer": add SCC Stub Runner \ndependency "API Consumer"->"API Consumer": write a SCC Stub Runner \nbased contract test -"SCC Stub Runner"->"Nexus / Artifactory": test asks for [API Producer] stubs -"Nexus / Artifactory"->"SCC Stub Runner": fetch the [API Producer] stubs +"SCC Stub Runner"->"Stub Storage": test asks for [API Producer] stubs +"Stub Storage"->"SCC Stub Runner": fetch the [API Producer] stubs "SCC Stub Runner"->"SCC Stub Runner": run in memory\n HTTP server stubs "API Consumer"->"SCC Stub Runner": send a request \nto the HTTP server stub "SCC Stub Runner"->"API Consumer": communication is correct ---- -[[spring-cloud-contract-verifier-intro-three-second-tour-producer]] -===== On the Producer Side +[[getting-started-three-second-tour-producer]] +=== On the Producer Side To start working with Spring Cloud Contract, add files with `REST`/messaging contracts expressed in either Groovy DSL or YAML to the contracts directory, which is set by the @@ -77,8 +196,8 @@ application and the stub artifacts are built and installed in the local Maven re The changes can now be merged, and both the application and the stub artifacts may be published in an online repository. -[[spring-cloud-contract-verifier-intro-three-second-tour-consumer]] -===== On the Consumer Side +[[getting-started-three-second-tour-consumer]] +=== On the Consumer Side `Spring Cloud Contract Stub Runner` can be used in the integration tests to get a running WireMock instance or messaging route that simulates the actual service. @@ -110,7 +229,7 @@ Stub Runner` properties, as shown in the following example: + [source,yaml,indent=0] ---- -include::{github-raw}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] +include::{introduction_url}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ---- Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, @@ -132,21 +251,46 @@ TIP: Use the `REMOTE` `stubsMode` when downloading stubs from an online reposito Now, in your integration test, you can receive stubbed versions of HTTP responses or messages that are expected to be emitted by the collaborator service. -[[spring-cloud-contract-verifier-intro-three-minute-tour]] -==== A Three-minute Tour +[[getting-started-first-application]] +== Developing Your First Spring Cloud Contract based application This brief tour walks through using Spring Cloud Contract: -* <> -* <> +* <> +* <> You can find an even more brief tour -<>. +<>. -[[spring-cloud-contract-verifier-intro-three-minute-tour-producer]] -===== On the Producer Side +For the sake of this example the `Stub Storage` will be Nexus / Artifactory. -To start working with `Spring Cloud Contract`, add files with `REST/` messaging contracts +image::getting-started-three-second.png[Getting started first application] + +[[getting-started-first-application-producer]] +=== On the Producer Side + +To start working with `Spring Cloud Contract`, add Spring Cloud Contract Verifier dependency and plugin to your build file, +as shown in the following example: + +[source,xml,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] +---- + +The following listing shows how to add the plugin, which should go in the build/plugins +portion of the file: + +[source,xml,indent=0] +---- + + org.springframework.cloud + spring-cloud-contract-maven-plugin + ${spring-cloud-contract.version} + true + +---- + +Now let's add files with `REST/` messaging contracts expressed in either Groovy DSL or YAML to the contracts directory, which is set by the `contractsDslDir` property. By default, it is `$rootDir/src/test/resources/contracts`. @@ -234,35 +378,22 @@ include::{verifier_core_path}/src/test/resources/yml/contract_message_scenario3. ---- ==== - -Then you can add Spring Cloud Contract Verifier dependency and plugin to your build file, -as shown in the following example: - -[source,xml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] ----- - -The following listing shows how to add the plugin, which should go in the build/plugins -portion of the file: - -[source,xml,indent=0] ----- - - org.springframework.cloud - spring-cloud-contract-maven-plugin - ${spring-cloud-contract.version} - true - ----- - Running `./mvnw clean install` automatically generates tests that verify the application compliance with the added contracts. By default, the generated tests are under `org.springframework.cloud.contract.verifier.tests.`. -The following example shows a sample auto-generated test for an HTTP contract: +The generated tests will differ, depending on which framework and test type you've setup in your plugin. -[source,java,indent=0] +In the samples below you'll find: + +- the default test mode for HTTP contracts via `MockMvc` +- JAX-RS client via the `JAXRS` test mode +- `WebTestClient` based test (this is particularly recommended while working with Reactive, `Web-Flux`-based applications) set via `WEBTESTCLIENT` test mode +- Spock based test via the `testFramework` property set to `SPOCK` + +==== +[source,java,indent=0,role="primary"] +.mockmvc ---- @Test public void validate_shouldMarkClientAsFraud() throws Exception { @@ -285,18 +416,45 @@ public void validate_shouldMarkClientAsFraud() throws Exception { } ---- -The preceding example uses Spring's `MockMvc` to run the tests. This is the default test -mode for HTTP contracts. However, JAX-RS client and explicit HTTP invocations can also be -used. (To do so, change the `testMode` property of the plugin to `JAX-RS` or `EXPLICIT`, -respectively.) +[source,java,indent=0,role="secondary"] +.jaxrs +---- +@SuppressWarnings("rawtypes") +public class FooTest { + WebTarget webTarget; -Since 2.1.0, it is also possible to use `RestAssuredWebTestClient`with Spring's reactive `WebTestClient` -run under the hood. This is particularly recommended while working with Reactive, `Web-Flux`-based applications. -In order to use `WebTestClient` set `testMode` to `WEBTESTCLIENT`. + @Test + public void validate_() throws Exception { -Here is an example of a test generated in `WEBTESTCLIENT` test mode: + // when: + Response response = webTarget + .path("/users") + .queryParam("limit", "10") + .queryParam("offset", "20") + .queryParam("filter", "email") + .queryParam("sort", "name") + .queryParam("search", "55") + .queryParam("age", "99") + .queryParam("name", "Denis.Stepanov") + .queryParam("email", "bob@email.com") + .request() + .build("GET") + .invoke(); + String responseAsString = response.readEntity(String.class); -[source,java,indent=0] + // then: + assertThat(response.getStatus()).isEqualTo(200); + + // and: + DocumentContext parsedJson = JsonPath.parse(responseAsString); + assertThatJson(parsedJson).field("['property1']").isEqualTo("a"); + } + +} +---- + +[source,java,indent=0,role="secondary"] +.webtestclient ---- @Test public void validate_shouldRejectABeerIfTooYoung() throws Exception { @@ -318,15 +476,8 @@ Here is an example of a test generated in `WEBTESTCLIENT` test mode: } ---- -Apart from the default JUnit 4, you can instead use JUnit 5 or Spock tests, by setting the plugin -`testFramework` property to either `JUNIT5` or `Spock`. - -TIP: You can now also generate WireMock scenarios based on the contracts, by including an -order number followed by an underscore at the beginning of the contract file names. - -The following example shows an auto-generated test in Spock for a messaging stub contract: - -[source,groovy,indent=0] +[source,groovy,indent=0,role="secondary"] +.spock ---- given: ContractVerifierMessage inputMessage = contractVerifierMessaging.create( @@ -341,6 +492,7 @@ then: noExceptionThrown() bookWasDeleted() ---- +==== As the implementation of the functionalities described by the contracts is not yet present, the tests fail. @@ -375,18 +527,8 @@ shown in the following example: You can now merge the changes and publish both the application and the stub artifacts in an online repository. -*Docker Project* - -In order to enable working with contracts while creating applications in non-JVM -technologies, the `springcloud/spring-cloud-contract` Docker image has been created. It -contains a project that automatically generates tests for HTTP contracts and executes them -in `EXPLICIT` test mode. Then, if the tests pass, it generates Wiremock stubs and, -optionally, publishes them to an artifact manager. In order to use the image, you can -mount the contracts into the `/contracts` directory and set a few environment variables. -// TODO: We should answer the obvious question: Which environment variables? - -[[spring-cloud-contract-verifier-intro-three-minute-tour-consumer]] -===== On the Consumer Side +[[getting-started-first-application-consumer]] +=== On the Consumer Side `Spring Cloud Contract Stub Runner` can be used in the integration tests to get a running WireMock instance or messaging route that simulates the actual service. @@ -417,7 +559,7 @@ Runner` properties, as shown in the following example: + [source,yaml,indent=0] ---- -include::{github-raw}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] +include::{introduction_url}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ---- Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, @@ -451,88 +593,8 @@ to the following in the build logs: 2016-07-19 14:22:27.737 INFO 41050 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}] ---- -==== Defining the Contract - -As consumers of services, we need to define what exactly we want to achieve. We need to -formulate our expectations. That is why we write contracts. - -Assume that you want to send a request containing the ID of a client company and the -amount it wants to borrow from us. You also want to send it to the /fraudcheck url via -the PUT method. - -==== -[source,groovy,indent=0,role="primary"] -.groovy ----- -include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[] ----- - -[source,yaml,indent=0,role="secondary"] -.yaml ----- -include::{introduction_url}/samples/standalone/yml/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.yml[] ----- -==== - -==== Client Side - -Spring Cloud Contract generates stubs, which you can use during client-side testing. -You get a running WireMock instance/Messaging route that simulates the service. -You would like to feed that instance with a proper stub definition. - -At some point in time, you need to send a request to the Fraud Detection service. - -[source,groovy,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-client/src/main/java/com/example/loan/LoanApplicationService.java[tags=client_call_server,indent=0] ----- - -Annotate your test class with `@AutoConfigureStubRunner`. In the annotation provide the group id and artifact id for the Stub Runner to download stubs of your collaborators. - -[source,groovy,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=autoconfigure_stubrunner,indent=0] ----- - -After that, during the tests, Spring Cloud Contract automatically finds the stubs -(simulating the real service) in the Maven repository and exposes them on a configured -(or random) port. - -==== Server Side - -Since you are developing your stub, you need to be sure that it actually resembles your -concrete implementation. You cannot have a situation where your stub acts in one way and -your application behaves in a different way, especially in production. - -To ensure that your application behaves the way you define in your stub, tests are -generated from the stub you provide. - -The autogenerated test looks, more or less, like this: - -[source,java,indent=0] ----- -@Test -public void validate_shouldMarkClientAsFraud() throws Exception { - // given: - MockMvcRequestSpecification request = given() - .header("Content-Type", "application/vnd.fraud.v1+json") - .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}"); - - // when: - ResponseOptions response = given().spec(request) - .put("/fraudcheck"); - - // then: - assertThat(response.statusCode()).isEqualTo(200); - assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*"); - // and: - DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); - assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}"); - assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high"); -} ----- - -=== Step-by-step Guide to Consumer Driven Contracts (CDC) +[[getting-started-cdc]] +== Step-by-step Guide to Consumer Driven Contracts (CDC) with contracts laying on the producer side Consider an example of Fraud Detection and the Loan Issuance process. The business scenario is such that we want to issue loans to people but do not want them to steal from @@ -542,11 +604,19 @@ Assume that `Loan Issuance` is a client to the `Fraud Detection` server. In the sprint, we must develop a new feature: if a client wants to borrow too much money, then we mark the client as a fraud. -Technical remark - Fraud Detection has an `artifact-id` of `http-server`, while Loan -Issuance has an artifact-id of `http-client`, and both have a `group-id` of `com.example`. +Technical remarks -Social remark - both client and server development teams need to communicate directly and -discuss changes while going through the process. CDC is all about communication. +* Fraud Detection has an `artifact-id` of `http-server`, +* Loan +Issuance has an artifact-id of `http-client` +* both have a `group-id` of `com.example` +* For the sake of this example the `Stub Storage` will be Nexus / Artifactory + +Social remarks + +* both client and server development teams need to communicate directly and +discuss changes while going through the process +* CDC is all about communication. The https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-server[server side code is available here] and https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-client[the @@ -555,7 +625,8 @@ client code here]. TIP: In this case, the producer owns the contracts. Physically, all the contract are in the producer's repository. -==== Technical note +[[getting-started-cdc-technical-note]] +=== Technical note If using the *SNAPSHOT* / *Milestone* / *Release Candidate* versions please add the following section to your build: @@ -572,7 +643,13 @@ include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=repo include::{introduction_url}/samples/standalone/dsl/http-server/build.gradle[tags=deps_repos,indent=0] ---- -==== Consumer side (Loan Issuance) +For simplicity we will use the following acronyms: + +- Loan Issuance - LI - the http client +- Fraud Detection - FD - the http server +- Spring Cloud Contract - SCC + +=== Consumer side (Loan Issuance) As a developer of the Loan Issuance service (a consumer of the Fraud Detection server), you might do the following steps: @@ -580,7 +657,7 @@ As a developer of the Loan Issuance service (a consumer of the Fraud Detection s . Write the missing implementation. . Clone the Fraud Detection service repository locally. . Define the contract locally in the repo of Fraud Detection service. -. Add the Spring Cloud Contract Verifier plugin. +. Add the Spring Cloud Contract (SCC) plugin. . Run the integration tests. . File a pull request. . Create an initial implementation. @@ -589,6 +666,36 @@ As a developer of the Loan Issuance service (a consumer of the Fraud Detection s . Deploy your app. . Work online. +Let's start with the Loan Issuance flow: + +[plantuml, getting-started-cdc-client, png] +---- +"Loan\nIssuance"->"Loan\nIssuance": start doing TDD\nby writing a test\nfor your feature +"Loan\nIssuance"->"Loan\nIssuance": write the \nmissing implementation +"Loan\nIssuance"->"Loan\nIssuance": run a test - it fails\ndue to no server running +"Loan\nIssuance"->"Fraud\nDetection\nClone": clone the repository +"Fraud\nDetection\nClone"->"Fraud\nDetection\nClone": add missing dependencies\n& define contracts +"Fraud\nDetection\nClone"->"Fraud\nDetection\nClone": add the SCC plugin +"Fraud\nDetection\nClone"->"FD \nClone Build": install the stubs locally +"FD \nClone Build"->"SCC Plugin \nin FD Clone": generate stubs \nand stubs \nartifact (e.g. stubs-jar) +"SCC Plugin \nin FD Clone"->"FD \nClone Build": stubs and artifacts\ngenerated +"FD \nClone Build"->"Local storage": install the stubs locally +"Local storage"->"FD \nClone Build": stub sucessfully installed +"FD \nClone Build"->"Fraud\nDetection\nClone": build successful +"Loan\nIssuance"->"Loan\nIssuance": add a SCC\nStub Runner\ndependency\nand setup +"Loan\nIssuance"->"LI\nSCC\nStub Runner": start stubs\nof FD from\nlocal storage +"LI\nSCC\nStub Runner"->"Local storage": find stubs of [FD] +"Local storage"->"LI\nSCC\nStub Runner": stubs of [FD] found +"LI\nSCC\nStub Runner"->"FD stub": run stubs of [FD] +"FD stub"->"LI\nSCC\nStub Runner": [FD] stub is running +"LI\nSCC\nStub Runner"->"Loan\nIssuance": stubs running and ready for the test +"Loan\nIssuance"->"Loan\nIssuance": run a test +"Loan\nIssuance"->"FD stub": the test\nsends a request\nto the running stub +"FD stub"->"Loan\nIssuance": stub responds successfuly +"Loan\nIssuance"->"Loan\nIssuance": the test passes successfully +"Loan\nIssuance"->"Fraud\nDetection": send a pull request\nwith the\nsuggested contracts +---- + *Start doing TDD by writing a test for your feature.* [source,groovy,indent=0] @@ -656,6 +763,7 @@ of an identifier or a timestamp, you need not hardcode a value. You want to allo different ranges of values. To enable ranges of values, you can set regular expressions matching those values for the consumer side. You can provide the body by means of either a map notation or String with interpolations. +//TODO: Ensure that the links are correct Consult the <> section for more information. We highly recommend using the map notation! TIP: You must understand the map notation in order to set up contracts. Please read the @@ -793,11 +901,37 @@ you wish. Once you are satisfied with the results and the test passes, publish a pull request to the server side. Currently, the consumer side work is done. -==== Producer side (Fraud Detection server) +=== Producer side (Fraud Detection server) -As a developer of the Fraud Detection server (a server to the Loan Issuance service): +As a developer of the Fraud Detection server (a server to the Loan Issuance service) we would like to: -*Create an initial implementation.* +- take over the pull request +- write the missing implementation +- deploy the application + +Let's look at the Fraud Detection flow: + +[plantuml, getting-started-cdc-server, png] +---- +"Fraud\nDetection"->"Fraud\nDetection": take over the\n pull request +"Fraud\nDetection"->"Fraud\nDetection": setup\nSpring Cloud\nContract plugin +"Fraud\nDetection"->"Fraud\nDetection\nBuild": run the build +"Fraud\nDetection\nBuild"->"SCC Plugin": generate tests\nstubs \nand stubs artifact \n(e.g. stubs-jar) +"SCC Plugin"->"Fraud\nDetection\nBuild": tests and stubs generated +"Fraud\nDetection\nBuild"->"Fraud\nDetection\nBuild": run tests +"Fraud\nDetection\nBuild"->"Fraud\nDetection": generated tests failed! +"Fraud\nDetection"->"Fraud\nDetection": setup\nbase classes\nfor contract tests +"Fraud\nDetection"->"Fraud\nDetection\nBuild": run the build +"Fraud\nDetection\nBuild"->"SCC Plugin": generate tests\nstubs \nand stubs artifact \n(e.g. stubs-jar) +"SCC Plugin"->"Fraud\nDetection\nBuild": tests and stubs generated +"Fraud\nDetection\nBuild"->"Fraud\nDetection\nBuild": run tests +"Fraud\nDetection\nBuild"->"Fraud\nDetection": all the tests passed! +"Fraud\nDetection"->"Fraud\nDetection": commit and push changes +"Fraud\nDetection"->"CI": commit pushed!\nTriggers the build +"CI"->"Stub Storage": build successful,\nupload artifacts +---- + +*Take over the pull request.* As a reminder, you can see the initial implementation here: @@ -808,8 +942,6 @@ include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com } ---- -*Take over the pull request.* - [source,bash,indent=0] ---- $ git checkout -b contract-change-pr master @@ -924,9 +1056,29 @@ $ git push origin master Your CI might run something like `./mvnw clean deploy`, which would publish both the application and the stub artifacts. -==== Consumer Side (Loan Issuance) Final Step +=== Consumer Side (Loan Issuance) Final Step -As a developer of the Loan Issuance service (a consumer of the Fraud Detection server): +As a developer of the Loan Issuance service (a consumer of the Fraud Detection server) we will want to: + +- merge our feature branch to `master` +- switch to online mode of working + + +[plantuml, getting-started-cdc-client, png] +---- +"Loan\nIssuance"->"Loan\nIssuance": merge the\nfeature branch\nto master branch +"Loan\nIssuance"->"Loan\nIssuance": setup SCC Stub Runner\nto fetch stubs\nfrom Stub Storage +"Loan\nIssuance"->"LI\nSCC\nStub Runner": start stubs\nof FD from\nStub Storage +"LI\nSCC\nStub Runner"->"Stub Storage": find stubs of [FD] +"Stub Storage"->"LI\nSCC\nStub Runner": stubs of [FD] found +"LI\nSCC\nStub Runner"->"FD stub": run stubs of [FD] +"FD stub"->"LI\nSCC\nStub Runner": [FD] stub is running +"LI\nSCC\nStub Runner"->"Loan\nIssuance": stubs running and ready for the test +"Loan\nIssuance"->"Loan\nIssuance": run a test +"Loan\nIssuance"->"FD stub": the test\nsends a request\nto the running stub +"FD stub"->"Loan\nIssuance": stub responds successfuly +"Loan\nIssuance"->"Loan\nIssuance": the test passes successfully +---- *Merge branch to master.* @@ -946,7 +1098,40 @@ achieving the same thing by changing the properties. [source,yaml,indent=0] ---- -include::{github-raw}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] +include::{introduction_url}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ---- -That's it! \ No newline at end of file +That's it! + +[[getting-started-whats-next]] +== What to Read Next +Hopefully, this section provided some of the {project-full-name} basics and got you on your way +to writing your own applications. If you are a task-oriented type of developer, you might +want to jump over to https://spring.io and check out some of the +https://spring.io/guides/[getting started] guides that solve specific "`How do I do that +with Spring?`" problems. We also have {project-full-name}-specific +"`<>`" reference documentation. + +Otherwise, the next logical step is to read _<>_. If +you are really impatient, you could also jump ahead and read about +_<>_. + +// TODO: Check if we can link courses +In addition to that you can check out the following videos: + +- "Consumer Driven Contracts and Your Microservice Architecture" by Olga Maciaszek-Sharma and Marcin Grzejszczak + +video::pDkC_00hhvA[youtube,width=640,height=480] + +- "Contract Tests in the Enterprise" by Marcin Grzejszczak + +video::ZyHG-VOzPZg[youtube,width=640,height=480] + +- "Why Contract Tests Matter?" by Marcin Grzejszczak + +video::TvpkZu1e2Dc[youtube,start=6262,width=640,height=480] + +You can find the default project samples at +https://github.com/spring-cloud-samples/spring-cloud-contract-samples[samples]. + +You can find the Spring Cloud Contract workshops https://cloud-samples.spring.io/spring-cloud-contract-samples/[over here]. \ No newline at end of file diff --git a/docs/src/main/asciidoc/_links.adoc b/docs/src/main/asciidoc/_links.adoc deleted file mode 100644 index e6104db048..0000000000 --- a/docs/src/main/asciidoc/_links.adoc +++ /dev/null @@ -1,11 +0,0 @@ -== Links - -The following links may be helpful when working with Spring Cloud Contract: - -* https://github.com/spring-cloud/spring-cloud-contract/[Spring Cloud Contract Github -Repository] -* https://github.com/spring-cloud-samples/spring-cloud-contract-samples/[Spring Cloud -Contract Samples] -* https://gitter.im/spring-cloud/spring-cloud-contract[Spring Cloud Contract Gitter] -* https://www.youtube.com/watch?v=sAAklvxmPmk[Spring Cloud Contract WJUG Presentation by -Marcin Grzejszczak] diff --git a/docs/src/main/asciidoc/_verifier_contract.adoc b/docs/src/main/asciidoc/_project-features-contract.adoc similarity index 60% rename from docs/src/main/asciidoc/_verifier_contract.adoc rename to docs/src/main/asciidoc/_project-features-contract.adoc index 2ca22db220..df80880e4a 100644 --- a/docs/src/main/asciidoc/_verifier_contract.adoc +++ b/docs/src/main/asciidoc/_project-features-contract.adoc @@ -1,8 +1,12 @@ [[contract-dsl]] == Contract DSL +include::_attributes.adoc[] -Spring Cloud Contract supports out of the box 2 types of DSL. One written in -`Groovy` and one written in `YAML`. +Spring Cloud Contract supports out of the box following types of DSL. + +* written in `Groovy` +* written in `YAML` +* written in `Java` If you decide to write the contract in Groovy, do not be alarmed if you have not used Groovy before. Knowledge of the language is not really needed, as the Contract DSL uses only a @@ -17,23 +21,26 @@ the `Contract` class: `import org.springframework.cloud.spec.Contract` and then TIP: Spring Cloud Contract supports defining multiple contracts in a single file. -The following is a complete example of a Groovy contract definition: +The following is a complete example of a contract definition: -[source,groovy,indent=0] +==== +[source,groovy,indent=0,subs="verbatim,attributes",role="primary"] +.groovy ---- -include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MethodBodyBuilderSpec.groovy[tags=dsl_example,indent=0] +include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/SpringTestMethodBodyBuildersSpec.groovy[tags=dsl_example,indent=0] ---- -The following is a complete example of a YAML contract definition: - -[source,yml,indent=0] +[source,yml,indent=0,subs="verbatim,attributes",role="secondary"] +.yml ---- include::{verifier_core_path}/src/test/resources/yml/contract_rest.yml[indent=0] ---- +==== TIP: You can compile contracts to stubs mapping using standalone maven command: `mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert` +[[contract-limitations]] === Limitations WARNING: Spring Cloud Contract Verifier does not properly support XML. Please use JSON or @@ -48,6 +55,7 @@ WARNING: Because JSON structure can have any form, it can be impossible to parse properly when using the Groovy DSL and the `value(consumer(...), producer(...))` notation in `GString`. That is why you should use the Groovy Map notation. +[[contract-common-top-elements]] === Common Top-Level elements The following sections describe the most common top-level elements: @@ -72,7 +80,7 @@ include::{contract_spec_tests_path}/src/test/groovy/org/springframework/cloud/co ---- [source,yaml,indent=0,role="secondary"] -.yaml +.yml ---- include::{verifier_core_path}/src/test/resources/yml/contract_rest.yml[indent=0] ---- @@ -99,7 +107,7 @@ include::{contract_spec_tests_path}/src/test/groovy/org/springframework/cloud/co ---- [source,yaml,indent=0,role="secondary"] -.yaml +.yml ---- include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=name,indent=0] ---- @@ -119,7 +127,7 @@ include::{contract_spec_tests_path}/src/test/groovy/org/springframework/cloud/co ---- [source,yaml,indent=0,role="secondary"] -.yaml +.yml ---- include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=ignored,indent=0] ---- @@ -152,7 +160,7 @@ include::{verifier_core_path}/src/test/resources/classpath/readFromFile.groovy[i ---- [source,yaml,indent=0,role="secondary"] -.yaml +.yml ---- include::{verifier_core_path}/src/test/resources/yml/contract_from_file.yml[indent=0] ---- @@ -160,17 +168,19 @@ include::{verifier_core_path}/src/test/resources/yml/contract_from_file.yml[inde Further assume that the JSON files is as follows: -*request.json* -[source,json,indent=0] +==== +[source,json,indent=0,subs="verbatim,attributes",role="primary"] +.request.json ---- include::{verifier_core_path}/src/test/resources/classpath/request.json[indent=0] ---- -*response.json* -[source,json,indent=0] +[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] +.response.json ---- include::{verifier_core_path}/src/test/resources/classpath/response.json[indent=0] ---- +==== When test or stub generation takes place, the contents of the file is passed to the body of a request or a response. The name of the file needs to be a file with location @@ -187,7 +197,7 @@ include::{verifier_core_path}/src/test/resources/body_builder/worksWithPdf.groov ---- [source,yaml,indent=0,role="secondary"] -.yaml +.yml ---- include::{verifier_core_path}/src/test/resources/yml/contract_pdf.yml[indent=0] ---- @@ -201,14 +211,15 @@ IMPORTANT: You should use this approach whenever you want to work with binary pa The following methods can be called in the top-level closure of a contract definition. `request` and `response` are mandatory. `priority` is optional. -.Groovy DSL -[source,groovy,indent=0] +==== +[source,groovy,indent=0,subs="verbatim,attributes",role="primary"] +.groovy ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=http_dsl,indent=0] ---- -.YAML -[source,yml,indent=0] +[source,yml,indent=0,subs="verbatim,attributes",role="secondary"] +.yml ---- include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=priority,indent=0] include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=request,indent=0] @@ -216,12 +227,14 @@ include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=request,i include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=response,indent=0] ... ---- +==== IMPORTANT: If you want to make your contract have a **higher** value of priority you need to pass a **lower** number to the `priority` tag / method. E.g. `priority` with value `5` has **higher** priority than `priority` with value `10`. -=== Request +[[contract-dsl-request]] +=== HTTP Request The HTTP protocol requires only **method and url** to be specified in a request. The same information is mandatory in request definition of the Contract. @@ -234,7 +247,7 @@ include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract ---- [source,yaml,indent=0,role="secondary"] -.yaml +.yml ---- include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=request_obligatory,indent=0] ---- @@ -251,7 +264,7 @@ include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract ---- [source,yaml,indent=0,role="secondary"] -.yaml +.yml ---- include::{verifier_core_path}/src/test/resources/yml/contract_rest_with_path.yml[tags=url_path,indent=0] ---- @@ -259,67 +272,75 @@ include::{verifier_core_path}/src/test/resources/yml/contract_rest_with_path.yml `request` may contain **query parameters**. -.Groovy DSL -[source,groovy,indent=0] +==== +[source,groovy,indent=0,subs="verbatim,attributes",role="primary"] +.groovy ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=urlpath,indent=0] ---- -.YAML -[source,yml,indent=0] +[source,yml,indent=0,subs="verbatim,attributes",role="secondary"] +.yml ---- include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=request,indent=0] ... include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=query_params,indent=0] ---- +==== `request` may contain additional **request headers**, as shown in the following example: -.Groovy DSL -[source,groovy,indent=0] +==== +[source,groovy,indent=0,subs="verbatim,attributes",role="primary"] +.groovy ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=headers,indent=0] ---- -.YAML -[source,yml,indent=0] +[source,yml,indent=0,subs="verbatim,attributes",role="secondary"] +.yml ---- include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=request,indent=0] ... include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=headers,indent=0] ---- +==== `request` may contain additional **request cookies**, as shown in the following example: -.Groovy DSL -[source,groovy,indent=0] +==== +[source,groovy,indent=0,subs="verbatim,attributes",role="primary"] +.groovy ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=cookies,indent=0] ---- -.YAML -[source,yml,indent=0] +[source,yml,indent=0,subs="verbatim,attributes",role="secondary"] +.yml ---- include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=request,indent=0] ... include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=cookies,indent=0] ---- +==== `request` may contain a **request body**: -.Groovy DSL -[source,groovy,indent=0] +==== +[source,groovy,indent=0,subs="verbatim,attributes",role="primary"] +.groovy ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=body,indent=0] ---- -.YAML -[source,yml,indent=0] +[source,yml,indent=0,subs="verbatim,attributes",role="secondary"] +.yml ---- include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=request,indent=0] ... include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=body,indent=0] ---- +==== `request` may contain **multipart** elements. To include multipart elements, use the `multipart` method/section, as shown in the following examples @@ -328,11 +349,11 @@ include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=body,inde [source,groovy,indent=0,role="primary"] .groovy ---- -include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MethodBodyBuilderSpec.groovy[tags=multipartdsl,indent=0] +include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/SpringTestMethodBodyBuildersSpec.groovy[tags=multipartdsl,indent=0] ---- [source,yaml,indent=0,role="secondary"] -.yaml +.yml ---- include::{verifier_core_path}/src/test/resources/yml/contract_multipart.yml[indent=0] ---- @@ -362,11 +383,13 @@ define the parameter name via `paramName` and then you can pass the parametrization of either `fileName` or `fileContent` via `regex` or a `predefined` regular expression -From this contract, the generated test is as follows: +From this contract, the generated test and stubs look as follows: -[source,java,indent=0] +==== +[source,java,indent=0,subs="verbatim,attributes",role="primary"] +.Test ---- - // given: +// given: MockMvcRequestSpecification request = given() .header("Content-Type", "multipart/form-data;boundary=AaB03x") .param("formParameter", "\"formParameterValue\"") @@ -381,31 +404,34 @@ From this contract, the generated test is as follows: assertThat(response.statusCode()).isEqualTo(200); ---- -The WireMock stub is as follows: - -[source,json,indent=0] +[source,json,indent=0,subs="verbatim,attributes",role="secondary"] +.Stub ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/dsl/wiremock/WireMockGroovyDslSpec.groovy[tags=multipartwiremock,indent=0] ---- +==== -=== Response +[[contract-dsl-response]] +=== HTTP Response The response must contain an **HTTP status code** and may contain other information. The following code shows an example: -.Groovy DSL -[source,groovy,indent=0] +==== +[source,groovy,indent=0,subs="verbatim,attributes",role="primary"] +.groovy ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=response,indent=0] ---- -.YAML -[source,yml,indent=0] +[source,yml,indent=0,subs="verbatim,attributes",role="secondary"] +.yml ---- include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=response,indent=0] ... include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=response_obligatory,indent=0] ---- +==== Besides status, the response may contain **headers**, **cookies** and a **body**, both of which are specified the same way as in the request (see the previous paragraph). @@ -414,6 +440,7 @@ TIP: Via the Groovy DSL you can reference the `org.springframework.cloud.contrac methods to provide a meaningful status instead of a digit. E.g. you can call `OK()` for a status `200` or `BAD_REQUEST()` for `400`. +[[contract-dsl-dynamic-properties]] === Dynamic properties The contract can contain some dynamic properties: timestamps, IDs, and so on. You do not @@ -429,16 +456,19 @@ check out the https://github.com/spring-cloud/spring-cloud-contract/wiki/Spring- For YAML you can only use the `matchers` section. +[[contract-dsl-dynamic-properties-in-body]] ==== Dynamic properties inside the body IMPORTANT: This section is valid only for Groovy DSL. Check out the -<> section for YAML examples of a similar feature. +<> section for YAML examples of a similar feature. You can set the properties inside the body either with the `value` method or, if you use the Groovy map notation, with `$()`. The following example shows how to set dynamic properties with the value method: -[source,groovy,indent=0] +==== +[source,groovy,indent=0,subs="verbatim,attributes",role="primary"] +.value ---- value(consumer(...), producer(...)) value(c(...), p(...)) @@ -446,23 +476,24 @@ value(stub(...), test(...)) value(client(...), server(...)) ---- -The following example shows how to set dynamic properties with `$()`: - -[source,groovy,indent=0] +[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] +.$ ---- $(consumer(...), producer(...)) $(c(...), p(...)) $(stub(...), test(...)) $(client(...), server(...)) ---- +==== Both approaches work equally well. `stub` and `client` methods are aliases over the `consumer` method. Subsequent sections take a closer look at what you can do with those values. +[[contract-dsl-regex]] ==== Regular expressions IMPORTANT: This section is valid only for Groovy DSL. Check out the -<> section for YAML examples of a similar feature. +<> section for YAML examples of a similar feature. You can use regular expressions to write your requests in Contract DSL. Doing so is particularly useful when you want to indicate that a given response should be provided @@ -472,7 +503,7 @@ need to use patterns and not exact values both for your test and your server sid Make sure that regex matches a whole region of a sequence as internally a call to https://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html#matches--[Pattern.matches()] is called. For instance, `abc` pattern doesn't match `aabc` string but `.abc` does. -There are several additional <> as well. +There are several additional <> as well. The following example shows how to use regular expressions to write a request: @@ -523,7 +554,7 @@ and this is an example of how you can reference those methods: include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=regex_creating_props,indent=0] ---- -[[regex-limitations]] +[[contract-dsl-regex-limitations]] ===== Limitations WARNING: Due to certain limitations of `Xeger` library that generates string out of @@ -534,10 +565,11 @@ WARNING: Do not use `LocalDate` instance as a value for `$` like this `$(consume It causes `java.lang.StackOverflowError`. Use `$(consumer(LocalDate.now().toString()))` instead. https://github.com/spring-cloud/spring-cloud-contract/issues/900[Issue 900] +[[contract-dsl-optional-params]] ==== Passing Optional Parameters IMPORTANT: This section is valid only for Groovy DSL. Check out the -<> section for YAML examples of a similar feature. +<> section for YAML examples of a similar feature. It is possible to provide optional parameters in your contract. However, you can provide optional parameters only for the following: @@ -569,10 +601,11 @@ The following stub would also be generated: include::{plugins_path}/spring-cloud-contract-converters/src/test/groovy/org/springframework/cloud/contract/verifier/wiremock/DslToWireMockClientConverterSpec.groovy[tags=wiremock,indent=0] ---- +[[contract-dsl-custom-methods]] ==== Executing Custom Methods on the Server Side IMPORTANT: This section is valid only for Groovy DSL. Check out the -<> section for YAML examples of a similar feature. +<> section for YAML examples of a similar feature. You can define a method call that executes on the server side during the test. Such a method can be added to the class defined as "baseClassForTests" in the configuration. The @@ -634,6 +667,7 @@ It should resemble the following code: assertThat(response.statusCode()).isEqualTo(200); ---- +[[contract-dsl-referencing-request-from-response]] ==== Referencing the Request from the Response The best situation is to provide fixed values, but sometimes you need to reference a @@ -677,11 +711,11 @@ Consider the following contract: [source,groovy,indent=0,role="primary"] .groovy ---- -include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MethodBodyBuilderSpec.groovy[tags=template_contract,indent=0] +include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/SpringTestMethodBodyBuildersSpec.groovy[tags=template_contract,indent=0] ---- [source,yaml,indent=0,role="secondary"] -.yaml +.yml ---- include::{verifier_core_path}/src/test/resources/yml/contract_reference_request.yml[indent=0] ---- @@ -786,32 +820,7 @@ proper values. Additionally, it registers two helper functions: * `escapejsonbody`: Escapes the request body in a format that can be embedded in a JSON. * `jsonpath`: For a given parameter, find an object in the request body. -==== Registering Your Own WireMock Extension - -WireMock lets you register custom extensions. By default, Spring Cloud Contract registers -the transformer, which lets you reference a request from a response. If you want to -provide your own extensions, you can register an implementation of the -`org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions` interface. -Since we use the spring.factories extension approach, you can create an entry in -`META-INF/spring.factories` file similar to the following: - -[source,groovy,indent=0] ----- -include::{stubrunner_core_path}/src/test/resources/META-INF/spring.factories[indent=0] ----- - -The following is an example of a custom extension: - -.TestWireMockExtensions.groovy -[source,groovy,indent=0] ----- -include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/dsl/wiremock/TestWireMockExtensions.groovy[indent=0] ----- - -IMPORTANT: Remember to override the `applyGlobally()` method and set it to `false` if you -want the transformation to be applied only for a mapping that explicitly requires it. - -[[contract-matchers]] +[[contract-dsl-matchers]] ==== Dynamic Properties in the Matchers Sections If you work with https://docs.pact.io/[Pact], the following discussion may seem familiar. @@ -937,7 +946,7 @@ include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract ---- [source,yaml,indent=0,role="secondary"] -.yaml +.yml ---- include::{verifier_core_path}/src/test/resources/yml/contract_matchers.yml[indent=0] ---- @@ -1079,35 +1088,18 @@ As you can see, the assertion is malformed. Only the first element of the array asserted. In order to fix this, you should apply the assertion to the whole `$.events` collection and assert it with the `byCommand(...)` method. -=== JAX-RS Support -The Spring Cloud Contract Verifier supports the JAX-RS 2 Client API. The base class needs -to define `protected WebTarget webTarget` and server initialization. The only option for -testing JAX-RS API is to start a web server. Also, a request with a body needs to have a -content type set. Otherwise, the default of `application/octet-stream` gets used. - -In order to use JAX-RS mode, use the following settings: - -[source,groovy,indent=0] ----- -testMode == 'JAXRSCLIENT' ----- - -The following example shows a generated test API: - -[source,groovy,indent=0] ----- -include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/JaxRsClientMethodBuilderSpec.groovy[tags=jaxrs,indent=0] ----- +[[contract-dsl-async]] === Async Support If you're using asynchronous communication on the server side (your controllers are returning `Callable`, `DeferredResult`, and so on), then, inside your contract, you must provide an `async()` method in the `response` section. The following code shows an example: -.Groovy DSL -[source,groovy,indent=0] +==== +[source,groovy,indent=0,subs="verbatim,attributes",role="primary"] +.groovy ---- org.springframework.cloud.contract.spec.Contract.make { request { @@ -1122,17 +1114,19 @@ org.springframework.cloud.contract.spec.Contract.make { } ---- -.YAML -[source,yml,indent=0] +[source,yml,indent=0,subs="verbatim,attributes",role="secondary"] +.yml ---- response: async: true ---- +==== You can also use the `fixedDelayMilliseconds` method / property to add delay to your stubs. -.Groovy DSL -[source,groovy,indent=0] +==== +[source,groovy,indent=0,subs="verbatim,attributes",role="primary"] +.groovy ---- org.springframework.cloud.contract.spec.Contract.make { request { @@ -1147,159 +1141,15 @@ org.springframework.cloud.contract.spec.Contract.make { } ---- -.YAML -[source,yml,indent=0] +[source,yml,indent=0,subs="verbatim,attributes",role="secondary"] +.yml ---- response: fixedDelayMilliseconds: 1000 ---- +==== -=== Working with Context Paths - -Spring Cloud Contract supports context paths. - -IMPORTANT: The only change needed to fully support context paths is the switch on the -*PRODUCER* side. Also, the autogenerated tests must use *EXPLICIT* mode. The consumer -side remains untouched. In order for the generated test to pass, you must use *EXPLICIT* -mode. - -[source,xml,indent=0,subs="verbatim,attributes",role="primary"] -.Maven ----- - - org.springframework.cloud - spring-cloud-contract-maven-plugin - ${spring-cloud-contract.version} - true - - EXPLICIT - - ----- - -[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] -.Gradle ----- -contracts { - testMode = 'EXPLICIT' -} ----- - -That way, you generate a test that *DOES NOT* use MockMvc. It means that you generate -real requests and you need to setup your generated test's base class to work on a real -socket. - -Consider the following contract: - -[source,groovy,indent=0] ----- -include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/SingleTestGeneratorSpec.groovy[tags=context_path_contract,indent=0] ----- - -The following example shows how to set up a base class and Rest Assured: - -[source,groovy,indent=0] ----- -include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/SingleTestGeneratorSpec.groovy[tags=context_path_baseclass,indent=0] ----- - -If you do it this way: - -* All of your requests in the autogenerated tests are sent to the real endpoint with your -context path included (for example, `/my-context-path/url`). -* Your contracts reflect that you have a context path. Your generated stubs also have -that information (for example, in the stubs, you have to call `/my-context-path/url`). - -=== Working with WebFlux - -Spring Cloud Contract offers two ways of working with WebFlux. - -==== WebFlux with WebTestClient - -One of them is via the `WebTestClient` mode. - -[source,xml,indent=0,subs="verbatim,attributes",role="primary"] -.Maven ----- - - org.springframework.cloud - spring-cloud-contract-maven-plugin - ${spring-cloud-contract.version} - true - - WEBTESTCLIENT - - ----- - -[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] -.Gradle ----- -contracts { - testMode = 'WEBTESTCLIENT' -} ----- - -The following example shows how to set up a `WebTestClient` base class and `RestAssured` -for WebFlux: - -[source,groovy,indent=0] ----- -import io.restassured.module.webtestclient.RestAssuredWebTestClient; -import org.junit.Before; - -public abstract class BeerRestBase { - - @Before - public void setup() { - RestAssuredWebTestClient.standaloneSetup( - new ProducerController(personToCheck -> personToCheck.age >= 20)); - } -} -} ----- - -==== WebFlux with Explicit mode - -Another way is with the `EXPLICIT` mode in your generated tests -to work with WebFlux. - -[source,xml,indent=0,subs="verbatim,attributes",role="primary"] -.Maven ----- - - org.springframework.cloud - spring-cloud-contract-maven-plugin - ${spring-cloud-contract.version} - true - - EXPLICIT - - ----- - -[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] -.Gradle ----- -contracts { - testMode = 'EXPLICIT' -} ----- - -The following example shows how to set up a base class and Rest Assured for Web Flux: - -[source,groovy,indent=0] ----- -include::{samples_url}/producer_webflux/src/test/java/com/example/BeerRestBase.java[tags=annotations,indent=0] - - // your tests go here - - // in this config class you define all controllers and mocked services -include::{samples_url}/producer_webflux/src/test/java/com/example/BeerRestBase.java[tags=config,indent=0] - -} ----- - +[[contract-dsl-xml]] === XML Support for REST For REST contracts, we also support XML request and response body. The XML body has to be passed within the `body` element @@ -1310,17 +1160,19 @@ and the appropriate `MatchingType` as second. All the body matchers apart from ` Here is an example of a Groovy DSL contract with XML response body: -[source,groovy,indent=0] +==== +[source,groovy,indent=0,subs="verbatim,attributes",role="primary"] +.groovy ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/XmlMethodBodyBuilderSpec.groovy[tags=xmlgroovy] ---- -And below is an example of a YAML contract with XML request and response bodies: - -[source,yaml,indent=0] +[source,yml,indent=0,subs="verbatim,attributes",role="secondary"] +.yml ---- include::{verifier_core_path}/src/test/resources/yml/contract_rest_xml.yml ---- +==== Here is an example of an automatically generated test for XML response body: @@ -1353,87 +1205,7 @@ public void validate_xmlMatches() throws Exception { } ---- -=== Messaging Top-Level Elements - -The DSL for messaging looks a little bit different than the one that focuses on HTTP. The -following sections explain the differences: - -* <> -* <> -* <> -* <> - -[[contract-dsl-output-triggered-method]] -==== Output Triggered by a Method - -The output message can be triggered by calling a method (such as a `Scheduler` when a was -started and a message was sent), as shown in the following example: - -.Groovy DSL -[source,groovy] ----- -include::{tests_path}/samples-messaging-integration/src/test/groovy/com/example/IntegrationMessagingApplicationSpec.groovy[tags=method_trigger,indent=0] ----- - -.YAML -[source,yml,indent=0] ----- -include::{verifier_core_path}/src/test/resources/yml/contract_message_method.yml[indent=0] ----- - -In the previous example case, the output message is sent to `output` if a method called -`bookReturnedTriggered` is executed. On the message *publisher's* side, we generate a -test that calls that method to trigger the message. On the *consumer* side, you can use -the `some_label` to trigger the message. - -[[contract-dsl-output-triggered-message]] -==== Output Triggered by a Message - -The output message can be triggered by receiving a message, as shown in the following -example: - -.Groovy DSL -[source,groovy] ----- -include::{tests_path}/samples-messaging-integration/src/test/groovy/com/example/IntegrationMessagingApplicationSpec.groovy[tags=message_trigger,indent=0] ----- - -.YAML -[source,yml,indent=0] ----- -include::{verifier_core_path}/src/test/resources/yml/contract_message_input_message.yml[indent=0] ----- - -In the preceding example, the output message is sent to `output` if a proper message is -received on the `input` destination. On the message *publisher's* side, the engine -generates a test that sends the input message to the defined destination. On the -*consumer* side, you can either send a message to the input destination or use a label -(`some_label` in the example) to trigger the message. - -[[contract-dsl-consumer-producer]] -==== Consumer/Producer - -IMPORTANT: This section is valid only for Groovy DSL. - -In HTTP, you have a notion of `client`/`stub and `server`/`test` notation. You can also -use those paradigms in messaging. In addition, Spring Cloud Contract Verifier also -provides the `consumer` and `producer` methods, as presented in the following example -(note that you can use either `$` or `value` methods to provide `consumer` and `producer` -parts): - -[source,groovy] ----- -include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=consumer_producer] ----- - -[[contract-dsl-common]] -==== Common - -In the `input` or `outputMessage` section you can call `assertThat` with the name -of a `method` (e.g. `assertThatMessageIsOnTheQueue()`) that you have defined in the -base class or in a static import. Spring Cloud Contract will execute that method -in the generated test. - +[[contract-dsl-multiple]] === Multiple Contracts in One File You can define multiple contracts in one file. Such a contract might resemble the @@ -1447,7 +1219,7 @@ include::{plugins_path}/spring-cloud-contract-maven-plugin/src/test/projects/mul ---- [source,yaml,indent=0,role="secondary"] -.yaml +.yml ---- include::{verifier_core_path}/src/test/resources/yml/multiple_contracts.yml[indent=0] ---- @@ -1522,565 +1294,37 @@ case, the contract had an index of `1` in the list of contracts in the file). TIP: As you can see, it is much better if you name your contracts because doing so makes your tests far more meaningful. -=== Generating Spring REST Docs snippets from the contracts +[[contract-stateful-contracts]] +== Stateful Contracts -When you want to include the requests and responses of your API using Spring REST Docs, -you only need to make some minor changes to your setup if you are using MockMvc and RestAssuredMockMvc. -Simply include the following dependencies if you haven't already. +Stateful contracts (known also as scenarios) are contract definitions that should be read in order. This might be useful in the following situations: -[source,xml,indent=0] -.Maven +* you want to execute the contract in a precisely defined order, since you're using Spring Cloud Contract to test your stateful application +** NOTE: we really discourage you to do that since contract tests should be stateless +* you want the same endpoint to return different results for the same request + +All you need to do is to +stick to the proper naming convention while creating your contracts. The convention +requires including an order number followed by an underscore. This will work regardless + of whether you're working with YAML or Groovy. Example: + +[source,indent=0] ---- -include::{standalone_restdocs_path}/http-server/pom.xml[tags=dependencies,indent=0] +my_contracts_dir\ + scenario1\ + 1_login.groovy + 2_showCart.groovy + 3_logout.groovy ---- -[source,groovy,indent=0] -.Gradle ----- -include::{standalone_restdocs_path}/http-server/build.gradle[tags=dependencies,indent=0] ----- +Such a tree causes Spring Cloud Contract Verifier to generate WireMock's scenario with a +name of `scenario1` and the three following steps: -Next you need to make some changes to your base class like the following example. +. login marked as `Started` pointing to... +. showCart marked as `Step1` pointing to... +. logout marked as `Step2` which will close the scenario. -[source,java,indent=0] ----- -include::{standalone_restdocs_path}/http-server/src/test/java/com/example/fraud/FraudBaseWithWebAppSetup.java[tags=base_class,indent=0] ----- +More details about WireMock scenarios can be found at +https://wiremock.org/docs/stateful-behaviour/[https://wiremock.org/docs/stateful-behaviour/] -In case you are using the standalone setup, you can set up RestAssuredMockMvc like this: - -[source,java,indent=0] ----- -include::{standalone_restdocs_path}/http-server/src/test/java/com/example/fraud/FraudBaseWithStandaloneSetup.java[tags=base_class,indent=0] ----- - -TIP: You don't need to specify the output directory for the generated snippets since version 1.2.0.RELEASE of Spring REST Docs. - -=== DSL Customization - -IMPORTANT: This section is valid only for Groovy DSL - -You can customize the Spring Cloud Contract Verifier by extending the DSL, as shown in -the remainder of this section. - -==== Extending the 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 document, you can see examples of: - -* Creating a JAR with reusable classes. -* Referencing of these classes in the DSLs. - -You can find the full example -https://github.com/spring-cloud-samples/spring-cloud-contract-samples[here]. - -===== Common JAR - -The following examples show three classes that can be reused in the DSLs. - -*PatternUtils* contains functions used by both the **consumer** and the **producer**. - -[source,java] ----- -include::{samples_url}/common/src/main/java/com/example/PatternUtils.java[] ----- - -*ConsumerUtils* contains functions used by the **consumer**. - -[source,java] ----- -include::{samples_url}/common/src/main/java/com/example/ConsumerUtils.java[] ----- - -*ProducerUtils* contains functions used by the **producer**. - -[source,java] ----- -include::{samples_url}/common/src/main/java/com/example/ProducerUtils.java[] ----- - -===== Adding the Dependency to the Project - -In order for the plugins and IDE to be able to reference the common JAR classes, you need -to pass the dependency to your project. - -// TODO missing code block here - we should show an example adding a dependency - -===== Test the Dependency in the Project's Dependencies - -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 examples show how to test the dependency: - -[source,xml,indent=0,subs="verbatim,attributes",role="primary"] -.Maven ----- -include::{samples_url}/producer/pom.xml[tags=test_dep,indent=0] ----- - -[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] -.Gradle ----- -include::{samples_url}/producer/build.gradle[tags=test_dep,indent=0] ----- - -===== Test a Dependency in the Plugin's Dependencies - -Now, you must add the dependency for the plugin to reuse at runtime, as shown in the -following example: - -[source,xml,indent=0,subs="verbatim,attributes",role="primary"] -.Maven ----- -include::{samples_url}/producer/pom.xml[tags=test_dep_in_plugin,indent=0] ----- - -[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] -.Gradle ----- -include::{samples_url}/producer/build.gradle[tags=test_dep_in_plugin,indent=0] ----- - -===== Referencing classes in DSLs - -You can now reference your classes in your DSL, as shown in the following example: - -[source,groovy] ----- -include::{samples_url}/producer/src/test/resources/contracts/beer/rest/shouldGrantABeerIfOldEnough.groovy[indent=0] ----- - -IMPORTANT: You can set the Spring Cloud Contract plugin up by setting `convertToYaml` to `true`. That way you will NOT have to add the dependency with the extended functionality to the consumer side, since the consumer side will be using YAML contracts instead of Groovy ones. - -== Using the Pluggable Architecture - -You may encounter cases where you have your contracts have been defined in other formats, -such as YAML, RAML or PACT. In those cases, you still want to benefit from the automatic -generation of tests and stubs. You can add your own implementation for generating both -tests and stubs. Also, you can customize the way tests are generated (for example, you -can generate tests for other languages) and the way stubs are generated (for example, you -can generate stubs for other HTTP server implementations). - -=== Custom Contract Converter - -The `ContractConverter` interface lets you register your own implementation of a contract -structure converter. The following code listing shows the `ContractConverter` interface: - -[source,java] ----- -include::{contract_spec_path}/src/main/java/org/springframework/cloud/contract/spec/ContractConverter.java[indent=0,lines=17..-1] ----- - -Your implementation must define the condition on which it should start the -conversion. Also, you must define how to perform that conversion in both directions. - -IMPORTANT: Once you create your implementation, you must create a -`/META-INF/spring.factories` file in which you provide the fully qualified name of your -implementation. - -The following example shows a typical `spring.factories` file: - -[source] ----- -org.springframework.cloud.contract.spec.ContractConverter=\ -org.springframework.cloud.contract.verifier.converter.YamlContractConverter ----- - -[[pact-converter]] -==== Pact Converter - -Spring Cloud Contract includes support for https://docs.pact.io/[Pact] representation of -contracts up until v4. Instead of using the Groovy DSL, you can use Pact files. In this section, we -present how to add Pact support for your project. Note however that not all functionality is supported. -Starting with v3 you can combine multiple matcher for the same element; -you can use matchers for the body, headers, request and path; and you can use value generators. -Spring Cloud Contract currently only supports multiple matchers that are combined using the AND rule logic. -Next to that the request and path matchers are skipped during the conversion. -When using a date, time or datetime value generator with a given format, -the given format will be skipped and the ISO format will be used. - -In order to properly support the Spring Cloud Contract way of doing messaging -with Pact you'll have to provide some additional meta data entries. Below you can find a list of such entries: - -- to define the destination to which a message gets sent, you have to -set a `metaData` entry in the Pact file, with key `sentTo` equal to the destination to which a message is to be sent. E.g. `"metaData": { "sentTo": "activemq:output" }` - -==== Pact Contract - -Consider following example of a Pact contract, which is a file under the -`src/test/resources/contracts` folder. - -[source,javascript,indent=0] ----- -include::{standalone_pact_path}/pact-http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.json[indent=0] ----- - -The remainder of this section about using Pact refers to the preceding file. - -==== Pact for Producers - -On the producer side, you must add two additional dependencies to your plugin -configuration. One is the Spring Cloud Contract Pact support, and the other represents -the current Pact version that you use. - -[source,xml,indent=0,subs="verbatim,attributes",role="primary"] -.Maven ----- -include::{standalone_pact_path}/pact-http-server/pom.xml[tags=pact_dependency,indent=0] ----- - -[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] -.Gradle ----- -include::{standalone_pact_path}/pact-http-server/build.gradle[tags=pact_dependency,indent=0] ----- - -When you execute the build of your application, a test will be generated. The generated -test might be as follows: - -[source,java,indent=0] ----- - @Test - public void validate_shouldMarkClientAsFraud() throws Exception { - // given: - MockMvcRequestSpecification request = given() - .header("Content-Type", "application/vnd.fraud.v1+json") - .body("{\"clientId\":\"1234567890\",\"loanAmount\":99999}"); - - // when: - ResponseOptions response = given().spec(request) - .put("/fraudcheck"); - - // then: - assertThat(response.statusCode()).isEqualTo(200); - assertThat(response.header("Content-Type")).matches("application/vnd\\.fraud\\.v1\\+json.*"); - // and: - DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); - assertThatJson(parsedJson).field("['rejectionReason']").isEqualTo("Amount too high"); - // and: - assertThat(parsedJson.read("$.fraudCheckStatus", String.class)).matches("FRAUD"); - } ----- - -The corresponding generated stub might be as follows: - -[source,javascript,indent=0] ----- -{ - "id" : "996ae5ae-6834-4db6-8fac-358ca187ab62", - "uuid" : "996ae5ae-6834-4db6-8fac-358ca187ab62", - "request" : { - "url" : "/fraudcheck", - "method" : "PUT", - "headers" : { - "Content-Type" : { - "matches" : "application/vnd\\.fraud\\.v1\\+json.*" - } - }, - "bodyPatterns" : [ { - "matchesJsonPath" : "$[?(@.['loanAmount'] == 99999)]" - }, { - "matchesJsonPath" : "$[?(@.clientId =~ /([0-9]{10})/)]" - } ] - }, - "response" : { - "status" : 200, - "body" : "{\"fraudCheckStatus\":\"FRAUD\",\"rejectionReason\":\"Amount too high\"}", - "headers" : { - "Content-Type" : "application/vnd.fraud.v1+json;charset=UTF-8" - }, - "transformers" : [ "response-template" ] - }, -} ----- - -==== Pact for Consumers - -On the producer side, you must add two additional dependencies to your project -dependencies. One is the Spring Cloud Contract Pact support, and the other represents the -current Pact version that you use. - -[source,xml,indent=0,subs="verbatim,attributes",role="primary"] -.Maven ----- -include::{standalone_pact_path}/pact-http-client/pom.xml[tags=pact_dependency,indent=0] ----- - -[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] -.Gradle ----- -include::{standalone_pact_path}/pact-http-client/build.gradle[tags=pact_dependency,indent=0] ----- - -=== Using the Custom Test Generator - -If you want to generate tests for languages other than Java or you are not happy with the -way the verifier builds Java tests, you can register your own implementation. - -The `SingleTestGenerator` interface lets you register your own implementation. The -following code listing shows the `SingleTestGenerator` interface: - -[source,groovy] ----- -include::{verifier_core_path}/src/main/groovy/org/springframework/cloud/contract/verifier/builder/SingleTestGenerator.java[indent=0,lines=17..-1] ----- - -Again, you must provide a `spring.factories` file, such as the one shown in the following -example: - -[source] ----- -org.springframework.cloud.contract.verifier.builder.SingleTestGenerator=/ -com.example.MyGenerator ----- - -=== Using the Custom Stub Generator - -If you want to generate stubs for stub servers other than WireMock, you can plug in your -own implementation of the `StubGenerator` interface. The following code listing shows the -`StubGenerator` interface: - -[source,groovy] ----- -include::{converters_path}/src/main/groovy/org/springframework/cloud/contract/verifier/converter/StubGenerator.groovy[indent=0,lines=16..-1] ----- - -Again, you must provide a `spring.factories` file, such as the one shown in the following -example: - -[source] ----- -include::{converters_path}/src/main/resources/META-INF/spring.factories[indent=0] ----- - -The default implementation is the WireMock stub generation. - -TIP: You can provide multiple stub generator implementations. For example, from a single -DSL, you can produce both WireMock stubs and Pact files. - -=== Using the Custom Stub Runner - -If you decide to use a custom stub generation, you also need a custom way of running -stubs with your different stub provider. - -Assume that you use https://github.com/dreamhead/moco[Moco] to build your stubs and that -you have written a stub generator and placed your stubs in a JAR file. - -In order for Stub Runner to know how to run your stubs, you have to define a custom -HTTP Stub server implementation, which might resemble the following example: - -[source,groovy] ----- -include::{tests_path}/spring-cloud-contract-stub-runner-moco/src/test/groovy/org/springframework/cloud/contract/stubrunner/provider/moco/MocoHttpServerStub.groovy[indent=0,lines=16..-1] ----- - -Then, you can register it in your `spring.factories` file, as shown in the following -example: - -[source] ----- -org.springframework.cloud.contract.stubrunner.HttpServerStub=\ -org.springframework.cloud.contract.stubrunner.provider.moco.MocoHttpServerStub ----- - -Now you can run stubs with Moco. - -IMPORTANT: If you do not provide any implementation, then the default (WireMock) -implementation is used. If you provide more than one, the first one on the list is used. - -=== Using the Custom Stub Downloader - -You can customize the way your stubs are downloaded by creating an implementation of the -`StubDownloaderBuilder` interface, as shown in the following example: - -[source,java] ----- -package com.example; - -class CustomStubDownloaderBuilder implements StubDownloaderBuilder { - - @Override - public StubDownloader build(final StubRunnerOptions stubRunnerOptions) { - return new StubDownloader() { - @Override - public Map.Entry downloadAndUnpackStubJar( - StubConfiguration config) { - File unpackedStubs = retrieveStubs(); - return new AbstractMap.SimpleEntry<>( - new StubConfiguration(config.getGroupId(), config.getArtifactId(), version, - config.getClassifier()), unpackedStubs); - } - - File retrieveStubs() { - // here goes your custom logic to provide a folder where all the stubs reside - } -} ----- - -Then you can register it in your `spring.factories` file, as shown in the following -example: - -[source] ----- -# Example of a custom Stub Downloader Provider -org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder=\ -com.example.CustomStubDownloaderBuilder ----- - -Now you can pick a folder with the source of your stubs. - -IMPORTANT: If you do not provide any implementation, then the default is used (scan classpath). -If you provide the `stubsMode = StubRunnerProperties.StubsMode.LOCAL` or -`, stubsMode = StubRunnerProperties.StubsMode.REMOTE` then the Aether implementation will be used -If you provide more than one, then the first one on the list is used. - -[[scm-stub-downloader]] -=== Using the SCM Stub Downloader - -Whenever the `repositoryRoot` starts with a SCM protocol -(currently we support only `git://`), the stub downloader will try -to clone the repository and use it as a source of contracts -to generate tests or stubs. - -Either via environment variables, system properties, properties set -inside the plugin or contracts repository configuration you can -tweak the downloader's behaviour. Below you can find the list of -properties - -.SCM Stub Downloader properties -|=== -|Type of a property |Name of the property | Description -| -* `git.branch` (plugin prop) - -* `stubrunner.properties.git.branch` (system prop) - -* `STUBRUNNER_PROPERTIES_GIT_BRANCH` (env prop) -|master -|Which branch to checkout - -| -* `git.username` (plugin prop) - -* `stubrunner.properties.git.username` (system prop) - -* `STUBRUNNER_PROPERTIES_GIT_USERNAME` (env prop) -| -|Git clone username - -| -* `git.password` (plugin prop) - -* `stubrunner.properties.git.password` (system prop) - -* `STUBRUNNER_PROPERTIES_GIT_PASSWORD` (env prop) -| -|Git clone password - -| -* `git.no-of-attempts` (plugin prop) - -* `stubrunner.properties.git.no-of-attempts` (system prop) - -* `STUBRUNNER_PROPERTIES_GIT_NO_OF_ATTEMPTS` (env prop) -|10 -|Number of attempts to push the commits to `origin` - -| -* `git.wait-between-attempts` (Plugin prop) - -* `stubrunner.properties.git.wait-between-attempts` (system prop) - -* `STUBRUNNER_PROPERTIES_GIT_WAIT_BETWEEN_ATTEMPTS` (env prop) -|1000 -|Number of millis to wait between attempts to push the commits to `origin` -|=== - -[[pact-stub-downloader]] -=== Using the Pact Stub Downloader - -Whenever the `repositoryRoot` starts with a Pact protocol -(starts with `pact://`), the stub downloader will try -to fetch the Pact contract definitions from the Pact Broker. -Whatever is set after `pact://` will be parsed as the Pact Broker URL. - -Either via environment variables, system properties, properties set -inside the plugin or contracts repository configuration you can -tweak the downloader's behaviour. Below you can find the list of -properties - -.SCM Stub Downloader properties -|=== -|Name of a property |Default | Description -| -* `pactbroker.host` (plugin prop) - -* `stubrunner.properties.pactbroker.host` (system prop) - -* `STUBRUNNER_PROPERTIES_PACTBROKER_HOST` (env prop) -|Host from URL passed to `repositoryRoot` -|What is the URL of Pact Broker - -| -* `pactbroker.port` (plugin prop) - -* `stubrunner.properties.pactbroker.port` (system prop) - -* `STUBRUNNER_PROPERTIES_PACTBROKER_PORT` (env prop) -|Port from URL passed to `repositoryRoot` -|What is the port of Pact Broker - -| -* `pactbroker.protocol` (plugin prop) - -* `stubrunner.properties.pactbroker.protocol` (system prop) - -* `STUBRUNNER_PROPERTIES_PACTBROKER_PROTOCOL` (env prop) -|Protocol from URL passed to `repositoryRoot` -|What is the protocol of Pact Broker - -| -* `pactbroker.tags` (plugin prop) - -* `stubrunner.properties.pactbroker.tags` (system prop) - -* `STUBRUNNER_PROPERTIES_PACTBROKER_TAGS` (env prop) -|Version of the stub, or `latest` if version is `+` -|What tags should be used to fetch the stub - -| -* `pactbroker.auth.scheme` (plugin prop) - -* `stubrunner.properties.pactbroker.auth.scheme` (system prop) - -* `STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_SCHEME` (env prop) -|`Basic` -|What kind of authentication should be used to connect to the Pact Broker - -| -* `pactbroker.auth.username` (plugin prop) - -* `stubrunner.properties.pactbroker.auth.username` (system prop) - -* `STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_USERNAME` (env prop) -|The username passed to `contractsRepositoryUsername` (maven) or `contractRepository.username` (gradle) -|Username used to connect to the Pact Broker - -| -* `pactbroker.auth.password` (plugin prop) - -* `stubrunner.properties.pactbroker.auth.password` (system prop) - -* `STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_PASSWORD` (env prop) -|The password passed to `contractsRepositoryPassword` (maven) or `contractRepository.password` (gradle) -|Password used to connect to the Pact Broker - -| -* `pactbroker.provider-name-with-group-id` (plugin prop) - -* `stubrunner.properties.pactbroker.provider-name-with-group-id` (system prop) - -* `STUBRUNNER_PROPERTIES_PACTBROKER_PROVIDER_NAME_WITH_GROUP_ID` (env prop) -|false -|When `true`, the provider name will be a combination of `groupId:artifactId`. If `false`, just `artifactId` is used -|=== +Spring Cloud Contract also generates tests with a guaranteed order of execution. \ No newline at end of file diff --git a/docs/src/main/asciidoc/_project-features-flows.adoc b/docs/src/main/asciidoc/_project-features-flows.adoc new file mode 100644 index 0000000000..7ef5b542ea --- /dev/null +++ b/docs/src/main/asciidoc/_project-features-flows.adoc @@ -0,0 +1,417 @@ +[[features-jax-rs]] +== JAX-RS +include::_attributes.adoc[] + +The Spring Cloud Contract supports the JAX-RS 2 Client API. The base class needs +to define `protected WebTarget webTarget` and server initialization. The only option for +testing JAX-RS API is to start a web server. Also, a request with a body needs to have a +content type set. Otherwise, the default of `application/octet-stream` gets used. + +In order to use JAX-RS mode, use the following settings: + +[source,groovy,indent=0] +---- +testMode == 'JAXRSCLIENT' +---- + +The following example shows a generated test API: + +[source,groovy,indent=0] +---- +include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/JaxRsClientMethodBuilderSpec.groovy[tags=jaxrs,indent=0] +---- + +[[contract-webflux]] +== WebFlux + +Spring Cloud Contract offers two ways of working with WebFlux. + +[[contract-webtestclient]] +=== WebFlux with WebTestClient + +One of them is via the `WebTestClient` mode. + +==== +[source,xml,indent=0,subs="verbatim,attributes",role="primary"] +.Maven +---- + + org.springframework.cloud + spring-cloud-contract-maven-plugin + ${spring-cloud-contract.version} + true + + WEBTESTCLIENT + + +---- + +[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] +.Gradle +---- +contracts { + testMode = 'WEBTESTCLIENT' +} +---- +==== + +The following example shows how to set up a `WebTestClient` base class and `RestAssured` +for WebFlux: + +[source,groovy,indent=0] +---- +import io.restassured.module.webtestclient.RestAssuredWebTestClient; +import org.junit.Before; + +public abstract class BeerRestBase { + + @Before + public void setup() { + RestAssuredWebTestClient.standaloneSetup( + new ProducerController(personToCheck -> personToCheck.age >= 20)); + } +} +} +---- + +[[contract-webflux-explicit]] +=== WebFlux with Explicit mode + +Another way is with the `EXPLICIT` mode in your generated tests +to work with WebFlux. + +==== +[source,xml,indent=0,subs="verbatim,attributes",role="primary"] +.Maven +---- + + org.springframework.cloud + spring-cloud-contract-maven-plugin + ${spring-cloud-contract.version} + true + + EXPLICIT + + +---- + +[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] +.Gradle +---- +contracts { + testMode = 'EXPLICIT' +} +---- +==== + +The following example shows how to set up a base class and Rest Assured for Web Flux: + +[source,groovy,indent=0] +---- +include::{samples_url}/producer_webflux/src/test/java/com/example/BeerRestBase.java[tags=annotations,indent=0] + + // your tests go here + + // in this config class you define all controllers and mocked services +include::{samples_url}/producer_webflux/src/test/java/com/example/BeerRestBase.java[tags=config,indent=0] + +} +---- + +[[features-context-paths]] +=== Working with Context Paths + +Spring Cloud Contract supports context paths. + +IMPORTANT: The only change needed to fully support context paths is the switch on the +*PRODUCER* side. Also, the autogenerated tests must use *EXPLICIT* mode. The consumer +side remains untouched. In order for the generated test to pass, you must use *EXPLICIT* +mode. + +==== +[source,xml,indent=0,subs="verbatim,attributes",role="primary"] +.Maven +---- + + org.springframework.cloud + spring-cloud-contract-maven-plugin + ${spring-cloud-contract.version} + true + + EXPLICIT + + +---- + +[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] +.Gradle +---- +contracts { + testMode = 'EXPLICIT' +} +---- +==== + +That way, you generate a test that *DOES NOT* use MockMvc. It means that you generate +real requests and you need to setup your generated test's base class to work on a real +socket. + +Consider the following contract: + +[source,groovy,indent=0] +---- +include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/SingleTestGeneratorSpec.groovy[tags=context_path_contract,indent=0] +---- + +The following example shows how to set up a base class and Rest Assured: + +[source,groovy,indent=0] +---- +include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/SingleTestGeneratorSpec.groovy[tags=context_path_baseclass,indent=0] +---- + +If you do it this way: + +* All of your requests in the autogenerated tests are sent to the real endpoint with your +context path included (for example, `/my-context-path/url`). +* Your contracts reflect that you have a context path. Your generated stubs also have +that information (for example, in the stubs, you have to call `/my-context-path/url`). + +[[features-rest-docs]] +=== Working with REST Docs + +https://projects.spring.io/spring-restdocs[Spring REST Docs] can be used to generate +documentation (for example in Asciidoctor format) for an HTTP API with Spring MockMvc +or `WebTestClient` or Rest Assured. At the same time that you generate documentation for your API, you can also +generate WireMock stubs by using Spring Cloud Contract WireMock. To do so, write your +normal REST Docs test cases and use `@AutoConfigureRestDocs` to have stubs be +automatically generated in the REST Docs output directory. + +[plantuml, rest-docs, png] +---- +"API Producer"->"API Producer": add Spring Cloud Contract (SCC) \nStub Runner dependency +"API Producer"->"API Producer": setup stub jar assembly +"API Producer"->"API Producer": write and setup REST Docs tests +"API Producer"->"Build": run build +"Build"->"REST Docs": generate API \ndocumentation +"REST Docs"->"SCC": generate stubs from the \nREST Docs tests +"REST Docs"->"SCC": generate contracts from the \nREST Docs tests +"Build"->"Build": assemble stubs jar with \nstubs and contracts +"Build"->"Nexus / Artifactory": upload contracts \nand stubs and the project arifact +"Build"->"API Producer": Build successful +"API Consumer"->"API Consumer": add SCC Stub Runner \ndependency +"API Consumer"->"API Consumer": write a SCC Stub Runner \nbased contract test +"SCC Stub Runner"->"Nexus / Artifactory": test asks for [API Producer] stubs +"Nexus / Artifactory"->"SCC Stub Runner": fetch the [API Producer] stubs +"SCC Stub Runner"->"SCC Stub Runner": run in memory\n HTTP server stubs +"API Consumer"->"SCC Stub Runner": send a request \nto the HTTP server stub +"SCC Stub Runner"->"API Consumer": communication is correct +---- + +The following code shows an +example using `MockMvc`: + +[source,java,indent=0] +---- +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureRestDocs(outputDir = "target/snippets") +@AutoConfigureMockMvc +public class ApplicationTests { + + @Autowired + private MockMvc mockMvc; + + @Test + public void contextLoads() throws Exception { + mockMvc.perform(get("/resource")) + .andExpect(content().string("Hello World")) + .andDo(document("resource")); + } +} +---- + +This test generates a WireMock stub at "target/snippets/stubs/resource.json". It matches +all GET requests to the "/resource" path. The same example with `WebTestClient` (used +for testing Spring WebFlux applications) would look like this: + +[source,java,indent=0] +---- +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureRestDocs(outputDir = "target/snippets") +@AutoConfigureWebTestClient +public class ApplicationTests { + + @Autowired + private WebTestClient client; + + @Test + public void contextLoads() throws Exception { + client.get().uri("/resource").exchange() + .expectBody(String.class).isEqualTo("Hello World") + .consumeWith(document("resource")); + } +} +---- + +Without any additional configuration, these tests create a stub with a request matcher +for the HTTP method and all headers except "host" and "content-length". To match the +request more precisely (for example, to match the body of a POST or PUT), we need to +explicitly create a request matcher. Doing so has two effects: + +* Creating a stub that matches only in the way you specify. +* Asserting that the request in the test case also matches the same conditions. + +The main entry point for this feature is `WireMockRestDocs.verify()`, which can be used +as a substitute for the `document()` convenience method, as shown in the following +example: + +[source,java,indent=0] + +import static org.springframework.cloud.contract.wiremock.restdocs.WireMockRestDocs.verify; + +---- +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureRestDocs(outputDir = "target/snippets") +@AutoConfigureMockMvc +public class ApplicationTests { + + @Autowired + private MockMvc mockMvc; + + @Test + public void contextLoads() throws Exception { + mockMvc.perform(post("/resource") + .content("{\"id\":\"123456\",\"message\":\"Hello World\"}")) + .andExpect(status().isOk()) + .andDo(verify().jsonPath("$.id") + .stub("resource")); + } +} +---- + +This contract specifies that any valid POST with an "id" field receives the response +defined in this test. You can chain together calls to `.jsonPath()` to add additional +matchers. If JSON Path is unfamiliar, The https://github.com/jayway/JsonPath[JayWay +documentation] can help you get up to speed. The `WebTestClient` version of this test +has a similar `verify()` static helper that you insert in the same place. + +Instead of the `jsonPath` and `contentType` convenience methods, you can also use the +WireMock APIs to verify that the request matches the created stub, as shown in the +following example: + +[source,java,indent=0] +---- + @Test + public void contextLoads() throws Exception { + mockMvc.perform(post("/resource") + .content("{\"id\":\"123456\",\"message\":\"Hello World\"}")) + .andExpect(status().isOk()) + .andDo(verify() + .wiremock(WireMock.post( + urlPathEquals("/resource")) + .withRequestBody(matchingJsonPath("$.id")) + .stub("post-resource")); + } +---- + +The WireMock API is rich. You can match headers, query parameters, and request body by +regex as well as by JSON path. These features can be used to create stubs with a wider +range of parameters. The above example generates a stub resembling the following example: + +.post-resource.json +[source,json] +---- +{ + "request" : { + "url" : "/resource", + "method" : "POST", + "bodyPatterns" : [ { + "matchesJsonPath" : "$.id" + }] + }, + "response" : { + "status" : 200, + "body" : "Hello World", + "headers" : { + "X-Application-Context" : "application:-1", + "Content-Type" : "text/plain" + } + } +} +---- + +NOTE: You can use either the `wiremock()` method or the `jsonPath()` and `contentType()` +methods to create request matchers, but you can't use both approaches. + +On the consumer side, you can make the `resource.json` generated earlier in this section +available on the classpath (by +<= 20)]', byType()) + } + } +} +---- + +The generated document (formatted in Asciidoc in this case) contains a formatted +contract. The location of this file would be `index/dsl-contract.adoc`. diff --git a/docs/src/main/asciidoc/_project-features-messaging.adoc b/docs/src/main/asciidoc/_project-features-messaging.adoc new file mode 100644 index 0000000000..e43743bb16 --- /dev/null +++ b/docs/src/main/asciidoc/_project-features-messaging.adoc @@ -0,0 +1,922 @@ +include::_attributes.adoc[] + +[[features-messaging]] +== Messaging +Spring Cloud Contract lets you verify applications that use messaging as a +means of communication. All of the integrations shown in this document work with Spring, +but you can also create one of your own and use that. + +[[contract-dsl-messaging-top-level]] +=== Messaging DSL Top-Level Elements + +The DSL for messaging looks a little bit different than the one that focuses on HTTP. The +following sections explain the differences: + +* <> +* <> +* <> +* <> + +[[contract-dsl-output-triggered-method]] +==== Output Triggered by a Method + +The output message can be triggered by calling a method (such as a `Scheduler` when a was +started and a message was sent), as shown in the following example: + +==== +[source,groovy,indent=0,subs="verbatim,attributes",role="primary"] +.groovy +---- +include::{tests_path}/samples-messaging-integration/src/test/groovy/com/example/IntegrationMessagingApplicationSpec.groovy[tags=method_trigger,indent=0] +---- + +[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] +.yml +---- +include::{verifier_core_path}/src/test/resources/yml/contract_message_method.yml[indent=0] +---- +==== + +In the previous example case, the output message is sent to `output` if a method called +`bookReturnedTriggered` is executed. On the message *publisher's* side, we generate a +test that calls that method to trigger the message. On the *consumer* side, you can use +the `some_label` to trigger the message. + +[[contract-dsl-output-triggered-message]] +==== Output Triggered by a Message + +The output message can be triggered by receiving a message, as shown in the following +example: + +==== +[source,groovy,indent=0,subs="verbatim,attributes",role="primary"] +.groovy +---- +include::{tests_path}/samples-messaging-integration/src/test/groovy/com/example/IntegrationMessagingApplicationSpec.groovy[tags=message_trigger,indent=0] +---- + +[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] +.yml +---- +include::{verifier_core_path}/src/test/resources/yml/contract_message_input_message.yml[indent=0] +---- +==== + +In the preceding example, the output message is sent to `output` if a proper message is +received on the `input` destination. On the message *publisher's* side, the engine +generates a test that sends the input message to the defined destination. On the +*consumer* side, you can either send a message to the input destination or use a label +(`some_label` in the example) to trigger the message. + +[[contract-dsl-consumer-producer]] +==== Consumer/Producer + +IMPORTANT: This section is valid only for Groovy DSL. + +In HTTP, you have a notion of `client`/`stub and `server`/`test` notation. You can also +use those paradigms in messaging. In addition, Spring Cloud Contract Verifier also +provides the `consumer` and `producer` methods, as presented in the following example +(note that you can use either `$` or `value` methods to provide `consumer` and `producer` +parts): + +[source,groovy] +---- +include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=consumer_producer] +---- + +[[contract-dsl-messaging-common]] +==== Common + +In the `input` or `outputMessage` section you can call `assertThat` with the name +of a `method` (e.g. `assertThatMessageIsOnTheQueue()`) that you have defined in the +base class or in a static import. Spring Cloud Contract will execute that method +in the generated test. + +[[features-messaging-integrations]] +=== Integrations + +You can use one of the following four integration configurations: + +* Apache Camel +* Spring Integration +* Spring Cloud Stream +* Spring AMQP + +Since we use Spring Boot, if you have added one of these libraries to the classpath, all +the messaging configuration is automatically set up. + +IMPORTANT: Remember to put `@AutoConfigureMessageVerifier` on the base class of your +generated tests. Otherwise, messaging part of Spring Cloud Contract does not +work. + +IMPORTANT: If you want to use Spring Cloud Stream, remember to add a dependency on +`org.springframework.cloud:spring-cloud-stream-test-support`, as shown below + +===== +[source,xml,indent=0,subs="verbatim,attributes",role="primary"] +.Maven +---- + + org.springframework.cloud + spring-cloud-stream-test-support + test + +---- + +[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] +.Gradle +---- +testCompile "org.springframework.cloud:spring-cloud-stream-test-support" +---- +===== + +[[features-messaging-manual]] +==== Manual Integration Testing + +The main interface used by the tests is +`org.springframework.cloud.contract.verifier.messaging.MessageVerifier`. +It defines how to send and receive messages. You can create your own implementation to +achieve the same goal. + +In a test, you can inject a `ContractVerifierMessageExchange` to send and receive +messages that follow the contract. Then add `@AutoConfigureMessageVerifier` to your test. +Here's an example: + +[source,java,indent=0] +---- +@RunWith(SpringTestRunner.class) +@SpringBootTest +@AutoConfigureMessageVerifier +public static class MessagingContractTests { + + @Autowired + private MessageVerifier verifier; + ... +} +---- + +NOTE: If your tests require stubs as well, then `@AutoConfigureStubRunner` includes the +messaging configuration, so you only need the one annotation. + +[[features-messaging-test-generation]] +=== Messaging Producer Side Test Generation + +Having the `input` or `outputMessage` sections in your DSL results in creation of tests +on the publisher's side. By default, JUnit 4 tests are created. However, there is also a +possibility to create JUnit 5, TestNG or Spock tests. + +There are 3 main scenarios that we should take into consideration: + +* Scenario 1: There is no input message that produces an output message. The output +message is triggered by a component inside the application (for example, scheduler). +* Scenario 2: The input message triggers an output message. +* Scenario 3: The input message is consumed and there is no output message. + +IMPORTANT: The destination passed to `messageFrom` or `sentTo` can have different +meanings for different messaging implementations. For *Stream* and *Integration* it is +first resolved as a `destination` of a channel. Then, if there is no such `destination` +it is resolved as a channel name. For *Camel*, that's a certain component (for example, +`jms`). + +[[features-messaging-scenario1]] +==== Scenario 1: No Input Message + +For the given contract: + +===== +[source,groovy,indent=0,subs="verbatim,attributes",role="primary"] +.groovy +---- +include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_method_dsl] +---- + +[source,yml,indent=0,subs="verbatim,attributes",role="secondary"] +.yml +[source,yml,indent=0] +---- +include::{verifier_core_path}/src/test/resources/yml/contract_message_scenario1.yml[indent=0] +---- +===== + +The following test would be created + +==== +[source,java,indent=0,subs="verbatim,attributes",role="primary"] +.JUnit +---- +include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_method_junit_test] +---- + +[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] +.Spock +---- +include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_method_test] +---- +==== + +[[features-messaging-scenario2]] +==== Scenario 2: Output Triggered by Input + +For the given contract: + +===== +[source,groovy,indent=0,subs="verbatim,attributes",role="primary"] +.groovy +---- +include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_message_dsl] +---- + +[source,yml,indent=0,subs="verbatim,attributes",role="secondary"] +.yml +---- +include::{verifier_core_path}/src/test/resources/yml/contract_message_scenario2.yml[indent=0] +---- +===== + +The following test would be created + +==== +[source,java,indent=0,subs="verbatim,attributes",role="primary"] +.JUnit +---- +include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_message_junit] +---- + +[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] +.Spock +---- +include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_message_spock] +---- +==== + +[[features-messaging-scenario3]] +==== Scenario 3: No Output Message + +For the given contract: + +==== +[source,groovy,indent=0,subs="verbatim,attributes",role="primary"] +.groovy +---- +include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_no_output_dsl] +---- + +[source,yml,indent=0,subs="verbatim,attributes",role="secondary"] +.yml +---- +include::{verifier_core_path}/src/test/resources/yml/contract_message_scenario3.yml[indent=0] +---- +==== + +The following test would be created + +==== +[source,java,indent=0,subs="verbatim,attributes",role="primary"] +.JUnit +---- +include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_no_output_junit] +---- + +[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] +.Spock +---- +include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_no_output_spock] +---- +==== + +[[features-messaging-consumer]] +=== Consumer Stub Generation + +Unlike the HTTP part, in messaging, we need to publish the contract definition inside the JAR with +a stub. Then it is parsed on the consumer side and proper stubbed routes are created. + +IMPORTANT: If you have multiple frameworks on the classpath Stub Runner will need to +define which one should be used. Let's assume that you have both AMQP, Spring Cloud Stream and Spring Integration +on the classpath. Then you need to set `stubrunner.stream.enabled=false` and `stubrunner.integration.enabled=false`. +That way the only remaining framework is Spring AMQP. + +[[features-messaging-stub-triggering]] +==== Stub triggering + +To trigger a message, use the `StubTrigger` interface: + +[source,groovy] +---- +include::{stubrunner_core_path}/src/main/java/org/springframework/cloud/contract/stubrunner/StubTrigger.java[lines=16..-1] +---- + +For convenience, the `StubFinder` interface extends `StubTrigger`, so you only need one +or the other in your tests. + +`StubTrigger` gives you the following options to trigger a message: + +* <> +* <> +* <> +* <> + +[[features-messaging-trigger-label]] +==== Trigger by Label + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_trigger,indent=0] +---- +[[features-messaging-trigger-group-artifact-ids]] +==== Trigger by Group and Artifact Ids + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=trigger_group_artifact,indent=0] +---- + +[[features-messaging-trigger-artifact-ids]] +==== Trigger by Artifact Ids + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=trigger_artifact,indent=0] +---- + +[[features-messaging-trigger-all-messages]] +==== Trigger All Messages + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=trigger_all,indent=0] +---- + +:input_name: jms:input +:output_name: jms:output + +[[features-messaging-stub-runner-camel]] +=== Messaging Consumer Side With Apache Camel + +Spring Cloud Contract Stub Runner's messaging module gives you an easy way to integrate with Apache Camel. +For the provided artifacts it will automatically download the stubs and register the required +routes. + +[[features-messaging-stub-runner-camel-adding]] +==== Adding it to the project + +It's enough to have both Apache Camel and Spring Cloud Contract Stub Runner on classpath. +Remember to annotate your test class with `@AutoConfigureStubRunner`. + +[[features-messaging-stub-runner-camel-disabling]] +==== Disabling the functionality + +If you need to disable this functionality just pass `stubrunner.camel.enabled=false` property. + +[[features-messaging-stub-runner-camel-example]] +==== Examples + +Let us assume that we have the following Maven repository with a deployed stubs for the +`camelService` application. + +[source,bash,indent=0] +---- +└── .m2 + └── repository + └── io + └── codearte + └── accurest + └── stubs + └── camelService + ├── 0.0.1-SNAPSHOT + │   ├── camelService-0.0.1-SNAPSHOT.pom + │   ├── camelService-0.0.1-SNAPSHOT-stubs.jar + │   └── maven-metadata-local.xml + └── maven-metadata-local.xml +---- + +And the stubs contain the following structure: + +[source,bash,indent=0] +---- +├── META-INF +│   └── MANIFEST.MF +└── repository + ├── accurest + │   ├── bookDeleted.groovy + │   ├── bookReturned1.groovy + │   └── bookReturned2.groovy + └── mappings +---- + +Let's consider the following contracts (let' number it with *1*): + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-camel/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=sample_dsl,indent=0] +---- + +and number *2* + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-camel/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=sample_dsl_2,indent=0] +---- + +[[features-messaging-stub-runner-camel-scenario1]] +===== Scenario 1 (no input message) + +So as to trigger a message via the `return_book_1` label we'll use the `StubTigger` interface as follows + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-camel/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=client_trigger,indent=0] +---- + +Next we'll want to listen to the output of the message sent to `{output_name}` + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-camel/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=client_trigger_receive,indent=0] +---- + +And the received message would pass the following assertions + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-camel/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=client_trigger_message,indent=0] +---- +[[features-messaging-stub-runner-camel-scenario2]] +===== Scenario 2 (output triggered by input) + +Since the route is set for you it's enough to just send a message to the `{output_name}` destination. + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-camel/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=client_send,indent=0] +---- + +Next we'll want to listen to the output of the message sent to `{output_name}` + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-camel/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=client_receive,indent=0] +---- + +And the received message would pass the following assertions + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-camel/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=client_receive_message,indent=0] +---- + +[[features-messaging-stub-runner-camel-scenario3]] +===== Scenario 3 (input with no output) + +Since the route is set for you it's enough to just send a message to the `{output_name}` destination. + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-camel/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=trigger_no_output,indent=0] +---- + +:input_name: input +:output_name: output + +[[features-messaging-stub-runner-integration]] +=== Messaging Consumer Side With Spring Integration + +Spring Cloud Contract Stub Runner's messaging module gives you an easy way to +integrate with Spring Integration. For the provided artifacts, it automatically downloads +the stubs and registers the required routes. + +[[features-messaging-stub-runner-integration-adding]] +==== Adding the Runner to the Project + +You can have both Spring Integration and Spring Cloud Contract Stub Runner on the +classpath. Remember to annotate your test class with `@AutoConfigureStubRunner`. + +[[features-messaging-stub-runner-integration-disabling]] +==== Disabling the functionality + +If you need to disable this functionality, set the +`stubrunner.integration.enabled=false` property. + +[[features-messaging-stub-runner-integration-example]] +==== Examples + +Assume that you have the following Maven repository with deployed stubs for the +`integrationService` application: + +[source,bash,indent=0] +---- +└── .m2 + └── repository + └── io + └── codearte + └── accurest + └── stubs + └── integrationService + ├── 0.0.1-SNAPSHOT + │   ├── integrationService-0.0.1-SNAPSHOT.pom + │   ├── integrationService-0.0.1-SNAPSHOT-stubs.jar + │   └── maven-metadata-local.xml + └── maven-metadata-local.xml +---- + +Further assume the stubs contain the following structure: + +[source,bash,indent=0] +---- +├── META-INF +│   └── MANIFEST.MF +└── repository + ├── accurest + │   ├── bookDeleted.groovy + │   ├── bookReturned1.groovy + │   └── bookReturned2.groovy + └── mappings +---- + +Consider the following contracts (numbered *1*): + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=sample_dsl,indent=0] +---- + +Now consider *2*: + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=sample_dsl_2,indent=0] +---- + +and the following Spring Integration Route: + +[source,xml] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/resources/integration-context.xml[lines=1;18..-1] +---- + +These examples lend themselves to three scenarios: + +* <> +* <> +* <> + +[[features-messaging-stub-runner-integration-scenario1]] +===== Scenario 1 (no input message) + +To trigger a message via the `return_book_1` label, use the `StubTigger` interface, as +follows: + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_trigger,indent=0] +---- + +To listen to the output of the message sent to `{output_name}`: + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_trigger_receive,indent=0] +---- + +The received message would pass the following assertions: + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_trigger_message,indent=0] +---- + +[[features-messaging-stub-runner-integration-scenario2]] +===== Scenario 2 (output triggered by input) + +Since the route is set for you, you can send a message to the `{output_name}` +destination: + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_send,indent=0] +---- + +To listen to the output of the message sent to `{output_name}`: + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_receive,indent=0] +---- + +The received message passes the following assertions: + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_receive_message,indent=0] +---- + +[[features-messaging-stub-runner-integration-scenario3]] +===== Scenario 3 (input with no output) + +Since the route is set for you, you can send a message to the `{input_name}` destination: + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=trigger_no_output,indent=0] +---- + +[[features-messaging-stub-runner-stream]] +=== Messaging Consumer Side With Spring Cloud Stream + +Spring Cloud Contract Stub Runner's messaging module gives you an easy way to +integrate with Spring Stream. For the provided artifacts, it automatically downloads the +stubs and registers the required routes. + +WARNING: If Stub Runner's integration with Stream the `messageFrom` or `sentTo` Strings +are resolved first as a `destination` of a channel and no such `destination` exists, the +destination is resolved as a channel name. + +IMPORTANT: If you want to use Spring Cloud Stream remember, to add a dependency on +`org.springframework.cloud:spring-cloud-stream-test-support`. + +==== +[source,xml,indent=0,subs="verbatim,attributes",role="primary"] +.Maven +---- + + org.springframework.cloud + spring-cloud-stream-test-support + test + +---- + +[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] +.Gradle +---- +testCompile "org.springframework.cloud:spring-cloud-stream-test-support" +---- +==== + +[[features-messaging-stub-runner-stream-adding]] +==== Adding the Runner to the Project + +You can have both Spring Cloud Stream and Spring Cloud Contract Stub Runner on the +classpath. Remember to annotate your test class with `@AutoConfigureStubRunner`. + +[[features-messaging-stub-runner-stream-disabling]] +==== Disabling the functionality + +If you need to disable this functionality, set the `stubrunner.stream.enabled=false` +property. + +[[features-messaging-stub-runner-stream-example]] +==== Examples + +Assume that you have the following Maven repository with a deployed stubs for the +`streamService` application: + +[source,bash,indent=0] +---- +└── .m2 + └── repository + └── io + └── codearte + └── accurest + └── stubs + └── streamService + ├── 0.0.1-SNAPSHOT + │   ├── streamService-0.0.1-SNAPSHOT.pom + │   ├── streamService-0.0.1-SNAPSHOT-stubs.jar + │   └── maven-metadata-local.xml + └── maven-metadata-local.xml +---- + +Further assume the stubs contain the following structure: + +[source,bash,indent=0] +---- +├── META-INF +│   └── MANIFEST.MF +└── repository + ├── accurest + │   ├── bookDeleted.groovy + │   ├── bookReturned1.groovy + │   └── bookReturned2.groovy + └── mappings +---- + +Consider the following contracts (numbered *1*): + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=sample_dsl,indent=0] +---- + +Now consider *2*: + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=sample_dsl_2,indent=0] +---- + +Now consider the following Spring configuration: + +[source,yaml] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/resources/application.yml[] +---- + +These examples lend themselves to three scenarios: + +* <> +* <> +* <> + +[[features-messaging-stub-runner-stream-scenario1]] +===== Scenario 1 (no input message) + +To trigger a message via the `return_book_1` label, use the `StubTrigger` interface as +follows: + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_trigger,indent=0] +---- + +To listen to the output of the message sent to a channel whose `destination` is +`returnBook`: + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_trigger_receive,indent=0] +---- + +The received message passes the following assertions: + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_trigger_message,indent=0] +---- + +[[features-messaging-stub-runner-stream-scenario2]] +===== Scenario 2 (output triggered by input) + +Since the route is set for you, you can send a message to the `bookStorage` +`destination`: + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_send,indent=0] +---- + +To listen to the output of the message sent to `returnBook`: + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_receive,indent=0] +---- + +The received message passes the following assertions: + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_receive_message,indent=0] +---- + +[[features-messaging-stub-runner-stream-scenario3]] +===== Scenario 3 (input with no output) + +Since the route is set for you, you can send a message to the `{output_name}` +destination: + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=trigger_no_output,indent=0] +---- + +[[features-messaging-stub-runner-amqp]] +=== Messaging Consumer Side With Spring AMQP + +Spring Cloud Contract Stub Runner's messaging module provides an easy way to +integrate with Spring AMQP's Rabbit Template. For the provided artifacts, it +automatically downloads the stubs and registers the required routes. + +The integration tries to work standalone (that is, without interaction with a running +RabbitMQ message broker). It expects a `RabbitTemplate` on the application context and +uses it as a spring boot test named `@SpyBean`. As a result, it can use the mockito spy +functionality to verify and inspect messages sent by the application. + +On the message consumer side, the stub runner considers all `@RabbitListener` annotated +endpoints and all `SimpleMessageListenerContainer` objects on the application context. + +As messages are usually sent to exchanges in AMQP, the message contract contains the +exchange name as the destination. Message listeners on the other side are bound to +queues. Bindings connect an exchange to a queue. If message contracts are triggered, the +Spring AMQP stub runner integration looks for bindings on the application context that +match this exchange. Then it collects the queues from the Spring exchanges and tries to +find message listeners bound to these queues. The message is triggered for all matching +message listeners. + +If you need to work with routing keys, it's enough to pass them via the `amqp_receivedRoutingKey` +messaging header. + +[[features-messaging-stub-runner-amqp-adding]] +==== Adding the Runner to the Project + +You can have both Spring AMQP and Spring Cloud Contract Stub Runner on the classpath and +set the property `stubrunner.amqp.enabled=true`. Remember to annotate your test class +with `@AutoConfigureStubRunner`. + +IMPORTANT: If you already have Stream and Integration on the classpath, you need +to disable them explicitly by setting the `stubrunner.stream.enabled=false` and +`stubrunner.integration.enabled=false` properties. + +[[features-messaging-stub-runner-amqp-example]] +==== Examples + +Assume that you have the following Maven repository with a deployed stubs for the +`spring-cloud-contract-amqp-test` application. + +[source,bash,indent=0] +---- +└── .m2 + └── repository + └── com + └── example + └── spring-cloud-contract-amqp-test + ├── 0.4.0-SNAPSHOT + │   ├── spring-cloud-contract-amqp-test-0.4.0-SNAPSHOT.pom + │   ├── spring-cloud-contract-amqp-test-0.4.0-SNAPSHOT-stubs.jar + │   └── maven-metadata-local.xml + └── maven-metadata-local.xml +---- + +Further assume that the stubs contain the following structure: + +[source,bash,indent=0] +---- +├── META-INF +│   └── MANIFEST.MF +└── contracts + └── shouldProduceValidPersonData.groovy +---- + +Consider the following contract: + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-amqp/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpStubRunnerSpec.groovy[tags=amqp_contract,indent=0] +---- + +Now consider the following Spring configuration: + +[source,yaml] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-amqp/src/test/resources/application.yml[] +---- + +[[features-messaging-stub-runner-amqp-triggering]] +===== Triggering the message + +To trigger a message using the contract above, use the `StubTrigger` interface as +follows: + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-amqp/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpStubRunnerSpec.groovy[tags=client_trigger,indent=0] +---- + +The message has a destination of `contract-test.exchange`, so the Spring AMQP stub runner +integration looks for bindings related to this exchange. + +[source,java] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpMessagingApplication.java[tags=amqp_binding,indent=0] +---- + +The binding definition binds the queue `test.queue`. As a result, the following listener +definition is matched and invoked with the contract message. + +[source,java] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpMessagingApplication.java[tags=amqp_listener,indent=0] +---- + +Also, the following annotated listener matches and is invoked: +[source,java] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/MessageSubscriberRabbitListener.java[tags=amqp_annotated_listener,indent=0] +---- + +NOTE: The message is directly handed over to the `onMessage` method of the +`MessageListener` associated with the matching `SimpleMessageListenerContainer`. + +[[features-messaging-stub-runner-amqp-configuration]] +===== Spring AMQP Test Configuration + +In order to avoid Spring AMQP trying to connect to a running broker during our tests +configure a mock `ConnectionFactory`. + +To disable the mocked ConnectionFactory, set the following property: +`stubrunner.amqp.mockConnection=false` + +[source,yaml] +---- +stubrunner: + amqp: + mockConnection: false +---- \ No newline at end of file diff --git a/spring-cloud-contract-stub-runner/README.adoc b/docs/src/main/asciidoc/_project-features-stubrunner.adoc similarity index 70% rename from spring-cloud-contract-stub-runner/README.adoc rename to docs/src/main/asciidoc/_project-features-stubrunner.adoc index e973a7caa7..5d64dc5bef 100644 --- a/spring-cloud-contract-stub-runner/README.adoc +++ b/docs/src/main/asciidoc/_project-features-stubrunner.adoc @@ -1,14 +1,74 @@ -:branch: master -:samples_branch: 2.2.x +[[features-stub-runner-features-stub-runner]] +== Spring Cloud Contract Stub Runner +One of the issues that you might encounter while using Spring Cloud Contract Verifier is +passing the generated WireMock JSON stubs from the server side to the client side (or to +various clients). The same takes place in terms of client-side generation for messaging. + +Copying the JSON files and setting the client side for messaging manually is out of the +question. That is why we introduced Spring Cloud Contract Stub Runner. It can +automatically download and run the stubs for you. + +[[features-stub-runner-features-stub-runner-snapshot-versions]] +=== Snapshot versions + +Add the additional snapshot repository to your `build.gradle` file to use snapshot +versions, which are automatically uploaded after every successful build: + +==== +[source,xml,indent=0,subs="verbatim,attributes",role="primary"] +.Maven +---- +include::{standalone_samples_path}/http-server/pom.xml[tags=repos,indent=0] +---- + +[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] +.Gradle +---- +include::{standalone_samples_path}/http-server/build.gradle[tags=repos,indent=0] +---- +==== + +[[features-stub-runner-publishing-stubs-as-jars]] +=== Publishing Stubs as JARs + +The easiest approach would be to centralize the way stubs are kept. For example, you can +keep them as jars in a Maven repository. + +TIP: For both Maven and Gradle, the setup comes ready to work. However, you can customize +it if you want to. + +==== +[source,xml,indent=0,subs="verbatim,attributes",role="primary"] +.Maven +---- + +include::{samples_url}/producer_with_restdocs/pom.xml[tags=skip_jar,indent=0] + + +include::{samples_url}/producer_with_restdocs/pom.xml[tags=assembly,indent=0] + + +include::{samples_url}/producer_with_restdocs/src/assembly/stub.xml[indent=0] +---- + +[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] +.Gradle +---- +include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/resources/functionalTest/scenarioProject/build.gradle[tags=jar_setup,indent=0] +---- +==== + +[[features-stub-runner-core]] === Stub Runner Core -Runs stubs for service collaborators. Treating stubs as contracts of services allows to use stub-runner as an implementation of +Runs stubs for service collaborators. Treating stubs as contracts of services allows to use stub-runner as an implementation of https://martinfowler.com/articles/consumerDrivenContracts.html[Consumer Driven Contracts]. Stub Runner allows you to automatically download the stubs of the provided dependencies (or pick those from the classpath), start WireMock servers for them and feed them with proper stub definitions. For messaging, special stub routes are defined. +[[features-stub-runner-retrieving]] ==== Retrieving stubs You can pick the following options of acquiring stubs @@ -17,8 +77,10 @@ You can pick the following options of acquiring stubs - Classpath scanning solution that searches classpath via pattern to retrieve stubs - Write your own implementation of the `org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder` for full customization +// TODO: Fix link The latter example is described in the <> section. +[[features-stub-runner-downloading-stub]] ===== Stub downloading You can control the stub downloading via the `stubsMode` switch. It picks value from the @@ -35,6 +97,7 @@ Example: @AutoConfigureStubRunner(repositoryRoot="https://foo.bar", ids = "com.example:beer-api-producer:+:stubs:8095", stubsMode = StubRunnerProperties.StubsMode.LOCAL) ---- +[[features-stub-runner-classpath-scanning]] ===== Classpath scanning If you set the `stubsMode` property to `StubRunnerProperties.StubsMode.CLASSPATH` @@ -51,6 +114,7 @@ Let's look at the following example: If you've added the dependencies to your classpath +==== [source,xml,indent=0,subs="verbatim,attributes",role="primary"] .Maven ---- @@ -92,6 +156,7 @@ testCompile("com.example.foo:bar:1.0.0:superstubs") { transitive = false } ---- +==== Then the following locations on your classpath will get scanned. For `com.example:beer-api-producer-restdocs` @@ -146,6 +211,7 @@ structure in your stubs jar. By maintaining this structure classpath gets scanned and you can profit from the messaging / HTTP stubs without the need to download artifacts. +[[features-stub-runner-configuring-http-server-stubs]] ===== Configuring HTTP Server Stubs Stub Runner has a notion of a `HttpServerStub` that abstracts the underlaying @@ -165,57 +231,22 @@ case might be starting WireMock for the given artifact id, on an HTTPs port. Exa .WireMockHttpServerStubConfigurer implementation [source,groovy,indent=0] ---- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/StubRunnerConfigurationSpec.groovy[tags=wireMockHttpServerStubConfigurer] +include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/StubRunnerConfigurationSpec.groovy[tags=wireMockHttpServerStubConfigurer] ---- You can then reuse it via the annotation [source,groovy,indent=0] ---- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/StubRunnerConfigurationSpec.groovy[tags=annotation] +include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/StubRunnerConfigurationSpec.groovy[tags=annotation] ---- Whenever an https port is found, it will take precedence over the http one. +[[features-stub-runner-running-stubs]] ==== Running stubs -===== Running using main app - -You can set the following options to the main class: - -[source,groovy,indent=0] ----- --c, --classifier Suffix for the jar containing stubs (e. - g. 'stubs' if the stub jar would - have a 'stubs' classifier for stubs: - foobar-stubs ). Defaults to 'stubs' - (default: stubs) ---maxPort, --maxp Maximum port value to be assigned to - the WireMock instance. Defaults to - 15000 (default: 15000) ---minPort, --minp Minimum port value to be assigned to - the WireMock instance. Defaults to - 10000 (default: 10000) --p, --password Password to user when connecting to - repository ---phost, --proxyHost Proxy host to use for repository - requests ---pport, --proxyPort [Integer] Proxy port to use for repository - requests --r, --root Location of a Jar containing server - where you keep your stubs (e.g. http: - //nexus. - net/content/repositories/repository) --s, --stubs Comma separated list of Ivy - representation of jars with stubs. - Eg. groupid:artifactid1,groupid2: - artifactid2:classifier ---sm, --stubsMode Stubs mode to be used. Acceptable values - [CLASSPATH, LOCAL, REMOTE] --u, --username Username to user when connecting to - repository ----- - +[[features-stub-runner-http-stubs]] ===== HTTP Stubs Stubs are defined in JSON documents, whose syntax is defined in http://wiremock.org/stubbing.html[WireMock documentation] @@ -239,6 +270,7 @@ Example: } ---- +[[features-stub-runner-viewing]] ===== Viewing registered mappings Every stubbed collaborator exposes list of defined mappings under `__/admin/` endpoint. @@ -294,17 +326,19 @@ mappings available for the given server: ] ---- +[[features-stub-runner-messaging]] ===== Messaging Stubs Depending on the provided Stub Runner dependency and the DSL the messaging routes are automatically set up. +[[features-stub-runner-junit]] === Stub Runner JUnit Rule and Stub Runner JUnit5 Extension Stub Runner comes with a JUnit rule thanks to which you can very easily download and run stubs for given group and artifact id: [source,java,indent=0] ---- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleJUnitTest.java[tags=classrule] +include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleJUnitTest.java[tags=classrule] ---- There's also a `StubRunnerExtension` available for JUnit 5. `StubRunnerRule` and `StubRunnerExtension` work in a very @@ -317,74 +351,79 @@ similar fashion. After the rule/ extension is executed, Stub Runner connects to - feed the WireMock server with all JSON files that are valid WireMock definitions - can also send messages (remember to pass an implementation of `MessageVerifier` interface) -Stub Runner uses https://wiki.eclipse.org/Aether[Eclipse Aether] mechanism to download the Maven dependencies. +Stub Runner uses https://wiki.eclipse.org/Aether[Eclipse Aether] mechanism to download the Maven dependencies. Check their https://wiki.eclipse.org/Aether[docs] for more information. Since the `StubRunnerRule` and `StubRunnerExtension` implement the `StubFinder` they allow you to find the started stubs: [source,groovy,indent=0] ---- -include::src/main/java/org/springframework/cloud/contract/stubrunner/StubFinder.java[lines=16..-1] +include::{stubrunner_core_path}/src/main/java/org/springframework/cloud/contract/stubrunner/StubFinder.java[lines=16..-1] ---- -Example of usage in Spock tests: -[source,groovy,indent=0] +==== +[source,groovy,indent=0,subs="verbatim,attributes",role="primary"] +.spock ---- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleSpec.groovy[tags=classrule] +include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleSpec.groovy[tags=classrule] ---- -Example of usage in JUnit tests: - -[source,java,indent=0] +[source,java,indent=0,subs="verbatim,attributes",role="secondary"] +.junit 4 ---- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleJUnitTest.java[tags=test] +include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleJUnitTest.java[tags=test] ---- -JUnit 5 Extension example: - -[source,java,indent=0] +[source,java,indent=0,subs="verbatim,attributes",role="secondary"] +.junit 5 ---- -include::src/test/java/org/springframework/cloud/contract/stubrunner/junit/StubRunnerJUnit5ExtensionTests.java[tags=extension] +include::{stubrunner_core_path}/src/test/java/org/springframework/cloud/contract/stubrunner/junit/StubRunnerJUnit5ExtensionTests.java[tags=extension] ---- +==== +//TODO: Fix link Check the *Common properties for JUnit and Spring* for more information on how to apply global configuration of Stub Runner. IMPORTANT: To use the JUnit rule or JUnit 5 extension together with messaging, you have to provide an implementation of the `MessageVerifier` interface to the rule builder (e.g. `rule.messageVerifier(new MyMessageVerifier())`). If you don't do this, then whenever you try to send a message an exception will be thrown. +[[features-stub-runner-rule-maven-settings]] ==== Maven settings The stub downloader honors Maven settings for a different local repository folder. Authentication details for repositories and profiles are currently not taken into account, so you need to specify it using the properties mentioned above. +[[features-stub-runner-rule-fixed-ports]] ==== Providing fixed ports You can also run your stubs on fixed ports. You can do it in two different ways. One is to pass it in the properties, and the other via fluent API of JUnit rule. +[[features-stub-runner-rule-fluent-api]] ==== Fluent API When using the `StubRunnerRule` or `StubRunnerExtension` you can add a stub to download and then pass the port for the last downloaded stub. [source,java,indent=0] ---- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleCustomPortJUnitTest.java[tags=classrule_with_port] +include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleCustomPortJUnitTest.java[tags=classrule_with_port] ---- You can see that for this example the following test is valid: [source,java,indent=0] ---- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleCustomPortJUnitTest.java[tags=test_with_port] +include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleCustomPortJUnitTest.java[tags=test_with_port] ---- +[[features-stub-runner-rule-spring]] ==== Stub Runner with Spring Sets up Spring configuration of the Stub Runner project. -By providing a list of stubs inside your configuration file the Stub Runner automatically downloads +By providing a list of stubs inside your configuration file the Stub Runner automatically downloads and registers in WireMock the selected stubs. If you want to find the URL of your stubbed dependency you can autowire the `StubFinder` interface and use @@ -392,14 +431,14 @@ its methods as presented below: [source,groovy,indent=0] ---- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/StubRunnerConfigurationSpec.groovy[tags=test] +include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/StubRunnerConfigurationSpec.groovy[tags=test] ---- for the following configuration file: [source,yml,indent=0] ---- -include::src/test/resources/application-test.yml[tags=test] +include::{stubrunner_core_path}/src/test/resources/application-test.yml[tags=test] ---- Instead of using the properties you can also use the properties inside the `@AutoConfigureStubRunner`. @@ -407,7 +446,7 @@ Below you can find an example of achieving the same result by setting values on [source,groovy,indent=0] ---- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerSpringCloudAutoConfigurationSpec.groovy[tags=autoconfigure] +include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerSpringCloudAutoConfigurationSpec.groovy[tags=autoconfigure] ---- Stub Runner Spring registers environment variables in the following manner @@ -433,6 +472,7 @@ int fooPort; int barPort; ---- +[[features-stub-runner-cloud]] === Stub Runner Spring Cloud Stub Runner can integrate with Spring Cloud. @@ -442,6 +482,7 @@ For real life examples you can check the - https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/producer[producer app sample] - https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/consumer_with_discovery[consumer app sample] +[[features-stub-runner-cloud-stubbing-discovery]] ==== Stubbing Service Discovery The most important feature of `Stub Runner Spring Cloud` is the fact that it's stubbing @@ -457,16 +498,17 @@ For example this test will pass [source,groovy,indent=0] ---- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerSpringCloudAutoConfigurationSpec.groovy[tags=test] +include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerSpringCloudAutoConfigurationSpec.groovy[tags=test] ---- for the following configuration file [source,yml,indent=0] ---- -include::src/test/resources/application.yml[tags=ids] +include::{stubrunner_core_path}/src/test/resources/application.yml[tags=ids] ---- +[[features-stub-runner-cloud-stubbing-profiles]] ===== Test profiles and service discovery In your integration tests you typically don't want to call neither a discovery service (e.g. Eureka) @@ -485,6 +527,7 @@ via a static block like presented below (example for Eureka) } ---- +[[features-stub-runner-additional-config]] ==== Additional Configuration You can match the artifactId of the stub with the name of your app by using the `stubrunner.idsToServiceIds:` map. @@ -503,6 +546,7 @@ via the following system properties or environment variables - `org.apache.maven.user-settings` - path to custom maven user settings location - `org.apache.maven.global-settings` - path to maven global settings location +[[features-stub-runner-boot]] === Stub Runner Boot Application Spring Cloud Contract Stub Runner Boot is a Spring Boot application that exposes REST endpoints to @@ -512,8 +556,10 @@ One of the use-cases is to run some smoke (end to end) tests on a deployed appli You can check out the https://github.com/spring-cloud/spring-cloud-pipelines[Spring Cloud Pipelines] project for more information. +[[features-stub-runner-boot-how]] ==== How to use it? +[[features-stub-runner-boot-server]] ===== Stub Runner Server Just add the @@ -527,6 +573,7 @@ Annotate a class with `@EnableStubRunnerServer`, build a fat-jar and you're read For the properties check the *Stub Runner Spring* section. +[[features-stub-runner-boot-how-fat-jar]] ===== Stub Runner Server Fat Jar You can download a standalone JAR from Maven (e.g. for version 2.0.1.RELEASE), as follows: @@ -537,6 +584,7 @@ $ wget -O stub-runner.jar 'https://search.maven.org/remotecontent?filepath=org/s $ java -jar stub-runner.jar --stubrunner.ids=... --stubrunner.repositoryRoot=... ---- +[[features-stub-runner-boot-how-cli]] ===== Spring Cloud CLI Starting from `1.4.0.RELEASE` version of the https://cloud.spring.io/spring-cloud-cli[Spring Cloud CLI] @@ -558,13 +606,16 @@ stubrunner: and then just call `spring cloud stubrunner` from your terminal window to start the Stub Runner server. It will be available at port `8750`. +[[features-stub-runner-boot-endpoints]] ==== Endpoints +[[features-stub-runner-boot-endpoints-http]] ===== HTTP - GET `/stubs` - returns a list of all running stubs in `ivy:integer` notation - GET `/stubs/{ivy}` - returns a port for the given `ivy` notation (when calling the endpoint `ivy` can also be `artifactId` only) +[[features-stub-runner-boot-endpoints-messaging]] ===== Messaging For Messaging @@ -573,13 +624,15 @@ For Messaging - POST `/triggers/{label}` - executes a trigger with `label` - POST `/triggers/{ivy}/{label}` - executes a trigger with `label` for the given `ivy` notation (when calling the endpoint `ivy` can also be `artifactId` only) +[[features-stub-runner-boot-endpoints-example]] ==== Example [source,groovy,indent=0] ---- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/server/StubRunnerBootSpec.groovy[tags=boot_usage] +include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/server/StubRunnerBootSpec.groovy[tags=boot_usage] ---- +[[features-stub-runner-boot-service-discovery]] ==== Stub Runner Boot with Service Discovery One of the possibilities of using Stub Runner Boot is to use it as a feed of stubs for "smoke-tests". What does it mean? @@ -597,7 +650,7 @@ The problem with this approach is such that if you're doing microservices most l [source,java,indent=0] ---- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/serverexamples/StubRunnerBootEurekaExample.java[tags=stubrunnereureka] +include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/serverexamples/StubRunnerBootEurekaExample.java[tags=stubrunnereureka] ---- As you can see we want to start a Stub Runner Boot server `@EnableStubRunnerServer`, enable Eureka client `@EnableEurekaClient` @@ -609,7 +662,7 @@ Now let's assume that we want to start this application so that the stubs get au [source,bash,indent=0] ---- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/serverexamples/StubRunnerBootEurekaExample.java[tags=stubrunnereureka_args] +include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/serverexamples/StubRunnerBootEurekaExample.java[tags=stubrunnereureka_args] ---- That way your deployed application can send requests to started WireMock servers via the service @@ -617,7 +670,8 @@ discovery. Most likely points 1-3 could be set by default in `application.yml` c likely to change. That way you can provide only the list of stubs to download whenever you start the Stub Runner Boot. -=== Stubs Per Consumer +[[features-stub-runner-stubs-per-consumer]] +=== Consumer-Driven Contracts: Stubs Per Consumer There are cases in which 2 consumers of the same endpoint want to have 2 different responses. @@ -687,7 +741,7 @@ Or set the test as follows: [source,groovy] ---- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerStubsPerConsumerSpec.groovy[tags=test] +include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerStubsPerConsumerSpec.groovy[tags=test] ... } ---- @@ -699,7 +753,7 @@ Or set the consumer name explicitly [source,groovy] ---- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerStubsPerConsumerWithConsumerNameSpec.groovy[tags=test] +include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerStubsPerConsumerWithConsumerNameSpec.groovy[tags=test] ... } ---- @@ -708,4 +762,63 @@ Then only the stubs registered under a path that contains the `foo-consumer` in `src/test/resources/contracts/foo-consumer/some/contracts/...` folder) will be allowed to be referenced. You can check out https://github.com/spring-cloud/spring-cloud-contract/issues/224[issue 224] for more -information about the reasons behind this change. \ No newline at end of file +information about the reasons behind this change. + +[[features-stub-runner-common]] +=== Common + +This section briefly describes common properties, including: + +* <> +* <> + +[[features-stub-runner-common-properties-junit-spring]] +==== Common Properties for JUnit and Spring + +You can set repetitive properties by using system properties or Spring configuration +properties. Here are their names with their default values: + +[frame="topbot",options="header"] +|=============== +| Property name | Default value | Description +|stubrunner.minPort|10000| Minimum value of a port for a started WireMock with stubs. +|stubrunner.maxPort|15000| Maximum value of a port for a started WireMock with stubs. +|stubrunner.repositoryRoot|| Maven repo URL. If blank, then call the local maven repo. +|stubrunner.classifier|stubs| Default classifier for the stub artifacts. +|stubrunner.stubsMode|CLASSPATH| The way you want to fetch and register the stubs +|stubrunner.ids|| Array of Ivy notation stubs to download. +|stubrunner.username|| Optional username to access the tool that stores the JARs with +stubs. +|stubrunner.password|| Optional password to access the tool that stores the JARs with +stubs. +|stubrunner.stubsPerConsumer|false| Set to `true` if you want to use different stubs for +each consumer instead of registering all stubs for every consumer. +|stubrunner.consumerName|| If you want to use a stub for each consumer and want to +override the consumer name just change this value. +|=============== + +[[features-stub-runner-stub-runner-stub-ids]] +==== Stub Runner Stubs IDs + +You can provide the stubs to download via the `stubrunner.ids` system property. They +follow this pattern: + +[source,java,indent=0] +---- +groupId:artifactId:version:classifier:port +---- + +Note that `version`, `classifier` and `port` are optional. + +* If you do not provide the `port`, a random one will be picked. +* If you do not provide the `classifier`, the default is used. (Note that you can +pass an empty classifier this way: `groupId:artifactId:version:`). +* If you do not provide the `version`, then the `+` will be passed and the latest one is +downloaded. + +`port` means the port of the WireMock server. + +IMPORTANT: Starting with version 1.0.4, you can provide a range of versions that you +would like the Stub Runner to take into consideration. You can read more about the +https://wiki.eclipse.org/Aether/New_and_Noteworthy#Version_Ranges[Aether versioning +ranges here]. \ No newline at end of file diff --git a/docs/src/main/asciidoc/_project-features-wiremock.adoc b/docs/src/main/asciidoc/_project-features-wiremock.adoc new file mode 100644 index 0000000000..3a8477ce0b --- /dev/null +++ b/docs/src/main/asciidoc/_project-features-wiremock.adoc @@ -0,0 +1,175 @@ +[[features-wiremock]] +== Spring Cloud Contract WireMock +include::_attributes.adoc[] + +The Spring Cloud Contract WireMock modules let you use https://github.com/tomakehurst/wiremock[WireMock] in a +Spring Boot application. Check out the +https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples[samples] +for more details. + +If you have a Spring Boot application that uses Tomcat as an embedded server (which is +the default with `spring-boot-starter-web`), you can add +`spring-cloud-starter-contract-stub-runner` to your classpath and add `@AutoConfigureWireMock` in +order to be able to use Wiremock in your tests. Wiremock runs as a stub server and you +can register stub behavior using a Java API or via static JSON declarations as part of +your test. The following code shows an example: + +[source,java,indent=0] +---- +include::{doc_samples}/src/test/java/com/example/WiremockForDocsTests.java[tags=wiremock_test1] +include::{doc_samples}/src/test/java/com/example/WiremockForDocsTests.java[tags=wiremock_test2] +---- + +To start the stub server on a different port use (for example), +`@AutoConfigureWireMock(port=9999)`. For a random port, use a value of `0`. The stub +server port can be bound in the test application context with the "wiremock.server.port" +property. Using `@AutoConfigureWireMock` adds a bean of type `WiremockConfiguration` to +your test application context, where it will be cached in between methods and classes +having the same context, the same as for Spring integration tests. Also you can inject a bean of type `WireMockServer` into your test. + +[[features-wiremock-registering-stubs]] +=== Registering Stubs Automatically + +If you use `@AutoConfigureWireMock`, it registers WireMock JSON stubs from the file +system or classpath (by default, from `file:src/test/resources/mappings`). You can +customize the locations using the `stubs` attribute in the annotation, which can be an +Ant-style resource pattern or a directory. In the case of a directory, `**/*.json` is +appended. The following code shows an example: + +---- +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureWireMock(stubs="classpath:/stubs") +public class WiremockImportApplicationTests { + + @Autowired + private Service service; + + @Test + public void contextLoads() throws Exception { + assertThat(this.service.go()).isEqualTo("Hello World!"); + } + +} +---- + +NOTE: Actually, WireMock always loads mappings from `src/test/resources/mappings` *as +well as* the custom locations in the stubs attribute. To change this behavior, you can +also specify a files root as described in the next section of this document. + +If you're using Spring Cloud Contract's default stub jars, then your +stubs are stored under `/META-INF/group-id/artifact-id/versions/mappings/` folder. If you want to register all stubs from that location, from all embedded JARs, then it's enough to use the following syntax. + +[source,java,indent=0] +---- +include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockFilesApplicationWithUrlResourceTests.java[tags=load_all_stubs] +---- + +[[features-wiremock-using-files]] +=== Using Files to Specify the Stub Bodies + +WireMock can read response bodies from files on the classpath or the file system. In that +case, you can see in the JSON DSL that the response has a `bodyFileName` instead of a +(literal) `body`. The files are resolved relative to a root directory (by default, +`src/test/resources/\__files`). To customize this location you can set the `files` +attribute in the `@AutoConfigureWireMock` annotation to the location of the parent +directory (in other words, `__files` is a subdirectory). You can use Spring resource +notation to refer to `file:...` or `classpath:...` locations. Generic URLs are not +supported. A list of values can be given, in which case WireMock resolves the first file +that exists when it needs to find a response body. + +NOTE: When you configure the `files` root, it also affects the +automatic loading of stubs, because they come from the root location +in a subdirectory called "mappings". The value of `files` has no +effect on the stubs loaded explicitly from the `stubs` attribute. + +[[features-wiremock-junit-rule]] +=== Alternative: Using JUnit Rules + +For a more conventional WireMock experience, you can use JUnit `@Rules` to start and stop +the server. To do so, use the `WireMockSpring` convenience class to obtain an `Options` +instance, as shown in the following example: + +[source,java,indent=0] +---- +include::{doc_samples}/src/test/java/com/example/WiremockForDocsClassRuleTests.java[tags=wiremock_test1] +include::{doc_samples}/src/test/java/com/example/WiremockForDocsClassRuleTests.java[tags=wiremock_test2] +---- + +The `@ClassRule` means that the server shuts down after all the methods in this class +have been run. + +[[features-wiremock-relaxed-ssl]] +=== Relaxed SSL Validation for Rest Template + +WireMock lets you stub a "secure" server with an "https" URL protocol. If your +application wants to contact that stub server in an integration test, it will find that +the SSL certificates are not valid (the usual problem with self-installed certificates). +The best option is often to re-configure the client to use "http". If that's not an +option, you can ask Spring to configure an HTTP client that ignores SSL validation errors +(do so only for tests, of course). + +To make this work with minimum fuss, you need to be using the Spring Boot +`RestTemplateBuilder` in your app, as shown in the following example: + +[source,java,indent=0] +---- + @Bean + public RestTemplate restTemplate(RestTemplateBuilder builder) { + return builder.build(); + } +---- + +You need `RestTemplateBuilder` because the builder is passed through callbacks to +initialize it, so the SSL validation can be set up in the client at that point. This +happens automatically in your test if you are using the `@AutoConfigureWireMock` +annotation or the stub runner. If you use the JUnit `@Rule` approach, you need to add the +`@AutoConfigureHttpClient` annotation as well, as shown in the following example: + +[source,java,indent=0] +---- +@RunWith(SpringRunner.class) +@SpringBootTest("app.baseUrl=https://localhost:6443") +@AutoConfigureHttpClient +public class WiremockHttpsServerApplicationTests { + + @ClassRule + public static WireMockClassRule wiremock = new WireMockClassRule( + WireMockSpring.options().httpsPort(6443)); +... +} +---- + +If you are using `spring-boot-starter-test`, you have the Apache HTTP client on the +classpath and it is selected by the `RestTemplateBuilder` and configured to ignore SSL +errors. If you use the default `java.net` client, you do not need the annotation (but it +won't do any harm). There is no support currently for other clients, but it may be added +in future releases. + +To disable the custom `RestTemplateBuilder`, set the `wiremock.rest-template-ssl-enabled` +property to `false`. + +[[features-wiremock-spring-mvc-mocks]] +=== WireMock and Spring MVC Mocks + +Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into +a Spring `MockRestServiceServer`. The following code shows an example: + +[source,java,indent=0] +---- +include::{doc_samples}/src/test/java/com/example/WiremockForDocsMockServerApplicationTests.java[tags=wiremock_test] +---- + +The `baseUrl` value is prepended to all mock calls, and the `stubs()` method takes a stub +path resource pattern as an argument. In the preceding example, the stub defined at +`/stubs/resource.json` is loaded into the mock server. If the `RestTemplate` is asked to +visit `https://example.org/`, it gets the responses as being declared at that URL. More +than one stub pattern can be specified, and each one can be a directory (for a recursive +list of all ".json"), a fixed filename (as in the example above), or an Ant-style +pattern. The JSON format is the normal WireMock format, which you can read about in the +https://wiremock.org/docs/stubbing/[WireMock website]. + +Currently, the Spring Cloud Contract Verifier supports Tomcat, Jetty, and Undertow as +Spring Boot embedded servers, and Wiremock itself has "native" support for a particular +version of Jetty (currently 9.2). To use the native Jetty, you need to add the native +Wiremock dependencies and exclude the Spring Boot container (if there is one). \ No newline at end of file diff --git a/docs/src/main/asciidoc/_spring-cloud-contract-verifier.adoc b/docs/src/main/asciidoc/_spring-cloud-contract-verifier.adoc deleted file mode 100644 index 484b905565..0000000000 --- a/docs/src/main/asciidoc/_spring-cloud-contract-verifier.adoc +++ /dev/null @@ -1,13 +0,0 @@ -include::_verifier_introduction.adoc[] - -include::_verifier_faq.adoc[] - -include::_verifier_setup.adoc[] - -include::_verifier_messaging.adoc[] - -include::_verifier_stubrunner.adoc[] - -include::_verifier_stubrunner_msg.adoc[] - -include::_verifier_contract.adoc[] \ No newline at end of file diff --git a/docs/src/main/asciidoc/_spring-cloud-wiremock.adoc b/docs/src/main/asciidoc/_spring-cloud-wiremock.adoc deleted file mode 100644 index e4203362c6..0000000000 --- a/docs/src/main/asciidoc/_spring-cloud-wiremock.adoc +++ /dev/null @@ -1,422 +0,0 @@ -:core_path: ../../.. -:doc_samples: {core_path}/samples/wiremock-jetty -:wiremock_tests: {core_path}/spring-cloud-contract-wiremock - -== Spring Cloud Contract WireMock - -The Spring Cloud Contract WireMock modules let you use https://github.com/tomakehurst/wiremock[WireMock] in a -Spring Boot application. Check out the -https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples[samples] -for more details. - -If you have a Spring Boot application that uses Tomcat as an embedded server (which is -the default with `spring-boot-starter-web`), you can add -`spring-cloud-starter-contract-stub-runner` to your classpath and add `@AutoConfigureWireMock` in -order to be able to use Wiremock in your tests. Wiremock runs as a stub server and you -can register stub behavior using a Java API or via static JSON declarations as part of -your test. The following code shows an example: - -[source,java,indent=0] ----- -include::{doc_samples}/src/test/java/com/example/WiremockForDocsTests.java[tags=wiremock_test1] -include::{doc_samples}/src/test/java/com/example/WiremockForDocsTests.java[tags=wiremock_test2] ----- - -To start the stub server on a different port use (for example), -`@AutoConfigureWireMock(port=9999)`. For a random port, use a value of `0`. The stub -server port can be bound in the test application context with the "wiremock.server.port" -property. Using `@AutoConfigureWireMock` adds a bean of type `WiremockConfiguration` to -your test application context, where it will be cached in between methods and classes -having the same context, the same as for Spring integration tests. Also you can inject a bean of type `WireMockServer` into your test. - -=== Registering Stubs Automatically - -If you use `@AutoConfigureWireMock`, it registers WireMock JSON stubs from the file -system or classpath (by default, from `file:src/test/resources/mappings`). You can -customize the locations using the `stubs` attribute in the annotation, which can be an -Ant-style resource pattern or a directory. In the case of a directory, `**/*.json` is -appended. The following code shows an example: - ----- -@RunWith(SpringRunner.class) -@SpringBootTest -@AutoConfigureWireMock(stubs="classpath:/stubs") -public class WiremockImportApplicationTests { - - @Autowired - private Service service; - - @Test - public void contextLoads() throws Exception { - assertThat(this.service.go()).isEqualTo("Hello World!"); - } - -} ----- - -NOTE: Actually, WireMock always loads mappings from `src/test/resources/mappings` *as -well as* the custom locations in the stubs attribute. To change this behavior, you can -also specify a files root as described in the next section of this document. - -If you're using Spring Cloud Contract's default stub jars, then your -stubs are stored under `/META-INF/group-id/artifact-id/versions/mappings/` folder. If you want to register all stubs from that location, from all embedded JARs, then it's enough to use the following syntax. - -[source,java,indent=0] ----- -include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockFilesApplicationWithUrlResourceTests.java[tags=load_all_stubs] ----- - -=== Using Files to Specify the Stub Bodies - -WireMock can read response bodies from files on the classpath or the file system. In that -case, you can see in the JSON DSL that the response has a `bodyFileName` instead of a -(literal) `body`. The files are resolved relative to a root directory (by default, -`src/test/resources/\__files`). To customize this location you can set the `files` -attribute in the `@AutoConfigureWireMock` annotation to the location of the parent -directory (in other words, `__files` is a subdirectory). You can use Spring resource -notation to refer to `file:...` or `classpath:...` locations. Generic URLs are not -supported. A list of values can be given, in which case WireMock resolves the first file -that exists when it needs to find a response body. - -NOTE: When you configure the `files` root, it also affects the -automatic loading of stubs, because they come from the root location -in a subdirectory called "mappings". The value of `files` has no -effect on the stubs loaded explicitly from the `stubs` attribute. - -=== Alternative: Using JUnit Rules - -For a more conventional WireMock experience, you can use JUnit `@Rules` to start and stop -the server. To do so, use the `WireMockSpring` convenience class to obtain an `Options` -instance, as shown in the following example: - -[source,java,indent=0] ----- -include::{doc_samples}/src/test/java/com/example/WiremockForDocsClassRuleTests.java[tags=wiremock_test1] -include::{doc_samples}/src/test/java/com/example/WiremockForDocsClassRuleTests.java[tags=wiremock_test2] ----- - -The `@ClassRule` means that the server shuts down after all the methods in this class -have been run. - -=== Relaxed SSL Validation for Rest Template - -WireMock lets you stub a "secure" server with an "https" URL protocol. If your -application wants to contact that stub server in an integration test, it will find that -the SSL certificates are not valid (the usual problem with self-installed certificates). -The best option is often to re-configure the client to use "http". If that's not an -option, you can ask Spring to configure an HTTP client that ignores SSL validation errors -(do so only for tests, of course). - -To make this work with minimum fuss, you need to be using the Spring Boot -`RestTemplateBuilder` in your app, as shown in the following example: - -[source,java,indent=0] ----- - @Bean - public RestTemplate restTemplate(RestTemplateBuilder builder) { - return builder.build(); - } ----- - -You need `RestTemplateBuilder` because the builder is passed through callbacks to -initialize it, so the SSL validation can be set up in the client at that point. This -happens automatically in your test if you are using the `@AutoConfigureWireMock` -annotation or the stub runner. If you use the JUnit `@Rule` approach, you need to add the -`@AutoConfigureHttpClient` annotation as well, as shown in the following example: - -[source,java,indent=0] ----- -@RunWith(SpringRunner.class) -@SpringBootTest("app.baseUrl=https://localhost:6443") -@AutoConfigureHttpClient -public class WiremockHttpsServerApplicationTests { - - @ClassRule - public static WireMockClassRule wiremock = new WireMockClassRule( - WireMockSpring.options().httpsPort(6443)); -... -} ----- - -If you are using `spring-boot-starter-test`, you have the Apache HTTP client on the -classpath and it is selected by the `RestTemplateBuilder` and configured to ignore SSL -errors. If you use the default `java.net` client, you do not need the annotation (but it -won't do any harm). There is no support currently for other clients, but it may be added -in future releases. - -To disable the custom `RestTemplateBuilder`, set the `wiremock.rest-template-ssl-enabled` -property to `false`. - -=== WireMock and Spring MVC Mocks - -Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into -a Spring `MockRestServiceServer`. The following code shows an example: - -[source,java,indent=0] ----- -include::{doc_samples}/src/test/java/com/example/WiremockForDocsMockServerApplicationTests.java[tags=wiremock_test] ----- - -The `baseUrl` value is prepended to all mock calls, and the `stubs()` method takes a stub -path resource pattern as an argument. In the preceding example, the stub defined at -`/stubs/resource.json` is loaded into the mock server. If the `RestTemplate` is asked to -visit `https://example.org/`, it gets the responses as being declared at that URL. More -than one stub pattern can be specified, and each one can be a directory (for a recursive -list of all ".json"), a fixed filename (as in the example above), or an Ant-style -pattern. The JSON format is the normal WireMock format, which you can read about in the -https://wiremock.org/docs/stubbing/[WireMock website]. - -Currently, the Spring Cloud Contract Verifier supports Tomcat, Jetty, and Undertow as -Spring Boot embedded servers, and Wiremock itself has "native" support for a particular -version of Jetty (currently 9.2). To use the native Jetty, you need to add the native -Wiremock dependencies and exclude the Spring Boot container (if there is one). - -=== Customization of WireMock configuration - -You can register a bean of `org.springframework.cloud.contract.wiremock.WireMockConfigurationCustomizer` type -in order to customize the WireMock configuration (e.g. add custom transformers). -Example: - -[source,java,indent=0] ----- -include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockConfigurationCustomizerTests.java[tags=customizer_1] -// perform your customization here -include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockConfigurationCustomizerTests.java[tags=customizer_2] ----- - -=== Generating Stubs using REST Docs - -https://projects.spring.io/spring-restdocs[Spring REST Docs] can be used to generate -documentation (for example in Asciidoctor format) for an HTTP API with Spring MockMvc -or `WebTestClient` or Rest Assured. At the same time that you generate documentation for your API, you can also -generate WireMock stubs by using Spring Cloud Contract WireMock. To do so, write your -normal REST Docs test cases and use `@AutoConfigureRestDocs` to have stubs be -automatically generated in the REST Docs output directory. - -[plantuml, rest-docs, png] ----- -"API Producer"->"API Producer": add Spring Cloud Contract (SCC) \nStub Runner dependency -"API Producer"->"API Producer": setup stub jar assembly -"API Producer"->"API Producer": write and setup REST Docs tests -"API Producer"->"Build": run build -"Build"->"REST Docs": generate API \ndocumentation -"REST Docs"->"SCC": generate stubs from the \nREST Docs tests -"REST Docs"->"SCC": generate contracts from the \nREST Docs tests -"Build"->"Build": assemble stubs jar with \nstubs and contracts -"Build"->"Nexus / Artifactory": upload contracts \nand stubs and the project arifact -"Build"->"API Producer": Build successful -"API Consumer"->"API Consumer": add SCC Stub Runner \ndependency -"API Consumer"->"API Consumer": write a SCC Stub Runner \nbased contract test -"SCC Stub Runner"->"Nexus / Artifactory": test asks for [API Producer] stubs -"Nexus / Artifactory"->"SCC Stub Runner": fetch the [API Producer] stubs -"SCC Stub Runner"->"SCC Stub Runner": run in memory\n HTTP server stubs -"API Consumer"->"SCC Stub Runner": send a request \nto the HTTP server stub -"SCC Stub Runner"->"API Consumer": communication is correct ----- - -The following code shows an -example using `MockMvc`: - -[source,java,indent=0] ----- -@RunWith(SpringRunner.class) -@SpringBootTest -@AutoConfigureRestDocs(outputDir = "target/snippets") -@AutoConfigureMockMvc -public class ApplicationTests { - - @Autowired - private MockMvc mockMvc; - - @Test - public void contextLoads() throws Exception { - mockMvc.perform(get("/resource")) - .andExpect(content().string("Hello World")) - .andDo(document("resource")); - } -} ----- - -This test generates a WireMock stub at "target/snippets/stubs/resource.json". It matches -all GET requests to the "/resource" path. The same example with `WebTestClient` (used -for testing Spring WebFlux applications) would look like this: - -[source,java,indent=0] ----- -@RunWith(SpringRunner.class) -@SpringBootTest -@AutoConfigureRestDocs(outputDir = "target/snippets") -@AutoConfigureWebTestClient -public class ApplicationTests { - - @Autowired - private WebTestClient client; - - @Test - public void contextLoads() throws Exception { - client.get().uri("/resource").exchange() - .expectBody(String.class).isEqualTo("Hello World") - .consumeWith(document("resource")); - } -} ----- - -Without any additional configuration, these tests create a stub with a request matcher -for the HTTP method and all headers except "host" and "content-length". To match the -request more precisely (for example, to match the body of a POST or PUT), we need to -explicitly create a request matcher. Doing so has two effects: - -* Creating a stub that matches only in the way you specify. -* Asserting that the request in the test case also matches the same conditions. - -The main entry point for this feature is `WireMockRestDocs.verify()`, which can be used -as a substitute for the `document()` convenience method, as shown in the following -example: - -[source,java,indent=0] - -import static org.springframework.cloud.contract.wiremock.restdocs.WireMockRestDocs.verify; - ----- -@RunWith(SpringRunner.class) -@SpringBootTest -@AutoConfigureRestDocs(outputDir = "target/snippets") -@AutoConfigureMockMvc -public class ApplicationTests { - - @Autowired - private MockMvc mockMvc; - - @Test - public void contextLoads() throws Exception { - mockMvc.perform(post("/resource") - .content("{\"id\":\"123456\",\"message\":\"Hello World\"}")) - .andExpect(status().isOk()) - .andDo(verify().jsonPath("$.id") - .stub("resource")); - } -} ----- - -This contract specifies that any valid POST with an "id" field receives the response -defined in this test. You can chain together calls to `.jsonPath()` to add additional -matchers. If JSON Path is unfamiliar, The https://github.com/jayway/JsonPath[JayWay -documentation] can help you get up to speed. The `WebTestClient` version of this test -has a similar `verify()` static helper that you insert in the same place. - -Instead of the `jsonPath` and `contentType` convenience methods, you can also use the -WireMock APIs to verify that the request matches the created stub, as shown in the -following example: - -[source,java,indent=0] ----- - @Test - public void contextLoads() throws Exception { - mockMvc.perform(post("/resource") - .content("{\"id\":\"123456\",\"message\":\"Hello World\"}")) - .andExpect(status().isOk()) - .andDo(verify() - .wiremock(WireMock.post( - urlPathEquals("/resource")) - .withRequestBody(matchingJsonPath("$.id")) - .stub("post-resource")); - } ----- - -The WireMock API is rich. You can match headers, query parameters, and request body by -regex as well as by JSON path. These features can be used to create stubs with a wider -range of parameters. The above example generates a stub resembling the following example: - -.post-resource.json -[source,json] ----- -{ - "request" : { - "url" : "/resource", - "method" : "POST", - "bodyPatterns" : [ { - "matchesJsonPath" : "$.id" - }] - }, - "response" : { - "status" : 200, - "body" : "Hello World", - "headers" : { - "X-Application-Context" : "application:-1", - "Content-Type" : "text/plain" - } - } -} ----- - -NOTE: You can use either the `wiremock()` method or the `jsonPath()` and `contentType()` -methods to create request matchers, but you can't use both approaches. - -On the consumer side, you can make the `resource.json` generated earlier in this section -available on the classpath (by -<= 20)]', byType()) - } - } -} ----- - -The generated document (formatted in Asciidoc in this case) contains a formatted -contract. The location of this file would be `index/dsl-contract.adoc`. diff --git a/docs/src/main/asciidoc/_verifier_introduction.adoc b/docs/src/main/asciidoc/_verifier_introduction.adoc deleted file mode 100644 index 75bf483d32..0000000000 --- a/docs/src/main/asciidoc/_verifier_introduction.adoc +++ /dev/null @@ -1,120 +0,0 @@ -== Spring Cloud Contract Introduction - -Spring Cloud Contract moves TDD to the level of software architecture. It allows to perform consumer, consumer-driven and producer-driven contract testing. - -=== History - -Before becoming Spring Cloud Contract, this project was called https://github.com/Codearte/accurest[Accurest]. -It was created by https://twitter.com/mgrzejszczak[Marcin Grzejszczak] and https://twitter.com/jkubrynski[Jakub Kubrynski] -from (https://github.com/Codearte[Codearte]. - -The `0.1.0` release took place on 26 Jan 2015 and it became stable with `1.0.0` release on 29 Feb 2016. - -=== Why a Contract Verifier? - -Assume that we have a system consisting of multiple microservices: - -image::{github-raw}/docs/src/main/asciidoc/images/Deps.png[Microservices Architecture] - -==== Testing issues - -If we wanted to test the application in top left corner to determine whether it can -communicate with other services, we could do one of two things: - -- Deploy all microservices and perform end-to-end tests. -- Mock other microservices in unit/integration tests. - -Both have their advantages but also a lot of disadvantages. - -*Deploy all microservices and perform end to end tests* - - -Advantages: - -- Simulates production. -- Tests real communication between services. - -Disadvantages: - -- To test one microservice, we have to deploy 6 microservices, a couple of databases, -etc. -- The environment where the tests run is locked for a single suite of tests (nobody else -would be able to run the tests in the meantime). -- They take a long time to run. -- The feedback comes very late in the process. -- They are extremely hard to debug. - -*Mock other microservices in unit/integration tests* - -Advantages: - -- They provide very fast feedback. -- They have no infrastructure requirements. - -Disadvantages: - -- The implementor of the service creates stubs that might have nothing to do with -reality. -- You can go to production with passing tests and failing production. - -To solve the aforementioned issues, Spring Cloud Contract was created. The main idea is to give you very fast feedback, without the need to set up the -whole world of microservices. If you work on stubs, then the only applications you need -are those that your application directly uses. - -image::{github-raw}/docs/src/main/asciidoc/images/Stubs2.png[Stubbed Services] - -Spring Cloud Contract gives you the certainty that the stubs that you use were -created by the service that you're calling. Also, if you can use them, it means that they -were tested against the producer's side. In short, you can trust those stubs. - -=== Purposes - -The main purposes of Spring Cloud Contract are: - -- To ensure that Http / Messaging stubs (used when developing the client) do exactly -what the actual server-side implementation does. -- To promote ATDD (acceptance test driven developement) method and Microservices architectural style. -- To provide a way to publish changes in contracts that are immediately visible on both -sides. -- To generate boilerplate test code to be used on the server side. - -By default Spring Cloud Contract integrates with http://wiremock.org[Wiremock] as the HTTP server stub. - -IMPORTANT: Spring Cloud Contract's purpose is NOT to start writing business -features in the contracts. Assume that we have a business use case of fraud check. If a -user can be a fraud for 100 different reasons, we would assume that you would create 2 -contracts, one for the positive case and one for the negative case. Contract tests are -used to test contracts between applications and not to simulate full behavior. - -include::_verifier_how_it_works.adoc[] - -=== Dependencies - -The best way to add dependencies is to use the proper `starter` dependency. - -For `stub-runner`, use `spring-cloud-starter-stub-runner`. When you use a plugin, add -`spring-cloud-starter-contract-verifier`. - -=== Additional Links - -Here are some resources related to Spring Cloud Contract Verifier and Stub Runner. Note -that some may be outdated, because the Spring Cloud Contract Verifier project is under -constant development. - -==== Spring Cloud Contract video - -You can check out the video from the Warsaw JUG about Spring Cloud Contract: - -video::sAAklvxmPmk[youtube,start=538,width=640,height=480] - -==== Readings - -- https://www.slideshare.net/MarcinGrzejszczak/stick-to-the-rules-consumer-driven-contracts-201507-confitura[Slides from Marcin Grzejszczak's talk about Accurest] -- https://toomuchcoding.com/blog/categories/accurest/[Accurest related articles from Marcin Grzejszczak's blog] -- https://toomuchcoding.com/blog/categories/spring-cloud-contract/[Spring Cloud Contract related articles from Marcin Grzejszczak's blog] -- https://groovy-lang.org/json.html[Groovy docs regarding JSON] - -=== Samples - -You can find some samples at -https://github.com/spring-cloud-samples/spring-cloud-contract-samples[samples]. diff --git a/docs/src/main/asciidoc/_verifier_messaging.adoc b/docs/src/main/asciidoc/_verifier_messaging.adoc deleted file mode 100644 index 7e3a419100..0000000000 --- a/docs/src/main/asciidoc/_verifier_messaging.adoc +++ /dev/null @@ -1,195 +0,0 @@ -== Spring Cloud Contract Verifier Messaging - -Spring Cloud Contract Verifier lets you verify applications that use messaging as a -means of communication. All of the integrations shown in this document work with Spring, -but you can also create one of your own and use that. - -=== Integrations - -You can use one of the following four integration configurations: - -* Apache Camel -* Spring Integration -* Spring Cloud Stream -* Spring AMQP - -Since we use Spring Boot, if you have added one of these libraries to the classpath, all -the messaging configuration is automatically set up. - -IMPORTANT: Remember to put `@AutoConfigureMessageVerifier` on the base class of your -generated tests. Otherwise, messaging part of Spring Cloud Contract Verifier does not -work. - -IMPORTANT: If you want to use Spring Cloud Stream, remember to add a dependency on -`org.springframework.cloud:spring-cloud-stream-test-support`, as shown here: - -[source,xml,indent=0,subs="verbatim,attributes",role="primary"] -.Maven ----- - - org.springframework.cloud - spring-cloud-stream-test-support - test - ----- - -[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] -.Gradle ----- -testCompile "org.springframework.cloud:spring-cloud-stream-test-support" ----- - -=== Manual Integration Testing - -The main interface used by the tests is -`org.springframework.cloud.contract.verifier.messaging.MessageVerifier`. -It defines how to send and receive messages. You can create your own implementation to -achieve the same goal. - -In a test, you can inject a `ContractVerifierMessageExchange` to send and receive -messages that follow the contract. Then add `@AutoConfigureMessageVerifier` to your test. -Here's an example: - -[source,java,indent=0] ----- -@RunWith(SpringTestRunner.class) -@SpringBootTest -@AutoConfigureMessageVerifier -public static class MessagingContractTests { - - @Autowired - private MessageVerifier verifier; - ... -} ----- - -NOTE: If your tests require stubs as well, then `@AutoConfigureStubRunner` includes the -messaging configuration, so you only need the one annotation. - -=== Publisher-Side Test Generation - -Having the `input` or `outputMessage` sections in your DSL results in creation of tests -on the publisher's side. By default, JUnit 4 tests are created. However, there is also a -possibility to create JUnit 5, TestNG or Spock tests. - -There are 3 main scenarios that we should take into consideration: - -* Scenario 1: There is no input message that produces an output message. The output -message is triggered by a component inside the application (for example, scheduler). -* Scenario 2: The input message triggers an output message. -* Scenario 3: The input message is consumed and there is no output message. - -IMPORTANT: The destination passed to `messageFrom` or `sentTo` can have different -meanings for different messaging implementations. For *Stream* and *Integration* it is -first resolved as a `destination` of a channel. Then, if there is no such `destination` -it is resolved as a channel name. For *Camel*, that's a certain component (for example, -`jms`). - -==== Scenario 1: No Input Message - -For the given contract: - -.Groovy DSL -[source,groovy] ----- -include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_method_dsl] ----- - -.YAML -[source,yml,indent=0] ----- -include::{verifier_core_path}/src/test/resources/yml/contract_message_scenario1.yml[indent=0] ----- - -The following JUnit test is created: - -[source,groovy] ----- -include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_method_junit_test] ----- - -And the following Spock test would be created: - -[source,groovy] ----- -include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_method_test] ----- - -==== Scenario 2: Output Triggered by Input - -For the given contract: - -.Groovy DSL -[source,groovy] ----- -include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_message_dsl] ----- - -.YAML -[source,yml,indent=0] ----- -include::{verifier_core_path}/src/test/resources/yml/contract_message_scenario2.yml[indent=0] ----- - -The following JUnit test is created: - -[source,groovy] ----- -include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_message_junit] ----- - -And the following Spock test would be created: - -[source,groovy] ----- -include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_message_spock] ----- - -==== Scenario 3: No Output Message - -For the given contract: - -.Groovy DSL -[source,groovy] ----- -include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_no_output_dsl] ----- - -.YAML -[source,yml,indent=0] ----- -include::{verifier_core_path}/src/test/resources/yml/contract_message_scenario3.yml[indent=0] ----- - -The following JUnit test is created: - -[source,groovy] ----- -include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_no_output_junit] ----- - -And the following Spock test would be created: - -[source,groovy] ----- -include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_no_output_spock] ----- - -=== Consumer Stub Generation - -Unlike the HTTP part, in messaging, we need to publish the Groovy DSL inside the JAR with -a stub. Then it is parsed on the consumer side and proper stubbed routes are created. - -For more information, see <> section. - -[source,xml,indent=0,subs="verbatim,attributes",role="primary"] -.Maven ----- -include::{standalone_messaging_samples_path}/stream-sink/pom.xml[tags=jars,indent=0] ----- - -[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] -.Gradle ----- -include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/resources/functionalTest/scenarioProject/build.gradle[tags=jar_setup,indent=0] ----- diff --git a/docs/src/main/asciidoc/_verifier_setup.adoc b/docs/src/main/asciidoc/_verifier_setup.adoc deleted file mode 100644 index e805a2d1c7..0000000000 --- a/docs/src/main/asciidoc/_verifier_setup.adoc +++ /dev/null @@ -1,7 +0,0 @@ -== Spring Cloud Contract Verifier Setup - -You can set up Spring Cloud Contract Verifier in the following ways: - -* link:gradle-project.html[As a Gradle project] -* link:maven-project.html[As a Maven project] -* link:docker-project.html[As a Docker project] \ No newline at end of file diff --git a/docs/src/main/asciidoc/_verifier_stubrunner.adoc b/docs/src/main/asciidoc/_verifier_stubrunner.adoc deleted file mode 100644 index a29dfc2b69..0000000000 --- a/docs/src/main/asciidoc/_verifier_stubrunner.adoc +++ /dev/null @@ -1,182 +0,0 @@ -== Spring Cloud Contract Stub Runner - -One of the issues that you might encounter while using Spring Cloud Contract Verifier is -passing the generated WireMock JSON stubs from the server side to the client side (or to -various clients). The same takes place in terms of client-side generation for messaging. - -Copying the JSON files and setting the client side for messaging manually is out of the -question. That is why we introduced Spring Cloud Contract Stub Runner. It can -automatically download and run the stubs for you. - -=== Snapshot versions - -Add the additional snapshot repository to your `build.gradle` file to use snapshot -versions, which are automatically uploaded after every successful build: - -[source,xml,indent=0,subs="verbatim,attributes",role="primary"] -.Maven ----- -include::{standalone_samples_path}/http-server/pom.xml[tags=repos,indent=0] ----- - -[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] -.Gradle ----- -include::{standalone_samples_path}/http-server/build.gradle[tags=repos,indent=0] ----- - -[[publishing-stubs-as-jars]] -=== Publishing Stubs as JARs - -The easiest approach would be to centralize the way stubs are kept. For example, you can -keep them as jars in a Maven repository. - -TIP: For both Maven and Gradle, the setup comes ready to work. However, you can customize -it if you want to. - -[source,xml,indent=0,subs="verbatim,attributes",role="primary"] -.Maven ----- - -include::{samples_url}/producer_with_restdocs/pom.xml[tags=skip_jar,indent=0] - - -include::{samples_url}/producer_with_restdocs/pom.xml[tags=assembly,indent=0] - - -include::{samples_url}/producer_with_restdocs/src/assembly/stub.xml[indent=0] ----- - -[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] -.Gradle ----- -include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/resources/functionalTest/scenarioProject/build.gradle[tags=jar_setup,indent=0] ----- - -include::{stubrunner_core_path}/README.adoc[] - -=== Common - -This section briefly describes common properties, including: - -* <> -* <> - -[[common-properties-junit-spring]] -==== Common Properties for JUnit and Spring - -You can set repetitive properties by using system properties or Spring configuration -properties. Here are their names with their default values: - -[frame="topbot",options="header"] -|=============== -| Property name | Default value | Description -|stubrunner.minPort|10000| Minimum value of a port for a started WireMock with stubs. -|stubrunner.maxPort|15000| Maximum value of a port for a started WireMock with stubs. -|stubrunner.repositoryRoot|| Maven repo URL. If blank, then call the local maven repo. -|stubrunner.classifier|stubs| Default classifier for the stub artifacts. -|stubrunner.stubsMode|CLASSPATH| The way you want to fetch and register the stubs -|stubrunner.ids|| Array of Ivy notation stubs to download. -|stubrunner.username|| Optional username to access the tool that stores the JARs with -stubs. -|stubrunner.password|| Optional password to access the tool that stores the JARs with -stubs. -|stubrunner.stubsPerConsumer|false| Set to `true` if you want to use different stubs for -each consumer instead of registering all stubs for every consumer. -|stubrunner.consumerName|| If you want to use a stub for each consumer and want to -override the consumer name just change this value. -|=============== - -[[stub-runner-stub-ids]] -==== Stub Runner Stubs IDs - -You can provide the stubs to download via the `stubrunner.ids` system property. They -follow this pattern: - -[source,java,indent=0] ----- -groupId:artifactId:version:classifier:port ----- - -Note that `version`, `classifier` and `port` are optional. - -* If you do not provide the `port`, a random one will be picked. -* If you do not provide the `classifier`, the default is used. (Note that you can -pass an empty classifier this way: `groupId:artifactId:version:`). -* If you do not provide the `version`, then the `+` will be passed and the latest one is -downloaded. - -`port` means the port of the WireMock server. - -IMPORTANT: Starting with version 1.0.4, you can provide a range of versions that you -would like the Stub Runner to take into consideration. You can read more about the -https://wiki.eclipse.org/Aether/New_and_Noteworthy#Version_Ranges[Aether versioning -ranges here]. - -[[stubrunner-docker]] -=== Stub Runner Docker - -We're publishing a `spring-cloud/spring-cloud-contract-stub-runner` Docker image -that will start the standalone version of Stub Runner. - -If you want to learn more about the basics of Maven, artifact ids, -group ids, classifiers and Artifact Managers, just click here <>. - -==== How to use it - -Just execute the docker image. You can pass any of the <> -as environment variables. The convention is that all the -letters should be upper case. The camel case notation should -and the dot (`.`) should be separated via underscore (`_`). E.g. - the `stubrunner.repositoryRoot` property should be represented - as a `STUBRUNNER_REPOSITORY_ROOT` environment variable. - -==== Example of client side usage in a non JVM project - -We'd like to use the stubs created in this <> step. -Let's assume that we want to run the stubs on port `9876`. The NodeJS code -is available here: - -```bash -$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs -$ cd bookstore -``` - -Let's run the Stub Runner Boot application with the stubs. - -```bash -# Provide the Spring Cloud Contract Docker version -$ SC_CONTRACT_DOCKER_VERSION="..." -# The IP at which the app is running and Docker container can reach it -$ APP_IP="192.168.0.100" -# Spring Cloud Contract Stub Runner properties -$ STUBRUNNER_PORT="8083" -# Stub coordinates 'groupId:artifactId:version:classifier:port' -$ STUBRUNNER_IDS="com.example:bookstore:0.0.1.RELEASE:stubs:9876" -$ STUBRUNNER_REPOSITORY_ROOT="http://${APP_IP}:8081/artifactory/libs-release-local" -# Run the docker with Stub Runner Boot -$ docker run --rm -e "STUBRUNNER_IDS=${STUBRUNNER_IDS}" -e "STUBRUNNER_REPOSITORY_ROOT=${STUBRUNNER_REPOSITORY_ROOT}" -e "STUBRUNNER_STUBS_MODE=REMOTE" -p "${STUBRUNNER_PORT}:${STUBRUNNER_PORT}" -p "9876:9876" springcloud/spring-cloud-contract-stub-runner:"${SC_CONTRACT_DOCKER_VERSION}" -``` - -What's happening is that - -- a standalone Stub Runner application got started -- it downloaded the stub with coordinates `com.example:bookstore:0.0.1.RELEASE:stubs` on port `9876` -- it got downloaded from Artifactory running at `http://192.168.0.100:8081/artifactory/libs-release-local` -- after a while Stub Runner will be running on port `8083` -- and the stubs will be running at port `9876` - -On the server side we built a stateful stub. Let's use curl to assert -that the stubs are setup properly. - -```bash -# let's execute the first request (no response is returned) -$ curl -H "Content-Type:application/json" -X POST --data '{ "title" : "Title", "genre" : "Genre", "description" : "Description", "author" : "Author", "publisher" : "Publisher", "pages" : 100, "image_url" : "https://d213dhlpdb53mu.cloudfront.net/assets/pivotal-square-logo-41418bd391196c3022f3cd9f3959b3f6d7764c47873d858583384e759c7db435.svg", "buy_url" : "https://pivotal.io" }' http://localhost:9876/api/books -# Now time for the second request -$ curl -X GET http://localhost:9876/api/books -# You will receive contents of the JSON -``` - -IMPORTANT: If you want use the stubs that you have built locally, on your host, -then you should pass the environment variable `-e STUBRUNNER_STUBS_MODE=LOCAL` and mount -the volume of your local m2 `-v "${HOME}/.m2/:/root/.m2:ro"` \ No newline at end of file diff --git a/docs/src/main/asciidoc/_verifier_stubrunner_msg.adoc b/docs/src/main/asciidoc/_verifier_stubrunner_msg.adoc deleted file mode 100644 index 1a5a68a96f..0000000000 --- a/docs/src/main/asciidoc/_verifier_stubrunner_msg.adoc +++ /dev/null @@ -1,75 +0,0 @@ -[[stub-runner-for-messaging]] -== Stub Runner for Messaging - -Stub Runner can run the published stubs in memory. It can integrate with the following -frameworks: - -* Spring Integration -* Spring Cloud Stream -* Apache Camel -* Spring AMQP - -It also provides entry points to integrate with any other solution on the market. - -IMPORTANT: If you have multiple frameworks on the classpath Stub Runner will need to -define which one should be used. Let's assume that you have both AMQP, Spring Cloud Stream and Spring Integration -on the classpath. Then you need to set `stubrunner.stream.enabled=false` and `stubrunner.integration.enabled=false`. -That way the only remaining framework is Spring AMQP. - -=== Stub triggering - -To trigger a message, use the `StubTrigger` interface: - -[source,groovy] ----- -include::{stubrunner_core_path}/src/main/java/org/springframework/cloud/contract/stubrunner/StubTrigger.java[lines=16..-1] ----- - -For convenience, the `StubFinder` interface extends `StubTrigger`, so you only need one -or the other in your tests. - -`StubTrigger` gives you the following options to trigger a message: - -* <> -* <> -* <> -* <> - -[[trigger-label]] -==== Trigger by Label - -[source,groovy] ----- -include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_trigger,indent=0] ----- -[[trigger-group-artifact-ids]] -==== Trigger by Group and Artifact Ids - -[source,groovy] ----- -include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=trigger_group_artifact,indent=0] ----- - -[[trigger-artifact-ids]] -==== Trigger by Artifact Ids - -[source,groovy] ----- -include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=trigger_artifact,indent=0] ----- - -[[trigger-all-messages]] -==== Trigger All Messages - -[source,groovy] ----- -include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=trigger_all,indent=0] ----- - -include::{tests_path}/spring-cloud-contract-stub-runner-camel/README.adoc[] - -include::{tests_path}/spring-cloud-contract-stub-runner-integration/README.adoc[] - -include::{tests_path}/spring-cloud-contract-stub-runner-stream/README.adoc[] - -include::{tests_path}/spring-cloud-contract-stub-runner-amqp/README.adoc[] diff --git a/docs/src/main/asciidoc/advanced.adoc b/docs/src/main/asciidoc/advanced.adoc new file mode 100644 index 0000000000..805a1e63c7 --- /dev/null +++ b/docs/src/main/asciidoc/advanced.adoc @@ -0,0 +1,373 @@ +[[contract-customization]] += Spring Cloud Contract customization +include::_attributes.adoc[] + +In this section we describe how to customize various parts of Spring Cloud Contract. + +[[customization-customization]] +== DSL Customization + +IMPORTANT: This section is valid only for Groovy DSL + +You can customize the Spring Cloud Contract Verifier by extending the DSL, as shown in +the remainder of this section. + +[[customization-extending]] +=== Extending the 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 document, you can see examples of: + +* Creating a JAR with reusable classes. +* Referencing of these classes in the DSLs. + +You can find the full example +https://github.com/spring-cloud-samples/spring-cloud-contract-samples[here]. + +[[customization-extending-common-jar]] +=== Common JAR + +The following examples show three classes that can be reused in the DSLs. + +*PatternUtils* contains functions used by both the **consumer** and the **producer**. + +[source,java] +---- +include::{samples_url}/common/src/main/java/com/example/PatternUtils.java[] +---- + +*ConsumerUtils* contains functions used by the **consumer**. + +[source,java] +---- +include::{samples_url}/common/src/main/java/com/example/ConsumerUtils.java[] +---- + +*ProducerUtils* contains functions used by the **producer**. + +[source,java] +---- +include::{samples_url}/common/src/main/java/com/example/ProducerUtils.java[] +---- + +[[customization-test-dep]] +=== Add a test dependency in the Project's Dependencies + +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 examples show how to test the dependency: + +== +[source,xml,indent=0,subs="verbatim,attributes",role="primary"] +.Maven +---- +include::{samples_url}/producer/pom.xml[tags=test_dep,indent=0] +---- + +[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] +.Gradle +---- +include::{samples_url}/producer/build.gradle[tags=test_dep,indent=0] +---- +== + +[[customization-plugin-dep]] +=== Add a test dependency in the Plugin's Dependencies + +Now, you must add the dependency for the plugin to reuse at runtime, as shown in the +following example: + +== +[source,xml,indent=0,subs="verbatim,attributes",role="primary"] +.Maven +---- +include::{samples_url}/producer/pom.xml[tags=test_dep_in_plugin,indent=0] +---- + +[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] +.Gradle +---- +include::{samples_url}/producer/build.gradle[tags=test_dep_in_plugin,indent=0] +---- +== + +[[customization-referencing]] +=== Referencing classes in DSLs + +You can now reference your classes in your DSL, as shown in the following example: + +[source,groovy] +---- +include::{samples_url}/producer/src/test/resources/contracts/beer/rest/shouldGrantABeerIfOldEnough.groovy[indent=0] +---- + +IMPORTANT: You can set the Spring Cloud Contract plugin up by setting `convertToYaml` to `true`. That way you will NOT have to add the dependency with the extended functionality to the consumer side, since the consumer side will be using YAML contracts instead of Groovy ones. + +[[customization-wiremock]] +== WireMock customization + +In this section you will learn how to customize the way you work with https://wiremock.org[WireMock]. + +[[customization-wiremock-extension]] +=== Registering Your Own WireMock Extension + +WireMock lets you register custom extensions. By default, Spring Cloud Contract registers +the transformer, which lets you reference a request from a response. If you want to +provide your own extensions, you can register an implementation of the +`org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions` interface. +Since we use the spring.factories extension approach, you can create an entry in +`META-INF/spring.factories` file similar to the following: + +[source,groovy,indent=0] +---- +include::{stubrunner_core_path}/src/test/resources/META-INF/spring.factories[indent=0] +---- + +The following is an example of a custom extension: + +.TestWireMockExtensions.groovy +[source,groovy,indent=0] +---- +include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/dsl/wiremock/TestWireMockExtensions.groovy[indent=0] +---- + +IMPORTANT: Remember to override the `applyGlobally()` method and set it to `false` if you +want the transformation to be applied only for a mapping that explicitly requires it. + +[[customization-wiremock-configuration]] +=== Customization of WireMock configuration + +You can register a bean of `org.springframework.cloud.contract.wiremock.WireMockConfigurationCustomizer` type +in order to customize the WireMock configuration (e.g. add custom transformers). +Example: + +[source,java,indent=0] +---- +include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockConfigurationCustomizerTests.java[tags=customizer_1] +// perform your customization here +include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockConfigurationCustomizerTests.java[tags=customizer_2] +---- + +[[customization-pluggable-architecture]] +== Using the Pluggable Architecture + +You may encounter cases where you have your contracts have been defined in other formats, +such as YAML, RAML or PACT. In those cases, you still want to benefit from the automatic +generation of tests and stubs. You can add your own implementation for generating both +tests and stubs. Also, you can customize the way tests are generated (for example, you +can generate tests for other languages) and the way stubs are generated (for example, you +can generate stubs for other HTTP server implementations). + +[[customization-custom-contract-converter]] +=== Custom Contract Converter + +The `ContractConverter` interface lets you register your own implementation of a contract +structure converter. The following code listing shows the `ContractConverter` interface: + +[source,java] +---- +include::{contract_spec_path}/src/main/java/org/springframework/cloud/contract/spec/ContractConverter.java[indent=0,lines=17..-1] +---- + +Your implementation must define the condition on which it should start the +conversion. Also, you must define how to perform that conversion in both directions. + +IMPORTANT: Once you create your implementation, you must create a +`/META-INF/spring.factories` file in which you provide the fully qualified name of your +implementation. + +The following example shows a typical `spring.factories` file: + +[source] +---- +org.springframework.cloud.contract.spec.ContractConverter=\ +org.springframework.cloud.contract.verifier.converter.YamlContractConverter +---- + +[[customization-custom-test-generator]] +=== Using the Custom Test Generator + +If you want to generate tests for languages other than Java or you are not happy with the +way the verifier builds Java tests, you can register your own implementation. + +The `SingleTestGenerator` interface lets you register your own implementation. The +following code listing shows the `SingleTestGenerator` interface: + +[source,groovy] +---- +include::{verifier_core_path}/src/main/groovy/org/springframework/cloud/contract/verifier/builder/SingleTestGenerator.java[indent=0,lines=17..-1] +---- + +Again, you must provide a `spring.factories` file, such as the one shown in the following +example: + +[source] +---- +org.springframework.cloud.contract.verifier.builder.SingleTestGenerator=/ +com.example.MyGenerator +---- + +[[customization-custom-stub-generator]] +=== Using the Custom Stub Generator + +If you want to generate stubs for stub servers other than WireMock, you can plug in your +own implementation of the `StubGenerator` interface. The following code listing shows the +`StubGenerator` interface: + +[source,groovy] +---- +include::{converters_path}/src/main/groovy/org/springframework/cloud/contract/verifier/converter/StubGenerator.groovy[indent=0,lines=16..-1] +---- + +Again, you must provide a `spring.factories` file, such as the one shown in the following +example: + +[source] +---- +include::{converters_path}/src/main/resources/META-INF/spring.factories[indent=0] +---- + +The default implementation is the WireMock stub generation. + +TIP: You can provide multiple stub generator implementations. For example, from a single +DSL, you can produce both WireMock stubs and Pact files. + +[[customization-custom-stub-runner]] +=== Using the Custom Stub Runner + +If you decide to use a custom stub generation, you also need a custom way of running +stubs with your different stub provider. + +Assume that you use https://github.com/dreamhead/moco[Moco] to build your stubs and that +you have written a stub generator and placed your stubs in a JAR file. + +In order for Stub Runner to know how to run your stubs, you have to define a custom +HTTP Stub server implementation, which might resemble the following example: + +[source,groovy] +---- +include::{tests_path}/spring-cloud-contract-stub-runner-moco/src/test/groovy/org/springframework/cloud/contract/stubrunner/provider/moco/MocoHttpServerStub.groovy[indent=0,lines=16..-1] +---- + +Then, you can register it in your `spring.factories` file, as shown in the following +example: + +[source] +---- +org.springframework.cloud.contract.stubrunner.HttpServerStub=\ +org.springframework.cloud.contract.stubrunner.provider.moco.MocoHttpServerStub +---- + +Now you can run stubs with Moco. + +IMPORTANT: If you do not provide any implementation, then the default (WireMock) +implementation is used. If you provide more than one, the first one on the list is used. + +[[customization-custom-stub-downloader]] +=== Using the Custom Stub Downloader + +You can customize the way your stubs are downloaded by creating an implementation of the +`StubDownloaderBuilder` interface, as shown in the following example: + +[source,java] +---- +package com.example; + +class CustomStubDownloaderBuilder implements StubDownloaderBuilder { + + @Override + public StubDownloader build(final StubRunnerOptions stubRunnerOptions) { + return new StubDownloader() { + @Override + public Map.Entry downloadAndUnpackStubJar( + StubConfiguration config) { + File unpackedStubs = retrieveStubs(); + return new AbstractMap.SimpleEntry<>( + new StubConfiguration(config.getGroupId(), config.getArtifactId(), version, + config.getClassifier()), unpackedStubs); + } + + File retrieveStubs() { + // here goes your custom logic to provide a folder where all the stubs reside + } +} +---- + +Then you can register it in your `spring.factories` file, as shown in the following +example: + +[source] +---- +# Example of a custom Stub Downloader Provider +org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder=\ +com.example.CustomStubDownloaderBuilder +---- + +Now you can pick a folder with the source of your stubs. + +IMPORTANT: If you do not provide any implementation, then the default is used (scan classpath). +If you provide the `stubsMode = StubRunnerProperties.StubsMode.LOCAL` or +`, stubsMode = StubRunnerProperties.StubsMode.REMOTE` then the Aether implementation will be used +If you provide more than one, then the first one on the list is used. + +[[scm-stub-downloader]] +=== Using the SCM Stub Downloader + +Whenever the `repositoryRoot` starts with a SCM protocol +(currently we support only `git://`), the stub downloader will try +to clone the repository and use it as a source of contracts +to generate tests or stubs. + +Either via environment variables, system properties, properties set +inside the plugin or contracts repository configuration you can +tweak the downloader's behaviour. Below you can find the list of +properties + +.SCM Stub Downloader properties +|==== +|Type of a property |Name of the property | Description +| +* `git.branch` (plugin prop) + +* `stubrunner.properties.git.branch` (system prop) + +* `STUBRUNNER_PROPERTIES_GIT_BRANCH` (env prop) +|master +|Which branch to checkout + +| +* `git.username` (plugin prop) + +* `stubrunner.properties.git.username` (system prop) + +* `STUBRUNNER_PROPERTIES_GIT_USERNAME` (env prop) +| +|Git clone username + +| +* `git.password` (plugin prop) + +* `stubrunner.properties.git.password` (system prop) + +* `STUBRUNNER_PROPERTIES_GIT_PASSWORD` (env prop) +| +|Git clone password + +| +* `git.no-of-attempts` (plugin prop) + +* `stubrunner.properties.git.no-of-attempts` (system prop) + +* `STUBRUNNER_PROPERTIES_GIT_NO_OF_ATTEMPTS` (env prop) +|10 +|Number of attempts to push the commits to `origin` + +| +* `git.wait-between-attempts` (Plugin prop) + +* `stubrunner.properties.git.wait-between-attempts` (system prop) + +* `STUBRUNNER_PROPERTIES_GIT_WAIT_BETWEEN_ATTEMPTS` (env prop) +|1000 +|Number of millis to wait between attempts to push the commits to `origin` +|==== diff --git a/docs/src/main/asciidoc/docker-project.adoc b/docs/src/main/asciidoc/docker-project.adoc index 2547579835..67185d90f1 100644 --- a/docs/src/main/asciidoc/docker-project.adoc +++ b/docs/src/main/asciidoc/docker-project.adoc @@ -1,3 +1,4 @@ +[[docker]] = Docker Project include::_attributes.adoc[] @@ -8,6 +9,10 @@ against a running application. TIP: The `EXPLICIT` mode means that the tests generated from contracts will send real requests and not the mocked ones. +We're also publishing a `spring-cloud/spring-cloud-contract-stub-runner` Docker image +that will start the standalone version of Stub Runner. + +[[docker-intro]] == Short intro to Maven, JARs and Binary storage Since the Docker image can be used by non JVM projects, it's good to @@ -48,7 +53,8 @@ and for Docker those would be Docker images. You can store those artifacts in a manager. Examples of such managers can be https://jfrog.com/artifactory/[Artifactory] or https://www.sonatype.org/nexus/[Nexus]. -== How it works +[[docker-how-it-works]] +== Generating tests on the producer side The image searches for contracts under the `/contracts` folder. The output from running the tests will be available under @@ -63,6 +69,7 @@ It's enough for you to mount your contracts, pass the environment variables - generate the https://github.com/tomakehurst/wiremock[WireMock] stubs - (optional - turned on by default) publish the stubs to a Artifact Manager +[[docker-env-vars]] === Environment Variables The Docker image requires some environment variables to point to @@ -94,12 +101,11 @@ requires authentication, defaults to `REPO_WITH_BINARIES_USERNAME`. If that's no requires authentication, defaults to `REPO_WITH_BINARIES_PASSWORD`. If that's not set defaults to `password`. - `EXTERNAL_CONTRACTS_PATH` - path to contracts for the given project, inside the project with contracts. Defaults to slash separated `EXTERNAL_CONTRACTS_GROUP_ID` concatenated with `/` and `EXTERNAL_CONTRACTS_ARTIFACT_ID`. E.g. -for group id `foo.bar` and artifact id `baz`, would result in `foo/bar/baz` contracts path. +for group id `foo-server-side.bar` and artifact id `baz`, would result in `foo/bar/baz` contracts path. - `EXTERNAL_CONTRACTS_WORK_OFFLINE` - if set to `true` then will retrieve artifact with contracts from the container's `.m2`. Mount your local `.m2` as a volume available at the container's `/root/.m2` path. You must not set both `EXTERNAL_CONTRACTS_WORK_OFFLINE` and `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL`. - These environment variables are used when tests are executed: - `APPLICATION_BASE_URL` - url against which tests should be executed. @@ -108,7 +114,8 @@ will not work) - `APPLICATION_USERNAME` - (optional) username for basic authentication to your application - `APPLICATION_PASSWORD` - (optional) password for basic authentication to your application -== Example of usage +[[docker-example-of-usage]] +=== Example of usage Let's take a look at a simple MVC application @@ -119,9 +126,6 @@ $ cd bookstore The contracts are available under `/contracts` folder. -[[docker-server-side]] -== Server side (nodejs) - Since we want to run tests, we could just execute: ```bash @@ -178,5 +182,72 @@ will be executed against the running application under http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/ . The stubs will be here http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar. -// TODO: Fix the link -To see how the client side looks like check out the <> section. +[[docker-stubrunner]] +== Running stubs on the consumer side + +This section describes hot to use Docker on the consumer side to fetch and run stubs. + +We're publishing a `spring-cloud/spring-cloud-contract-stub-runner` Docker image +that will start the standalone version of Stub Runner. + +[[docker-stubrunner-env-vars]] +=== Environment variables + +//TODO: Fix the link +Just execute the docker image. You can pass any of the <> +as environment variables. The convention is that all the +letters should be upper case. The camel case notation should +and the dot (`.`) should be separated via underscore (`_`). E.g. + the `stubrunner.repositoryRoot` property should be represented + as a `STUBRUNNER_REPOSITORY_ROOT` environment variable. + +[[docker-stubrunner-example]] +=== Example of usage + +We'd like to use the stubs created in this <> step. +Let's assume that we want to run the stubs on port `9876`. The NodeJS code +is available here: + +```bash +$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs +$ cd bookstore +``` + +Let's run the Stub Runner Boot application with the stubs. + +```bash +# Provide the Spring Cloud Contract Docker version +$ SC_CONTRACT_DOCKER_VERSION="..." +# The IP at which the app is running and Docker container can reach it +$ APP_IP="192.168.0.100" +# Spring Cloud Contract Stub Runner properties +$ STUBRUNNER_PORT="8083" +# Stub coordinates 'groupId:artifactId:version:classifier:port' +$ STUBRUNNER_IDS="com.example:bookstore:0.0.1.RELEASE:stubs:9876" +$ STUBRUNNER_REPOSITORY_ROOT="http://${APP_IP}:8081/artifactory/libs-release-local" +# Run the docker with Stub Runner Boot +$ docker run --rm -e "STUBRUNNER_IDS=${STUBRUNNER_IDS}" -e "STUBRUNNER_REPOSITORY_ROOT=${STUBRUNNER_REPOSITORY_ROOT}" -e "STUBRUNNER_STUBS_MODE=REMOTE" -p "${STUBRUNNER_PORT}:${STUBRUNNER_PORT}" -p "9876:9876" springcloud/spring-cloud-contract-stub-runner:"${SC_CONTRACT_DOCKER_VERSION}" +``` + +What's happening is that + +- a standalone Stub Runner application got started +- it downloaded the stub with coordinates `com.example:bookstore:0.0.1.RELEASE:stubs` on port `9876` +- it got downloaded from Artifactory running at `http://192.168.0.100:8081/artifactory/libs-release-local` +- after a while Stub Runner will be running on port `8083` +- and the stubs will be running at port `9876` + +On the server side we built a stateful stub. Let's use curl to assert +that the stubs are setup properly. + +```bash +# let's execute the first request (no response is returned) +$ curl -H "Content-Type:application/json" -X POST --data '{ "title" : "Title", "genre" : "Genre", "description" : "Description", "author" : "Author", "publisher" : "Publisher", "pages" : 100, "image_url" : "https://d213dhlpdb53mu.cloudfront.net/assets/pivotal-square-logo-41418bd391196c3022f3cd9f3959b3f6d7764c47873d858583384e759c7db435.svg", "buy_url" : "https://pivotal.io" }' http://localhost:9876/api/books +# Now time for the second request +$ curl -X GET http://localhost:9876/api/books +# You will receive contents of the JSON +``` + +IMPORTANT: If you want use the stubs that you have built locally, on your host, +then you should pass the environment variable `-e STUBRUNNER_STUBS_MODE=LOCAL` and mount +the volume of your local m2 `-v "${HOME}/.m2/:/root/.m2:ro"` diff --git a/docs/src/main/asciidoc/documentation-overview.adoc b/docs/src/main/asciidoc/documentation-overview.adoc index 05741c891d..d22f628f67 100644 --- a/docs/src/main/asciidoc/documentation-overview.adoc +++ b/docs/src/main/asciidoc/documentation-overview.adoc @@ -81,9 +81,7 @@ Need more details about {project-full-name}'s core features? * *Core Features:* <<{project-name}-features.adoc#contract-features-spring-application, SpringApplication>> | -<<{project-name}-features.adoc#contract-features-external-config, External Configuration>> | -<<{project-name}-features.adoc#contract-features-profiles, Profiles>> | -<<{project-name}-features.adoc#contract-features-logging, Logging>> +<<{project-name}-features.adoc#contract-features-external-config, External Configuration>> * *Build tools:* link:maven-project.html[Maven] | link:gradle-project.html[Gradle] | @@ -94,12 +92,22 @@ link:docker-project.html[Docker] == Advanced Topics Finally, we have a few topics for more advanced users: -* *{project-full-name} Applications Deployment:* -<> | -<> -* *Build tool plugins:* -<> | -<> +* *Customizing DSL:* +<> | +<> | +<> | +<> | +<> +* *Customizing WireMock:* +<> | +<> +* *Customizing {project-full-name}:* +<> | +<> | +<> | +<> | +<> | +<> * *Appendix:* <> | <> | diff --git a/docs/src/main/asciidoc/getting-started.adoc b/docs/src/main/asciidoc/getting-started.adoc index 3176d9aa4d..6b369a278f 100644 --- a/docs/src/main/asciidoc/getting-started.adoc +++ b/docs/src/main/asciidoc/getting-started.adoc @@ -1,1139 +1,4 @@ [[getting-started]] = Getting Started include::_attributes.adoc[] - -If you are getting started with {project-full-name}, or "`Spring`" in general, start by reading -this section. It answers the basic "`what?`", "`how?`" and "`why?`" questions. It -includes an introduction to {project-full-name}, along with installation instructions. We then -walk you through building your first {project-full-name} application, discussing some core -principles as we go. - -[[getting-started-introducing-spring-cloud-contract]] -== Introducing Spring Cloud Contract - -Spring Cloud Contract moves TDD to the level of software architecture. It allows to perform consumer, consumer-driven and producer-driven contract testing. - -[[getting-started-introducing-spring-cloud-contract-history]] -=== History - -Before becoming Spring Cloud Contract, this project was called https://github.com/Codearte/accurest[Accurest]. -It was created by https://twitter.com/mgrzejszczak[Marcin Grzejszczak] and https://twitter.com/jkubrynski[Jakub Kubrynski] -from (https://github.com/Codearte[Codearte]). - -The `0.1.0` release took place on 26 Jan 2015 and it became stable with `1.0.0` release on 29 Feb 2016. - -[[getting-started-introducing-spring-cloud-contract-why]] -==== Why would you need it? - -Assume that we have a system consisting of multiple microservices: - -image::images/Deps.png[Microservices Architecture] - -[[getting-started-introducing-spring-cloud-contract-testing-issues]] -==== Testing issues - -If we wanted to test the application in top left corner to determine whether it can -communicate with other services, we could do one of two things: - -- Deploy all microservices and perform end-to-end tests. -- Mock other microservices in unit/integration tests. - -Both have their advantages but also a lot of disadvantages. - -*Deploy all microservices and perform end to end tests* - -Advantages: - -- Simulates production. -- Tests real communication between services. - -Disadvantages: - -- To test one microservice, we have to deploy 6 microservices, a couple of databases, -etc. -- The environment where the tests run is locked for a single suite of tests (nobody else -would be able to run the tests in the meantime). -- They take a long time to run. -- The feedback comes very late in the process. -- They are extremely hard to debug. - -*Mock other microservices in unit/integration tests* - -Advantages: - -- They provide very fast feedback. -- They have no infrastructure requirements. - -Disadvantages: - -- The implementor of the service creates stubs that might have nothing to do with -reality. -- You can go to production with passing tests and failing production. - -To solve the aforementioned issues, Spring Cloud Contract was created. The main idea is to give you very fast feedback, without the need to set up the -whole world of microservices. If you work on stubs, then the only applications you need -are those that your application directly uses. - -image::images/Stubs2.png[Stubbed Services] - -Spring Cloud Contract gives you the certainty that the stubs that you use were -created by the service that you're calling. Also, if you can use them, it means that they -were tested against the producer's side. In short, you can trust those stubs. - -[[getting-started-introducing-spring-cloud-contract-purposes]] -=== Purposes - -The main purposes of Spring Cloud Contract are: - -- To ensure that HTTP / Messaging stubs (used when developing the client) do exactly -what the actual server-side implementation does. -- To promote ATDD (acceptance test driven developement) method and Microservices architectural style. -- To provide a way to publish changes in contracts that are immediately visible on both sides. -- To generate boilerplate test code to be used on the server side. - -By default Spring Cloud Contract integrates with http://wiremock.org[Wiremock] as the HTTP server stub. - -IMPORTANT: Spring Cloud Contract's purpose is NOT to start writing business -features in the contracts. Assume that we have a business use case of fraud check. If a -user can be a fraud for 100 different reasons, we would assume that you would create 2 -contracts, one for the positive case and one for the negative case. Contract tests are -used to test contracts between applications and not to simulate full behavior. - -[[getting-started-what-is-a-contract]] -=== What is a contract? - -As consumers of services, we need to define what exactly we want to achieve. We need to -formulate our expectations. That is why we write contracts. In other words a contract is an agreement on how the API / message communication should look like. Let's look at the following example - -Assume that you want to send a request containing the ID of a client company and the -amount it wants to borrow from us. You also want to send it to the /fraudcheck url via -the PUT method. - -==== -[source,groovy,indent=0,role="primary"] -.groovy ----- -include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[] ----- - -[source,yaml,indent=0,role="secondary"] -.yaml ----- -include::{introduction_url}/samples/standalone/yml/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.yml[] ----- -==== - -[[getting-started-three-second-tour]] -== A Three-second Tour - -This very brief tour walks through using Spring Cloud Contract: - -* <> -* <> - -You can find a somewhat longer tour -<>. - -[plantuml, getting-started-three-second, png] ----- -"API Producer"->"API Producer": add Spring Cloud \nContract (SCC) plugin -"API Producer"->"API Producer": add SCC Verifier dependency -"API Producer"->"API Producer": define contracts -"API Producer"->"Build": run build -"Build"->"SCC Plugin": generate \ntests, stubs and stubs \nartifact (e.g. stubs-jar) -"Build"->"Stub Storage": upload contracts \nand stubs and the project arifact -"Build"->"API Producer": Build successful -"API Consumer"->"API Consumer": add SCC Stub Runner \ndependency -"API Consumer"->"API Consumer": write a SCC Stub Runner \nbased contract test -"SCC Stub Runner"->"Stub Storage": test asks for [API Producer] stubs -"Stub Storage"->"SCC Stub Runner": fetch the [API Producer] stubs -"SCC Stub Runner"->"SCC Stub Runner": run in memory\n HTTP server stubs -"API Consumer"->"SCC Stub Runner": send a request \nto the HTTP server stub -"SCC Stub Runner"->"API Consumer": communication is correct ----- - -[[getting-started-three-second-tour-producer]] -=== On the Producer Side - -To start working with Spring Cloud Contract, add files with `REST`/messaging contracts -expressed in either Groovy DSL or YAML to the contracts directory, which is set by the -`contractsDslDir` property. By default, it is `$rootDir/src/test/resources/contracts`. - -Then add the Spring Cloud Contract Verifier dependency and plugin to your build file, as -shown in the following example: - -[source,xml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] ----- - -The following listing shows how to add the plugin, which should go in the build/plugins -portion of the file: - -[source,xml,indent=0] ----- - - org.springframework.cloud - spring-cloud-contract-maven-plugin - ${spring-cloud-contract.version} - true - ----- - -Running `./mvnw clean install` automatically generates tests that verify the application -compliance with the added contracts. By default, the tests get generated under -`org.springframework.cloud.contract.verifier.tests.`. - -As the implementation of the functionalities described by the contracts is not yet -present, the tests fail. - -To make them pass, you must add the correct implementation of either handling HTTP -requests or messages. Also, you must add a correct base test class for auto-generated -tests to the project. This class is extended by all the auto-generated tests, and it -should contain all the setup necessary to run them (for example `RestAssuredMockMvc` -controller setup or messaging test setup). - -Once the implementation and the test base class are in place, the tests pass, and both the -application and the stub artifacts are built and installed in the local Maven repository. -The changes can now be merged, and both the application and the stub artifacts may be -published in an online repository. - -[[getting-started-three-second-tour-consumer]] -=== On the Consumer Side - -`Spring Cloud Contract Stub Runner` can be used in the integration tests to get a running -WireMock instance or messaging route that simulates the actual service. - -To do so, add the dependency to `Spring Cloud Contract Stub Runner`, as shown in the -following example: - -[source,xml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] ----- - -You can get the Producer-side stubs installed in your Maven repository in either of two -ways: - -* By checking out the Producer side repository and adding contracts and generating the stubs -by running the following commands: -+ -[source,bash,indent=0] ----- -$ cd local-http-server-repo -$ ./mvnw clean install -DskipTests ----- -TIP: The tests are being skipped because the Producer-side contract implementation is not -in place yet, so the automatically-generated contract tests fail. -* By getting already-existing producer service stubs from a remote repository. To do so, -pass the stub artifact IDs and artifact repository URL as `Spring Cloud Contract -Stub Runner` properties, as shown in the following example: -+ -[source,yaml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ----- - -Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, -provide the `group-id` and `artifact-id` values for `Spring Cloud Contract Stub Runner` to -run the collaborators' stubs for you, as shown in the following example: - -[source,java, indent=0] ----- -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment=WebEnvironment.NONE) -@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"}, - stubsMode = StubRunnerProperties.StubsMode.LOCAL) -public class LoanApplicationServiceTests { ----- - -TIP: Use the `REMOTE` `stubsMode` when downloading stubs from an online repository and -`LOCAL` for offline work. - -Now, in your integration test, you can receive stubbed versions of HTTP responses or -messages that are expected to be emitted by the collaborator service. - -[[getting-started-first-application]] -== Developing Your First Spring Cloud Contract based application - -This brief tour walks through using Spring Cloud Contract: - -* <> -* <> - -You can find an even more brief tour -<>. - -For the sake of this example the `Stub Storage` will be Nexus / Artifactory. - -image::getting-started-three-second.png[Getting started first application] - -[[getting-started-first-application-producer]] -=== On the Producer Side - -To start working with `Spring Cloud Contract`, add Spring Cloud Contract Verifier dependency and plugin to your build file, -as shown in the following example: - -[source,xml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] ----- - -The following listing shows how to add the plugin, which should go in the build/plugins -portion of the file: - -[source,xml,indent=0] ----- - - org.springframework.cloud - spring-cloud-contract-maven-plugin - ${spring-cloud-contract.version} - true - ----- - -Now let's add files with `REST/` messaging contracts -expressed in either Groovy DSL or YAML to the contracts directory, which is set by the -`contractsDslDir` property. By default, it is `$rootDir/src/test/resources/contracts`. - -For the HTTP stubs, a contract defines what kind of response should be returned for a -given request (taking into account the HTTP methods, URLs, headers, status codes, and so -on). The following example shows how an HTTP stub contract: - -==== -[source,groovy,indent=0,role="primary"] -.groovy ----- -package contracts - -org.springframework.cloud.contract.spec.Contract.make { - request { - method 'PUT' - url '/fraudcheck' - body([ - "client.id": $(regex('[0-9]{10}')), - loanAmount: 99999 - ]) - headers { - contentType('application/json') - } - } - response { - status OK() - body([ - fraudCheckStatus: "FRAUD", - "rejection.reason": "Amount too high" - ]) - headers { - contentType('application/json') - } - } -} ----- - -[source,yaml,indent=0,role="secondary"] -.yaml ----- -request: - method: PUT - url: /fraudcheck - body: - "client.id": 1234567890 - loanAmount: 99999 - headers: - Content-Type: application/json - matchers: - body: - - path: $.['client.id'] - type: by_regex - value: "[0-9]{10}" -response: - status: 200 - body: - fraudCheckStatus: "FRAUD" - "rejection.reason": "Amount too high" - headers: - Content-Type: application/json;charset=UTF-8 ----- -==== - -In the case of messaging, you can define: - -* The input and the output messages can be defined (taking into account from and where it -was sent, the message body, and the header). -* The methods that should be called after the message is received. -* The methods that, when called, should trigger a message. - -The following example shows a Camel messaging contract: - -==== -[source,groovy,indent=0,role="primary"] -.groovy ----- -include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_no_output_dsl] ----- - -[source,yaml,indent=0,role="secondary"] -.yaml ----- -include::{verifier_core_path}/src/test/resources/yml/contract_message_scenario3.yml[indent=0] ----- -==== - -Running `./mvnw clean install` automatically generates tests that verify the application -compliance with the added contracts. By default, the generated tests are under -`org.springframework.cloud.contract.verifier.tests.`. - -The generated tests will differ, depending on which framework and test type you've setup in your plugin. - -In the samples below you'll find: - -- the default test mode for HTTP contracts via `MockMvc` -- JAX-RS client via the `JAXRS` test mode -- `WebTestClient` based test (this is particularly recommended while working with Reactive, `Web-Flux`-based applications) set via `WEBTESTCLIENT` test mode -- Spock based test via the `testFramework` property set to `SPOCK` - -==== -[source,java,indent=0,role="primary"] -.mockmvc ----- -@Test -public void validate_shouldMarkClientAsFraud() throws Exception { - // given: - MockMvcRequestSpecification request = given() - .header("Content-Type", "application/vnd.fraud.v1+json") - .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}"); - - // when: - ResponseOptions response = given().spec(request) - .put("/fraudcheck"); - - // then: - assertThat(response.statusCode()).isEqualTo(200); - assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*"); - // and: - DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); - assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}"); - assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high"); -} ----- - -[source,java,indent=0,role="secondary"] -.jaxrs ----- -@SuppressWarnings("rawtypes") -public class FooTest { - WebTarget webTarget; - - @Test - public void validate_() throws Exception { - - // when: - Response response = webTarget - .path("/users") - .queryParam("limit", "10") - .queryParam("offset", "20") - .queryParam("filter", "email") - .queryParam("sort", "name") - .queryParam("search", "55") - .queryParam("age", "99") - .queryParam("name", "Denis.Stepanov") - .queryParam("email", "bob@email.com") - .request() - .build("GET") - .invoke(); - String responseAsString = response.readEntity(String.class); - - // then: - assertThat(response.getStatus()).isEqualTo(200); - - // and: - DocumentContext parsedJson = JsonPath.parse(responseAsString); - assertThatJson(parsedJson).field("['property1']").isEqualTo("a"); - } - -} ----- - -[source,java,indent=0,role="secondary"] -.webtestclient ----- -@Test - public void validate_shouldRejectABeerIfTooYoung() throws Exception { - // given: - WebTestClientRequestSpecification request = given() - .header("Content-Type", "application/json") - .body("{\"age\":10}"); - - // when: - WebTestClientResponse response = given().spec(request) - .post("/check"); - - // then: - assertThat(response.statusCode()).isEqualTo(200); - assertThat(response.header("Content-Type")).matches("application/json.*"); - // and: - DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); - assertThatJson(parsedJson).field("['status']").isEqualTo("NOT_OK"); - } ----- - -[source,groovy,indent=0,role="secondary"] -.spock ----- -given: - ContractVerifierMessage inputMessage = contractVerifierMessaging.create( - \'\'\'{"bookName":"foo"}\'\'\', - ['sample': 'header'] - ) - -when: - contractVerifierMessaging.send(inputMessage, 'jms:delete') - -then: - noExceptionThrown() - bookWasDeleted() ----- -==== - -As the implementation of the functionalities described by the contracts is not yet -present, the tests fail. - -To make them pass, you must add the correct implementation of handling either HTTP -requests or messages. Also, you must add a correct base test class for auto-generated -tests to the project. This class is extended by all the auto-generated tests and should -contain all the setup necessary to run them (for example, `RestAssuredMockMvc` controller -setup or messaging test setup). - -Once the implementation and the test base class are in place, the tests pass, and both the -application and the stub artifacts are built and installed in the local Maven repository. -Information about installing the stubs jar to the local repository appears in the logs, as -shown in the following example: - -[source,bash,indent=0] ----- - [INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server --- - [INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar - [INFO] - [INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server --- - [INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar - [INFO] - [INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server --- - [INFO] - [INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server --- - [INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar - [INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom - [INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar ----- - -You can now merge the changes and publish both the application and the stub artifacts -in an online repository. - -[[getting-started-first-application-consumer]] -=== On the Consumer Side - -`Spring Cloud Contract Stub Runner` can be used in the integration tests to get a running -WireMock instance or messaging route that simulates the actual service. - -To get started, add the dependency to `Spring Cloud Contract Stub Runner`: - -[source,xml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] ----- - -You can get the Producer-side stubs installed in your Maven repository in either of two -ways: - -* By checking out the Producer side repository and adding contracts and generating the -stubs by running the following commands: -+ -[source,bash,indent=0] ----- -$ cd local-http-server-repo -$ ./mvnw clean install -DskipTests ----- -NOTE: The tests are skipped because the Producer-side contract implementation is not yet -in place, so the automatically-generated contract tests fail. -* Getting already existing producer service stubs from a remote repository. To do so, -pass the stub artifact IDs and artifact repository URl as `Spring Cloud Contract Stub -Runner` properties, as shown in the following example: -+ -[source,yaml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ----- - -Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, -provide the `group-id` and `artifact-id` for `Spring Cloud Contract Stub Runner` to run -the collaborators' stubs for you, as shown in the following example: - -[source,java, indent=0] ----- -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment=WebEnvironment.NONE) -@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"}, - stubsMode = StubRunnerProperties.StubsMode.LOCAL) -public class LoanApplicationServiceTests { ----- - -TIP: Use the `REMOTE` `stubsMode` when downloading stubs from an online repository and -`LOCAL` for offline work. - -In your integration test, you can receive stubbed versions of HTTP responses or messages -that are expected to be emitted by the collaborator service. You can see entries similar -to the following in the build logs: - -[source,bash,indent=0] ----- -2016-07-19 14:22:25.403 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Desired version is + - will try to resolve the latest version -2016-07-19 14:22:25.438 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved version is 0.0.1-SNAPSHOT -2016-07-19 14:22:25.439 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories [] -2016-07-19 14:22:25.451 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar -2016-07-19 14:22:25.465 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar] -2016-07-19 14:22:25.475 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265] -2016-07-19 14:22:27.737 INFO 41050 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}] ----- - -[[getting-started-cdc]] -== Step-by-step Guide to Consumer Driven Contracts (CDC) with contracts laying on the producer side - -Consider an example of Fraud Detection and the Loan Issuance process. The business -scenario is such that we want to issue loans to people but do not want them to steal from -us. The current implementation of our system grants loans to everybody. - -Assume that `Loan Issuance` is a client to the `Fraud Detection` server. In the current -sprint, we must develop a new feature: if a client wants to borrow too much money, then -we mark the client as a fraud. - -Technical remarks - -* Fraud Detection has an `artifact-id` of `http-server`, -* Loan -Issuance has an artifact-id of `http-client` -* both have a `group-id` of `com.example` -* For the sake of this example the `Stub Storage` will be Nexus / Artifactory - -Social remarks - -* both client and server development teams need to communicate directly and -discuss changes while going through the process -* CDC is all about communication. - -The https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-server[server -side code is available here] and https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-client[the -client code here]. - -TIP: In this case, the producer owns the contracts. Physically, all the contract are -in the producer's repository. - -[[getting-started-cdc-technical-note]] -=== Technical note - -If using the *SNAPSHOT* / *Milestone* / *Release Candidate* versions please add the -following section to your build: - -[source,xml,indent=0,subs="verbatim,attributes",role="primary"] -.Maven ----- -include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=repos,indent=0] ----- - -[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] -.Gradle ----- -include::{introduction_url}/samples/standalone/dsl/http-server/build.gradle[tags=deps_repos,indent=0] ----- - -For simplicity we will use the following acronyms: - -- Loan Issuance - LI - the http client -- Fraud Detection - FD - the http server -- Spring Cloud Contract - SCC - -=== Consumer side (Loan Issuance) - -As a developer of the Loan Issuance service (a consumer of the Fraud Detection server), you might do the following steps: - -. Start doing TDD by writing a test for your feature. -. Write the missing implementation. -. Clone the Fraud Detection service repository locally. -. Define the contract locally in the repo of Fraud Detection service. -. Add the Spring Cloud Contract (SCC) plugin. -. Run the integration tests. -. File a pull request. -. Create an initial implementation. -. Take over the pull request. -. Write the missing implementation. -. Deploy your app. -. Work online. - -Let's start with the Loan Issuance flow: - -[plantuml, getting-started-cdc-client, png] ----- -"Loan\nIssuance"->"Loan\nIssuance": start doing TDD\nby writing a test\nfor your feature -"Loan\nIssuance"->"Loan\nIssuance": write the \nmissing implementation -"Loan\nIssuance"->"Loan\nIssuance": run a test - it fails\ndue to no server running -"Loan\nIssuance"->"Fraud\nDetection\nClone": clone the repository -"Fraud\nDetection\nClone"->"Fraud\nDetection\nClone": add missing dependencies\n& define contracts -"Fraud\nDetection\nClone"->"Fraud\nDetection\nClone": add the SCC plugin -"Fraud\nDetection\nClone"->"FD \nClone Build": install the stubs locally -"FD \nClone Build"->"SCC Plugin \nin FD Clone": generate stubs \nand stubs \nartifact (e.g. stubs-jar) -"SCC Plugin \nin FD Clone"->"FD \nClone Build": stubs and artifacts\ngenerated -"FD \nClone Build"->"Local storage": install the stubs locally -"Local storage"->"FD \nClone Build": stub sucessfully installed -"FD \nClone Build"->"Fraud\nDetection\nClone": build successful -"Loan\nIssuance"->"Loan\nIssuance": add a SCC\nStub Runner\ndependency\nand setup -"Loan\nIssuance"->"LI\nSCC\nStub Runner": start stubs\nof FD from\nlocal storage -"LI\nSCC\nStub Runner"->"Local storage": find stubs of [FD] -"Local storage"->"LI\nSCC\nStub Runner": stubs of [FD] found -"LI\nSCC\nStub Runner"->"FD stub": run stubs of [FD] -"FD stub"->"LI\nSCC\nStub Runner": [FD] stub is running -"LI\nSCC\nStub Runner"->"Loan\nIssuance": stubs running and ready for the test -"Loan\nIssuance"->"Loan\nIssuance": run a test -"Loan\nIssuance"->"FD stub": the test\nsends a request\nto the running stub -"FD stub"->"Loan\nIssuance": stub responds successfuly -"Loan\nIssuance"->"Loan\nIssuance": the test passes successfully -"Loan\nIssuance"->"Fraud\nDetection": send a pull request\nwith the\nsuggested contracts ----- - -*Start doing TDD by writing a test for your feature.* - -[source,groovy,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=client_tdd,indent=0] ----- - -Assume that you have written a test of your new feature. If a loan application for a big -amount is received, the system should reject that loan application with some description. - -*Write the missing implementation.* - -At some point in time, you need to send a request to the Fraud Detection service. Assume -that you need to send the request containing the ID of the client and the amount the -client wants to borrow. You want to send it to the `/fraudcheck` url via the `PUT` method. - -[source,groovy,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-client/src/main/java/com/example/loan/LoanApplicationService.java[tags=client_call_server,indent=0] ----- - -For simplicity, the port of the Fraud Detection service is set to `8080`, and the -application runs on `8090`. - -If you start the test at this point, it breaks, because no service currently runs on port -`8080`. - -*Clone the Fraud Detection service repository locally.* - -You can start by playing around with the server side contract. To do so, you must first -clone it. - -[source,bash,indent=0] ----- -$ git clone https://your-git-server.com/server-side.git local-http-server-repo ----- - -*Define the contract locally in the repo of Fraud Detection service.* - -As a consumer, you need to define what exactly you want to achieve. You need to formulate -your expectations. To do so, write the following contract: - -IMPORTANT: Place the contract under `src/test/resources/contracts/fraud` folder. The `fraud` folder -is important because the producer's test base class name references that folder. - -==== -[source,groovy,indent=0,role="primary"] -.groovy ----- -include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[] ----- - -[source,yaml,indent=0,role="secondary"] -.yaml ----- -include::{introduction_url}/samples/standalone/yml/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.yml[] ----- -==== - -The YML contract is quite straight-forward. However when you take a look at the Contract -written using a statically typed Groovy DSL - you might wonder what the -`value(client(...), server(...))` parts are. By using this notation, Spring Cloud -Contract lets you define parts of a JSON block, a URL, etc., which are dynamic. In case -of an identifier or a timestamp, you need not hardcode a value. You want to allow some -different ranges of values. To enable ranges of values, you can set regular expressions -matching those values for the consumer side. You can provide the body by means of either -a map notation or String with interpolations. -//TODO: Ensure that the links are correct -Consult the <> section for more information. We highly recommend using the map notation! - -TIP: You must understand the map notation in order to set up contracts. Please read the -https://groovy-lang.org/json.html[Groovy docs regarding JSON]. - -The previously shown contract is an agreement between two sides that: - -- if an HTTP request is sent with all of -** a `PUT` method on the `/fraudcheck` endpoint, -** a JSON body with a `client.id` that matches the regular expression `[0-9]{10}` and -`loanAmount` equal to `99999`, -** and a `Content-Type` header with a value of `application/vnd.fraud.v1+json`, -- then an HTTP response is sent to the consumer that -** has status `200`, -** contains a JSON body with the `fraudCheckStatus` field containing a value `FRAUD` and -the `rejectionReason` field having value `Amount too high`, -** and a `Content-Type` header with a value of `application/vnd.fraud.v1+json`. - -Once you are ready to check the API in practice in the integration tests, you need to -install the stubs locally. - -*Add the Spring Cloud Contract Verifier plugin.* - -We can add either a Maven or a Gradle plugin. In this example, you see how to add Maven. -First, add the `Spring Cloud Contract` BOM. - -[source,xml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_bom,indent=0] ----- - -Next, add the `Spring Cloud Contract Verifier` Maven plugin - -[source,xml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0] ----- - -Since the plugin was added, you get the `Spring Cloud Contract Verifier` features which, -from the provided contracts: - -- generate and run tests -- produce and install stubs - -You do not want to generate tests since you, as the consumer, want only to play with the -stubs. You need to skip the test generation and execution. When you execute: - -[source,bash,indent=0] ----- -$ cd local-http-server-repo -$ ./mvnw clean install -DskipTests ----- - -In the logs, you see something like this: - -[source,bash,indent=0] ----- -[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server --- -[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar -[INFO] -[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server --- -[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar -[INFO] -[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server --- -[INFO] -[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server --- -[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar -[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom -[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar ----- - -The following line is extremely important: - -[source,bash,indent=0] ----- -[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar ----- - -It confirms that the stubs of the `http-server` have been installed in the local -repository. - -*Run the integration tests.* - -In order to profit from the Spring Cloud Contract Stub Runner functionality of automatic -stub downloading, you must do the following in your consumer side project (`Loan -Application service`): - -Add the `Spring Cloud Contract` BOM: - -[source,xml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=contract_bom,indent=0] ----- - -Add the dependency to `Spring Cloud Contract Stub Runner`: - -[source,xml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] ----- - -Annotate your test class with `@AutoConfigureStubRunner`. In the annotation, provide the -`group-id` and `artifact-id` for the Stub Runner to download the stubs of your -collaborators. (Optional step) Because you're playing with the collaborators offline, you -can also provide the offline work switch (`StubRunnerProperties.StubsMode.LOCAL`). - -[source,groovy,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=autoconfigure_stubrunner,indent=0] ----- - -Now, when you run your tests, you see something like this: - -[source,bash,indent=0] ----- -2016-07-19 14:22:25.403 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Desired version is + - will try to resolve the latest version -2016-07-19 14:22:25.438 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved version is 0.0.1-SNAPSHOT -2016-07-19 14:22:25.439 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories [] -2016-07-19 14:22:25.451 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar -2016-07-19 14:22:25.465 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar] -2016-07-19 14:22:25.475 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265] -2016-07-19 14:22:27.737 INFO 41050 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}] ----- - -This output means that Stub Runner has found your stubs and started a server for your app -with group id `com.example`, artifact id `http-server` with version `0.0.1-SNAPSHOT` of -the stubs and with `stubs` classifier on port `8080`. - -*File a pull request.* - -What you have done until now is an iterative process. You can play around with the -contract, install it locally, and work on the consumer side until the contract works as -you wish. - -Once you are satisfied with the results and the test passes, publish a pull request to -the server side. Currently, the consumer side work is done. - -=== Producer side (Fraud Detection server) - -As a developer of the Fraud Detection server (a server to the Loan Issuance service) we would like to: - -- take over the pull request -- write the missing implementation -- deploy the application - -Let's look at the Fraud Detection flow: - -[plantuml, getting-started-cdc-server, png] ----- -"Fraud\nDetection"->"Fraud\nDetection": take over the\n pull request -"Fraud\nDetection"->"Fraud\nDetection": setup\nSpring Cloud\nContract plugin -"Fraud\nDetection"->"Fraud\nDetection\nBuild": run the build -"Fraud\nDetection\nBuild"->"SCC Plugin": generate tests\nstubs \nand stubs artifact \n(e.g. stubs-jar) -"SCC Plugin"->"Fraud\nDetection\nBuild": tests and stubs generated -"Fraud\nDetection\nBuild"->"Fraud\nDetection\nBuild": run tests -"Fraud\nDetection\nBuild"->"Fraud\nDetection": generated tests failed! -"Fraud\nDetection"->"Fraud\nDetection": setup\nbase classes\nfor contract tests -"Fraud\nDetection"->"Fraud\nDetection\nBuild": run the build -"Fraud\nDetection\nBuild"->"SCC Plugin": generate tests\nstubs \nand stubs artifact \n(e.g. stubs-jar) -"SCC Plugin"->"Fraud\nDetection\nBuild": tests and stubs generated -"Fraud\nDetection\nBuild"->"Fraud\nDetection\nBuild": run tests -"Fraud\nDetection\nBuild"->"Fraud\nDetection": all the tests passed! -"Fraud\nDetection"->"Fraud\nDetection": commit and push changes -"Fraud\nDetection"->"CI": commit pushed!\nTriggers the build -"CI"->"Stub Storage": build successful,\nupload artifacts ----- - -*Take over the pull request.* - -As a reminder, you can see the initial implementation here: - -[source,java,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=server_api,indent=0] -include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=initial_impl,indent=0] -} ----- - -[source,bash,indent=0] ----- -$ git checkout -b contract-change-pr master -$ git pull https://your-git-server.com/server-side-fork.git contract-change-pr ----- - -You must add the dependencies needed by the autogenerated tests: - -[source,xml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] ----- - -In the configuration of the Maven plugin, pass the `packageWithBaseClasses` property - -[source,xml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0] ----- - -IMPORTANT: This example uses "convention based" naming by setting the -`packageWithBaseClasses` property. Doing so means that the two last packages combine to -make the name of the base test class. In our case, the contracts were placed under -`src/test/resources/contracts/fraud`. Since you do not have two packages starting from -the `contracts` folder, pick only one, which should be `fraud`. Add the `Base` suffix and -capitalize `fraud`. That gives you the `FraudBase` test class name. - -All the generated tests extend that class. Over there, you can set up your Spring Context -or whatever is necessary. In this case, use https://github.com/rest-assured/rest-assured[Rest Assured MVC] to -start the server side `FraudDetectionController`. - -[source,java,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-server/src/test/java/com/example/fraud/FraudBase.java[] ----- - -Now, if you run the `./mvnw clean install`, you get something like this: - -[source,bash,indent=0] ----- -Results : - -Tests in error: - ContractVerifierTest.validate_shouldMarkClientAsFraud:32 » IllegalState Parsed... ----- - -This error occurs because you have a new contract from which a test was generated and it -failed since you have not implemented the feature. The auto-generated test would look -like this: - -[source,java,indent=0] ----- -@Test -public void validate_shouldMarkClientAsFraud() throws Exception { - // given: - MockMvcRequestSpecification request = given() - .header("Content-Type", "application/vnd.fraud.v1+json") - .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}"); - - // when: - ResponseOptions response = given().spec(request) - .put("/fraudcheck"); - - // then: - assertThat(response.statusCode()).isEqualTo(200); - assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*"); - // and: - DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); - assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}"); - assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high"); -} ----- - -If you used the Groovy DSL, you can see, all the `producer()` parts of the Contract that were present in the -`value(consumer(...), producer(...))` blocks got injected into the test. -In case of using YAML, the same applied for the `matchers` sections of the `response`. - -Note that, on the producer side, you are also doing TDD. The expectations are expressed -in the form of a test. This test sends a request to our own application with the URL, -headers, and body defined in the contract. It also is expecting precisely defined values -in the response. In other words, you have the `red` part of `red`, `green`, and -`refactor`. It is time to convert the `red` into the `green`. - -*Write the missing implementation.* - -Because you know the expected input and expected output, you can write the missing -implementation: - -[source,java,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=server_api,indent=0] -include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=new_impl,indent=0] -include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=initial_impl,indent=0] -} ----- - -When you execute `./mvnw clean install` again, the tests pass. Since the `Spring Cloud -Contract Verifier` plugin adds the tests to the `generated-test-sources`, you can -actually run those tests from your IDE. - -*Deploy your app.* - -Once you finish your work, you can deploy your change. First, merge the branch: - -[source,bash,indent=0] ----- -$ git checkout master -$ git merge --no-ff contract-change-pr -$ git push origin master ----- - -Your CI might run something like `./mvnw clean deploy`, which would publish both the -application and the stub artifacts. - -=== Consumer Side (Loan Issuance) Final Step - -As a developer of the Loan Issuance service (a consumer of the Fraud Detection server) we will want to: - -- merge our feature branch to `master` -- switch to online mode of working - - -[plantuml, getting-started-cdc-client, png] ----- -"Loan\nIssuance"->"Loan\nIssuance": merge the\nfeature branch\nto master branch -"Loan\nIssuance"->"Loan\nIssuance": setup SCC Stub Runner\nto fetch stubs\nfrom Stub Storage -"Loan\nIssuance"->"LI\nSCC\nStub Runner": start stubs\nof FD from\nStub Storage -"LI\nSCC\nStub Runner"->"Stub Storage": find stubs of [FD] -"Stub Storage"->"LI\nSCC\nStub Runner": stubs of [FD] found -"LI\nSCC\nStub Runner"->"FD stub": run stubs of [FD] -"FD stub"->"LI\nSCC\nStub Runner": [FD] stub is running -"LI\nSCC\nStub Runner"->"Loan\nIssuance": stubs running and ready for the test -"Loan\nIssuance"->"Loan\nIssuance": run a test -"Loan\nIssuance"->"FD stub": the test\nsends a request\nto the running stub -"FD stub"->"Loan\nIssuance": stub responds successfuly -"Loan\nIssuance"->"Loan\nIssuance": the test passes successfully ----- - -*Merge branch to master.* - -[source,bash,indent=0] ----- -$ git checkout master -$ git merge --no-ff contract-change-pr ----- - -*Work online.* - -Now you can disable the offline work for Spring Cloud Contract Stub Runner and indicate -where the repository with your stubs is located. At this moment the stubs of the server -side are automatically downloaded from Nexus/Artifactory. You can set the value of -`stubsMode` to `REMOTE`. The following code shows an example of -achieving the same thing by changing the properties. - -[source,yaml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ----- - -That's it! - -[[getting-started-whats-next]] -== What to Read Next -Hopefully, this section provided some of the {project-full-name} basics and got you on your way -to writing your own applications. If you are a task-oriented type of developer, you might -want to jump over to https://spring.io and check out some of the -https://spring.io/guides/[getting started] guides that solve specific "`How do I do that -with Spring?`" problems. We also have {project-full-name}-specific -"`<>`" reference documentation. - -Otherwise, the next logical step is to read _<>_. If -you are really impatient, you could also jump ahead and read about -_<>_. - -// TODO: Check if we can link courses -In addition to that you can check out the following videos: - -- "Consumer Driven Contracts and Your Microservice Architecture" by Olga Maciaszek-Sharma and Marcin Grzejszczak - -video::pDkC_00hhvA[youtube,width=640,height=480] - -- "Contract Tests in the Enterprise" by Marcin Grzejszczak - -video::ZyHG-VOzPZg[youtube,width=640,height=480] - -- "Why Contract Tests Matter?" by Marcin Grzejszczak - -video::TvpkZu1e2Dc[youtube,start=6262,width=640,height=480] - -You can find the default project samples at -https://github.com/spring-cloud-samples/spring-cloud-contract-samples[samples]. - -You can find the Spring Cloud Contract workshops https://cloud-samples.spring.io/spring-cloud-contract-samples/[over here]. \ No newline at end of file +include::_getting-started.adoc[] \ No newline at end of file diff --git a/docs/src/main/asciidoc/howto.adoc b/docs/src/main/asciidoc/howto.adoc index bea57644cd..e3e0f1db3c 100644 --- a/docs/src/main/asciidoc/howto.adoc +++ b/docs/src/main/asciidoc/howto.adoc @@ -714,25 +714,247 @@ to store and share Pact definitions. Starting from Spring Cloud Contract 2.0.0 one can fetch Pact files from the Pact Broker to generate tests and stubs. -As a prerequisite the Pact Converter and Pact Stub Downloader -are required. You have to add them via the `spring-cloud-contract-pact` dependency. -You can read more about it in the <> section. - IMPORTANT: Pact follows the Consumer Contract convention. That means that the Consumer creates the Pact definitions first, then shares the files with the Producer. Those expectations are generated from the Consumer's code and can break the Producer if the expectations are not met. +[[how-to-use-pact-broker-pact]] +=== How to work with Pact + +Spring Cloud Contract includes support for https://docs.pact.io/[Pact] representation of +contracts up until v4. Instead of using the DSL, you can use Pact files. In this section, we +present how to add Pact support for your project. Note however that not all functionality is supported. +Starting with v3 you can combine multiple matcher for the same element; +you can use matchers for the body, headers, request and path; and you can use value generators. +Spring Cloud Contract currently only supports multiple matchers that are combined using the AND rule logic. +Next to that the request and path matchers are skipped during the conversion. +When using a date, time or datetime value generator with a given format, +the given format will be skipped and the ISO format will be used. + +[[how-to-use-pact-broker-pact-converter]] +=== Pact Converter + +In order to properly support the Spring Cloud Contract way of doing messaging +with Pact you'll have to provide some additional meta data entries. Below you can find a list of such entries: + +* to define the destination to which a message gets sent, you have to +set +** `metaData` entry in the Pact file +*** with key `sentTo` equal to the destination to which a message is to be sent. +*** E.g. `"metaData": { "sentTo": "activemq:output" }` + +[[how-to-use-pact-broker-pact-contract]] +=== Pact Contract + +Spring Cloud Contract can read the Pact JSON definition out of the box. It's enough to place the file under `src/test/resources/contracts` folder. An example of such a Pact contract can look like this: + +[source,javascript,indent=0] +---- +include::{standalone_pact_path}/pact-http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.json[indent=0] +---- + +[[how-to-use-pact-broker-pact-for-producers]] +=== Pact for Producers + +On the producer side, you must add two additional dependencies to your plugin +configuration. One is the Spring Cloud Contract Pact support, and the other represents +the current Pact version that you use. + +==== +[source,xml,indent=0,subs="verbatim,attributes",role="primary"] +.Maven +---- +include::{standalone_pact_path}/pact-http-server/pom.xml[tags=pact_dependency,indent=0] +---- + +[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] +.Gradle +---- +include::{standalone_pact_path}/pact-http-server/build.gradle[tags=pact_dependency,indent=0] +---- +==== + +When you execute the build of your application, a test and stub will be generated. + +==== +[source,java,indent=0,subs="verbatim,attributes",role="primary"] +.test +---- +@Test + public void validate_shouldMarkClientAsFraud() throws Exception { + // given: + MockMvcRequestSpecification request = given() + .header("Content-Type", "application/vnd.fraud.v1+json") + .body("{\"clientId\":\"1234567890\",\"loanAmount\":99999}"); + + // when: + ResponseOptions response = given().spec(request) + .put("/fraudcheck"); + + // then: + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.header("Content-Type")).matches("application/vnd\\.fraud\\.v1\\+json.*"); + // and: + DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); + assertThatJson(parsedJson).field("['rejectionReason']").isEqualTo("Amount too high"); + // and: + assertThat(parsedJson.read("$.fraudCheckStatus", String.class)).matches("FRAUD"); + } +---- + +[source,json,indent=0,subs="verbatim,attributes",role="secondary"] +.stub +---- +{ + "id" : "996ae5ae-6834-4db6-8fac-358ca187ab62", + "uuid" : "996ae5ae-6834-4db6-8fac-358ca187ab62", + "request" : { + "url" : "/fraudcheck", + "method" : "PUT", + "headers" : { + "Content-Type" : { + "matches" : "application/vnd\\.fraud\\.v1\\+json.*" + } + }, + "bodyPatterns" : [ { + "matchesJsonPath" : "$[?(@.['loanAmount'] = 99999)]" + }, { + "matchesJsonPath" : "$[?(@.clientId =~ /([0-9]{10})/)]" + } ] + }, + "response" : { + "status" : 200, + "body" : "{\"fraudCheckStatus\":\"FRAUD\",\"rejectionReason\":\"Amount too high\"}", + "headers" : { + "Content-Type" : "application/vnd.fraud.v1+json;charset=UTF-8" + }, + "transformers" : [ "response-template" ] + }, +} +---- +==== + +[[how-to-use-pact-broker-pact-consumers]] +=== Pact for Consumers + +On the producer side, you must add two additional dependencies to your project +dependencies. One is the Spring Cloud Contract Pact support, and the other represents the +current Pact version that you use. + +==== +[source,xml,indent=0,subs="verbatim,attributes",role="primary"] +.Maven +---- +include::{standalone_pact_path}/pact-http-client/pom.xml[tags=pact_dependency,indent=0] +---- + +[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] +.Gradle +---- +include::{standalone_pact_path}/pact-http-client/build.gradle[tags=pact_dependency,indent=0] +---- +==== + +[[pact-stub-downloader]] +=== Communicating with the Pact Broker + +Whenever the `repositoryRoot` starts with a Pact protocol +(starts with `pact://`), the stub downloader will try +to fetch the Pact contract definitions from the Pact Broker. +Whatever is set after `pact://` will be parsed as the Pact Broker URL. + +Either via environment variables, system properties, properties set +inside the plugin or contracts repository configuration you can +tweak the downloader's behaviour. Below you can find the list of +properties + +.Pact Stub Downloader properties +|==== +|Name of a property |Default | Description +| +* `pactbroker.host` (plugin prop) + +* `stubrunner.properties.pactbroker.host` (system prop) + +* `STUBRUNNER_PROPERTIES_PACTBROKER_HOST` (env prop) +|Host from URL passed to `repositoryRoot` +|What is the URL of Pact Broker + +| +* `pactbroker.port` (plugin prop) + +* `stubrunner.properties.pactbroker.port` (system prop) + +* `STUBRUNNER_PROPERTIES_PACTBROKER_PORT` (env prop) +|Port from URL passed to `repositoryRoot` +|What is the port of Pact Broker + +| +* `pactbroker.protocol` (plugin prop) + +* `stubrunner.properties.pactbroker.protocol` (system prop) + +* `STUBRUNNER_PROPERTIES_PACTBROKER_PROTOCOL` (env prop) +|Protocol from URL passed to `repositoryRoot` +|What is the protocol of Pact Broker + +| +* `pactbroker.tags` (plugin prop) + +* `stubrunner.properties.pactbroker.tags` (system prop) + +* `STUBRUNNER_PROPERTIES_PACTBROKER_TAGS` (env prop) +|Version of the stub, or `latest` if version is `+` +|What tags should be used to fetch the stub + +| +* `pactbroker.auth.scheme` (plugin prop) + +* `stubrunner.properties.pactbroker.auth.scheme` (system prop) + +* `STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_SCHEME` (env prop) +|`Basic` +|What kind of authentication should be used to connect to the Pact Broker + +| +* `pactbroker.auth.username` (plugin prop) + +* `stubrunner.properties.pactbroker.auth.username` (system prop) + +* `STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_USERNAME` (env prop) +|The username passed to `contractsRepositoryUsername` (maven) or `contractRepository.username` (gradle) +|Username used to connect to the Pact Broker + +| +* `pactbroker.auth.password` (plugin prop) + +* `stubrunner.properties.pactbroker.auth.password` (system prop) + +* `STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_PASSWORD` (env prop) +|The password passed to `contractsRepositoryPassword` (maven) or `contractRepository.password` (gradle) +|Password used to connect to the Pact Broker + +| +* `pactbroker.provider-name-with-group-id` (plugin prop) + +* `stubrunner.properties.pactbroker.provider-name-with-group-id` (system prop) + +* `STUBRUNNER_PROPERTIES_PACTBROKER_PROVIDER_NAME_WITH_GROUP_ID` (env prop) +|false +|When `true`, the provider name will be a combination of `groupId:artifactId`. If `false`, just `artifactId` is used +|==== + [[how-to-pact-consumer]] -=== Pact Consumer +=== Flow: Consumer Contract approach with Pact Broker | Consumer Side The consumer uses Pact framework to generate Pact files. The Pact files are sent to the Pact Broker. An example of such setup can be found https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/consumer_pact[here]. [[how-to-pact-producer]] -=== Producer +=== Flow: Consumer Contract approach with Pact Broker | Producer Side For the producer, to use the Pact files from the Pact Broker, we can reuse the same mechanism we use for external contracts. We route Spring Cloud Contract @@ -816,7 +1038,7 @@ With such a setup: * The JAR with the stubs gets automatically created as usual [[how-to-pact-consumer-producer-contract]] -=== Pact Consumer (Producer Contract approach) +=== Flow: Producer Contract approach with Pact | Consumer Side In the scenario where you don't want to do Consumer Contract approach (for every single consumer define the expectations) but you'd prefer @@ -900,9 +1122,6 @@ With such a setup: * Spring Cloud Contract will convert the Pact files into stub definitions * The stub servers will be started and fed with stubs -For more information about Pact support you can go to -the <> section. - [[how-to-debug]] == How can I debug the request/response being sent by the generated tests client? @@ -1048,4 +1267,43 @@ For example, you might decide to have no dependencies at all. [[how-to-work-with-transitivie-exclude]] === Exclude dependencies on the consumer side -As a consumer, if you add the stub dependency to your classpath, you can explicitly exclude the unwanted dependencies. \ No newline at end of file +As a consumer, if you add the stub dependency to your classpath, you can explicitly exclude the unwanted dependencies. + +[[contract-dsl-rest-docs]] +== Generating Spring REST Docs snippets from the contracts + +When you want to include the requests and responses of your API using Spring REST Docs, +you only need to make some minor changes to your setup if you are using MockMvc and RestAssuredMockMvc. +Simply include the following dependencies if you haven't already. + +==== +[source,xml,indent=0,subs="verbatim,attributes",role="primary"] +.maven +---- +include::{standalone_restdocs_path}/http-server/pom.xml[tags=dependencies,indent=0] +---- + +[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] +.gradle +---- +include::{standalone_restdocs_path}/http-server/build.gradle[tags=dependencies,indent=0] +---- +==== + +Next you need to make some changes to your base class. Below you can find examples for using `WebAppContext` and the standalone option when using RestAssured. + +==== +[source,java,indent=0,subs="verbatim,attributes",role="primary"] +.WebAppContext +---- +include::{standalone_restdocs_path}/http-server/src/test/java/com/example/fraud/FraudBaseWithWebAppSetup.java[tags=base_class,indent=0] +---- + +[source,java,indent=0,subs="verbatim,attributes",role="secondary"] +.Standalone +---- +include::{standalone_restdocs_path}/http-server/src/test/java/com/example/fraud/FraudBaseWithStandaloneSetup.java[tags=base_class,indent=0] +---- +==== + +TIP: You don't need to specify the output directory for the generated snippets since version 1.2.0.RELEASE of Spring REST Docs. \ No newline at end of file diff --git a/docs/src/main/asciidoc/index.htmladoc b/docs/src/main/asciidoc/index.htmladoc index cc009df9f7..eb633d129e 100644 --- a/docs/src/main/asciidoc/index.htmladoc +++ b/docs/src/main/asciidoc/index.htmladoc @@ -11,8 +11,6 @@ The reference documentation consists of the following sections: <> :: About the Documentation, Getting Help, First Steps, and more. <> :: Introducing {project-full-name}, System Requirements, Developing Your First {project-full-name} based Application <> :: {project-full-name} usage examples and workflows -<> :: Profiles, Logging, Security, Caching, Spring Integration, Testing, and more. -<> :: Monitoring, Metrics, Auditing, and more. -<> :: Maven Plugin, Gradle Plugin. -<> :: Application Development, Configuration, Embedded Servers, Data Access, and many more. -<> :: Properties, Metadata, Configuration, Dependencies, and more. +<> :: Profiles, Logging, Security, Caching, Spring Integration, Testing, and more.W +<> :: Maven Plugin, Gradle Plugin, Docker +<> :: Stubs versioning, Pact integration, Debugging, and more. diff --git a/docs/src/main/asciidoc/index.htmlpdfadoc b/docs/src/main/asciidoc/index.htmlpdfadoc index 5e8932ca92..46603b6857 100644 --- a/docs/src/main/asciidoc/index.htmlpdfadoc +++ b/docs/src/main/asciidoc/index.htmlpdfadoc @@ -9,6 +9,4 @@ include::documentation-overview.adoc[leveloffset=+1] include::getting-started.adoc[leveloffset=+1] include::using.adoc[leveloffset=+1] include::project-features.adoc[leveloffset=+1] -include::build-tool-plugins.adoc[leveloffset=+1] -include::howto.adoc[leveloffset=+1] -include::appendix.adoc[leveloffset=+1] \ No newline at end of file +include::howto.adoc[leveloffset=+1] \ No newline at end of file diff --git a/docs/src/main/asciidoc/index.htmlsingleadoc b/docs/src/main/asciidoc/index.htmlsingleadoc index 5e8932ca92..46603b6857 100644 --- a/docs/src/main/asciidoc/index.htmlsingleadoc +++ b/docs/src/main/asciidoc/index.htmlsingleadoc @@ -9,6 +9,4 @@ include::documentation-overview.adoc[leveloffset=+1] include::getting-started.adoc[leveloffset=+1] include::using.adoc[leveloffset=+1] include::project-features.adoc[leveloffset=+1] -include::build-tool-plugins.adoc[leveloffset=+1] -include::howto.adoc[leveloffset=+1] -include::appendix.adoc[leveloffset=+1] \ No newline at end of file +include::howto.adoc[leveloffset=+1] \ No newline at end of file diff --git a/docs/src/main/asciidoc/project-features.adoc b/docs/src/main/asciidoc/project-features.adoc index f5614b1b18..8666a0fff6 100644 --- a/docs/src/main/asciidoc/project-features.adoc +++ b/docs/src/main/asciidoc/project-features.adoc @@ -8,6 +8,24 @@ might want to read the "<>" and "<>" sections, so that you have a good grounding of the basics. +include::_project-features-contract.adoc[] + +include::_project-features-flows.adoc[] + +include::_project-features-messaging.adoc[] + +include::_project-features-stubrunner.adoc[] + +include::_project-features-wiremock.adoc[] + +[[features-build-tools]] +== Build Tools integration + +You can run test generation / stub execution in various ways. The most common ones are + +* link:maven-project.html[Maven] +* link:gradle-project.html[Gradle] +* link:docker-project.html[Docker] [[features-whats-next]] == What to Read Next @@ -16,4 +34,5 @@ If you want to learn more about any of the classes discussed in this section, yo <> section. If you are comfortable with {project-full-name}'s core features, you can continue on and read -about ... +about +_<>_. diff --git a/specs/spring-cloud-contract-spec-java/src/main/java/org/springframework/cloud/contract/spec/internal/RegexCreatingProperty.java b/specs/spring-cloud-contract-spec-java/src/main/java/org/springframework/cloud/contract/spec/internal/RegexCreatingProperty.java index ad098c697d..4bf7e7e900 100644 --- a/specs/spring-cloud-contract-spec-java/src/main/java/org/springframework/cloud/contract/spec/internal/RegexCreatingProperty.java +++ b/specs/spring-cloud-contract-spec-java/src/main/java/org/springframework/cloud/contract/spec/internal/RegexCreatingProperty.java @@ -21,6 +21,7 @@ package org.springframework.cloud.contract.spec.internal; */ interface RegexCreatingProperty { + // tag::regex_creating_props[] T anyAlphaUnicode(); T anyAlphaNumeric(); @@ -62,5 +63,6 @@ interface RegexCreatingProperty { T anyNonEmptyString(); T anyOf(String... values); + // end::regex_creating_props[] } diff --git a/spring-cloud-contract-stub-runner/src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleJUnitTest.java b/spring-cloud-contract-stub-runner/src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleJUnitTest.java index 44fec08967..4c44099a97 100644 --- a/spring-cloud-contract-stub-runner/src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleJUnitTest.java +++ b/spring-cloud-contract-stub-runner/src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleJUnitTest.java @@ -62,7 +62,6 @@ public class StubRunnerRuleJUnitTest { return ""; } } - // end::test[] // tag::test[] @Test @@ -90,6 +89,7 @@ public class StubRunnerRuleJUnitTest { then(httpGet(rule.findStubUrl("fraudDetectionServer").toString() + "/name")) .isEqualTo("fraudDetectionServer"); } + // end::test[] private String httpGet(String url) throws Exception { try (InputStream stream = URI.create(url).toURL().openStream()) { diff --git a/spring-cloud-contract-verifier/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy b/spring-cloud-contract-verifier/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy index dc09c61c8f..01a5d961bd 100644 --- a/spring-cloud-contract-verifier/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy +++ b/spring-cloud-contract-verifier/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy @@ -101,6 +101,22 @@ class ContractHttpDocsSpec extends Specification { } // end::http_dsl[] + org.springframework.cloud.contract.spec.Contract methodDsl = + org.springframework.cloud.contract.spec.Contract.make { + request { + // tag::method[] + method GET() + // end::method[] + url "/foo" + } + + response { + status 200 + } + + priority 1 + } + org.springframework.cloud.contract.spec.Contract request = // tag::request[] org.springframework.cloud.contract.spec.Contract.make { diff --git a/spring-cloud-contract-verifier/src/test/resources/yml/contract.yml b/spring-cloud-contract-verifier/src/test/resources/yml/contract.yml index 1cf282d093..6f1a02c319 100644 --- a/spring-cloud-contract-verifier/src/test/resources/yml/contract.yml +++ b/spring-cloud-contract-verifier/src/test/resources/yml/contract.yml @@ -21,7 +21,7 @@ request: queryParameters: a: b b: c - #tag::query_params[] + #end::query_params[] #tag::headers[] headers: foo: bar diff --git a/tests/spring-cloud-contract-stub-runner-amqp/README.adoc b/tests/spring-cloud-contract-stub-runner-amqp/README.adoc deleted file mode 100644 index 033e4fa094..0000000000 --- a/tests/spring-cloud-contract-stub-runner-amqp/README.adoc +++ /dev/null @@ -1,125 +0,0 @@ -=== Stub Runner Spring AMQP - -Spring Cloud Contract Verifier Stub Runner's messaging module provides an easy way to -integrate with Spring AMQP's Rabbit Template. For the provided artifacts, it -automatically downloads the stubs and registers the required routes. - -The integration tries to work standalone (that is, without interaction with a running -RabbitMQ message broker). It expects a `RabbitTemplate` on the application context and -uses it as a spring boot test named `@SpyBean`. As a result, it can use the mockito spy -functionality to verify and inspect messages sent by the application. - -On the message consumer side, the stub runner considers all `@RabbitListener` annotated -endpoints and all `SimpleMessageListenerContainer` objects on the application context. - -As messages are usually sent to exchanges in AMQP, the message contract contains the -exchange name as the destination. Message listeners on the other side are bound to -queues. Bindings connect an exchange to a queue. If message contracts are triggered, the -Spring AMQP stub runner integration looks for bindings on the application context that -match this exchange. Then it collects the queues from the Spring exchanges and tries to -find message listeners bound to these queues. The message is triggered for all matching -message listeners. - -If you need to work with routing keys, it's enough to pass them via the `amqp_receivedRoutingKey` -messaging header. - -==== Adding the Runner to the Project - -You can have both Spring AMQP and Spring Cloud Contract Stub Runner on the classpath and -set the property `stubrunner.amqp.enabled=true`. Remember to annotate your test class -with `@AutoConfigureStubRunner`. - -IMPORTANT: If you already have Stream and Integration on the classpath, you need -to disable them explicitly by setting the `stubrunner.stream.enabled=false` and -`stubrunner.integration.enabled=false` properties. - -Assume that you have the following Maven repository with a deployed stubs for the -`spring-cloud-contract-amqp-test` application. - -[source,bash,indent=0] ----- -└── .m2 - └── repository - └── com - └── example - └── spring-cloud-contract-amqp-test - ├── 0.4.0-SNAPSHOT - │   ├── spring-cloud-contract-amqp-test-0.4.0-SNAPSHOT.pom - │   ├── spring-cloud-contract-amqp-test-0.4.0-SNAPSHOT-stubs.jar - │   └── maven-metadata-local.xml - └── maven-metadata-local.xml ----- - -Further assume that the stubs contain the following structure: - -[source,bash,indent=0] ----- -├── META-INF -│   └── MANIFEST.MF -└── contracts - └── shouldProduceValidPersonData.groovy ----- - -Consider the following contract: - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpStubRunnerSpec.groovy[tags=amqp_contract,indent=0] ----- - -Now consider the following Spring configuration: - -[source,yaml] ----- -include::src/test/resources/application.yml[] ----- - -===== Triggering the message - -To trigger a message using the contract above, use the `StubTrigger` interface as -follows: - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpStubRunnerSpec.groovy[tags=client_trigger,indent=0] ----- - -The message has a destination of `contract-test.exchange`, so the Spring AMQP stub runner -integration looks for bindings related to this exchange. - -[source,java] ----- -include::src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpMessagingApplication.java[tags=amqp_binding,indent=0] ----- - -The binding definition binds the queue `test.queue`. As a result, the following listener -definition is matched and invoked with the contract message. - -[source,java] ----- -include::src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpMessagingApplication.java[tags=amqp_listener,indent=0] ----- - -Also, the following annotated listener matches and is invoked: -[source,java] ----- -include::src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/MessageSubscriberRabbitListener.java[tags=amqp_annotated_listener,indent=0] ----- - -NOTE: The message is directly handed over to the `onMessage` method of the -`MessageListener` associated with the matching `SimpleMessageListenerContainer`. - -===== Spring AMQP Test Configuration - -In order to avoid Spring AMQP trying to connect to a running broker during our tests -configure a mock `ConnectionFactory`. - -To disable the mocked ConnectionFactory, set the following property: -`stubrunner.amqp.mockConnection=false` - -[source,yaml] ----- -stubrunner: - amqp: - mockConnection: false ----- diff --git a/tests/spring-cloud-contract-stub-runner-camel/README.adoc b/tests/spring-cloud-contract-stub-runner-camel/README.adoc deleted file mode 100644 index 30c50c8e55..0000000000 --- a/tests/spring-cloud-contract-stub-runner-camel/README.adoc +++ /dev/null @@ -1,123 +0,0 @@ -:input_name: jms:input -:output_name: jms:output - -=== Stub Runner Camel - -Spring Cloud Contract Verifier Stub Runner's messaging module gives you an easy way to integrate with Apache Camel. -For the provided artifacts it will automatically download the stubs and register the required -routes. - -==== Adding it to the project - -It's enough to have both Apache Camel and Spring Cloud Contract Stub Runner on classpath. -Remember to annotate your test class with `@AutoConfigureStubRunner`. - -==== Disabling the functionality - -If you need to disable this functionality just pass `stubrunner.camel.enabled=false` property. - -==== Examples - -===== Stubs structure - -Let us assume that we have the following Maven repository with a deployed stubs for the -`camelService` application. - -[source,bash,indent=0] ----- -└── .m2 - └── repository - └── io - └── codearte - └── accurest - └── stubs - └── camelService - ├── 0.0.1-SNAPSHOT - │   ├── camelService-0.0.1-SNAPSHOT.pom - │   ├── camelService-0.0.1-SNAPSHOT-stubs.jar - │   └── maven-metadata-local.xml - └── maven-metadata-local.xml ----- - -And the stubs contain the following structure: - -[source,bash,indent=0] ----- -├── META-INF -│   └── MANIFEST.MF -└── repository - ├── accurest - │   ├── bookDeleted.groovy - │   ├── bookReturned1.groovy - │   └── bookReturned2.groovy - └── mappings ----- - -Let's consider the following contracts (let' number it with *1*): - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=sample_dsl,indent=0] ----- - -and number *2* - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=sample_dsl_2,indent=0] ----- - -===== Scenario 1 (no input message) - -So as to trigger a message via the `return_book_1` label we'll use the `StubTigger` interface as follows - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=client_trigger,indent=0] ----- - -Next we'll want to listen to the output of the message sent to `{output_name}` - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=client_trigger_receive,indent=0] ----- - -And the received message would pass the following assertions - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=client_trigger_message,indent=0] ----- - -===== Scenario 2 (output triggered by input) - -Since the route is set for you it's enough to just send a message to the `{output_name}` destination. - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=client_send,indent=0] ----- - -Next we'll want to listen to the output of the message sent to `{output_name}` - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=client_receive,indent=0] ----- - -And the received message would pass the following assertions - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=client_receive_message,indent=0] ----- - -===== Scenario 3 (input with no output) - -Since the route is set for you it's enough to just send a message to the `{output_name}` destination. - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=trigger_no_output,indent=0] ----- diff --git a/tests/spring-cloud-contract-stub-runner-integration/README.adoc b/tests/spring-cloud-contract-stub-runner-integration/README.adoc deleted file mode 100644 index ccae044b9a..0000000000 --- a/tests/spring-cloud-contract-stub-runner-integration/README.adoc +++ /dev/null @@ -1,138 +0,0 @@ -:input_name: input -:output_name: output - -=== Stub Runner Integration - -Spring Cloud Contract Verifier Stub Runner's messaging module gives you an easy way to -integrate with Spring Integration. For the provided artifacts, it automatically downloads -the stubs and registers the required routes. - -==== Adding the Runner to the Project - -You can have both Spring Integration and Spring Cloud Contract Stub Runner on the -classpath. Remember to annotate your test class with `@AutoConfigureStubRunner`. - -==== Disabling the functionality - -If you need to disable this functionality, set the -`stubrunner.integration.enabled=false` property. - -Assume that you have the following Maven repository with deployed stubs for the -`integrationService` application: - -[source,bash,indent=0] ----- -└── .m2 - └── repository - └── io - └── codearte - └── accurest - └── stubs - └── integrationService - ├── 0.0.1-SNAPSHOT - │   ├── integrationService-0.0.1-SNAPSHOT.pom - │   ├── integrationService-0.0.1-SNAPSHOT-stubs.jar - │   └── maven-metadata-local.xml - └── maven-metadata-local.xml ----- - -Further assume the stubs contain the following structure: - -[source,bash,indent=0] ----- -├── META-INF -│   └── MANIFEST.MF -└── repository - ├── accurest - │   ├── bookDeleted.groovy - │   ├── bookReturned1.groovy - │   └── bookReturned2.groovy - └── mappings ----- - -Consider the following contracts (numbered *1*): - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=sample_dsl,indent=0] ----- - -Now consider *2*: - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=sample_dsl_2,indent=0] ----- - -and the following Spring Integration Route: - -[source,xml] ----- -include::src/test/resources/integration-context.xml[lines=1;18..-1] ----- - -These examples lend themselves to three scenarios: - -* <> -* <> -* <> - -[[integration-scenario-1]] -===== Scenario 1 (no input message) - -To trigger a message via the `return_book_1` label, use the `StubTigger` interface, as -follows: - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_trigger,indent=0] ----- - -To listen to the output of the message sent to `{output_name}`: - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_trigger_receive,indent=0] ----- - -The received message would pass the following assertions: - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_trigger_message,indent=0] ----- - -[[integration-scenario-2]] -===== Scenario 2 (output triggered by input) - -Since the route is set for you, you can send a message to the `{output_name}` -destination: - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_send,indent=0] ----- - -To listen to the output of the message sent to `{output_name}`: - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_receive,indent=0] ----- - -The received message passes the following assertions: - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_receive_message,indent=0] ----- - -[[integration-scenario-3]] -===== Scenario 3 (input with no output) - -Since the route is set for you, you can send a message to the `{input_name}` destination: - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=trigger_no_output,indent=0] ----- diff --git a/tests/spring-cloud-contract-stub-runner-stream/README.adoc b/tests/spring-cloud-contract-stub-runner-stream/README.adoc deleted file mode 100644 index fad7b0ad93..0000000000 --- a/tests/spring-cloud-contract-stub-runner-stream/README.adoc +++ /dev/null @@ -1,160 +0,0 @@ -=== Stub Runner Stream - -Spring Cloud Contract Verifier Stub Runner's messaging module gives you an easy way to -integrate with Spring Stream. For the provided artifacts, it automatically downloads the -stubs and registers the required routes. - -WARNING: If Stub Runner's integration with Stream the `messageFrom` or `sentTo` Strings -are resolved first as a `destination` of a channel and no such `destination` exists, the -destination is resolved as a channel name. - -IMPORTANT: If you want to use Spring Cloud Stream remember, to add a dependency on -`org.springframework.cloud:spring-cloud-stream-test-support`. - -[source,xml,indent=0,subs="verbatim,attributes",role="primary"] -.Maven ----- - - org.springframework.cloud - spring-cloud-stream-test-support - test - ----- - -[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] -.Gradle ----- -testCompile "org.springframework.cloud:spring-cloud-stream-test-support" ----- - -==== Adding the Runner to the Project - -You can have both Spring Cloud Stream and Spring Cloud Contract Stub Runner on the -classpath. Remember to annotate your test class with `@AutoConfigureStubRunner`. - -==== Disabling the functionality - -If you need to disable this functionality, set the `stubrunner.stream.enabled=false` -property. - -Assume that you have the following Maven repository with a deployed stubs for the -`streamService` application: - -[source,bash,indent=0] ----- -└── .m2 - └── repository - └── io - └── codearte - └── accurest - └── stubs - └── streamService - ├── 0.0.1-SNAPSHOT - │   ├── streamService-0.0.1-SNAPSHOT.pom - │   ├── streamService-0.0.1-SNAPSHOT-stubs.jar - │   └── maven-metadata-local.xml - └── maven-metadata-local.xml ----- - -Further assume the stubs contain the following structure: - -[source,bash,indent=0] ----- -├── META-INF -│   └── MANIFEST.MF -└── repository - ├── accurest - │   ├── bookDeleted.groovy - │   ├── bookReturned1.groovy - │   └── bookReturned2.groovy - └── mappings ----- - -Consider the following contracts (numbered *1*): - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=sample_dsl,indent=0] ----- - -Now consider *2*: - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=sample_dsl_2,indent=0] ----- - -Now consider the following Spring configuration: - -[source,yaml] ----- -include::src/test/resources/application.yml[] ----- - -These examples lend themselves to three scenarios: - -* <> -* <> -* <> - -[[stream-scenario-1]] -===== Scenario 1 (no input message) - -To trigger a message via the `return_book_1` label, use the `StubTrigger` interface as -follows: - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_trigger,indent=0] ----- - -To listen to the output of the message sent to a channel whose `destination` is -`returnBook`: - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_trigger_receive,indent=0] ----- - -The received message passes the following assertions: - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_trigger_message,indent=0] ----- - -[[stream-scenario-2]] -===== Scenario 2 (output triggered by input) - -Since the route is set for you, you can send a message to the `bookStorage` -`destination`: - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_send,indent=0] ----- - -To listen to the output of the message sent to `returnBook`: - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_receive,indent=0] ----- - -The received message passes the following assertions: - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_receive_message,indent=0] ----- - -[[stream-scenario-3]] -===== Scenario 3 (input with no output) - -Since the route is set for you, you can send a message to the `{output_name}` -destination: - -[source,groovy] ----- -include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=trigger_no_output,indent=0] ----- From bffe539f4bbfe2e9c7790ba12d1606fd1f28f3c9 Mon Sep 17 00:00:00 2001 From: Marcin Grzejszczak Date: Thu, 25 Jul 2019 14:42:04 +0200 Subject: [PATCH 14/18] Working docs --- docs/src/main/asciidoc/_getting-started.adoc | 1137 ---------------- .../main/asciidoc/documentation-overview.adoc | 4 - docs/src/main/asciidoc/getting-started.adoc | 1139 ++++++++++++++++- 3 files changed, 1138 insertions(+), 1142 deletions(-) delete mode 100644 docs/src/main/asciidoc/_getting-started.adoc diff --git a/docs/src/main/asciidoc/_getting-started.adoc b/docs/src/main/asciidoc/_getting-started.adoc deleted file mode 100644 index 50ed913b7c..0000000000 --- a/docs/src/main/asciidoc/_getting-started.adoc +++ /dev/null @@ -1,1137 +0,0 @@ -include::_attributes.adoc[] - -If you are getting started with {project-full-name}, or "`Spring`" in general, start by reading -this section. It answers the basic "`what?`", "`how?`" and "`why?`" questions. It -includes an introduction to {project-full-name}, along with installation instructions. We then -walk you through building your first {project-full-name} application, discussing some core -principles as we go. - -[[getting-started-introducing-spring-cloud-contract]] -== Introducing Spring Cloud Contract - -Spring Cloud Contract moves TDD to the level of software architecture. It allows to perform consumer, consumer-driven and producer-driven contract testing. - -[[getting-started-introducing-spring-cloud-contract-history]] -=== History - -Before becoming Spring Cloud Contract, this project was called https://github.com/Codearte/accurest[Accurest]. -It was created by https://twitter.com/mgrzejszczak[Marcin Grzejszczak] and https://twitter.com/jkubrynski[Jakub Kubrynski] -from (https://github.com/Codearte[Codearte]). - -The `0.1.0` release took place on 26 Jan 2015 and it became stable with `1.0.0` release on 29 Feb 2016. - -[[getting-started-introducing-spring-cloud-contract-why]] -==== Why would you need it? - -Assume that we have a system consisting of multiple microservices: - -image::images/Deps.png[Microservices Architecture] - -[[getting-started-introducing-spring-cloud-contract-testing-issues]] -==== Testing issues - -If we wanted to test the application in top left corner to determine whether it can -communicate with other services, we could do one of two things: - -- Deploy all microservices and perform end-to-end tests. -- Mock other microservices in unit/integration tests. - -Both have their advantages but also a lot of disadvantages. - -*Deploy all microservices and perform end to end tests* - -Advantages: - -- Simulates production. -- Tests real communication between services. - -Disadvantages: - -- To test one microservice, we have to deploy 6 microservices, a couple of databases, -etc. -- The environment where the tests run is locked for a single suite of tests (nobody else -would be able to run the tests in the meantime). -- They take a long time to run. -- The feedback comes very late in the process. -- They are extremely hard to debug. - -*Mock other microservices in unit/integration tests* - -Advantages: - -- They provide very fast feedback. -- They have no infrastructure requirements. - -Disadvantages: - -- The implementor of the service creates stubs that might have nothing to do with -reality. -- You can go to production with passing tests and failing production. - -To solve the aforementioned issues, Spring Cloud Contract was created. The main idea is to give you very fast feedback, without the need to set up the -whole world of microservices. If you work on stubs, then the only applications you need -are those that your application directly uses. - -image::images/Stubs2.png[Stubbed Services] - -Spring Cloud Contract gives you the certainty that the stubs that you use were -created by the service that you're calling. Also, if you can use them, it means that they -were tested against the producer's side. In short, you can trust those stubs. - -[[getting-started-introducing-spring-cloud-contract-purposes]] -=== Purposes - -The main purposes of Spring Cloud Contract are: - -- To ensure that HTTP / Messaging stubs (used when developing the client) do exactly -what the actual server-side implementation does. -- To promote ATDD (acceptance test driven developement) method and Microservices architectural style. -- To provide a way to publish changes in contracts that are immediately visible on both sides. -- To generate boilerplate test code to be used on the server side. - -By default Spring Cloud Contract integrates with http://wiremock.org[Wiremock] as the HTTP server stub. - -IMPORTANT: Spring Cloud Contract's purpose is NOT to start writing business -features in the contracts. Assume that we have a business use case of fraud check. If a -user can be a fraud for 100 different reasons, we would assume that you would create 2 -contracts, one for the positive case and one for the negative case. Contract tests are -used to test contracts between applications and not to simulate full behavior. - -[[getting-started-what-is-a-contract]] -=== What is a contract? - -As consumers of services, we need to define what exactly we want to achieve. We need to -formulate our expectations. That is why we write contracts. In other words a contract is an agreement on how the API / message communication should look like. Let's look at the following example - -Assume that you want to send a request containing the ID of a client company and the -amount it wants to borrow from us. You also want to send it to the /fraudcheck url via -the PUT method. - -==== -[source,groovy,indent=0,role="primary"] -.groovy ----- -include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[] ----- - -[source,yaml,indent=0,role="secondary"] -.yaml ----- -include::{introduction_url}/samples/standalone/yml/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.yml[] ----- -==== - -[[getting-started-three-second-tour]] -== A Three-second Tour - -This very brief tour walks through using Spring Cloud Contract: - -* <> -* <> - -You can find a somewhat longer tour -<>. - -[plantuml, getting-started-three-second, png] ----- -"API Producer"->"API Producer": add Spring Cloud \nContract (SCC) plugin -"API Producer"->"API Producer": add SCC Verifier dependency -"API Producer"->"API Producer": define contracts -"API Producer"->"Build": run build -"Build"->"SCC Plugin": generate \ntests, stubs and stubs \nartifact (e.g. stubs-jar) -"Build"->"Stub Storage": upload contracts \nand stubs and the project arifact -"Build"->"API Producer": Build successful -"API Consumer"->"API Consumer": add SCC Stub Runner \ndependency -"API Consumer"->"API Consumer": write a SCC Stub Runner \nbased contract test -"SCC Stub Runner"->"Stub Storage": test asks for [API Producer] stubs -"Stub Storage"->"SCC Stub Runner": fetch the [API Producer] stubs -"SCC Stub Runner"->"SCC Stub Runner": run in memory\n HTTP server stubs -"API Consumer"->"SCC Stub Runner": send a request \nto the HTTP server stub -"SCC Stub Runner"->"API Consumer": communication is correct ----- - -[[getting-started-three-second-tour-producer]] -=== On the Producer Side - -To start working with Spring Cloud Contract, add files with `REST`/messaging contracts -expressed in either Groovy DSL or YAML to the contracts directory, which is set by the -`contractsDslDir` property. By default, it is `$rootDir/src/test/resources/contracts`. - -Then add the Spring Cloud Contract Verifier dependency and plugin to your build file, as -shown in the following example: - -[source,xml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] ----- - -The following listing shows how to add the plugin, which should go in the build/plugins -portion of the file: - -[source,xml,indent=0] ----- - - org.springframework.cloud - spring-cloud-contract-maven-plugin - ${spring-cloud-contract.version} - true - ----- - -Running `./mvnw clean install` automatically generates tests that verify the application -compliance with the added contracts. By default, the tests get generated under -`org.springframework.cloud.contract.verifier.tests.`. - -As the implementation of the functionalities described by the contracts is not yet -present, the tests fail. - -To make them pass, you must add the correct implementation of either handling HTTP -requests or messages. Also, you must add a correct base test class for auto-generated -tests to the project. This class is extended by all the auto-generated tests, and it -should contain all the setup necessary to run them (for example `RestAssuredMockMvc` -controller setup or messaging test setup). - -Once the implementation and the test base class are in place, the tests pass, and both the -application and the stub artifacts are built and installed in the local Maven repository. -The changes can now be merged, and both the application and the stub artifacts may be -published in an online repository. - -[[getting-started-three-second-tour-consumer]] -=== On the Consumer Side - -`Spring Cloud Contract Stub Runner` can be used in the integration tests to get a running -WireMock instance or messaging route that simulates the actual service. - -To do so, add the dependency to `Spring Cloud Contract Stub Runner`, as shown in the -following example: - -[source,xml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] ----- - -You can get the Producer-side stubs installed in your Maven repository in either of two -ways: - -* By checking out the Producer side repository and adding contracts and generating the stubs -by running the following commands: -+ -[source,bash,indent=0] ----- -$ cd local-http-server-repo -$ ./mvnw clean install -DskipTests ----- -TIP: The tests are being skipped because the Producer-side contract implementation is not -in place yet, so the automatically-generated contract tests fail. -* By getting already-existing producer service stubs from a remote repository. To do so, -pass the stub artifact IDs and artifact repository URL as `Spring Cloud Contract -Stub Runner` properties, as shown in the following example: -+ -[source,yaml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ----- - -Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, -provide the `group-id` and `artifact-id` values for `Spring Cloud Contract Stub Runner` to -run the collaborators' stubs for you, as shown in the following example: - -[source,java, indent=0] ----- -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment=WebEnvironment.NONE) -@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"}, - stubsMode = StubRunnerProperties.StubsMode.LOCAL) -public class LoanApplicationServiceTests { ----- - -TIP: Use the `REMOTE` `stubsMode` when downloading stubs from an online repository and -`LOCAL` for offline work. - -Now, in your integration test, you can receive stubbed versions of HTTP responses or -messages that are expected to be emitted by the collaborator service. - -[[getting-started-first-application]] -== Developing Your First Spring Cloud Contract based application - -This brief tour walks through using Spring Cloud Contract: - -* <> -* <> - -You can find an even more brief tour -<>. - -For the sake of this example the `Stub Storage` will be Nexus / Artifactory. - -image::getting-started-three-second.png[Getting started first application] - -[[getting-started-first-application-producer]] -=== On the Producer Side - -To start working with `Spring Cloud Contract`, add Spring Cloud Contract Verifier dependency and plugin to your build file, -as shown in the following example: - -[source,xml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] ----- - -The following listing shows how to add the plugin, which should go in the build/plugins -portion of the file: - -[source,xml,indent=0] ----- - - org.springframework.cloud - spring-cloud-contract-maven-plugin - ${spring-cloud-contract.version} - true - ----- - -Now let's add files with `REST/` messaging contracts -expressed in either Groovy DSL or YAML to the contracts directory, which is set by the -`contractsDslDir` property. By default, it is `$rootDir/src/test/resources/contracts`. - -For the HTTP stubs, a contract defines what kind of response should be returned for a -given request (taking into account the HTTP methods, URLs, headers, status codes, and so -on). The following example shows how an HTTP stub contract: - -==== -[source,groovy,indent=0,role="primary"] -.groovy ----- -package contracts - -org.springframework.cloud.contract.spec.Contract.make { - request { - method 'PUT' - url '/fraudcheck' - body([ - "client.id": $(regex('[0-9]{10}')), - loanAmount: 99999 - ]) - headers { - contentType('application/json') - } - } - response { - status OK() - body([ - fraudCheckStatus: "FRAUD", - "rejection.reason": "Amount too high" - ]) - headers { - contentType('application/json') - } - } -} ----- - -[source,yaml,indent=0,role="secondary"] -.yaml ----- -request: - method: PUT - url: /fraudcheck - body: - "client.id": 1234567890 - loanAmount: 99999 - headers: - Content-Type: application/json - matchers: - body: - - path: $.['client.id'] - type: by_regex - value: "[0-9]{10}" -response: - status: 200 - body: - fraudCheckStatus: "FRAUD" - "rejection.reason": "Amount too high" - headers: - Content-Type: application/json;charset=UTF-8 ----- -==== - -In the case of messaging, you can define: - -* The input and the output messages can be defined (taking into account from and where it -was sent, the message body, and the header). -* The methods that should be called after the message is received. -* The methods that, when called, should trigger a message. - -The following example shows a Camel messaging contract: - -==== -[source,groovy,indent=0,role="primary"] -.groovy ----- -include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_no_output_dsl] ----- - -[source,yaml,indent=0,role="secondary"] -.yaml ----- -include::{verifier_core_path}/src/test/resources/yml/contract_message_scenario3.yml[indent=0] ----- -==== - -Running `./mvnw clean install` automatically generates tests that verify the application -compliance with the added contracts. By default, the generated tests are under -`org.springframework.cloud.contract.verifier.tests.`. - -The generated tests will differ, depending on which framework and test type you've setup in your plugin. - -In the samples below you'll find: - -- the default test mode for HTTP contracts via `MockMvc` -- JAX-RS client via the `JAXRS` test mode -- `WebTestClient` based test (this is particularly recommended while working with Reactive, `Web-Flux`-based applications) set via `WEBTESTCLIENT` test mode -- Spock based test via the `testFramework` property set to `SPOCK` - -==== -[source,java,indent=0,role="primary"] -.mockmvc ----- -@Test -public void validate_shouldMarkClientAsFraud() throws Exception { - // given: - MockMvcRequestSpecification request = given() - .header("Content-Type", "application/vnd.fraud.v1+json") - .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}"); - - // when: - ResponseOptions response = given().spec(request) - .put("/fraudcheck"); - - // then: - assertThat(response.statusCode()).isEqualTo(200); - assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*"); - // and: - DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); - assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}"); - assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high"); -} ----- - -[source,java,indent=0,role="secondary"] -.jaxrs ----- -@SuppressWarnings("rawtypes") -public class FooTest { - WebTarget webTarget; - - @Test - public void validate_() throws Exception { - - // when: - Response response = webTarget - .path("/users") - .queryParam("limit", "10") - .queryParam("offset", "20") - .queryParam("filter", "email") - .queryParam("sort", "name") - .queryParam("search", "55") - .queryParam("age", "99") - .queryParam("name", "Denis.Stepanov") - .queryParam("email", "bob@email.com") - .request() - .build("GET") - .invoke(); - String responseAsString = response.readEntity(String.class); - - // then: - assertThat(response.getStatus()).isEqualTo(200); - - // and: - DocumentContext parsedJson = JsonPath.parse(responseAsString); - assertThatJson(parsedJson).field("['property1']").isEqualTo("a"); - } - -} ----- - -[source,java,indent=0,role="secondary"] -.webtestclient ----- -@Test - public void validate_shouldRejectABeerIfTooYoung() throws Exception { - // given: - WebTestClientRequestSpecification request = given() - .header("Content-Type", "application/json") - .body("{\"age\":10}"); - - // when: - WebTestClientResponse response = given().spec(request) - .post("/check"); - - // then: - assertThat(response.statusCode()).isEqualTo(200); - assertThat(response.header("Content-Type")).matches("application/json.*"); - // and: - DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); - assertThatJson(parsedJson).field("['status']").isEqualTo("NOT_OK"); - } ----- - -[source,groovy,indent=0,role="secondary"] -.spock ----- -given: - ContractVerifierMessage inputMessage = contractVerifierMessaging.create( - \'\'\'{"bookName":"foo"}\'\'\', - ['sample': 'header'] - ) - -when: - contractVerifierMessaging.send(inputMessage, 'jms:delete') - -then: - noExceptionThrown() - bookWasDeleted() ----- -==== - -As the implementation of the functionalities described by the contracts is not yet -present, the tests fail. - -To make them pass, you must add the correct implementation of handling either HTTP -requests or messages. Also, you must add a correct base test class for auto-generated -tests to the project. This class is extended by all the auto-generated tests and should -contain all the setup necessary to run them (for example, `RestAssuredMockMvc` controller -setup or messaging test setup). - -Once the implementation and the test base class are in place, the tests pass, and both the -application and the stub artifacts are built and installed in the local Maven repository. -Information about installing the stubs jar to the local repository appears in the logs, as -shown in the following example: - -[source,bash,indent=0] ----- - [INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server --- - [INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar - [INFO] - [INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server --- - [INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar - [INFO] - [INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server --- - [INFO] - [INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server --- - [INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar - [INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom - [INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar ----- - -You can now merge the changes and publish both the application and the stub artifacts -in an online repository. - -[[getting-started-first-application-consumer]] -=== On the Consumer Side - -`Spring Cloud Contract Stub Runner` can be used in the integration tests to get a running -WireMock instance or messaging route that simulates the actual service. - -To get started, add the dependency to `Spring Cloud Contract Stub Runner`: - -[source,xml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] ----- - -You can get the Producer-side stubs installed in your Maven repository in either of two -ways: - -* By checking out the Producer side repository and adding contracts and generating the -stubs by running the following commands: -+ -[source,bash,indent=0] ----- -$ cd local-http-server-repo -$ ./mvnw clean install -DskipTests ----- -NOTE: The tests are skipped because the Producer-side contract implementation is not yet -in place, so the automatically-generated contract tests fail. -* Getting already existing producer service stubs from a remote repository. To do so, -pass the stub artifact IDs and artifact repository URl as `Spring Cloud Contract Stub -Runner` properties, as shown in the following example: -+ -[source,yaml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ----- - -Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, -provide the `group-id` and `artifact-id` for `Spring Cloud Contract Stub Runner` to run -the collaborators' stubs for you, as shown in the following example: - -[source,java, indent=0] ----- -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment=WebEnvironment.NONE) -@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"}, - stubsMode = StubRunnerProperties.StubsMode.LOCAL) -public class LoanApplicationServiceTests { ----- - -TIP: Use the `REMOTE` `stubsMode` when downloading stubs from an online repository and -`LOCAL` for offline work. - -In your integration test, you can receive stubbed versions of HTTP responses or messages -that are expected to be emitted by the collaborator service. You can see entries similar -to the following in the build logs: - -[source,bash,indent=0] ----- -2016-07-19 14:22:25.403 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Desired version is + - will try to resolve the latest version -2016-07-19 14:22:25.438 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved version is 0.0.1-SNAPSHOT -2016-07-19 14:22:25.439 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories [] -2016-07-19 14:22:25.451 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar -2016-07-19 14:22:25.465 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar] -2016-07-19 14:22:25.475 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265] -2016-07-19 14:22:27.737 INFO 41050 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}] ----- - -[[getting-started-cdc]] -== Step-by-step Guide to Consumer Driven Contracts (CDC) with contracts laying on the producer side - -Consider an example of Fraud Detection and the Loan Issuance process. The business -scenario is such that we want to issue loans to people but do not want them to steal from -us. The current implementation of our system grants loans to everybody. - -Assume that `Loan Issuance` is a client to the `Fraud Detection` server. In the current -sprint, we must develop a new feature: if a client wants to borrow too much money, then -we mark the client as a fraud. - -Technical remarks - -* Fraud Detection has an `artifact-id` of `http-server`, -* Loan -Issuance has an artifact-id of `http-client` -* both have a `group-id` of `com.example` -* For the sake of this example the `Stub Storage` will be Nexus / Artifactory - -Social remarks - -* both client and server development teams need to communicate directly and -discuss changes while going through the process -* CDC is all about communication. - -The https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-server[server -side code is available here] and https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-client[the -client code here]. - -TIP: In this case, the producer owns the contracts. Physically, all the contract are -in the producer's repository. - -[[getting-started-cdc-technical-note]] -=== Technical note - -If using the *SNAPSHOT* / *Milestone* / *Release Candidate* versions please add the -following section to your build: - -[source,xml,indent=0,subs="verbatim,attributes",role="primary"] -.Maven ----- -include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=repos,indent=0] ----- - -[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] -.Gradle ----- -include::{introduction_url}/samples/standalone/dsl/http-server/build.gradle[tags=deps_repos,indent=0] ----- - -For simplicity we will use the following acronyms: - -- Loan Issuance - LI - the http client -- Fraud Detection - FD - the http server -- Spring Cloud Contract - SCC - -=== Consumer side (Loan Issuance) - -As a developer of the Loan Issuance service (a consumer of the Fraud Detection server), you might do the following steps: - -. Start doing TDD by writing a test for your feature. -. Write the missing implementation. -. Clone the Fraud Detection service repository locally. -. Define the contract locally in the repo of Fraud Detection service. -. Add the Spring Cloud Contract (SCC) plugin. -. Run the integration tests. -. File a pull request. -. Create an initial implementation. -. Take over the pull request. -. Write the missing implementation. -. Deploy your app. -. Work online. - -Let's start with the Loan Issuance flow: - -[plantuml, getting-started-cdc-client, png] ----- -"Loan\nIssuance"->"Loan\nIssuance": start doing TDD\nby writing a test\nfor your feature -"Loan\nIssuance"->"Loan\nIssuance": write the \nmissing implementation -"Loan\nIssuance"->"Loan\nIssuance": run a test - it fails\ndue to no server running -"Loan\nIssuance"->"Fraud\nDetection\nClone": clone the repository -"Fraud\nDetection\nClone"->"Fraud\nDetection\nClone": add missing dependencies\n& define contracts -"Fraud\nDetection\nClone"->"Fraud\nDetection\nClone": add the SCC plugin -"Fraud\nDetection\nClone"->"FD \nClone Build": install the stubs locally -"FD \nClone Build"->"SCC Plugin \nin FD Clone": generate stubs \nand stubs \nartifact (e.g. stubs-jar) -"SCC Plugin \nin FD Clone"->"FD \nClone Build": stubs and artifacts\ngenerated -"FD \nClone Build"->"Local storage": install the stubs locally -"Local storage"->"FD \nClone Build": stub sucessfully installed -"FD \nClone Build"->"Fraud\nDetection\nClone": build successful -"Loan\nIssuance"->"Loan\nIssuance": add a SCC\nStub Runner\ndependency\nand setup -"Loan\nIssuance"->"LI\nSCC\nStub Runner": start stubs\nof FD from\nlocal storage -"LI\nSCC\nStub Runner"->"Local storage": find stubs of [FD] -"Local storage"->"LI\nSCC\nStub Runner": stubs of [FD] found -"LI\nSCC\nStub Runner"->"FD stub": run stubs of [FD] -"FD stub"->"LI\nSCC\nStub Runner": [FD] stub is running -"LI\nSCC\nStub Runner"->"Loan\nIssuance": stubs running and ready for the test -"Loan\nIssuance"->"Loan\nIssuance": run a test -"Loan\nIssuance"->"FD stub": the test\nsends a request\nto the running stub -"FD stub"->"Loan\nIssuance": stub responds successfuly -"Loan\nIssuance"->"Loan\nIssuance": the test passes successfully -"Loan\nIssuance"->"Fraud\nDetection": send a pull request\nwith the\nsuggested contracts ----- - -*Start doing TDD by writing a test for your feature.* - -[source,groovy,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=client_tdd,indent=0] ----- - -Assume that you have written a test of your new feature. If a loan application for a big -amount is received, the system should reject that loan application with some description. - -*Write the missing implementation.* - -At some point in time, you need to send a request to the Fraud Detection service. Assume -that you need to send the request containing the ID of the client and the amount the -client wants to borrow. You want to send it to the `/fraudcheck` url via the `PUT` method. - -[source,groovy,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-client/src/main/java/com/example/loan/LoanApplicationService.java[tags=client_call_server,indent=0] ----- - -For simplicity, the port of the Fraud Detection service is set to `8080`, and the -application runs on `8090`. - -If you start the test at this point, it breaks, because no service currently runs on port -`8080`. - -*Clone the Fraud Detection service repository locally.* - -You can start by playing around with the server side contract. To do so, you must first -clone it. - -[source,bash,indent=0] ----- -$ git clone https://your-git-server.com/server-side.git local-http-server-repo ----- - -*Define the contract locally in the repo of Fraud Detection service.* - -As a consumer, you need to define what exactly you want to achieve. You need to formulate -your expectations. To do so, write the following contract: - -IMPORTANT: Place the contract under `src/test/resources/contracts/fraud` folder. The `fraud` folder -is important because the producer's test base class name references that folder. - -==== -[source,groovy,indent=0,role="primary"] -.groovy ----- -include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[] ----- - -[source,yaml,indent=0,role="secondary"] -.yaml ----- -include::{introduction_url}/samples/standalone/yml/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.yml[] ----- -==== - -The YML contract is quite straight-forward. However when you take a look at the Contract -written using a statically typed Groovy DSL - you might wonder what the -`value(client(...), server(...))` parts are. By using this notation, Spring Cloud -Contract lets you define parts of a JSON block, a URL, etc., which are dynamic. In case -of an identifier or a timestamp, you need not hardcode a value. You want to allow some -different ranges of values. To enable ranges of values, you can set regular expressions -matching those values for the consumer side. You can provide the body by means of either -a map notation or String with interpolations. -//TODO: Ensure that the links are correct -Consult the <> section for more information. We highly recommend using the map notation! - -TIP: You must understand the map notation in order to set up contracts. Please read the -https://groovy-lang.org/json.html[Groovy docs regarding JSON]. - -The previously shown contract is an agreement between two sides that: - -- if an HTTP request is sent with all of -** a `PUT` method on the `/fraudcheck` endpoint, -** a JSON body with a `client.id` that matches the regular expression `[0-9]{10}` and -`loanAmount` equal to `99999`, -** and a `Content-Type` header with a value of `application/vnd.fraud.v1+json`, -- then an HTTP response is sent to the consumer that -** has status `200`, -** contains a JSON body with the `fraudCheckStatus` field containing a value `FRAUD` and -the `rejectionReason` field having value `Amount too high`, -** and a `Content-Type` header with a value of `application/vnd.fraud.v1+json`. - -Once you are ready to check the API in practice in the integration tests, you need to -install the stubs locally. - -*Add the Spring Cloud Contract Verifier plugin.* - -We can add either a Maven or a Gradle plugin. In this example, you see how to add Maven. -First, add the `Spring Cloud Contract` BOM. - -[source,xml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_bom,indent=0] ----- - -Next, add the `Spring Cloud Contract Verifier` Maven plugin - -[source,xml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0] ----- - -Since the plugin was added, you get the `Spring Cloud Contract Verifier` features which, -from the provided contracts: - -- generate and run tests -- produce and install stubs - -You do not want to generate tests since you, as the consumer, want only to play with the -stubs. You need to skip the test generation and execution. When you execute: - -[source,bash,indent=0] ----- -$ cd local-http-server-repo -$ ./mvnw clean install -DskipTests ----- - -In the logs, you see something like this: - -[source,bash,indent=0] ----- -[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server --- -[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar -[INFO] -[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server --- -[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar -[INFO] -[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server --- -[INFO] -[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server --- -[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar -[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom -[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar ----- - -The following line is extremely important: - -[source,bash,indent=0] ----- -[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar ----- - -It confirms that the stubs of the `http-server` have been installed in the local -repository. - -*Run the integration tests.* - -In order to profit from the Spring Cloud Contract Stub Runner functionality of automatic -stub downloading, you must do the following in your consumer side project (`Loan -Application service`): - -Add the `Spring Cloud Contract` BOM: - -[source,xml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=contract_bom,indent=0] ----- - -Add the dependency to `Spring Cloud Contract Stub Runner`: - -[source,xml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] ----- - -Annotate your test class with `@AutoConfigureStubRunner`. In the annotation, provide the -`group-id` and `artifact-id` for the Stub Runner to download the stubs of your -collaborators. (Optional step) Because you're playing with the collaborators offline, you -can also provide the offline work switch (`StubRunnerProperties.StubsMode.LOCAL`). - -[source,groovy,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=autoconfigure_stubrunner,indent=0] ----- - -Now, when you run your tests, you see something like this: - -[source,bash,indent=0] ----- -2016-07-19 14:22:25.403 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Desired version is + - will try to resolve the latest version -2016-07-19 14:22:25.438 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved version is 0.0.1-SNAPSHOT -2016-07-19 14:22:25.439 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories [] -2016-07-19 14:22:25.451 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar -2016-07-19 14:22:25.465 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar] -2016-07-19 14:22:25.475 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265] -2016-07-19 14:22:27.737 INFO 41050 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}] ----- - -This output means that Stub Runner has found your stubs and started a server for your app -with group id `com.example`, artifact id `http-server` with version `0.0.1-SNAPSHOT` of -the stubs and with `stubs` classifier on port `8080`. - -*File a pull request.* - -What you have done until now is an iterative process. You can play around with the -contract, install it locally, and work on the consumer side until the contract works as -you wish. - -Once you are satisfied with the results and the test passes, publish a pull request to -the server side. Currently, the consumer side work is done. - -=== Producer side (Fraud Detection server) - -As a developer of the Fraud Detection server (a server to the Loan Issuance service) we would like to: - -- take over the pull request -- write the missing implementation -- deploy the application - -Let's look at the Fraud Detection flow: - -[plantuml, getting-started-cdc-server, png] ----- -"Fraud\nDetection"->"Fraud\nDetection": take over the\n pull request -"Fraud\nDetection"->"Fraud\nDetection": setup\nSpring Cloud\nContract plugin -"Fraud\nDetection"->"Fraud\nDetection\nBuild": run the build -"Fraud\nDetection\nBuild"->"SCC Plugin": generate tests\nstubs \nand stubs artifact \n(e.g. stubs-jar) -"SCC Plugin"->"Fraud\nDetection\nBuild": tests and stubs generated -"Fraud\nDetection\nBuild"->"Fraud\nDetection\nBuild": run tests -"Fraud\nDetection\nBuild"->"Fraud\nDetection": generated tests failed! -"Fraud\nDetection"->"Fraud\nDetection": setup\nbase classes\nfor contract tests -"Fraud\nDetection"->"Fraud\nDetection\nBuild": run the build -"Fraud\nDetection\nBuild"->"SCC Plugin": generate tests\nstubs \nand stubs artifact \n(e.g. stubs-jar) -"SCC Plugin"->"Fraud\nDetection\nBuild": tests and stubs generated -"Fraud\nDetection\nBuild"->"Fraud\nDetection\nBuild": run tests -"Fraud\nDetection\nBuild"->"Fraud\nDetection": all the tests passed! -"Fraud\nDetection"->"Fraud\nDetection": commit and push changes -"Fraud\nDetection"->"CI": commit pushed!\nTriggers the build -"CI"->"Stub Storage": build successful,\nupload artifacts ----- - -*Take over the pull request.* - -As a reminder, you can see the initial implementation here: - -[source,java,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=server_api,indent=0] -include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=initial_impl,indent=0] -} ----- - -[source,bash,indent=0] ----- -$ git checkout -b contract-change-pr master -$ git pull https://your-git-server.com/server-side-fork.git contract-change-pr ----- - -You must add the dependencies needed by the autogenerated tests: - -[source,xml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] ----- - -In the configuration of the Maven plugin, pass the `packageWithBaseClasses` property - -[source,xml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0] ----- - -IMPORTANT: This example uses "convention based" naming by setting the -`packageWithBaseClasses` property. Doing so means that the two last packages combine to -make the name of the base test class. In our case, the contracts were placed under -`src/test/resources/contracts/fraud`. Since you do not have two packages starting from -the `contracts` folder, pick only one, which should be `fraud`. Add the `Base` suffix and -capitalize `fraud`. That gives you the `FraudBase` test class name. - -All the generated tests extend that class. Over there, you can set up your Spring Context -or whatever is necessary. In this case, use https://github.com/rest-assured/rest-assured[Rest Assured MVC] to -start the server side `FraudDetectionController`. - -[source,java,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-server/src/test/java/com/example/fraud/FraudBase.java[] ----- - -Now, if you run the `./mvnw clean install`, you get something like this: - -[source,bash,indent=0] ----- -Results : - -Tests in error: - ContractVerifierTest.validate_shouldMarkClientAsFraud:32 » IllegalState Parsed... ----- - -This error occurs because you have a new contract from which a test was generated and it -failed since you have not implemented the feature. The auto-generated test would look -like this: - -[source,java,indent=0] ----- -@Test -public void validate_shouldMarkClientAsFraud() throws Exception { - // given: - MockMvcRequestSpecification request = given() - .header("Content-Type", "application/vnd.fraud.v1+json") - .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}"); - - // when: - ResponseOptions response = given().spec(request) - .put("/fraudcheck"); - - // then: - assertThat(response.statusCode()).isEqualTo(200); - assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*"); - // and: - DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); - assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}"); - assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high"); -} ----- - -If you used the Groovy DSL, you can see, all the `producer()` parts of the Contract that were present in the -`value(consumer(...), producer(...))` blocks got injected into the test. -In case of using YAML, the same applied for the `matchers` sections of the `response`. - -Note that, on the producer side, you are also doing TDD. The expectations are expressed -in the form of a test. This test sends a request to our own application with the URL, -headers, and body defined in the contract. It also is expecting precisely defined values -in the response. In other words, you have the `red` part of `red`, `green`, and -`refactor`. It is time to convert the `red` into the `green`. - -*Write the missing implementation.* - -Because you know the expected input and expected output, you can write the missing -implementation: - -[source,java,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=server_api,indent=0] -include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=new_impl,indent=0] -include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=initial_impl,indent=0] -} ----- - -When you execute `./mvnw clean install` again, the tests pass. Since the `Spring Cloud -Contract Verifier` plugin adds the tests to the `generated-test-sources`, you can -actually run those tests from your IDE. - -*Deploy your app.* - -Once you finish your work, you can deploy your change. First, merge the branch: - -[source,bash,indent=0] ----- -$ git checkout master -$ git merge --no-ff contract-change-pr -$ git push origin master ----- - -Your CI might run something like `./mvnw clean deploy`, which would publish both the -application and the stub artifacts. - -=== Consumer Side (Loan Issuance) Final Step - -As a developer of the Loan Issuance service (a consumer of the Fraud Detection server) we will want to: - -- merge our feature branch to `master` -- switch to online mode of working - - -[plantuml, getting-started-cdc-client, png] ----- -"Loan\nIssuance"->"Loan\nIssuance": merge the\nfeature branch\nto master branch -"Loan\nIssuance"->"Loan\nIssuance": setup SCC Stub Runner\nto fetch stubs\nfrom Stub Storage -"Loan\nIssuance"->"LI\nSCC\nStub Runner": start stubs\nof FD from\nStub Storage -"LI\nSCC\nStub Runner"->"Stub Storage": find stubs of [FD] -"Stub Storage"->"LI\nSCC\nStub Runner": stubs of [FD] found -"LI\nSCC\nStub Runner"->"FD stub": run stubs of [FD] -"FD stub"->"LI\nSCC\nStub Runner": [FD] stub is running -"LI\nSCC\nStub Runner"->"Loan\nIssuance": stubs running and ready for the test -"Loan\nIssuance"->"Loan\nIssuance": run a test -"Loan\nIssuance"->"FD stub": the test\nsends a request\nto the running stub -"FD stub"->"Loan\nIssuance": stub responds successfuly -"Loan\nIssuance"->"Loan\nIssuance": the test passes successfully ----- - -*Merge branch to master.* - -[source,bash,indent=0] ----- -$ git checkout master -$ git merge --no-ff contract-change-pr ----- - -*Work online.* - -Now you can disable the offline work for Spring Cloud Contract Stub Runner and indicate -where the repository with your stubs is located. At this moment the stubs of the server -side are automatically downloaded from Nexus/Artifactory. You can set the value of -`stubsMode` to `REMOTE`. The following code shows an example of -achieving the same thing by changing the properties. - -[source,yaml,indent=0] ----- -include::{introduction_url}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ----- - -That's it! - -[[getting-started-whats-next]] -== What to Read Next -Hopefully, this section provided some of the {project-full-name} basics and got you on your way -to writing your own applications. If you are a task-oriented type of developer, you might -want to jump over to https://spring.io and check out some of the -https://spring.io/guides/[getting started] guides that solve specific "`How do I do that -with Spring?`" problems. We also have {project-full-name}-specific -"`<>`" reference documentation. - -Otherwise, the next logical step is to read _<>_. If -you are really impatient, you could also jump ahead and read about -_<>_. - -// TODO: Check if we can link courses -In addition to that you can check out the following videos: - -- "Consumer Driven Contracts and Your Microservice Architecture" by Olga Maciaszek-Sharma and Marcin Grzejszczak - -video::pDkC_00hhvA[youtube,width=640,height=480] - -- "Contract Tests in the Enterprise" by Marcin Grzejszczak - -video::ZyHG-VOzPZg[youtube,width=640,height=480] - -- "Why Contract Tests Matter?" by Marcin Grzejszczak - -video::TvpkZu1e2Dc[youtube,start=6262,width=640,height=480] - -You can find the default project samples at -https://github.com/spring-cloud-samples/spring-cloud-contract-samples[samples]. - -You can find the Spring Cloud Contract workshops https://cloud-samples.spring.io/spring-cloud-contract-samples/[over here]. \ No newline at end of file diff --git a/docs/src/main/asciidoc/documentation-overview.adoc b/docs/src/main/asciidoc/documentation-overview.adoc index d22f628f67..b70c364876 100644 --- a/docs/src/main/asciidoc/documentation-overview.adoc +++ b/docs/src/main/asciidoc/documentation-overview.adoc @@ -108,8 +108,4 @@ Finally, we have a few topics for more advanced users: <> | <> | <> -* *Appendix:* -<> | -<> | -<> diff --git a/docs/src/main/asciidoc/getting-started.adoc b/docs/src/main/asciidoc/getting-started.adoc index 6b369a278f..ce8d92c0ee 100644 --- a/docs/src/main/asciidoc/getting-started.adoc +++ b/docs/src/main/asciidoc/getting-started.adoc @@ -1,4 +1,1141 @@ [[getting-started]] = Getting Started include::_attributes.adoc[] -include::_getting-started.adoc[] \ No newline at end of file + +include::_attributes.adoc[] + +If you are getting started with {project-full-name}, or "`Spring`" in general, start by reading +this section. It answers the basic "`what?`", "`how?`" and "`why?`" questions. It +includes an introduction to {project-full-name}, along with installation instructions. We then +walk you through building your first {project-full-name} application, discussing some core +principles as we go. + +[[getting-started-introducing-spring-cloud-contract]] +== Introducing Spring Cloud Contract + +Spring Cloud Contract moves TDD to the level of software architecture. It allows to perform consumer, consumer-driven and producer-driven contract testing. + +[[getting-started-introducing-spring-cloud-contract-history]] +=== History + +Before becoming Spring Cloud Contract, this project was called https://github.com/Codearte/accurest[Accurest]. +It was created by https://twitter.com/mgrzejszczak[Marcin Grzejszczak] and https://twitter.com/jkubrynski[Jakub Kubrynski] +from (https://github.com/Codearte[Codearte]). + +The `0.1.0` release took place on 26 Jan 2015 and it became stable with `1.0.0` release on 29 Feb 2016. + +[[getting-started-introducing-spring-cloud-contract-why]] +==== Why would you need it? + +Assume that we have a system consisting of multiple microservices: + +image::images/Deps.png[Microservices Architecture] + +[[getting-started-introducing-spring-cloud-contract-testing-issues]] +==== Testing issues + +If we wanted to test the application in top left corner to determine whether it can +communicate with other services, we could do one of two things: + +- Deploy all microservices and perform end-to-end tests. +- Mock other microservices in unit/integration tests. + +Both have their advantages but also a lot of disadvantages. + +*Deploy all microservices and perform end to end tests* + +Advantages: + +- Simulates production. +- Tests real communication between services. + +Disadvantages: + +- To test one microservice, we have to deploy 6 microservices, a couple of databases, +etc. +- The environment where the tests run is locked for a single suite of tests (nobody else +would be able to run the tests in the meantime). +- They take a long time to run. +- The feedback comes very late in the process. +- They are extremely hard to debug. + +*Mock other microservices in unit/integration tests* + +Advantages: + +- They provide very fast feedback. +- They have no infrastructure requirements. + +Disadvantages: + +- The implementor of the service creates stubs that might have nothing to do with +reality. +- You can go to production with passing tests and failing production. + +To solve the aforementioned issues, Spring Cloud Contract was created. The main idea is to give you very fast feedback, without the need to set up the +whole world of microservices. If you work on stubs, then the only applications you need +are those that your application directly uses. + +image::images/Stubs2.png[Stubbed Services] + +Spring Cloud Contract gives you the certainty that the stubs that you use were +created by the service that you're calling. Also, if you can use them, it means that they +were tested against the producer's side. In short, you can trust those stubs. + +[[getting-started-introducing-spring-cloud-contract-purposes]] +=== Purposes + +The main purposes of Spring Cloud Contract are: + +- To ensure that HTTP / Messaging stubs (used when developing the client) do exactly +what the actual server-side implementation does. +- To promote ATDD (acceptance test driven developement) method and Microservices architectural style. +- To provide a way to publish changes in contracts that are immediately visible on both sides. +- To generate boilerplate test code to be used on the server side. + +By default Spring Cloud Contract integrates with http://wiremock.org[Wiremock] as the HTTP server stub. + +IMPORTANT: Spring Cloud Contract's purpose is NOT to start writing business +features in the contracts. Assume that we have a business use case of fraud check. If a +user can be a fraud for 100 different reasons, we would assume that you would create 2 +contracts, one for the positive case and one for the negative case. Contract tests are +used to test contracts between applications and not to simulate full behavior. + +[[getting-started-what-is-a-contract]] +=== What is a contract? + +As consumers of services, we need to define what exactly we want to achieve. We need to +formulate our expectations. That is why we write contracts. In other words a contract is an agreement on how the API / message communication should look like. Let's look at the following example + +Assume that you want to send a request containing the ID of a client company and the +amount it wants to borrow from us. You also want to send it to the /fraudcheck url via +the PUT method. + +==== +[source,groovy,indent=0,role="primary"] +.groovy +---- +include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[] +---- + +[source,yaml,indent=0,role="secondary"] +.yaml +---- +include::{introduction_url}/samples/standalone/yml/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.yml[] +---- +==== + +[[getting-started-three-second-tour]] +== A Three-second Tour + +This very brief tour walks through using Spring Cloud Contract: + +* <> +* <> + +You can find a somewhat longer tour +<>. + +[plantuml, getting-started-three-second, png] +---- +"API Producer"->"API Producer": add Spring Cloud \nContract (SCC) plugin +"API Producer"->"API Producer": add SCC Verifier dependency +"API Producer"->"API Producer": define contracts +"API Producer"->"Build": run build +"Build"->"SCC Plugin": generate \ntests, stubs and stubs \nartifact (e.g. stubs-jar) +"Build"->"Stub Storage": upload contracts \nand stubs and the project arifact +"Build"->"API Producer": Build successful +"API Consumer"->"API Consumer": add SCC Stub Runner \ndependency +"API Consumer"->"API Consumer": write a SCC Stub Runner \nbased contract test +"SCC Stub Runner"->"Stub Storage": test asks for [API Producer] stubs +"Stub Storage"->"SCC Stub Runner": fetch the [API Producer] stubs +"SCC Stub Runner"->"SCC Stub Runner": run in memory\n HTTP server stubs +"API Consumer"->"SCC Stub Runner": send a request \nto the HTTP server stub +"SCC Stub Runner"->"API Consumer": communication is correct +---- + +[[getting-started-three-second-tour-producer]] +=== On the Producer Side + +To start working with Spring Cloud Contract, add files with `REST`/messaging contracts +expressed in either Groovy DSL or YAML to the contracts directory, which is set by the +`contractsDslDir` property. By default, it is `$rootDir/src/test/resources/contracts`. + +Then add the Spring Cloud Contract Verifier dependency and plugin to your build file, as +shown in the following example: + +[source,xml,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] +---- + +The following listing shows how to add the plugin, which should go in the build/plugins +portion of the file: + +[source,xml,indent=0] +---- + + org.springframework.cloud + spring-cloud-contract-maven-plugin + ${spring-cloud-contract.version} + true + +---- + +Running `./mvnw clean install` automatically generates tests that verify the application +compliance with the added contracts. By default, the tests get generated under +`org.springframework.cloud.contract.verifier.tests.`. + +As the implementation of the functionalities described by the contracts is not yet +present, the tests fail. + +To make them pass, you must add the correct implementation of either handling HTTP +requests or messages. Also, you must add a correct base test class for auto-generated +tests to the project. This class is extended by all the auto-generated tests, and it +should contain all the setup necessary to run them (for example `RestAssuredMockMvc` +controller setup or messaging test setup). + +Once the implementation and the test base class are in place, the tests pass, and both the +application and the stub artifacts are built and installed in the local Maven repository. +The changes can now be merged, and both the application and the stub artifacts may be +published in an online repository. + +[[getting-started-three-second-tour-consumer]] +=== On the Consumer Side + +`Spring Cloud Contract Stub Runner` can be used in the integration tests to get a running +WireMock instance or messaging route that simulates the actual service. + +To do so, add the dependency to `Spring Cloud Contract Stub Runner`, as shown in the +following example: + +[source,xml,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] +---- + +You can get the Producer-side stubs installed in your Maven repository in either of two +ways: + +* By checking out the Producer side repository and adding contracts and generating the stubs +by running the following commands: ++ +[source,bash,indent=0] +---- +$ cd local-http-server-repo +$ ./mvnw clean install -DskipTests +---- +TIP: The tests are being skipped because the Producer-side contract implementation is not +in place yet, so the automatically-generated contract tests fail. +* By getting already-existing producer service stubs from a remote repository. To do so, +pass the stub artifact IDs and artifact repository URL as `Spring Cloud Contract +Stub Runner` properties, as shown in the following example: ++ +[source,yaml,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] +---- + +Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, +provide the `group-id` and `artifact-id` values for `Spring Cloud Contract Stub Runner` to +run the collaborators' stubs for you, as shown in the following example: + +[source,java, indent=0] +---- +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment=WebEnvironment.NONE) +@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"}, + stubsMode = StubRunnerProperties.StubsMode.LOCAL) +public class LoanApplicationServiceTests { +---- + +TIP: Use the `REMOTE` `stubsMode` when downloading stubs from an online repository and +`LOCAL` for offline work. + +Now, in your integration test, you can receive stubbed versions of HTTP responses or +messages that are expected to be emitted by the collaborator service. + +[[getting-started-first-application]] +== Developing Your First Spring Cloud Contract based application + +This brief tour walks through using Spring Cloud Contract: + +* <> +* <> + +You can find an even more brief tour +<>. + +For the sake of this example the `Stub Storage` will be Nexus / Artifactory. + +image::getting-started-three-second.png[Getting started first application] + +[[getting-started-first-application-producer]] +=== On the Producer Side + +To start working with `Spring Cloud Contract`, add Spring Cloud Contract Verifier dependency and plugin to your build file, +as shown in the following example: + +[source,xml,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] +---- + +The following listing shows how to add the plugin, which should go in the build/plugins +portion of the file: + +[source,xml,indent=0] +---- + + org.springframework.cloud + spring-cloud-contract-maven-plugin + ${spring-cloud-contract.version} + true + +---- + +Now let's add files with `REST/` messaging contracts +expressed in either Groovy DSL or YAML to the contracts directory, which is set by the +`contractsDslDir` property. By default, it is `$rootDir/src/test/resources/contracts`. + +For the HTTP stubs, a contract defines what kind of response should be returned for a +given request (taking into account the HTTP methods, URLs, headers, status codes, and so +on). The following example shows how an HTTP stub contract: + +==== +[source,groovy,indent=0,role="primary"] +.groovy +---- +package contracts + +org.springframework.cloud.contract.spec.Contract.make { + request { + method 'PUT' + url '/fraudcheck' + body([ + "client.id": $(regex('[0-9]{10}')), + loanAmount: 99999 + ]) + headers { + contentType('application/json') + } + } + response { + status OK() + body([ + fraudCheckStatus: "FRAUD", + "rejection.reason": "Amount too high" + ]) + headers { + contentType('application/json') + } + } +} +---- + +[source,yaml,indent=0,role="secondary"] +.yaml +---- +request: + method: PUT + url: /fraudcheck + body: + "client.id": 1234567890 + loanAmount: 99999 + headers: + Content-Type: application/json + matchers: + body: + - path: $.['client.id'] + type: by_regex + value: "[0-9]{10}" +response: + status: 200 + body: + fraudCheckStatus: "FRAUD" + "rejection.reason": "Amount too high" + headers: + Content-Type: application/json;charset=UTF-8 +---- +==== + +In the case of messaging, you can define: + +* The input and the output messages can be defined (taking into account from and where it +was sent, the message body, and the header). +* The methods that should be called after the message is received. +* The methods that, when called, should trigger a message. + +The following example shows a Camel messaging contract: + +==== +[source,groovy,indent=0,role="primary"] +.groovy +---- +include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_no_output_dsl] +---- + +[source,yaml,indent=0,role="secondary"] +.yaml +---- +include::{verifier_core_path}/src/test/resources/yml/contract_message_scenario3.yml[indent=0] +---- +==== + +Running `./mvnw clean install` automatically generates tests that verify the application +compliance with the added contracts. By default, the generated tests are under +`org.springframework.cloud.contract.verifier.tests.`. + +The generated tests will differ, depending on which framework and test type you've setup in your plugin. + +In the samples below you'll find: + +- the default test mode for HTTP contracts via `MockMvc` +- JAX-RS client via the `JAXRS` test mode +- `WebTestClient` based test (this is particularly recommended while working with Reactive, `Web-Flux`-based applications) set via `WEBTESTCLIENT` test mode +- Spock based test via the `testFramework` property set to `SPOCK` + +==== +[source,java,indent=0,role="primary"] +.mockmvc +---- +@Test +public void validate_shouldMarkClientAsFraud() throws Exception { + // given: + MockMvcRequestSpecification request = given() + .header("Content-Type", "application/vnd.fraud.v1+json") + .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}"); + + // when: + ResponseOptions response = given().spec(request) + .put("/fraudcheck"); + + // then: + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*"); + // and: + DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); + assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}"); + assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high"); +} +---- + +[source,java,indent=0,role="secondary"] +.jaxrs +---- +@SuppressWarnings("rawtypes") +public class FooTest { + WebTarget webTarget; + + @Test + public void validate_() throws Exception { + + // when: + Response response = webTarget + .path("/users") + .queryParam("limit", "10") + .queryParam("offset", "20") + .queryParam("filter", "email") + .queryParam("sort", "name") + .queryParam("search", "55") + .queryParam("age", "99") + .queryParam("name", "Denis.Stepanov") + .queryParam("email", "bob@email.com") + .request() + .build("GET") + .invoke(); + String responseAsString = response.readEntity(String.class); + + // then: + assertThat(response.getStatus()).isEqualTo(200); + + // and: + DocumentContext parsedJson = JsonPath.parse(responseAsString); + assertThatJson(parsedJson).field("['property1']").isEqualTo("a"); + } + +} +---- + +[source,java,indent=0,role="secondary"] +.webtestclient +---- +@Test + public void validate_shouldRejectABeerIfTooYoung() throws Exception { + // given: + WebTestClientRequestSpecification request = given() + .header("Content-Type", "application/json") + .body("{\"age\":10}"); + + // when: + WebTestClientResponse response = given().spec(request) + .post("/check"); + + // then: + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.header("Content-Type")).matches("application/json.*"); + // and: + DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); + assertThatJson(parsedJson).field("['status']").isEqualTo("NOT_OK"); + } +---- + +[source,groovy,indent=0,role="secondary"] +.spock +---- +given: + ContractVerifierMessage inputMessage = contractVerifierMessaging.create( + \'\'\'{"bookName":"foo"}\'\'\', + ['sample': 'header'] + ) + +when: + contractVerifierMessaging.send(inputMessage, 'jms:delete') + +then: + noExceptionThrown() + bookWasDeleted() +---- +==== + +As the implementation of the functionalities described by the contracts is not yet +present, the tests fail. + +To make them pass, you must add the correct implementation of handling either HTTP +requests or messages. Also, you must add a correct base test class for auto-generated +tests to the project. This class is extended by all the auto-generated tests and should +contain all the setup necessary to run them (for example, `RestAssuredMockMvc` controller +setup or messaging test setup). + +Once the implementation and the test base class are in place, the tests pass, and both the +application and the stub artifacts are built and installed in the local Maven repository. +Information about installing the stubs jar to the local repository appears in the logs, as +shown in the following example: + +[source,bash,indent=0] +---- + [INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server --- + [INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar + [INFO] + [INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server --- + [INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar + [INFO] + [INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server --- + [INFO] + [INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server --- + [INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar + [INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom + [INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar +---- + +You can now merge the changes and publish both the application and the stub artifacts +in an online repository. + +[[getting-started-first-application-consumer]] +=== On the Consumer Side + +`Spring Cloud Contract Stub Runner` can be used in the integration tests to get a running +WireMock instance or messaging route that simulates the actual service. + +To get started, add the dependency to `Spring Cloud Contract Stub Runner`: + +[source,xml,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] +---- + +You can get the Producer-side stubs installed in your Maven repository in either of two +ways: + +* By checking out the Producer side repository and adding contracts and generating the +stubs by running the following commands: ++ +[source,bash,indent=0] +---- +$ cd local-http-server-repo +$ ./mvnw clean install -DskipTests +---- +NOTE: The tests are skipped because the Producer-side contract implementation is not yet +in place, so the automatically-generated contract tests fail. +* Getting already existing producer service stubs from a remote repository. To do so, +pass the stub artifact IDs and artifact repository URl as `Spring Cloud Contract Stub +Runner` properties, as shown in the following example: ++ +[source,yaml,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] +---- + +Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, +provide the `group-id` and `artifact-id` for `Spring Cloud Contract Stub Runner` to run +the collaborators' stubs for you, as shown in the following example: + +[source,java, indent=0] +---- +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment=WebEnvironment.NONE) +@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"}, + stubsMode = StubRunnerProperties.StubsMode.LOCAL) +public class LoanApplicationServiceTests { +---- + +TIP: Use the `REMOTE` `stubsMode` when downloading stubs from an online repository and +`LOCAL` for offline work. + +In your integration test, you can receive stubbed versions of HTTP responses or messages +that are expected to be emitted by the collaborator service. You can see entries similar +to the following in the build logs: + +[source,bash,indent=0] +---- +2016-07-19 14:22:25.403 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Desired version is + - will try to resolve the latest version +2016-07-19 14:22:25.438 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved version is 0.0.1-SNAPSHOT +2016-07-19 14:22:25.439 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories [] +2016-07-19 14:22:25.451 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar +2016-07-19 14:22:25.465 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar] +2016-07-19 14:22:25.475 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265] +2016-07-19 14:22:27.737 INFO 41050 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}] +---- + +[[getting-started-cdc]] +== Step-by-step Guide to Consumer Driven Contracts (CDC) with contracts laying on the producer side + +Consider an example of Fraud Detection and the Loan Issuance process. The business +scenario is such that we want to issue loans to people but do not want them to steal from +us. The current implementation of our system grants loans to everybody. + +Assume that `Loan Issuance` is a client to the `Fraud Detection` server. In the current +sprint, we must develop a new feature: if a client wants to borrow too much money, then +we mark the client as a fraud. + +Technical remarks + +* Fraud Detection has an `artifact-id` of `http-server`, +* Loan +Issuance has an artifact-id of `http-client` +* both have a `group-id` of `com.example` +* For the sake of this example the `Stub Storage` will be Nexus / Artifactory + +Social remarks + +* both client and server development teams need to communicate directly and +discuss changes while going through the process +* CDC is all about communication. + +The https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-server[server +side code is available here] and https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-client[the +client code here]. + +TIP: In this case, the producer owns the contracts. Physically, all the contract are +in the producer's repository. + +[[getting-started-cdc-technical-note]] +=== Technical note + +If using the *SNAPSHOT* / *Milestone* / *Release Candidate* versions please add the +following section to your build: + +[source,xml,indent=0,subs="verbatim,attributes",role="primary"] +.Maven +---- +include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=repos,indent=0] +---- + +[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] +.Gradle +---- +include::{introduction_url}/samples/standalone/dsl/http-server/build.gradle[tags=deps_repos,indent=0] +---- + +For simplicity we will use the following acronyms: + +- Loan Issuance - LI - the http client +- Fraud Detection - FD - the http server +- Spring Cloud Contract - SCC + +=== Consumer side (Loan Issuance) + +As a developer of the Loan Issuance service (a consumer of the Fraud Detection server), you might do the following steps: + +. Start doing TDD by writing a test for your feature. +. Write the missing implementation. +. Clone the Fraud Detection service repository locally. +. Define the contract locally in the repo of Fraud Detection service. +. Add the Spring Cloud Contract (SCC) plugin. +. Run the integration tests. +. File a pull request. +. Create an initial implementation. +. Take over the pull request. +. Write the missing implementation. +. Deploy your app. +. Work online. + +Let's start with the Loan Issuance flow: + +[plantuml, getting-started-cdc-client, png] +---- +"Loan\nIssuance"->"Loan\nIssuance": start doing TDD\nby writing a test\nfor your feature +"Loan\nIssuance"->"Loan\nIssuance": write the \nmissing implementation +"Loan\nIssuance"->"Loan\nIssuance": run a test - it fails\ndue to no server running +"Loan\nIssuance"->"Fraud\nDetection\nClone": clone the repository +"Fraud\nDetection\nClone"->"Fraud\nDetection\nClone": add missing dependencies\n& define contracts +"Fraud\nDetection\nClone"->"Fraud\nDetection\nClone": add the SCC plugin +"Fraud\nDetection\nClone"->"FD \nClone Build": install the stubs locally +"FD \nClone Build"->"SCC Plugin \nin FD Clone": generate stubs \nand stubs \nartifact (e.g. stubs-jar) +"SCC Plugin \nin FD Clone"->"FD \nClone Build": stubs and artifacts\ngenerated +"FD \nClone Build"->"Local storage": install the stubs locally +"Local storage"->"FD \nClone Build": stub sucessfully installed +"FD \nClone Build"->"Fraud\nDetection\nClone": build successful +"Loan\nIssuance"->"Loan\nIssuance": add a SCC\nStub Runner\ndependency\nand setup +"Loan\nIssuance"->"LI\nSCC\nStub Runner": start stubs\nof FD from\nlocal storage +"LI\nSCC\nStub Runner"->"Local storage": find stubs of [FD] +"Local storage"->"LI\nSCC\nStub Runner": stubs of [FD] found +"LI\nSCC\nStub Runner"->"FD stub": run stubs of [FD] +"FD stub"->"LI\nSCC\nStub Runner": [FD] stub is running +"LI\nSCC\nStub Runner"->"Loan\nIssuance": stubs running and ready for the test +"Loan\nIssuance"->"Loan\nIssuance": run a test +"Loan\nIssuance"->"FD stub": the test\nsends a request\nto the running stub +"FD stub"->"Loan\nIssuance": stub responds successfuly +"Loan\nIssuance"->"Loan\nIssuance": the test passes successfully +"Loan\nIssuance"->"Fraud\nDetection": send a pull request\nwith the\nsuggested contracts +---- + +*Start doing TDD by writing a test for your feature.* + +[source,groovy,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=client_tdd,indent=0] +---- + +Assume that you have written a test of your new feature. If a loan application for a big +amount is received, the system should reject that loan application with some description. + +*Write the missing implementation.* + +At some point in time, you need to send a request to the Fraud Detection service. Assume +that you need to send the request containing the ID of the client and the amount the +client wants to borrow. You want to send it to the `/fraudcheck` url via the `PUT` method. + +[source,groovy,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-client/src/main/java/com/example/loan/LoanApplicationService.java[tags=client_call_server,indent=0] +---- + +For simplicity, the port of the Fraud Detection service is set to `8080`, and the +application runs on `8090`. + +If you start the test at this point, it breaks, because no service currently runs on port +`8080`. + +*Clone the Fraud Detection service repository locally.* + +You can start by playing around with the server side contract. To do so, you must first +clone it. + +[source,bash,indent=0] +---- +$ git clone https://your-git-server.com/server-side.git local-http-server-repo +---- + +*Define the contract locally in the repo of Fraud Detection service.* + +As a consumer, you need to define what exactly you want to achieve. You need to formulate +your expectations. To do so, write the following contract: + +IMPORTANT: Place the contract under `src/test/resources/contracts/fraud` folder. The `fraud` folder +is important because the producer's test base class name references that folder. + +==== +[source,groovy,indent=0,role="primary"] +.groovy +---- +include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[] +---- + +[source,yaml,indent=0,role="secondary"] +.yaml +---- +include::{introduction_url}/samples/standalone/yml/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.yml[] +---- +==== + +The YML contract is quite straight-forward. However when you take a look at the Contract +written using a statically typed Groovy DSL - you might wonder what the +`value(client(...), server(...))` parts are. By using this notation, Spring Cloud +Contract lets you define parts of a JSON block, a URL, etc., which are dynamic. In case +of an identifier or a timestamp, you need not hardcode a value. You want to allow some +different ranges of values. To enable ranges of values, you can set regular expressions +matching those values for the consumer side. You can provide the body by means of either +a map notation or String with interpolations. +//TODO: Ensure that the links are correct +Consult the <> section for more information. We highly recommend using the map notation! + +TIP: You must understand the map notation in order to set up contracts. Please read the +https://groovy-lang.org/json.html[Groovy docs regarding JSON]. + +The previously shown contract is an agreement between two sides that: + +- if an HTTP request is sent with all of +** a `PUT` method on the `/fraudcheck` endpoint, +** a JSON body with a `client.id` that matches the regular expression `[0-9]{10}` and +`loanAmount` equal to `99999`, +** and a `Content-Type` header with a value of `application/vnd.fraud.v1+json`, +- then an HTTP response is sent to the consumer that +** has status `200`, +** contains a JSON body with the `fraudCheckStatus` field containing a value `FRAUD` and +the `rejectionReason` field having value `Amount too high`, +** and a `Content-Type` header with a value of `application/vnd.fraud.v1+json`. + +Once you are ready to check the API in practice in the integration tests, you need to +install the stubs locally. + +*Add the Spring Cloud Contract Verifier plugin.* + +We can add either a Maven or a Gradle plugin. In this example, you see how to add Maven. +First, add the `Spring Cloud Contract` BOM. + +[source,xml,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_bom,indent=0] +---- + +Next, add the `Spring Cloud Contract Verifier` Maven plugin + +[source,xml,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0] +---- + +Since the plugin was added, you get the `Spring Cloud Contract Verifier` features which, +from the provided contracts: + +- generate and run tests +- produce and install stubs + +You do not want to generate tests since you, as the consumer, want only to play with the +stubs. You need to skip the test generation and execution. When you execute: + +[source,bash,indent=0] +---- +$ cd local-http-server-repo +$ ./mvnw clean install -DskipTests +---- + +In the logs, you see something like this: + +[source,bash,indent=0] +---- +[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server --- +[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar +[INFO] +[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server --- +[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar +[INFO] +[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server --- +[INFO] +[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server --- +[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar +[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom +[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar +---- + +The following line is extremely important: + +[source,bash,indent=0] +---- +[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar +---- + +It confirms that the stubs of the `http-server` have been installed in the local +repository. + +*Run the integration tests.* + +In order to profit from the Spring Cloud Contract Stub Runner functionality of automatic +stub downloading, you must do the following in your consumer side project (`Loan +Application service`): + +Add the `Spring Cloud Contract` BOM: + +[source,xml,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=contract_bom,indent=0] +---- + +Add the dependency to `Spring Cloud Contract Stub Runner`: + +[source,xml,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] +---- + +Annotate your test class with `@AutoConfigureStubRunner`. In the annotation, provide the +`group-id` and `artifact-id` for the Stub Runner to download the stubs of your +collaborators. (Optional step) Because you're playing with the collaborators offline, you +can also provide the offline work switch (`StubRunnerProperties.StubsMode.LOCAL`). + +[source,groovy,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=autoconfigure_stubrunner,indent=0] +---- + +Now, when you run your tests, you see something like this: + +[source,bash,indent=0] +---- +2016-07-19 14:22:25.403 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Desired version is + - will try to resolve the latest version +2016-07-19 14:22:25.438 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved version is 0.0.1-SNAPSHOT +2016-07-19 14:22:25.439 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories [] +2016-07-19 14:22:25.451 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar +2016-07-19 14:22:25.465 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar] +2016-07-19 14:22:25.475 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265] +2016-07-19 14:22:27.737 INFO 41050 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}] +---- + +This output means that Stub Runner has found your stubs and started a server for your app +with group id `com.example`, artifact id `http-server` with version `0.0.1-SNAPSHOT` of +the stubs and with `stubs` classifier on port `8080`. + +*File a pull request.* + +What you have done until now is an iterative process. You can play around with the +contract, install it locally, and work on the consumer side until the contract works as +you wish. + +Once you are satisfied with the results and the test passes, publish a pull request to +the server side. Currently, the consumer side work is done. + +=== Producer side (Fraud Detection server) + +As a developer of the Fraud Detection server (a server to the Loan Issuance service) we would like to: + +- take over the pull request +- write the missing implementation +- deploy the application + +Let's look at the Fraud Detection flow: + +[plantuml, getting-started-cdc-server, png] +---- +"Fraud\nDetection"->"Fraud\nDetection": take over the\n pull request +"Fraud\nDetection"->"Fraud\nDetection": setup\nSpring Cloud\nContract plugin +"Fraud\nDetection"->"Fraud\nDetection\nBuild": run the build +"Fraud\nDetection\nBuild"->"SCC Plugin": generate tests\nstubs \nand stubs artifact \n(e.g. stubs-jar) +"SCC Plugin"->"Fraud\nDetection\nBuild": tests and stubs generated +"Fraud\nDetection\nBuild"->"Fraud\nDetection\nBuild": run tests +"Fraud\nDetection\nBuild"->"Fraud\nDetection": generated tests failed! +"Fraud\nDetection"->"Fraud\nDetection": setup\nbase classes\nfor contract tests +"Fraud\nDetection"->"Fraud\nDetection\nBuild": run the build +"Fraud\nDetection\nBuild"->"SCC Plugin": generate tests\nstubs \nand stubs artifact \n(e.g. stubs-jar) +"SCC Plugin"->"Fraud\nDetection\nBuild": tests and stubs generated +"Fraud\nDetection\nBuild"->"Fraud\nDetection\nBuild": run tests +"Fraud\nDetection\nBuild"->"Fraud\nDetection": all the tests passed! +"Fraud\nDetection"->"Fraud\nDetection": commit and push changes +"Fraud\nDetection"->"CI": commit pushed!\nTriggers the build +"CI"->"Stub Storage": build successful,\nupload artifacts +---- + +*Take over the pull request.* + +As a reminder, you can see the initial implementation here: + +[source,java,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=server_api,indent=0] +include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=initial_impl,indent=0] +} +---- + +[source,bash,indent=0] +---- +$ git checkout -b contract-change-pr master +$ git pull https://your-git-server.com/server-side-fork.git contract-change-pr +---- + +You must add the dependencies needed by the autogenerated tests: + +[source,xml,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] +---- + +In the configuration of the Maven plugin, pass the `packageWithBaseClasses` property + +[source,xml,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0] +---- + +IMPORTANT: This example uses "convention based" naming by setting the +`packageWithBaseClasses` property. Doing so means that the two last packages combine to +make the name of the base test class. In our case, the contracts were placed under +`src/test/resources/contracts/fraud`. Since you do not have two packages starting from +the `contracts` folder, pick only one, which should be `fraud`. Add the `Base` suffix and +capitalize `fraud`. That gives you the `FraudBase` test class name. + +All the generated tests extend that class. Over there, you can set up your Spring Context +or whatever is necessary. In this case, use https://github.com/rest-assured/rest-assured[Rest Assured MVC] to +start the server side `FraudDetectionController`. + +[source,java,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-server/src/test/java/com/example/fraud/FraudBase.java[] +---- + +Now, if you run the `./mvnw clean install`, you get something like this: + +[source,bash,indent=0] +---- +Results : + +Tests in error: + ContractVerifierTest.validate_shouldMarkClientAsFraud:32 » IllegalState Parsed... +---- + +This error occurs because you have a new contract from which a test was generated and it +failed since you have not implemented the feature. The auto-generated test would look +like this: + +[source,java,indent=0] +---- +@Test +public void validate_shouldMarkClientAsFraud() throws Exception { + // given: + MockMvcRequestSpecification request = given() + .header("Content-Type", "application/vnd.fraud.v1+json") + .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}"); + + // when: + ResponseOptions response = given().spec(request) + .put("/fraudcheck"); + + // then: + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*"); + // and: + DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); + assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}"); + assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high"); +} +---- + +If you used the Groovy DSL, you can see, all the `producer()` parts of the Contract that were present in the +`value(consumer(...), producer(...))` blocks got injected into the test. +In case of using YAML, the same applied for the `matchers` sections of the `response`. + +Note that, on the producer side, you are also doing TDD. The expectations are expressed +in the form of a test. This test sends a request to our own application with the URL, +headers, and body defined in the contract. It also is expecting precisely defined values +in the response. In other words, you have the `red` part of `red`, `green`, and +`refactor`. It is time to convert the `red` into the `green`. + +*Write the missing implementation.* + +Because you know the expected input and expected output, you can write the missing +implementation: + +[source,java,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=server_api,indent=0] +include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=new_impl,indent=0] +include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=initial_impl,indent=0] +} +---- + +When you execute `./mvnw clean install` again, the tests pass. Since the `Spring Cloud +Contract Verifier` plugin adds the tests to the `generated-test-sources`, you can +actually run those tests from your IDE. + +*Deploy your app.* + +Once you finish your work, you can deploy your change. First, merge the branch: + +[source,bash,indent=0] +---- +$ git checkout master +$ git merge --no-ff contract-change-pr +$ git push origin master +---- + +Your CI might run something like `./mvnw clean deploy`, which would publish both the +application and the stub artifacts. + +=== Consumer Side (Loan Issuance) Final Step + +As a developer of the Loan Issuance service (a consumer of the Fraud Detection server) we will want to: + +- merge our feature branch to `master` +- switch to online mode of working + + +[plantuml, getting-started-cdc-client, png] +---- +"Loan\nIssuance"->"Loan\nIssuance": merge the\nfeature branch\nto master branch +"Loan\nIssuance"->"Loan\nIssuance": setup SCC Stub Runner\nto fetch stubs\nfrom Stub Storage +"Loan\nIssuance"->"LI\nSCC\nStub Runner": start stubs\nof FD from\nStub Storage +"LI\nSCC\nStub Runner"->"Stub Storage": find stubs of [FD] +"Stub Storage"->"LI\nSCC\nStub Runner": stubs of [FD] found +"LI\nSCC\nStub Runner"->"FD stub": run stubs of [FD] +"FD stub"->"LI\nSCC\nStub Runner": [FD] stub is running +"LI\nSCC\nStub Runner"->"Loan\nIssuance": stubs running and ready for the test +"Loan\nIssuance"->"Loan\nIssuance": run a test +"Loan\nIssuance"->"FD stub": the test\nsends a request\nto the running stub +"FD stub"->"Loan\nIssuance": stub responds successfuly +"Loan\nIssuance"->"Loan\nIssuance": the test passes successfully +---- + +*Merge branch to master.* + +[source,bash,indent=0] +---- +$ git checkout master +$ git merge --no-ff contract-change-pr +---- + +*Work online.* + +Now you can disable the offline work for Spring Cloud Contract Stub Runner and indicate +where the repository with your stubs is located. At this moment the stubs of the server +side are automatically downloaded from Nexus/Artifactory. You can set the value of +`stubsMode` to `REMOTE`. The following code shows an example of +achieving the same thing by changing the properties. + +[source,yaml,indent=0] +---- +include::{introduction_url}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] +---- + +That's it! + +[[getting-started-whats-next]] +== What to Read Next +Hopefully, this section provided some of the {project-full-name} basics and got you on your way +to writing your own applications. If you are a task-oriented type of developer, you might +want to jump over to https://spring.io and check out some of the +https://spring.io/guides/[getting started] guides that solve specific "`How do I do that +with Spring?`" problems. We also have {project-full-name}-specific +"`<>`" reference documentation. + +Otherwise, the next logical step is to read _<>_. If +you are really impatient, you could also jump ahead and read about +_<>_. + +// TODO: Check if we can link courses +In addition to that you can check out the following videos: + +- "Consumer Driven Contracts and Your Microservice Architecture" by Olga Maciaszek-Sharma and Marcin Grzejszczak + +video::pDkC_00hhvA[youtube,width=640,height=480] + +- "Contract Tests in the Enterprise" by Marcin Grzejszczak + +video::ZyHG-VOzPZg[youtube,width=640,height=480] + +- "Why Contract Tests Matter?" by Marcin Grzejszczak + +video::TvpkZu1e2Dc[youtube,start=6262,width=640,height=480] + +You can find the default project samples at +https://github.com/spring-cloud-samples/spring-cloud-contract-samples[samples]. + +You can find the Spring Cloud Contract workshops https://cloud-samples.spring.io/spring-cloud-contract-samples/[over here]. \ No newline at end of file From e9d467877cd237716bfdafef8949871b4df1e317 Mon Sep 17 00:00:00 2001 From: Marcin Grzejszczak Date: Thu, 25 Jul 2019 18:03:52 +0200 Subject: [PATCH 15/18] Polish --- .../asciidoc/_project-features-contract.adoc | 2 +- .../asciidoc/_project-features-flows.adoc | 20 +++---- .../asciidoc/_project-features-messaging.adoc | 4 +- .../_project-features-stubrunner.adoc | 10 ++-- docs/src/main/asciidoc/docker-project.adoc | 3 +- .../main/asciidoc/documentation-overview.adoc | 13 +++- docs/src/main/asciidoc/getting-started.adoc | 59 +++++++++++-------- docs/src/main/asciidoc/howto.adoc | 6 +- docs/src/main/asciidoc/index.htmladoc | 4 +- docs/src/main/asciidoc/using.adoc | 6 +- 10 files changed, 70 insertions(+), 57 deletions(-) diff --git a/docs/src/main/asciidoc/_project-features-contract.adoc b/docs/src/main/asciidoc/_project-features-contract.adoc index df80880e4a..f9d721b10c 100644 --- a/docs/src/main/asciidoc/_project-features-contract.adoc +++ b/docs/src/main/asciidoc/_project-features-contract.adoc @@ -1295,7 +1295,7 @@ TIP: As you can see, it is much better if you name your contracts because doing your tests far more meaningful. [[contract-stateful-contracts]] -== Stateful Contracts +=== Stateful Contracts Stateful contracts (known also as scenarios) are contract definitions that should be read in order. This might be useful in the following situations: diff --git a/docs/src/main/asciidoc/_project-features-flows.adoc b/docs/src/main/asciidoc/_project-features-flows.adoc index 7ef5b542ea..d936a3eaf3 100644 --- a/docs/src/main/asciidoc/_project-features-flows.adoc +++ b/docs/src/main/asciidoc/_project-features-flows.adoc @@ -1,7 +1,10 @@ -[[features-jax-rs]] -== JAX-RS +[[feature-integrations]] +== Integrations include::_attributes.adoc[] +[[features-jax-rs]] +=== JAX-RS + The Spring Cloud Contract supports the JAX-RS 2 Client API. The base class needs to define `protected WebTarget webTarget` and server initialization. The only option for testing JAX-RS API is to start a web server. Also, a request with a body needs to have a @@ -21,15 +24,10 @@ The following example shows a generated test API: include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/JaxRsClientMethodBuilderSpec.groovy[tags=jaxrs,indent=0] ---- -[[contract-webflux]] -== WebFlux - -Spring Cloud Contract offers two ways of working with WebFlux. - -[[contract-webtestclient]] +[[feature-webflux]] === WebFlux with WebTestClient -One of them is via the `WebTestClient` mode. +You can work with WebFlux via the `WebTestClient` mode. ==== [source,xml,indent=0,subs="verbatim,attributes",role="primary"] @@ -74,7 +72,9 @@ public abstract class BeerRestBase { } ---- -[[contract-webflux-explicit]] +IMPORTANT: The `WebTestClient` mode is faster than the `EXPLICIT` mode + +[[feature-webflux-explicit]] === WebFlux with Explicit mode Another way is with the `EXPLICIT` mode in your generated tests diff --git a/docs/src/main/asciidoc/_project-features-messaging.adoc b/docs/src/main/asciidoc/_project-features-messaging.adoc index e43743bb16..b71316b584 100644 --- a/docs/src/main/asciidoc/_project-features-messaging.adoc +++ b/docs/src/main/asciidoc/_project-features-messaging.adoc @@ -1,7 +1,7 @@ -include::_attributes.adoc[] - [[features-messaging]] == Messaging +include::_attributes.adoc[] + Spring Cloud Contract lets you verify applications that use messaging as a means of communication. All of the integrations shown in this document work with Spring, but you can also create one of your own and use that. diff --git a/docs/src/main/asciidoc/_project-features-stubrunner.adoc b/docs/src/main/asciidoc/_project-features-stubrunner.adoc index 5d64dc5bef..cfa0ff4a4b 100644 --- a/docs/src/main/asciidoc/_project-features-stubrunner.adoc +++ b/docs/src/main/asciidoc/_project-features-stubrunner.adoc @@ -1,4 +1,4 @@ -[[features-stub-runner-features-stub-runner]] +[[features-stub-runner]] == Spring Cloud Contract Stub Runner One of the issues that you might encounter while using Spring Cloud Contract Verifier is @@ -9,7 +9,7 @@ Copying the JSON files and setting the client side for messaging manually is out question. That is why we introduced Spring Cloud Contract Stub Runner. It can automatically download and run the stubs for you. -[[features-stub-runner-features-stub-runner-snapshot-versions]] +[[features-stub-runner-snapshot-versions]] === Snapshot versions Add the additional snapshot repository to your `build.gradle` file to use snapshot @@ -77,8 +77,7 @@ You can pick the following options of acquiring stubs - Classpath scanning solution that searches classpath via pattern to retrieve stubs - Write your own implementation of the `org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder` for full customization -// TODO: Fix link -The latter example is described in the <> section. +The latter example is described in the <> section. [[features-stub-runner-downloading-stub]] ===== Stub downloading @@ -382,8 +381,7 @@ include::{stubrunner_core_path}/src/test/java/org/springframework/cloud/contract ---- ==== -//TODO: Fix link -Check the *Common properties for JUnit and Spring* for more information on how to apply global configuration of Stub Runner. +Check the <> for more information on how to apply global configuration of Stub Runner. IMPORTANT: To use the JUnit rule or JUnit 5 extension together with messaging, you have to provide an implementation of the `MessageVerifier` interface to the rule builder (e.g. `rule.messageVerifier(new MyMessageVerifier())`). diff --git a/docs/src/main/asciidoc/docker-project.adoc b/docs/src/main/asciidoc/docker-project.adoc index 67185d90f1..3d29cff4ce 100644 --- a/docs/src/main/asciidoc/docker-project.adoc +++ b/docs/src/main/asciidoc/docker-project.adoc @@ -193,8 +193,7 @@ that will start the standalone version of Stub Runner. [[docker-stubrunner-env-vars]] === Environment variables -//TODO: Fix the link -Just execute the docker image. You can pass any of the <> +Just execute the docker image. You can pass any of the <> as environment variables. The convention is that all the letters should be upper case. The camel case notation should and the dot (`.`) should be separated via underscore (`_`). E.g. diff --git a/docs/src/main/asciidoc/documentation-overview.adoc b/docs/src/main/asciidoc/documentation-overview.adoc index b70c364876..8e9d44faeb 100644 --- a/docs/src/main/asciidoc/documentation-overview.adoc +++ b/docs/src/main/asciidoc/documentation-overview.adoc @@ -80,15 +80,22 @@ Need more details about {project-full-name}'s core features? <>: * *Core Features:* -<<{project-name}-features.adoc#contract-features-spring-application, SpringApplication>> | -<<{project-name}-features.adoc#contract-features-external-config, External Configuration>> +<> | +<> +* *Integrations:* +<> | +<> | +<> | +<> +* *Modules:* +<> | +<> * *Build tools:* link:maven-project.html[Maven] | link:gradle-project.html[Gradle] | link:docker-project.html[Docker] - == Advanced Topics Finally, we have a few topics for more advanced users: diff --git a/docs/src/main/asciidoc/getting-started.adoc b/docs/src/main/asciidoc/getting-started.adoc index ce8d92c0ee..2e6a4a3945 100644 --- a/docs/src/main/asciidoc/getting-started.adoc +++ b/docs/src/main/asciidoc/getting-started.adoc @@ -29,7 +29,7 @@ The `0.1.0` release took place on 26 Jan 2015 and it became stable with `1.0.0` Assume that we have a system consisting of multiple microservices: -image::images/Deps.png[Microservices Architecture] +image::Deps.png[Microservices Architecture] [[getting-started-introducing-spring-cloud-contract-testing-issues]] ==== Testing issues @@ -76,7 +76,7 @@ To solve the aforementioned issues, Spring Cloud Contract was created. The main whole world of microservices. If you work on stubs, then the only applications you need are those that your application directly uses. -image::images/Stubs2.png[Stubbed Services] +image::Stubs2.png[Stubbed Services] Spring Cloud Contract gives you the certainty that the stubs that you use were created by the service that you're calling. Also, if you can use them, it means that they @@ -108,8 +108,8 @@ As consumers of services, we need to define what exactly we want to achieve. We formulate our expectations. That is why we write contracts. In other words a contract is an agreement on how the API / message communication should look like. Let's look at the following example Assume that you want to send a request containing the ID of a client company and the -amount it wants to borrow from us. You also want to send it to the /fraudcheck url via -the PUT method. +amount it wants to borrow from us. You also want to send it to the `/fraudcheck` url via +the `PUT` method. ==== [source,groovy,indent=0,role="primary"] @@ -157,7 +157,7 @@ You can find a somewhat longer tour [[getting-started-three-second-tour-producer]] === On the Producer Side -To start working with Spring Cloud Contract, add files with `REST`/messaging contracts +To start working with Spring Cloud Contract, add files with REST/messaging contracts expressed in either Groovy DSL or YAML to the contracts directory, which is set by the `contractsDslDir` property. By default, it is `$rootDir/src/test/resources/contracts`. @@ -653,6 +653,7 @@ For simplicity we will use the following acronyms: - Fraud Detection - FD - the http server - Spring Cloud Contract - SCC +[[getting-started-cdc-consumer]] === Consumer side (Loan Issuance) As a developer of the Loan Issuance service (a consumer of the Fraud Detection server), you might do the following steps: @@ -700,7 +701,8 @@ Let's start with the Loan Issuance flow: "Loan\nIssuance"->"Fraud\nDetection": send a pull request\nwith the\nsuggested contracts ---- -*Start doing TDD by writing a test for your feature.* +[[getting-started-cdc-consumer-start]] +==== Start doing TDD by writing a test for your feature [source,groovy,indent=0] ---- @@ -710,7 +712,8 @@ include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com Assume that you have written a test of your new feature. If a loan application for a big amount is received, the system should reject that loan application with some description. -*Write the missing implementation.* +[[getting-started-cdc-consumer-write]] +==== Write the missing implementation At some point in time, you need to send a request to the Fraud Detection service. Assume that you need to send the request containing the ID of the client and the amount the @@ -727,7 +730,8 @@ application runs on `8090`. If you start the test at this point, it breaks, because no service currently runs on port `8080`. -*Clone the Fraud Detection service repository locally.* +[[getting-started-cdc-consumer-clone]] +==== Clone the Fraud Detection service repository locally You can start by playing around with the server side contract. To do so, you must first clone it. @@ -737,7 +741,8 @@ clone it. $ git clone https://your-git-server.com/server-side.git local-http-server-repo ---- -*Define the contract locally in the repo of Fraud Detection service.* +[[getting-started-cdc-consumer-define]] +==== Define the contract locally in the repo of Fraud Detection service As a consumer, you need to define what exactly you want to achieve. You need to formulate your expectations. To do so, write the following contract: @@ -766,9 +771,7 @@ Contract lets you define parts of a JSON block, a URL, etc., which are dynamic. of an identifier or a timestamp, you need not hardcode a value. You want to allow some different ranges of values. To enable ranges of values, you can set regular expressions matching those values for the consumer side. You can provide the body by means of either -a map notation or String with interpolations. -//TODO: Ensure that the links are correct -Consult the <> section for more information. We highly recommend using the map notation! +a map notation or String with interpolations. We highly recommend using the map notation! TIP: You must understand the map notation in order to set up contracts. Please read the https://groovy-lang.org/json.html[Groovy docs regarding JSON]. @@ -789,7 +792,8 @@ the `rejectionReason` field having value `Amount too high`, Once you are ready to check the API in practice in the integration tests, you need to install the stubs locally. -*Add the Spring Cloud Contract Verifier plugin.* +[[getting-started-cdc-consumer-add]] +==== Add the Spring Cloud Contract Verifier plugin We can add either a Maven or a Gradle plugin. In this example, you see how to add Maven. First, add the `Spring Cloud Contract` BOM. @@ -849,7 +853,8 @@ The following line is extremely important: It confirms that the stubs of the `http-server` have been installed in the local repository. -*Run the integration tests.* +[[getting-started-cdc-consumer-run]] +==== Run the integration tests In order to profit from the Spring Cloud Contract Stub Runner functionality of automatic stub downloading, you must do the following in your consumer side project (`Loan @@ -896,7 +901,8 @@ This output means that Stub Runner has found your stubs and started a server for with group id `com.example`, artifact id `http-server` with version `0.0.1-SNAPSHOT` of the stubs and with `stubs` classifier on port `8080`. -*File a pull request.* +[[getting-started-cdc-consumer-file]] +==== File a pull request What you have done until now is an iterative process. You can play around with the contract, install it locally, and work on the consumer side until the contract works as @@ -905,6 +911,7 @@ you wish. Once you are satisfied with the results and the test passes, publish a pull request to the server side. Currently, the consumer side work is done. +[[getting-started-cdc-producer]] === Producer side (Fraud Detection server) As a developer of the Fraud Detection server (a server to the Loan Issuance service) we would like to: @@ -935,7 +942,8 @@ Let's look at the Fraud Detection flow: "CI"->"Stub Storage": build successful,\nupload artifacts ---- -*Take over the pull request.* +[[getting-started-cdc-producer-pr]] +==== Take over the pull request As a reminder, you can see the initial implementation here: @@ -1029,7 +1037,8 @@ headers, and body defined in the contract. It also is expecting precisely define in the response. In other words, you have the `red` part of `red`, `green`, and `refactor`. It is time to convert the `red` into the `green`. -*Write the missing implementation.* +[[getting-started-cdc-producer-impl]] +==== Write the missing implementation Because you know the expected input and expected output, you can write the missing implementation: @@ -1046,7 +1055,8 @@ When you execute `./mvnw clean install` again, the tests pass. Since the `Spring Contract Verifier` plugin adds the tests to the `generated-test-sources`, you can actually run those tests from your IDE. -*Deploy your app.* +[[getting-started-cdc-producer-deploy]] +==== Deploy your app Once you finish your work, you can deploy your change. First, merge the branch: @@ -1060,6 +1070,7 @@ $ git push origin master Your CI might run something like `./mvnw clean deploy`, which would publish both the application and the stub artifacts. +[[getting-started-cdc-consumer-final]] === Consumer Side (Loan Issuance) Final Step As a developer of the Loan Issuance service (a consumer of the Fraud Detection server) we will want to: @@ -1067,8 +1078,7 @@ As a developer of the Loan Issuance service (a consumer of the Fraud Detection s - merge our feature branch to `master` - switch to online mode of working - -[plantuml, getting-started-cdc-client, png] +[plantuml, getting-started-cdc-client-final, png] ---- "Loan\nIssuance"->"Loan\nIssuance": merge the\nfeature branch\nto master branch "Loan\nIssuance"->"Loan\nIssuance": setup SCC Stub Runner\nto fetch stubs\nfrom Stub Storage @@ -1084,7 +1094,8 @@ As a developer of the Loan Issuance service (a consumer of the Fraud Detection s "Loan\nIssuance"->"Loan\nIssuance": the test passes successfully ---- -*Merge branch to master.* +[[getting-started-cdc-consumer-final-merge]] +==== Merge branch to master [source,bash,indent=0] ---- @@ -1092,7 +1103,8 @@ $ git checkout master $ git merge --no-ff contract-change-pr ---- -*Work online.* +[[getting-started-cdc-consumer-final-online]] +==== Work online Now you can disable the offline work for Spring Cloud Contract Stub Runner and indicate where the repository with your stubs is located. At this moment the stubs of the server @@ -1116,11 +1128,10 @@ https://spring.io/guides/[getting started] guides that solve specific "`How do I with Spring?`" problems. We also have {project-full-name}-specific "`<>`" reference documentation. -Otherwise, the next logical step is to read _<>_. If +Otherwise, the next logical step is to read _<>_. If you are really impatient, you could also jump ahead and read about _<>_. -// TODO: Check if we can link courses In addition to that you can check out the following videos: - "Consumer Driven Contracts and Your Microservice Architecture" by Olga Maciaszek-Sharma and Marcin Grzejszczak diff --git a/docs/src/main/asciidoc/howto.adoc b/docs/src/main/asciidoc/howto.adoc index e3e0f1db3c..9094dfa857 100644 --- a/docs/src/main/asciidoc/howto.adoc +++ b/docs/src/main/asciidoc/howto.adoc @@ -32,8 +32,7 @@ Spring Cloud Contract Verifier stand out on the "market" of Consumer Driven Cont [[how-to-not-write-contracts-in-groovy]] == How can I write contracts in a language different than Groovy? -// TODO: Add a link -No problem. You can write a contract in YAML! Check this section for more information +No problem. You can write a contract in YAML! Check <> for more information. We are working on allowing more ways of describing the contracts. You can check the {github-issues}[github-issues] for more information. @@ -125,8 +124,7 @@ How can you then provide one time a matcher for the consumer and a concrete valu In Spring Cloud Contract we're allowing you to provide a *dynamic value*. That means that it can differ for both sides of the communication. -// TODO: Ensure that the link is correct -You can read more about this in the <> section. +You can read more about this in the <> section. IMPORTANT: Please read the https://groovy-lang.org/json.html[Groovy docs related to JSON] to understand how to properly structure the request / response bodies. diff --git a/docs/src/main/asciidoc/index.htmladoc b/docs/src/main/asciidoc/index.htmladoc index eb633d129e..4ee1bab1c8 100644 --- a/docs/src/main/asciidoc/index.htmladoc +++ b/docs/src/main/asciidoc/index.htmladoc @@ -9,8 +9,8 @@ The reference documentation consists of the following sections: [horizontal] <> :: Legal information. <> :: About the Documentation, Getting Help, First Steps, and more. -<> :: Introducing {project-full-name}, System Requirements, Developing Your First {project-full-name} based Application +<> :: Introducing {project-full-name}, Developing Your First {project-full-name} based Application <> :: {project-full-name} usage examples and workflows -<> :: Profiles, Logging, Security, Caching, Spring Integration, Testing, and more.W +<> :: Contract DSL, Messaging, Spring Cloud Contract Stub Runner, Spring Cloud Contract WireMock <> :: Maven Plugin, Gradle Plugin, Docker <> :: Stubs versioning, Pact integration, Debugging, and more. diff --git a/docs/src/main/asciidoc/using.adoc b/docs/src/main/asciidoc/using.adoc index 07ddd2d03e..9fa0e8ab80 100644 --- a/docs/src/main/asciidoc/using.adoc +++ b/docs/src/main/asciidoc/using.adoc @@ -3,8 +3,8 @@ include::_attributes.adoc[] This section goes into more detail about how you should use {project-full-name}. It covers topics -such as description of flows of how to work with {{project-full-name}}. We also -cover some {{project-full-name}} best practices. +such as description of flows of how to work with {project-full-name}. We also +cover some {project-full-name} best practices. If you are starting out with {project-full-name}, you should probably read the _<>_ guide before diving into this @@ -778,4 +778,4 @@ Since the consumer flow isn't affected by the tool used to generate the stubs, y You should now understand how you can use {project-full-name} and some best practices that you should follow. You can now go on to learn about specific _<>_ in depth, or you could -skip ahead and read about the ... +skip ahead and read about the _link:advanced.html[advanced features of {project-full-name}]_. From 371c32d5eb24574eea728eddc36b02ff25a15a80 Mon Sep 17 00:00:00 2001 From: Olga Maciaszek-Sharma Date: Fri, 26 Jul 2019 14:38:14 +0200 Subject: [PATCH 16/18] Review and add fixes. --- .../asciidoc/_project-features-contract.adoc | 24 +++++++++++------ .../main/asciidoc/documentation-overview.adoc | 26 +++++++++++++------ docs/src/main/asciidoc/getting-started.adoc | 8 +++--- 3 files changed, 38 insertions(+), 20 deletions(-) diff --git a/docs/src/main/asciidoc/_project-features-contract.adoc b/docs/src/main/asciidoc/_project-features-contract.adoc index f9d721b10c..d8137c05a0 100644 --- a/docs/src/main/asciidoc/_project-features-contract.adoc +++ b/docs/src/main/asciidoc/_project-features-contract.adoc @@ -6,7 +6,9 @@ Spring Cloud Contract supports out of the box following types of DSL. * written in `Groovy` * written in `YAML` -* written in `Java` + +TIP: If you're not familiar with Groovy, don't worry - you can use Java syntax in the +Groovy DSL files as well. If you decide to write the contract in Groovy, do not be alarmed if you have not used Groovy before. Knowledge of the language is not really needed, as the Contract DSL uses only a @@ -43,9 +45,6 @@ TIP: You can compile contracts to stubs mapping using standalone maven command: [[contract-limitations]] === Limitations -WARNING: Spring Cloud Contract Verifier does not properly support XML. Please use JSON or -help us implement this feature. - WARNING: The support for verifying the size of JSON arrays is experimental. If you want to turn it on, please set the value of the following system property to `true`: `spring.cloud.contract.verifier.assert.size`. By default, this feature is set to `false`. @@ -64,7 +63,6 @@ The following sections describe the most common top-level elements: * <> * <> * <> -* <> [[contract-dsl-description]] ==== Description @@ -205,8 +203,18 @@ include::{verifier_core_path}/src/test/resources/yml/contract_pdf.yml[indent=0] IMPORTANT: You should use this approach whenever you want to work with binary payloads both for HTTP and messaging. +[[features-http]] +== Contracts for HTTP + +Spring Cloud Contract allows you to verify applications that use REST or HTTP as a +means of communication. Spring Cloud Contract verifies that for a request that matches the +criteria from the `request` part of the contract, the server provides a response that is in +keeping with the `response` part of the contract. Subsequently, the contracts are used to +generate wiremock stubs that for any request matching the provided criteria, will provide a +suitable response. + [[contract-dsl-http-top-level-elements]] -==== HTTP Top-Level Elements +=== HTTP Top-Level Elements The following methods can be called in the top-level closure of a contract definition. `request` and `response` are mandatory. `priority` is optional. @@ -1150,8 +1158,8 @@ response: ==== [[contract-dsl-xml]] -=== XML Support for REST -For REST contracts, we also support XML request and response body. +=== XML Support for HTTP +For HTTP contracts, we also support XML request and response body. The XML body has to be passed within the `body` element as a `String` or `GString`. Also body matchers can be provided for both request and response. In place of the `jsonPath(...)` method, the `org.springframework.cloud.contract.spec.internal.BodyMatchers.xPath` diff --git a/docs/src/main/asciidoc/documentation-overview.adoc b/docs/src/main/asciidoc/documentation-overview.adoc index 8e9d44faeb..2db0e9eb79 100644 --- a/docs/src/main/asciidoc/documentation-overview.adoc +++ b/docs/src/main/asciidoc/documentation-overview.adoc @@ -32,13 +32,13 @@ starting out with {project-full-name}, try one of the https://spring.io/guides[g * Ask a question. We monitor https://stackoverflow.com[stackoverflow.com] for questions tagged with https://stackoverflow.com/tags/{project-name}[`{project-name}`]. * Report bugs with {project-full-name} at https://github.com/spring-cloud/{project-name}/issues. +* Chat with us at http://https://gitter.im/spring-cloud/{project-name}[{project-full-name} Gitter] NOTE: All of {project-full-name} is open source, including the documentation. If you find problems with the docs or if you want to improve them, please {github-code}[get involved]. - [[contract-documentation-first-steps]] == First Steps If you are getting started with {project-full-name} or 'Spring' in general, start with @@ -50,8 +50,8 @@ If you are getting started with {project-full-name} or 'Spring' in general, star <> * *Tutorial:* <> | -<> | -<> | +<> | +<> | <> @@ -73,7 +73,15 @@ you covered>>: ** <> ** <> +TIP: We talk about *Provider Contracts* when it's the producer of the API that defines the contracts and +publishes it for all its consumers to use. This approach is useful for producers that can't +directly collaborate with their consumers; for example, when there are too many consumers, +the consumers are external (don't work within the same company). +TIP: We use the term *Consumer-Driven Contracts* to refer to workflows where the consumers of an API +play a vital role in the process of creating the contracts; it's the recommended approach, easy +to implement when both producer and consumer teams work for the same organisations and the number +of consumers is not extremely large. == Learning about {project-full-name} Features Need more details about {project-full-name}'s core features? @@ -81,18 +89,20 @@ Need more details about {project-full-name}'s core features? * *Core Features:* <> | -<> +<> | +<> * *Integrations:* <> | -<> | <> | <> +<> * *Modules:* <> | <> -* *Build tools:* -link:maven-project.html[Maven] | -link:gradle-project.html[Gradle] | +// TODO: links don't work in "build Tools" section +* *Build Tools:* +link:maven-project.html[Contract Verifier - Maven] | +link:gradle-project.html[Contract Verifier - Gradle] | link:docker-project.html[Docker] diff --git a/docs/src/main/asciidoc/getting-started.adoc b/docs/src/main/asciidoc/getting-started.adoc index 2e6a4a3945..b10b6972c1 100644 --- a/docs/src/main/asciidoc/getting-started.adoc +++ b/docs/src/main/asciidoc/getting-started.adoc @@ -13,7 +13,7 @@ principles as we go. [[getting-started-introducing-spring-cloud-contract]] == Introducing Spring Cloud Contract -Spring Cloud Contract moves TDD to the level of software architecture. It allows to perform consumer, consumer-driven and producer-driven contract testing. +Spring Cloud Contract moves TDD to the level of software architecture. It allows to perform consumer-driven and producer-driven contract testing. [[getting-started-introducing-spring-cloud-contract-history]] === History @@ -914,7 +914,7 @@ the server side. Currently, the consumer side work is done. [[getting-started-cdc-producer]] === Producer side (Fraud Detection server) -As a developer of the Fraud Detection server (a server to the Loan Issuance service) we would like to: +As a developer of the Fraud Detection server (a server to the Loan Issuance service) I would like to: - take over the pull request - write the missing implementation @@ -1073,7 +1073,7 @@ application and the stub artifacts. [[getting-started-cdc-consumer-final]] === Consumer Side (Loan Issuance) Final Step -As a developer of the Loan Issuance service (a consumer of the Fraud Detection server) we will want to: +As a developer of the Loan Issuance service (a consumer of the Fraud Detection server) I will want to: - merge our feature branch to `master` - switch to online mode of working @@ -1120,7 +1120,7 @@ include::{introduction_url}/samples/standalone/dsl/http-client/src/test/resource That's it! [[getting-started-whats-next]] -== What to Read Next +== Next Steps Hopefully, this section provided some of the {project-full-name} basics and got you on your way to writing your own applications. If you are a task-oriented type of developer, you might want to jump over to https://spring.io and check out some of the From da3a09669ca762d5367b24e592cd84bf642e3902 Mon Sep 17 00:00:00 2001 From: Jay Bryant Date: Tue, 6 Aug 2019 14:37:41 -0500 Subject: [PATCH 17/18] Editing pass for the new docs layout I did a full editing pass on all the asciidoc files. --- README.adoc | 75 +- docs/src/main/asciidoc/README.adoc | 4 +- docs/src/main/asciidoc/_building.adoc | 70 +- .../asciidoc/_project-features-contract.adoc | 380 +++++----- .../asciidoc/_project-features-flows.adoc | 120 +-- .../asciidoc/_project-features-messaging.adoc | 303 +++++--- .../_project-features-stubrunner.adoc | 496 ++++++++----- .../asciidoc/_project-features-wiremock.adoc | 79 +- docs/src/main/asciidoc/advanced.adoc | 124 ++-- docs/src/main/asciidoc/docker-project.adoc | 279 +++---- .../main/asciidoc/documentation-overview.adoc | 38 +- docs/src/main/asciidoc/getting-started.adoc | 431 ++++++----- docs/src/main/asciidoc/gradle-project.adoc | 203 +++--- docs/src/main/asciidoc/howto.adoc | 685 +++++++++++------- docs/src/main/asciidoc/index.htmladoc | 6 +- docs/src/main/asciidoc/index.htmlpdfadoc | 3 +- docs/src/main/asciidoc/maven-project.adoc | 231 +++--- docs/src/main/asciidoc/project-features.adoc | 10 +- docs/src/main/asciidoc/sagan-boot.adoc | 54 +- docs/src/main/asciidoc/sagan-index.adoc | 32 +- docs/src/main/asciidoc/using.adoc | 398 ++++++---- 21 files changed, 2392 insertions(+), 1629 deletions(-) diff --git a/README.adoc b/README.adoc index 33f0acfdfc..d8f382be32 100644 --- a/README.adoc +++ b/README.adoc @@ -7,8 +7,8 @@ Edit the files in the src/main/asciidoc/ directory instead. == Spring Cloud Contract You always need confidence when pushing new features into a new application or service in -a distributed system. To that end, this project provides support for Consumer-driven -Contracts and service schemas in Spring applications, covering a range of options for +a distributed system. To that end, this project provides support for consumer-driven +contracts and service schemas in Spring applications, covering a range of options for writing tests, publishing them as assets, and asserting that a contract is kept by producers and consumers -- for both HTTP and message-based interactions. @@ -204,21 +204,21 @@ Go to `File` -> `Settings` -> `Other settings` -> `Checkstyle`. There click on t IMPORTANT: Remember to set the `Scan Scope` to `All sources` since we apply checkstyle rules for production and test sources. -== How to build it +== How to Build Spring Cloud Contract IMPORTANT: You need to have all the necessary Groovy plugins - installed for your IDE to properly resolve the sources. For example in - Intellij IDEA having both Eclipse Groovy Compiler Plugin & GMavenPlus Intellij Plugin - results in properly imported project. +installed for your IDE to properly resolve the sources. For example, in +Intellij IDEA, having both the Eclipse Groovy Compiler Plugin and the GMavenPlus Intellij +Plugin results in properly imported project. IMPORTANT: Spring Cloud Contract builds Docker images. Remember to have Docker installed. -IMPORTANT: If you want to run the build in offline mode, you have to have Maven 3.5.2+ installed. +IMPORTANT: If you want to run the build in offline mode, you must have Maven 3.5.2+ installed. === Project structure -Here you can find the Spring Cloud Contract folder structure +The following listing shows the Spring Cloud Contract folder structure: ``` ├── config @@ -237,34 +237,38 @@ Here you can find the Spring Cloud Contract folder structure └── tests ``` - - `config` - folder contains setup for Spring Cloud Release Tools automated release process - - `docker` - folder contains docker images - - `samples` - folder contains test samples together with standalone ones used also to build documentation - - `scripts` - contains scripts to build and test `Spring Cloud Contract` with Maven, Gradle and standalone projects - - `specs` - contains specifications for the Contract DSL. - - `spring-cloud-contract-dependencies` - contains Spring Cloud Contract BOM - - `spring-cloud-contract-shade` - shaded dependencies used by the plugins - - `spring-cloud-contract-starters` - contains Spring Cloud Contract Starters - - `spring-cloud-contract-spec` - contains specification modules (contains concept of a Contract) - - `spring-cloud-contract-stub-runner` - contains Stub Runner related modules - - `spring-cloud-contract-stub-runner-boot` - contains Stub Runner Boot app - - `spring-cloud-contract-tools` - Gradle and Maven plugin for `Spring Cloud Contract Verifier` - - `spring-cloud-contract-verifier` - core of the `Spring Cloud Contract Verifier` functionality - - `spring-cloud-contract-wiremock` - all WireMock related functionality - - `tests` - integration tests for different messaging technologies +The following list describes each of the top-level folders in the project structure: + +- `config`: Folder contains setup for Spring Cloud Release Tools automated release process +- `docker`: Folder contains docker images +- `samples`: Folder contains test samples together with standalone ones used also to build documentation +- `scripts`: Contains scripts to build and test `Spring Cloud Contract` with Maven, Gradle and standalone projects +- `specs`: Contains specifications for the Contract DSL. +- `spring-cloud-contract-dependencies`: Contains Spring Cloud Contract BOM +- `spring-cloud-contract-shade`: Shaded dependencies used by the plugins +- `spring-cloud-contract-starters`: Contains Spring Cloud Contract Starters +- `spring-cloud-contract-spec`: Contains specification modules (contains concept of a Contract) +- `spring-cloud-contract-stub-runner`: Contains Stub Runner related modules +- `spring-cloud-contract-stub-runner-boot`: Contains Stub Runner Boot app +- `spring-cloud-contract-tools`: Gradle and Maven plugin for `Spring Cloud Contract Verifier` +- `spring-cloud-contract-verifier`: Core of the `Spring Cloud Contract Verifier` functionality +- `spring-cloud-contract-wiremock`: All WireMock related functionality +- `tests`: Integration tests for different messaging technologies === Commands -To build the core functionality together with Maven Plugin you can run +To build the core functionality together with the Maven Plugin, you can run the following +command: ``` ./mvnw clean install -P integration ``` -Calling that function will build core, Maven plugin, Gradle plugin and run end to end tests on the -standalone samples in proper order (both for Maven and Gradle). +Calling that function builds the core, the Maven plugin, and the Gradle plugin and runs +end-to_end tests on the +standalone samples in the proper order (both for Maven and Gradle). -To build the Gradle Plugin only +To build only the Gradle Plugin, you can run the following commands: ``` cd spring-cloud-contract-tools/spring-cloud-contract-gradle-plugin @@ -273,34 +277,37 @@ cd spring-cloud-contract-tools/spring-cloud-contract-gradle-plugin === Helpful scripts -We're providing a couple of helpful scripts to build the project. +We provide a couple of helpful scripts to build the project. -To build the project in parallel (by default uses 4 cores but you can change it) +To build the project in parallel (by default, it uses four cores, but you can change it), +run the following command: ``` ./scripts/parallelBuild.sh ``` -and with 8 cores +To use eight 8 cores, run thke following command: ``` CORES=8 ./scripts/parallelBuild.sh ``` -To build the project without any integration tests (by default uses 1 core) +To build the project without any integration tests (by default, this uses one core), run +the following command: ``` ./scripts/noIntegration.sh ``` -and with 8 cores +To use eight cores, run the following command: ``` CORES=8 ./scripts/noIntegration.sh ``` -To generate the documentation (both the root one and the maven plugin one) +To generate the documentation (for both the root project and the maven plugin), run the +following command: ``` ./scripts/generateDocs.sh -``` +``` \ No newline at end of file diff --git a/docs/src/main/asciidoc/README.adoc b/docs/src/main/asciidoc/README.adoc index 0286658de7..aaf76dd536 100644 --- a/docs/src/main/asciidoc/README.adoc +++ b/docs/src/main/asciidoc/README.adoc @@ -1,8 +1,8 @@ == Spring Cloud Contract You always need confidence when pushing new features into a new application or service in -a distributed system. To that end, this project provides support for Consumer-driven -Contracts and service schemas in Spring applications, covering a range of options for +a distributed system. To that end, this project provides support for consumer-driven +contracts and service schemas in Spring applications, covering a range of options for writing tests, publishing them as assets, and asserting that a contract is kept by producers and consumers -- for both HTTP and message-based interactions. diff --git a/docs/src/main/asciidoc/_building.adoc b/docs/src/main/asciidoc/_building.adoc index 79fe0f349a..57c00a928d 100644 --- a/docs/src/main/asciidoc/_building.adoc +++ b/docs/src/main/asciidoc/_building.adoc @@ -1,18 +1,18 @@ -== How to build it +== How to Build Spring Cloud Contract IMPORTANT: You need to have all the necessary Groovy plugins - installed for your IDE to properly resolve the sources. For example in - Intellij IDEA having both Eclipse Groovy Compiler Plugin & GMavenPlus Intellij Plugin - results in properly imported project. +installed for your IDE to properly resolve the sources. For example, in +Intellij IDEA, having both the Eclipse Groovy Compiler Plugin and the GMavenPlus Intellij +Plugin results in properly imported project. IMPORTANT: Spring Cloud Contract builds Docker images. Remember to have Docker installed. -IMPORTANT: If you want to run the build in offline mode, you have to have Maven 3.5.2+ installed. +IMPORTANT: If you want to run the build in offline mode, you must have Maven 3.5.2+ installed. === Project structure -Here you can find the Spring Cloud Contract folder structure +The following listing shows the Spring Cloud Contract folder structure: ``` ├── config @@ -31,34 +31,38 @@ Here you can find the Spring Cloud Contract folder structure └── tests ``` - - `config` - folder contains setup for Spring Cloud Release Tools automated release process - - `docker` - folder contains docker images - - `samples` - folder contains test samples together with standalone ones used also to build documentation - - `scripts` - contains scripts to build and test `Spring Cloud Contract` with Maven, Gradle and standalone projects - - `specs` - contains specifications for the Contract DSL. - - `spring-cloud-contract-dependencies` - contains Spring Cloud Contract BOM - - `spring-cloud-contract-shade` - shaded dependencies used by the plugins - - `spring-cloud-contract-starters` - contains Spring Cloud Contract Starters - - `spring-cloud-contract-spec` - contains specification modules (contains concept of a Contract) - - `spring-cloud-contract-stub-runner` - contains Stub Runner related modules - - `spring-cloud-contract-stub-runner-boot` - contains Stub Runner Boot app - - `spring-cloud-contract-tools` - Gradle and Maven plugin for `Spring Cloud Contract Verifier` - - `spring-cloud-contract-verifier` - core of the `Spring Cloud Contract Verifier` functionality - - `spring-cloud-contract-wiremock` - all WireMock related functionality - - `tests` - integration tests for different messaging technologies +The following list describes each of the top-level folders in the project structure: + +- `config`: Folder contains setup for Spring Cloud Release Tools automated release process +- `docker`: Folder contains docker images +- `samples`: Folder contains test samples together with standalone ones used also to build documentation +- `scripts`: Contains scripts to build and test `Spring Cloud Contract` with Maven, Gradle and standalone projects +- `specs`: Contains specifications for the Contract DSL. +- `spring-cloud-contract-dependencies`: Contains Spring Cloud Contract BOM +- `spring-cloud-contract-shade`: Shaded dependencies used by the plugins +- `spring-cloud-contract-starters`: Contains Spring Cloud Contract Starters +- `spring-cloud-contract-spec`: Contains specification modules (contains concept of a Contract) +- `spring-cloud-contract-stub-runner`: Contains Stub Runner related modules +- `spring-cloud-contract-stub-runner-boot`: Contains Stub Runner Boot app +- `spring-cloud-contract-tools`: Gradle and Maven plugin for `Spring Cloud Contract Verifier` +- `spring-cloud-contract-verifier`: Core of the `Spring Cloud Contract Verifier` functionality +- `spring-cloud-contract-wiremock`: All WireMock related functionality +- `tests`: Integration tests for different messaging technologies === Commands -To build the core functionality together with Maven Plugin you can run +To build the core functionality together with the Maven Plugin, you can run the following +command: ``` ./mvnw clean install -P integration ``` -Calling that function will build core, Maven plugin, Gradle plugin and run end to end tests on the -standalone samples in proper order (both for Maven and Gradle). +Calling that function builds the core, the Maven plugin, and the Gradle plugin and runs +end-to_end tests on the +standalone samples in the proper order (both for Maven and Gradle). -To build the Gradle Plugin only +To build only the Gradle Plugin, you can run the following commands: ``` cd spring-cloud-contract-tools/spring-cloud-contract-gradle-plugin @@ -67,35 +71,37 @@ cd spring-cloud-contract-tools/spring-cloud-contract-gradle-plugin === Helpful scripts -We're providing a couple of helpful scripts to build the project. +We provide a couple of helpful scripts to build the project. -To build the project in parallel (by default uses 4 cores but you can change it) +To build the project in parallel (by default, it uses four cores, but you can change it), +run the following command: ``` ./scripts/parallelBuild.sh ``` -and with 8 cores +To use eight 8 cores, run thke following command: ``` CORES=8 ./scripts/parallelBuild.sh ``` -To build the project without any integration tests (by default uses 1 core) +To build the project without any integration tests (by default, this uses one core), run +the following command: ``` ./scripts/noIntegration.sh ``` -and with 8 cores +To use eight cores, run the following command: ``` CORES=8 ./scripts/noIntegration.sh ``` -To generate the documentation (both the root one and the maven plugin one) +To generate the documentation (for both the root project and the maven plugin), run the +following command: ``` ./scripts/generateDocs.sh ``` - diff --git a/docs/src/main/asciidoc/_project-features-contract.adoc b/docs/src/main/asciidoc/_project-features-contract.adoc index d8137c05a0..76ac7db7ad 100644 --- a/docs/src/main/asciidoc/_project-features-contract.adoc +++ b/docs/src/main/asciidoc/_project-features-contract.adoc @@ -2,28 +2,28 @@ == Contract DSL include::_attributes.adoc[] -Spring Cloud Contract supports out of the box following types of DSL. +Spring Cloud Contract supports the DSLs written in the following languages: -* written in `Groovy` -* written in `YAML` +* Groovy +* YAML -TIP: If you're not familiar with Groovy, don't worry - you can use Java syntax in the +TIP: If you are not familiar with Groovy, do not worry - you can use Java syntax in the Groovy DSL files as well. If you decide to write the contract in Groovy, do not be alarmed if you have not used Groovy before. Knowledge of the language is not really needed, as the Contract DSL uses only a -tiny subset of it (only literals, method calls and closures). Also, the DSL is statically +tiny subset of it (only literals, method calls, and closures). Also, the DSL is statically typed, to make it programmer-readable without any knowledge of the DSL itself. IMPORTANT: Remember that, inside the Groovy contract file, you have to provide the fully qualified name to the `Contract` class and `make` static imports, such as `org.springframework.cloud.spec.Contract.make { ... }`. You can also provide an import to -the `Contract` class: `import org.springframework.cloud.spec.Contract` and then call +the `Contract` class (`import org.springframework.cloud.spec.Contract`) and then call `Contract.make { ... }`. TIP: Spring Cloud Contract supports defining multiple contracts in a single file. -The following is a complete example of a contract definition: +The following example shows a contract definition: ==== [source,groovy,indent=0,subs="verbatim,attributes",role="primary"] @@ -39,23 +39,30 @@ include::{verifier_core_path}/src/test/resources/yml/contract_rest.yml[indent=0] ---- ==== -TIP: You can compile contracts to stubs mapping using standalone maven command: -`mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert` + +[TIP] +==== +You can compile contracts to stubs mapping by using the following standalone Maven command: + +---- +mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert +---- +==== [[contract-limitations]] === Limitations WARNING: The support for verifying the size of JSON arrays is experimental. If you want -to turn it on, please set the value of the following system property to `true`: +to turn it on, set the value of the following system property to `true`: `spring.cloud.contract.verifier.assert.size`. By default, this feature is set to `false`. -You can also provide the `assertJsonSize` property in the plugin configuration. +You can also set the `assertJsonSize` property in the plugin configuration. WARNING: Because JSON structure can have any form, it can be impossible to parse it properly when using the Groovy DSL and the `value(consumer(...), producer(...))` notation in `GString`. That is why you should use the Groovy Map notation. [[contract-common-top-elements]] -=== Common Top-Level elements +=== Common Top-Level Elements The following sections describe the most common top-level elements: @@ -97,6 +104,8 @@ generated test not compile. Also, remember that, if you provide the same name fo multiple contracts, your autogenerated tests fail to compile and your generated stubs override each other. +The following example shows how to add a name to a contract: + ==== [source,groovy,indent=0,role="primary"] .groovy @@ -114,8 +123,9 @@ include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=name,inde [[contract-dsl-ignoring-contracts]] ==== Ignoring Contracts -If you want to ignore a contract, you can either set a value of ignored contracts in the -plugin configuration or set the `ignored` property on the contract itself: +If you want to ignore a contract, you can either set a value for ignored contracts in the +plugin configuration or set the `ignored` property on the contract itself. The following +example shows how to do so: ==== [source,groovy,indent=0,role="primary"] @@ -135,7 +145,7 @@ include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=ignored,i ==== Passing Values from Files Starting with version `1.2.0`, you can pass values from files. Assume that you have the -following resources in our project. +following resources in your project: [source,bash,indent=0] ---- @@ -180,12 +190,14 @@ include::{verifier_core_path}/src/test/resources/classpath/response.json[indent= ---- ==== -When test or stub generation takes place, the contents of the file is passed to the body +When test or stub generation takes place, the contents of the `readFromFile.groovy` file is passed to the body of a request or a response. The name of the file needs to be a file with location relative to the folder in which the contract lays. -If you need to pass the contents of a file in a binary form -it's enough for you to use the `fileAsBytes` method in Groovy DSL or `bodyFromFileAsBytes` field in YAML. +If you need to pass the contents of a file in binary form, +you can use the `fileAsBytes` method in Groovy DSL or a `bodyFromFileAsBytes` field in YAML. + +The following example shows how to pass the contents of binary files: ==== [source,groovy,indent=0,role="primary"] @@ -201,23 +213,29 @@ include::{verifier_core_path}/src/test/resources/yml/contract_pdf.yml[indent=0] ---- ==== -IMPORTANT: You should use this approach whenever you want to work with binary payloads both for HTTP and messaging. +IMPORTANT: You should use this approach whenever you want to work with binary payloads, + both for HTTP and messaging. [[features-http]] == Contracts for HTTP -Spring Cloud Contract allows you to verify applications that use REST or HTTP as a -means of communication. Spring Cloud Contract verifies that for a request that matches the +Spring Cloud Contract lets you verify applications that use REST or HTTP as a +means of communication. Spring Cloud Contract verifies that, for a request that matches the criteria from the `request` part of the contract, the server provides a response that is in keeping with the `response` part of the contract. Subsequently, the contracts are used to -generate wiremock stubs that for any request matching the provided criteria, will provide a +generate WireMock stubs that, for any request matching the provided criteria, provide a suitable response. [[contract-dsl-http-top-level-elements]] === HTTP Top-Level Elements -The following methods can be called in the top-level closure of a contract definition. -`request` and `response` are mandatory. `priority` is optional. +You can call the following methods in the top-level closure of a contract definition: + +* `request`: Mandatory +* `response` : Mandatory +* `priority`: Optional + +The following example shows how to define an HTTP request contract: ==== [source,groovy,indent=0,subs="verbatim,attributes",role="primary"] @@ -237,15 +255,17 @@ include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=response, ---- ==== -IMPORTANT: If you want to make your contract have a **higher** value of priority -you need to pass a **lower** number to the `priority` tag / method. E.g. `priority` with -value `5` has **higher** priority than `priority` with value `10`. +IMPORTANT: If you want to make your contract have a higher priority, +you need to pass a lower number to the `priority` tag or method. For example, a `priority` with +a value of `5` has higher priority than a `priority` with a value of `10`. [[contract-dsl-request]] === HTTP Request -The HTTP protocol requires only **method and url** to be specified in a request. The -same information is mandatory in request definition of the Contract. +The HTTP protocol requires only the method and the URL to be specified in a request. The +same information is mandatory in request definition of the contract. + +The following example shows a contract for a request: ==== [source,groovy,indent=0,role="primary"] @@ -261,8 +281,10 @@ include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=request_o ---- ==== -It is possible to specify an absolute rather than relative `url`, but using `urlPath` is -the recommended way, as doing so makes the tests **host-independent**. +You can specify an absolute rather than a relative `url`, but using `urlPath` is +the recommended way, as doing so makes the tests be host-independent. + +The following example uses `url`: ==== [source,groovy,indent=0,role="primary"] @@ -278,7 +300,7 @@ include::{verifier_core_path}/src/test/resources/yml/contract_rest_with_path.yml ---- ==== -`request` may contain **query parameters**. +`request` may contain query parameters, as the following example (which uses `urlPath`) shows: ==== [source,groovy,indent=0,subs="verbatim,attributes",role="primary"] @@ -296,7 +318,7 @@ include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=query_par ---- ==== -`request` may contain additional **request headers**, as shown in the following example: +`request` can contain additional request headers, as the following example shows: ==== [source,groovy,indent=0,subs="verbatim,attributes",role="primary"] @@ -314,7 +336,7 @@ include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=headers,i ---- ==== -`request` may contain additional **request cookies**, as shown in the following example: +`request` may contain additional request cookies, as the following example shows: ==== [source,groovy,indent=0,subs="verbatim,attributes",role="primary"] @@ -332,7 +354,7 @@ include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=cookies,i ---- ==== -`request` may contain a **request body**: +`request` may contain a request body, as the following example shows: ==== [source,groovy,indent=0,subs="verbatim,attributes",role="primary"] @@ -350,8 +372,8 @@ include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=body,inde ---- ==== -`request` may contain **multipart** elements. To include multipart elements, use the -`multipart` method/section, as shown in the following examples +`request` can contain multipart elements. To include multipart elements, use the +`multipart` method/section, as the following examples show: ==== [source,groovy,indent=0,role="primary"] @@ -373,25 +395,25 @@ In the preceding example, we define parameters in either of two ways: * Directly, by using the map notation, where the value can be a dynamic property (such as `formParameter: $(consumer(...), producer(...))`). * By using the `named(...)` method that lets you set a named parameter. A named parameter -can set a `name` and `content`. You can call it either via a method with two arguments, -such as `named("fileName", "fileContent")`, or via a map notation, such as +can set a `name` and `content`. You can call it either by using a method with two arguments, +such as `named("fileName", "fileContent")`, or by using a map notation, such as `named(name: "fileName", content: "fileContent")`. .YAML -* The multipart parameters are set via `multipart.params` section +* The multipart parameters are set in the `multipart.params` section. * The named parameters (the `fileName` and `fileContent` for a given parameter name) -can be set via the `multipart.named` section. That section contains -the `paramName` (name of the parameter), `fileName` (name of the file), -`fileContent` (content of the file) fields -* The dynamic bits can be set via the `matchers.multipart` section -** for parameters use the `params` section that can accept -`regex` or a `predefined` regular expression -** for named params use the `named` section where first you -define the parameter name via `paramName` and then you can pass the -parametrization of either `fileName` or `fileContent` via -`regex` or a `predefined` regular expression +can be set in the `multipart.named` section. That section contains +the `paramName` (the name of the parameter), `fileName` (the name of the file), +`fileContent` (the content of the file) fields. +* The dynamic bits can be set via the `matchers.multipart` section. +** For parameters, use the `params` section, which can accept +`regex` or a `predefined` regular expression. +** for named params, use the `named` section where first you +define the parameter name with `paramName`. Then you can pass the +parametrization of either `fileName` or `fileContent` in a +`regex` or in a `predefined` regular expression. -From this contract, the generated test and stubs look as follows: +From the contract in the preceding example, the generated test and stubs look as follows: ==== [source,java,indent=0,subs="verbatim,attributes",role="primary"] @@ -422,7 +444,7 @@ include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract [[contract-dsl-response]] === HTTP Response -The response must contain an **HTTP status code** and may contain other information. The +The response must contain an HTTP status code and may contain other information. The following code shows an example: ==== @@ -441,11 +463,11 @@ include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=response_ ---- ==== -Besides status, the response may contain **headers**, **cookies** and a **body**, both of which are -specified the same way as in the request (see the previous paragraph). +Besides status, the response may contain headers, cookies, and a body, which are +specified the same way as in the request (see <>). -TIP: Via the Groovy DSL you can reference the `org.springframework.cloud.contract.spec.internal.HttpStatus` -methods to provide a meaningful status instead of a digit. E.g. you can call +TIP: In the Groovy DSL, you can reference the `org.springframework.cloud.contract.spec.internal.HttpStatus` +methods to provide a meaningful status instead of a digit. For example, you can call `OK()` for a status `200` or `BAD_REQUEST()` for `400`. [[contract-dsl-dynamic-properties]] @@ -455,19 +477,19 @@ The contract can contain some dynamic properties: timestamps, IDs, and so on. Yo want to force the consumers to stub their clocks to always return the same value of time so that it gets matched by the stub. -For Groovy DSL you can provide the dynamic parts in your contracts +For the Groovy DSL, you can provide the dynamic parts in your contracts in two ways: pass them directly in the body or set them in a separate section called `bodyMatchers`. -NOTE: Before 2.0.0 these were set using `testMatchers` and `stubMatchers`, -check out the https://github.com/spring-cloud/spring-cloud-contract/wiki/Spring-Cloud-Contract-2.0-Migration-Guide[migration guide] for more information. +NOTE: Before 2.0.0, these were set by using `testMatchers` and `stubMatchers`. +See the https://github.com/spring-cloud/spring-cloud-contract/wiki/Spring-Cloud-Contract-2.0-Migration-Guide[migration guide] for more information. -For YAML you can only use the `matchers` section. +For YAML, you can use only the `matchers` section. [[contract-dsl-dynamic-properties-in-body]] -==== Dynamic properties inside the body +==== Dynamic Properties inside the Body -IMPORTANT: This section is valid only for Groovy DSL. Check out the +IMPORTANT: This section is valid only for the Groovy DSL. Check out the <> section for YAML examples of a similar feature. You can set the properties inside the body either with the `value` method or, if you use @@ -494,23 +516,23 @@ $(client(...), server(...)) ---- ==== -Both approaches work equally well. `stub` and `client` methods are aliases over the `consumer` +Both approaches work equally well. The `stub` and `client` methods are aliases over the `consumer` method. Subsequent sections take a closer look at what you can do with those values. [[contract-dsl-regex]] -==== Regular expressions +==== Regular Expressions IMPORTANT: This section is valid only for Groovy DSL. Check out the <> section for YAML examples of a similar feature. -You can use regular expressions to write your requests in Contract DSL. Doing so is +You can use regular expressions to write your requests in the contract DSL. Doing so is particularly useful when you want to indicate that a given response should be provided for requests that follow a given pattern. Also, you can use regular expressions when you -need to use patterns and not exact values both for your test and your server side tests. +need to use patterns and not exact values both for your tests and your server-side tests. -Make sure that regex matches a whole region of a sequence as internally a call to -https://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html#matches--[Pattern.matches()] -is called. For instance, `abc` pattern doesn't match `aabc` string but `.abc` does. +Make sure that regex matches a whole region of a sequence, as, internally, a call to +https://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html#matches[`Pattern.matches()`] +is called. For instance, `abc` does not match `aabc`, but `.abc` does. There are several additional <> as well. The following example shows how to use regular expressions to write a request: @@ -533,29 +555,30 @@ In the preceding example, the opposite side of the communication has the respect generated for request and response. Spring Cloud Contract comes with a series of predefined regular expressions that you can -use in your contracts, as shown in the following example: +use in your contracts, as the following example shows: [source,java,indent=0] ---- include::{contract_spec_path}/src/main/java/org/springframework/cloud/contract/spec/internal/RegexPatterns.java[tags=regexps,indent=0] ---- -In your contract, you can use it as shown in the following example: +In your contract, you can use it as follows: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/SpringTestMethodBodyBuildersSpec.groovy[tags=contract_with_regex,indent=0] ---- -To make matters even simpler you can use a set of predefined objects that will automatically assume that you want a regular expression to be passed. -All of those methods start with `any` prefix: +To make matters even simpler, you can use a set of predefined objects that automatically +assume that you want a regular expression to be passed. +All of those methods start with the `any` prefix, as follows: [source,java,indent=0] ---- include::{contract_spec_path}/src/main/java/org/springframework/cloud/contract/spec/internal/RegexCreatingProperty.java[tags=regex_creating_props,indent=0] ---- -and this is an example of how you can reference those methods: +The following example shows how you can reference those methods: [source,groovy,indent=0] ---- @@ -565,13 +588,13 @@ include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract [[contract-dsl-regex-limitations]] ===== Limitations -WARNING: Due to certain limitations of `Xeger` library that generates string out of -regex, do not use `$` and `^` signs in your regex if you rely on automatic -generation. https://github.com/spring-cloud/spring-cloud-contract/issues/899[Issue 899] +WARNING: Due to certain limitations of the `Xeger` library that generates a string out of +a regex, do not use the `$` and `^` signs in your regex if you rely on automatic +generation. See https://github.com/spring-cloud/spring-cloud-contract/issues/899[Issue 899]. -WARNING: Do not use `LocalDate` instance as a value for `$` like this `$(consumer(LocalDate.now()))`. -It causes `java.lang.StackOverflowError`. Use `$(consumer(LocalDate.now().toString()))` instead. -https://github.com/spring-cloud/spring-cloud-contract/issues/900[Issue 900] +WARNING: Do not use a `LocalDate` instance as a value for `$` (for example, `$(consumer(LocalDate.now()))`). +It causes a `java.lang.StackOverflowError`. Use `$(consumer(LocalDate.now().toString()))` instead. +See https://github.com/spring-cloud/spring-cloud-contract/issues/900[Issue 900]. [[contract-dsl-optional-params]] ==== Passing Optional Parameters @@ -579,11 +602,11 @@ https://github.com/spring-cloud/spring-cloud-contract/issues/900[Issue 900] IMPORTANT: This section is valid only for Groovy DSL. Check out the <> section for YAML examples of a similar feature. -It is possible to provide optional parameters in your contract. However, you can provide +You can provide optional parameters in your contract. However, you can provide optional parameters only for the following: -* __STUB__ side of the Request -* __TEST__ side of the Response +* The STUB side of the Request +* The TEST side of the Response The following example shows how to provide optional parameters: @@ -595,7 +618,7 @@ include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract By wrapping a part of the body with the `optional()` method, you create a regular expression that must be present 0 or more times. -If you use Spock for, the following test would be generated from the previous example: +If you use Spock, the following test would be generated from the previous example: [source,groovy,indent=0] ---- @@ -615,8 +638,8 @@ include::{plugins_path}/spring-cloud-contract-converters/src/test/groovy/org/spr IMPORTANT: This section is valid only for Groovy DSL. Check out the <> section for YAML examples of a similar feature. -You can define a method call that executes on the server side during the test. Such a -method can be added to the class defined as "baseClassForTests" in the configuration. The +You can define a method call that runs on the server side during the test. Such a +method can be added to the class defined as `baseClassForTests` in the configuration. The following code shows an example of the contract portion of the test case: [source,groovy,indent=0] @@ -631,7 +654,7 @@ The following code shows the base class portion of the test case: include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/resources/functionalTest/bootSimple/src/test/groovy/org/springframework/cloud/contract/verifier/twitter/places/BaseMockMvcSpec.groovy[tags=base_class,indent=0] ---- -IMPORTANT: You cannot use both a String and `execute` to perform concatenation. For +IMPORTANT: You cannot use both a `String` and `execute` to perform concatenation. For example, calling `header('Authorization', 'Bearer ' + execute('authToken()'))` leads to improper results. Instead, call `header('Authorization', execute('authToken()'))` and ensure that the `authToken()` method returns everything you need. @@ -642,14 +665,14 @@ JSON path: * `String`: If you point to a `String` value in the JSON. * `JSONArray`: If you point to a `List` in the JSON. * `Map`: If you point to a `Map` in the JSON. -* `Number`: If you point to `Integer`, `Double` etc. in the JSON. +* `Number`: If you point to `Integer`, `Double`, and other numeric type in the JSON. * `Boolean`: If you point to a `Boolean` in the JSON. In the request part of the contract, you can specify that the `body` should be taken from a method. IMPORTANT: You must provide both the consumer and the producer side. The `execute` part -is applied for the whole body - not for parts of it. +is applied for the whole body, not for parts of it. The following example shows how to read an object from JSON: @@ -681,7 +704,7 @@ It should resemble the following code: The best situation is to provide fixed values, but sometimes you need to reference a request in your response. -If you're writing contracts using Groovy DSL, you can use the `fromRequest()` method, which lets +If you write contracts in the Groovy DSL, you can use the `fromRequest()` method, which lets you reference a bunch of elements from the HTTP request. You can use the following options: @@ -697,21 +720,21 @@ given name. * `fromRequest().body(String jsonPath)`: Returns the element from the request that matches the JSON Path. -If you're using the YAML contract definition you have to use the -https://handlebarsjs.com/[Handlebars] `{{{ }}}` notation with custom, Spring Cloud Contract - functions to achieve this. +If you use the YAML contract definition, you have to use the +https://handlebarsjs.com/[Handlebars] `{{{ }}}` notation with custom Spring Cloud Contract +functions to achieve this. In that case, you can use the following options: * `{{{ request.url }}}`: Returns the request URL and query parameters. * `{{{ request.query.key.[index] }}}`: Returns the nth query parameter with a given name. -E.g. for key `foo`, first entry `{{{ request.query.foo.[0] }}}` +For example, for a key of `thing`, the first entry is `{{{ request.query.thing.[0] }}}` * `{{{ request.path }}}`: Returns the full path. -* `{{{ request.path.[index] }}}`: Returns the nth path element. E.g. -for first entry ```{{{ request.path.[0] }}} +* `{{{ request.path.[index] }}}`: Returns the nth path element. For example, +the first entry is ```{{{ request.path.[0] }}} * `{{{ request.headers.key }}}`: Returns the first header with a given name. * `{{{ request.headers.key.[index] }}}`: Returns the nth header with a given name. * `{{{ request.body }}}`: Returns the full request body. * `{{{ jsonpath this 'your.json.path' }}}`: Returns the element from the request that -matches the JSON Path. E.g. for json path `$.foo` - `{{{ jsonpath this '$.foo' }}}` +matches the JSON Path. For example, for a JSON path of `$.here`, use `{{{ jsonpath this '$.here' }}}` Consider the following contract: @@ -820,7 +843,7 @@ in sending the following response body: } ---- -IMPORTANT: This feature works only with WireMock having a version greater than or equal +IMPORTANT: This feature works only with WireMock versions greater than or equal to 2.5.1. The Spring Cloud Contract Verifier uses WireMock's `response-template` response transformer. It uses Handlebars to convert the Mustache `{{{ }}}` templates into proper values. Additionally, it registers two helper functions: @@ -843,77 +866,79 @@ You can set it in the `request` or `inputMessage` part of your contract. This section is present in the `response` or `outputMessage` side of the contract. -Currently, Spring Cloud Contract Verifier supports only JSON Path-based matchers with the +Currently, Spring Cloud Contract Verifier supports only JSON path-based matchers with the following matching possibilities: -.Groovy DSL +===== Groovy DSL -* For the stubs(in tests on the Consumer's side): -** `byEquality()`: The value taken from the consumer's request via the provided JSON Path must be +* For the stubs (in tests on the consumer's side): +** `byEquality()`: The value taken from the consumer's request in the provided JSON path must be equal to the value provided in the contract. -** `byRegex(...)`: The value taken from the consumer's request via the provided JSON Path must -match the regex. You can also pass the type of the expected matched value (e.g. `asString()`, `asLong()` etc.) -** `byDate()`: The value taken from the consumer's request via the provided JSON Path must +** `byRegex(...)`: The value taken from the consumer's request in the provided JSON path must +match the regex. You can also pass the type of the expected matched value (for example, `asString()`, `asLong()`, and so on). +** `byDate()`: The value taken from the consumer's request in the provided JSON path must match the regex for an ISO Date value. -** `byTimestamp()`: The value taken from the consumer's request via the provided JSON Path must +** `byTimestamp()`: The value taken from the consumer's request in the provided JSON path must match the regex for an ISO DateTime value. -** `byTime()`: The value taken from the consumer's request via the provided JSON Path must +** `byTime()`: The value taken from the consumer's request in the provided JSON path must match the regex for an ISO Time value. -* For the verification(in generated tests on the Producer's side): -** `byEquality()`: The value taken from the producer's response via the provided JSON Path must be +* For the verification (in generated tests on the Producer's side): +** `byEquality()`: The value taken from the producer's response in the provided JSON path must be equal to the provided value in the contract. -** `byRegex(...)`: The value taken from the producer's response via the provided JSON Path must +** `byRegex(...)`: The value taken from the producer's response in the provided JSON path must match the regex. -** `byDate()`: The value taken from the producer's response via the provided JSON Path must match +** `byDate()`: The value taken from the producer's response in the provided JSON path must match the regex for an ISO Date value. -** `byTimestamp()`: The value taken from the producer's response via the provided JSON Path must +** `byTimestamp()`: The value taken from the producer's response in the provided JSON path must match the regex for an ISO DateTime value. -** `byTime()`: The value taken from the producer's response via the provided JSON Path must match +** `byTime()`: The value taken from the producer's response in the provided JSON path must match the regex for an ISO Time value. -** `byType()`: The value taken from the producer's response via the provided JSON Path needs to be +** `byType()`: The value taken from the producer's response in the provided JSON path needs to be of the same type as the type defined in the body of the response in the contract. -`byType` can take a closure, in which you can set `minOccurrence` and `maxOccurrence`. For the request side, you should use the closure to assert size of the collection. +`byType` can take a closure, in which you can set `minOccurrence` and `maxOccurrence`. For the +request side, you should use the closure to assert size of the collection. That way, you can assert the size of the flattened collection. To check the size of an -unflattened collection, use a custom method with the `byCommand(...)` testMatcher. -** `byCommand(...)`: The value taken from the producer's response via the provided JSON Path is +unflattened collection, use a custom method with the `byCommand(...)` `testMatcher`. +** `byCommand(...)`: The value taken from the producer's response in the provided JSON path is passed as an input to the custom method that you provide. For example, -`byCommand('foo($it)')` results in calling a `foo` method to which the value matching the +`byCommand('thing($it)')` results in calling a `thing` method to which the value matching the JSON Path gets passed. The type of the object read from the JSON can be one of the following, depending on the JSON path: *** `String`: If you point to a `String` value. *** `JSONArray`: If you point to a `List`. *** `Map`: If you point to a `Map`. -*** `Number`: If you point to `Integer`, `Double`, or other kind of number. +*** `Number`: If you point to `Integer`, `Double`, or another kind of number. *** `Boolean`: If you point to a `Boolean`. -** `byNull()`: The value taken from the response via the provided JSON Path must be null +** `byNull()`: The value taken from the response in the provided JSON path must be null. -.YAML +===== YAML -_Please read the Groovy section for detailed explanation of -what the types mean_ +NOTE: See the Groovy section for detailed explanation of +what the types mean. -For YAML the structure of a matcher looks like this +For YAML, the structure of a matcher resembles the following example: [source,yml,indent=0] ---- -- path: $.foo +- path: $.thing1 type: by_regex - value: bar + value: thing2 regexType: as_string ---- -Or if you want to use one of the predefined regular expressions +Alternatively, if you want to use one of the predefined regular expressions `[only_alpha_unicode, number, any_boolean, ip_address, hostname, -email, url, uuid, iso_date, iso_date_time, iso_time, iso_8601_with_offset, non_empty, non_blank]`: +email, url, uuid, iso_date, iso_date_time, iso_time, iso_8601_with_offset, non_empty, +non_blank]`, you can use something similar to the following example: [source,yml,indent=0] ---- -- path: $.foo +- path: $.thing1 type: by_regex predefined: only_alpha_unicode ---- -Below you can find the allowed list of `type`s. +The following list shows the allowed list of `type` values: * For `stubMatchers`: ** `by_equality` @@ -922,7 +947,7 @@ Below you can find the allowed list of `type`s. ** `by_timestamp` ** `by_time` ** `by_type` -*** there are 2 additional fields accepted: `minOccurrence` and `maxOccurrence`. +*** Two additional fields (`minOccurrence` and `maxOccurrence`) are accepted. * For `testMatchers`: ** `by_equality` ** `by_regex` @@ -930,19 +955,20 @@ Below you can find the allowed list of `type`s. ** `by_timestamp` ** `by_time` ** `by_type` -*** there are 2 additional fields accepted: `minOccurrence` and `maxOccurrence`. +*** Two additional fields (`minOccurrence` and `maxOccurrence`) are accepted. ** `by_command` ** `by_null` -You can also define which type the regular expression corresponds to via the `regexType` field. Below you can find the allowed list of regular expression types: +You can also define which type the regular expression corresponds to in the `regexType` +field. The following list shows the allowed regular expression types: -* as_integer -* as_double -* as_float, -* as_long -* as_short -* as_boolean -* as_string +* `as_integer` +* `as_double` +* `as_float` +* `as_long` +* `as_short` +* `as_boolean` +* `as_string` Consider the following example: @@ -974,14 +1000,14 @@ has a value for which the JSON path matches the given field, is of the same type defined in the response body, and passes the following check (based on the method being called): * For `$.valueWithTypeMatch`, the engine checks whether the type is the same. -* For `$.valueWithMin`, the engine check the type and asserts whether the size is greater +* For `$.valueWithMin`, the engine checks the type and asserts whether the size is greater than or equal to the minimum occurrence. * For `$.valueWithMax`, the engine checks the type and asserts whether the size is smaller than or equal to the maximum occurrence. * For `$.valueWithMinMax`, the engine checks the type and asserts whether the size is -between the min and maximum occurrence. +between the minimum and maximum occurrence. -The resulting test would resemble the following example (note that an `and` section +The resulting test resembles the following example (note that an `and` section separates the autogenerated assertions and the assertion from matchers): [source,java,indent=0] @@ -1039,7 +1065,7 @@ The resulting WireMock stub is in the following example: include::{plugins_path}/spring-cloud-contract-converters/src/test/groovy/org/springframework/cloud/contract/verifier/wiremock/DslToWireMockClientConverterSpec.groovy[tags=matchers,indent=0] ---- -IMPORTANT: If you use a `matcher`, then the part of the request and response that the +IMPORTANT: If you use a `matcher`, the part of the request and response that the `matcher` addresses with the JSON Path gets removed from the assertion. In the case of verifying a collection, you must create matchers for *all* the elements of the collection. @@ -1099,9 +1125,9 @@ collection and assert it with the `byCommand(...)` method. [[contract-dsl-async]] -=== Async Support +=== Asynchronous Support -If you're using asynchronous communication on the server side (your controllers are +If you use asynchronous communication on the server side (your controllers are returning `Callable`, `DeferredResult`, and so on), then, inside your contract, you must provide an `async()` method in the `response` section. The following code shows an example: @@ -1130,7 +1156,8 @@ response: ---- ==== -You can also use the `fixedDelayMilliseconds` method / property to add delay to your stubs. +You can also use the `fixedDelayMilliseconds` method or property to add delay to your stubs. +The following example shows how to do so: ==== [source,groovy,indent=0,subs="verbatim,attributes",role="primary"] @@ -1159,14 +1186,15 @@ response: [[contract-dsl-xml]] === XML Support for HTTP -For HTTP contracts, we also support XML request and response body. + +For HTTP contracts, we also support using XML in the request and response body. The XML body has to be passed within the `body` element -as a `String` or `GString`. Also body matchers can be provided for -both request and response. In place of the `jsonPath(...)` method, the `org.springframework.cloud.contract.spec.internal.BodyMatchers.xPath` +as a `String` or `GString`. Also, body matchers can be provided for +both the request and the response. In place of the `jsonPath(...)` method, the `org.springframework.cloud.contract.spec.internal.BodyMatchers.xPath` method should be used, with the desired `xPath` provided as the first argument and the appropriate `MatchingType` as second. All the body matchers apart from `byType()` are supported. -Here is an example of a Groovy DSL contract with XML response body: +The following example shows a Groovy DSL contract with XML in the response body: ==== [source,groovy,indent=0,subs="verbatim,attributes",role="primary"] @@ -1182,7 +1210,7 @@ include::{verifier_core_path}/src/test/resources/yml/contract_rest_xml.yml ---- ==== -Here is an example of an automatically generated test for XML response body: +The following example shows an automatically generated test for XML in the response body: [source,java,indent=0] ---- @@ -1234,7 +1262,7 @@ include::{verifier_core_path}/src/test/resources/yml/multiple_contracts.yml[inde ==== In the preceding example, one contract has the `name` field and the other does not. This -leads to generation of two tests that look more or less like this: +leads to generation of two tests that look more or less like the following: [source,java,indent=0] ---- @@ -1283,39 +1311,46 @@ public class V1Test extends TestBase { ---- Notice that, for the contract that has the `name` field, the generated test method is named -`validate_should_post_a_user`. For the one that does not have the name, it is called +`validate_should_post_a_user`. The one that does not have the `name` field is called `validate_withList_1`. It corresponds to the name of the file `WithList.groovy` and the index of the contract in the list. -The generated stubs is shown in the following example: +The generated stubs are shown in the following example: +==== [source] ---- should post a user.json 1_WithList.json ---- +==== -As you can see, the first file got the `name` parameter from the contract. The second +The first file got the `name` parameter from the contract. The second got the name of the contract file (`WithList.groovy`) prefixed with the index (in this case, the contract had an index of `1` in the list of contracts in the file). -TIP: As you can see, it is much better if you name your contracts because doing so makes +TIP: It is much better to name your contracts, because doing so makes your tests far more meaningful. [[contract-stateful-contracts]] === Stateful Contracts -Stateful contracts (known also as scenarios) are contract definitions that should be read in order. This might be useful in the following situations: +Stateful contracts (known also as scenarios) are contract definitions that should be read +in order. This might be useful in the following situations: -* you want to execute the contract in a precisely defined order, since you're using Spring Cloud Contract to test your stateful application -** NOTE: we really discourage you to do that since contract tests should be stateless -* you want the same endpoint to return different results for the same request +* You want to execute the contract in a precisely defined order, since you use Spring +Cloud Contract to test your stateful application -All you need to do is to -stick to the proper naming convention while creating your contracts. The convention -requires including an order number followed by an underscore. This will work regardless - of whether you're working with YAML or Groovy. Example: +TIP: We really discourage you from doing that, since contract tests should be stateless. +* You want the same endpoint to return different results for the same request. + +To create stateful contracts (or scenarios), you need to +use the proper naming convention while creating your contracts. The convention +requires including an order number followed by an underscore. This works regardless +of whether you work with YAML or Groovy. The following listing shows an example: + +==== [source,indent=0] ---- my_contracts_dir\ @@ -1324,15 +1359,18 @@ my_contracts_dir\ 2_showCart.groovy 3_logout.groovy ---- +==== Such a tree causes Spring Cloud Contract Verifier to generate WireMock's scenario with a name of `scenario1` and the three following steps: -. login marked as `Started` pointing to... -. showCart marked as `Step1` pointing to... -. logout marked as `Step2` which will close the scenario. +. login, marked as `Started` pointing to... +. showCart, marked as `Step1` pointing to... +. logout, marked as `Step2` (which closes the scenario). -More details about WireMock scenarios can be found at -https://wiremock.org/docs/stateful-behaviour/[https://wiremock.org/docs/stateful-behaviour/] +You can find nore details about WireMock scenarios at +https://wiremock.org/docs/stateful-behaviour/[https://wiremock.org/docs/stateful-behaviour/]. -Spring Cloud Contract also generates tests with a guaranteed order of execution. \ No newline at end of file +Spring Cloud Contract also generates tests with a guaranteed order of execution. +// TODO: How can someone specify the order of execution in SC Contract? +// That sentence is a great lead-in to more content, which then does not appear. diff --git a/docs/src/main/asciidoc/_project-features-flows.adoc b/docs/src/main/asciidoc/_project-features-flows.adoc index d936a3eaf3..177794758a 100644 --- a/docs/src/main/asciidoc/_project-features-flows.adoc +++ b/docs/src/main/asciidoc/_project-features-flows.adoc @@ -8,7 +8,7 @@ include::_attributes.adoc[] The Spring Cloud Contract supports the JAX-RS 2 Client API. The base class needs to define `protected WebTarget webTarget` and server initialization. The only option for testing JAX-RS API is to start a web server. Also, a request with a body needs to have a -content type set. Otherwise, the default of `application/octet-stream` gets used. +content type be set. Otherwise, the default of `application/octet-stream` gets used. In order to use JAX-RS mode, use the following settings: @@ -27,7 +27,8 @@ include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract [[feature-webflux]] === WebFlux with WebTestClient -You can work with WebFlux via the `WebTestClient` mode. +You can work with WebFlux by using WebTestClient. The following listing shows how to +configure WebTestClient as the test mode: ==== [source,xml,indent=0,subs="verbatim,attributes",role="primary"] @@ -53,7 +54,7 @@ contracts { ---- ==== -The following example shows how to set up a `WebTestClient` base class and `RestAssured` +The following example shows how to set up a WebTestClient base class and RestAssured for WebFlux: [source,groovy,indent=0] @@ -72,13 +73,13 @@ public abstract class BeerRestBase { } ---- -IMPORTANT: The `WebTestClient` mode is faster than the `EXPLICIT` mode +TIP: The `WebTestClient` mode is faster than the `EXPLICIT` mode. [[feature-webflux-explicit]] -=== WebFlux with Explicit mode +=== WebFlux with Explicit Mode -Another way is with the `EXPLICIT` mode in your generated tests -to work with WebFlux. +You can also use WebFlux with the explicit mode in your generated tests +to work with WebFlux. The following example shows how to configure using explicit mode: ==== [source,xml,indent=0,subs="verbatim,attributes",role="primary"] @@ -104,7 +105,7 @@ contracts { ---- ==== -The following example shows how to set up a base class and Rest Assured for Web Flux: +The following example shows how to set up a base class and RestAssured for Web Flux: [source,groovy,indent=0] ---- @@ -123,10 +124,12 @@ include::{samples_url}/producer_webflux/src/test/java/com/example/BeerRestBase.j Spring Cloud Contract supports context paths. -IMPORTANT: The only change needed to fully support context paths is the switch on the -*PRODUCER* side. Also, the autogenerated tests must use *EXPLICIT* mode. The consumer -side remains untouched. In order for the generated test to pass, you must use *EXPLICIT* -mode. +[IMPORTANT] +===== +The only change needed to fully support context paths is the switch on the +producer side. Also, the autogenerated tests must use explicit mode. The consumer +side remains untouched. In order for the generated test to pass, you must use explicit +mode. The following example shows how to set the test mode to `EXPLICIT`: ==== [source,xml,indent=0,subs="verbatim,attributes",role="primary"] @@ -151,9 +154,10 @@ contracts { } ---- ==== +===== -That way, you generate a test that *DOES NOT* use MockMvc. It means that you generate -real requests and you need to setup your generated test's base class to work on a real +That way, you generate a test that does not use MockMvc. It means that you generate +real requests and you need to set up your generated test's base class to work on a real socket. Consider the following contract: @@ -163,7 +167,7 @@ Consider the following contract: include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/SingleTestGeneratorSpec.groovy[tags=context_path_contract,indent=0] ---- -The following example shows how to set up a base class and Rest Assured: +The following example shows how to set up a base class and RestAssured: [source,groovy,indent=0] ---- @@ -180,36 +184,35 @@ that information (for example, in the stubs, you have to call `/my-context-path/ [[features-rest-docs]] === Working with REST Docs -https://projects.spring.io/spring-restdocs[Spring REST Docs] can be used to generate -documentation (for example in Asciidoctor format) for an HTTP API with Spring MockMvc -or `WebTestClient` or Rest Assured. At the same time that you generate documentation for your API, you can also +You can use https://projects.spring.io/spring-restdocs[Spring REST Docs] to generate +documentation (for example, in Asciidoc format) for an HTTP API with Spring MockMvc, +`WebTestClient`, or RestAssured. At the same time that you generate documentation for your API, you can also generate WireMock stubs by using Spring Cloud Contract WireMock. To do so, write your normal REST Docs test cases and use `@AutoConfigureRestDocs` to have stubs be automatically generated in the REST Docs output directory. [plantuml, rest-docs, png] ---- -"API Producer"->"API Producer": add Spring Cloud Contract (SCC) \nStub Runner dependency -"API Producer"->"API Producer": setup stub jar assembly -"API Producer"->"API Producer": write and setup REST Docs tests -"API Producer"->"Build": run build -"Build"->"REST Docs": generate API \ndocumentation -"REST Docs"->"SCC": generate stubs from the \nREST Docs tests -"REST Docs"->"SCC": generate contracts from the \nREST Docs tests -"Build"->"Build": assemble stubs jar with \nstubs and contracts -"Build"->"Nexus / Artifactory": upload contracts \nand stubs and the project arifact +"API Producer"->"API Producer": Add Spring Cloud Contract (SCC) \nStub Runner dependency +"API Producer"->"API Producer": Set up stub jar assembly +"API Producer"->"API Producer": Write and set up REST Docs tests +"API Producer"->"Build": Run build +"Build"->"REST Docs": Generate API \ndocumentation +"REST Docs"->"SCC": Generate stubs from the \nREST Docs tests +"REST Docs"->"SCC": Generate contracts from the \nREST Docs tests +"Build"->"Build": Assemble stubs jar with \nstubs and contracts +"Build"->"Nexus / Artifactory": Upload contracts \nand stubs and the project arifact "Build"->"API Producer": Build successful -"API Consumer"->"API Consumer": add SCC Stub Runner \ndependency -"API Consumer"->"API Consumer": write a SCC Stub Runner \nbased contract test -"SCC Stub Runner"->"Nexus / Artifactory": test asks for [API Producer] stubs -"Nexus / Artifactory"->"SCC Stub Runner": fetch the [API Producer] stubs -"SCC Stub Runner"->"SCC Stub Runner": run in memory\n HTTP server stubs -"API Consumer"->"SCC Stub Runner": send a request \nto the HTTP server stub -"SCC Stub Runner"->"API Consumer": communication is correct +"API Consumer"->"API Consumer": Add SCC Stub Runner \ndependency +"API Consumer"->"API Consumer": Write a SCC Stub Runner \nbased contract test +"SCC Stub Runner"->"Nexus / Artifactory": Test asks for [API Producer] stubs +"Nexus / Artifactory"->"SCC Stub Runner": Fetch the [API Producer] stubs +"SCC Stub Runner"->"SCC Stub Runner": Run in memory\n HTTP server stubs +"API Consumer"->"SCC Stub Runner": Send a request \nto the HTTP server stub +"SCC Stub Runner"->"API Consumer": Communication is correct ---- -The following code shows an -example using `MockMvc`: +The following example uses `MockMvc`: [source,java,indent=0] ---- @@ -231,9 +234,9 @@ public class ApplicationTests { } ---- -This test generates a WireMock stub at "target/snippets/stubs/resource.json". It matches -all GET requests to the "/resource" path. The same example with `WebTestClient` (used -for testing Spring WebFlux applications) would look like this: +This test generates a WireMock stub at `target/snippets/stubs/resource.json`. It matches +all `GET` requests to the `/resource` path. The same example with `WebTestClient` (used +for testing Spring WebFlux applications) would be as follows: [source,java,indent=0] ---- @@ -256,7 +259,7 @@ public class ApplicationTests { ---- Without any additional configuration, these tests create a stub with a request matcher -for the HTTP method and all headers except "host" and "content-length". To match the +for the HTTP method and all headers except `host` and `content-length`. To match the request more precisely (for example, to match the body of a POST or PUT), we need to explicitly create a request matcher. Doing so has two effects: @@ -264,14 +267,14 @@ explicitly create a request matcher. Doing so has two effects: * Asserting that the request in the test case also matches the same conditions. The main entry point for this feature is `WireMockRestDocs.verify()`, which can be used -as a substitute for the `document()` convenience method, as shown in the following -example: +as a substitute for the `document()` convenience method, as the following +example shows: +==== [source,java,indent=0] - +---- import static org.springframework.cloud.contract.wiremock.restdocs.WireMockRestDocs.verify; ----- @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureRestDocs(outputDir = "target/snippets") @@ -291,16 +294,17 @@ public class ApplicationTests { } } ---- +==== -This contract specifies that any valid POST with an "id" field receives the response +The preceding contract specifies that any valid POST with an `id` field receives the response defined in this test. You can chain together calls to `.jsonPath()` to add additional -matchers. If JSON Path is unfamiliar, The https://github.com/jayway/JsonPath[JayWay +matchers. If JSON Path is unfamiliar, the https://github.com/jayway/JsonPath[JayWay documentation] can help you get up to speed. The `WebTestClient` version of this test has a similar `verify()` static helper that you insert in the same place. Instead of the `jsonPath` and `contentType` convenience methods, you can also use the -WireMock APIs to verify that the request matches the created stub, as shown in the -following example: +WireMock APIs to verify that the request matches the created stub, as the +following example shows: [source,java,indent=0] ---- @@ -317,9 +321,9 @@ following example: } ---- -The WireMock API is rich. You can match headers, query parameters, and request body by -regex as well as by JSON path. These features can be used to create stubs with a wider -range of parameters. The above example generates a stub resembling the following example: +The WireMock API is rich. You can match headers, query parameters, and the request body by +regex as well as by JSON path. You can use these features to create stubs with a wider +range of parameters. The preceding example generates a stub resembling the following example: .post-resource.json [source,json] @@ -344,17 +348,17 @@ range of parameters. The above example generates a stub resembling the following ---- NOTE: You can use either the `wiremock()` method or the `jsonPath()` and `contentType()` -methods to create request matchers, but you can't use both approaches. +methods to create request matchers, but you cannot use both approaches. On the consumer side, you can make the `resource.json` generated earlier in this section available on the classpath (by -<> -* <> -* <> +. <> +. <> +. <> [[features-messaging-stub-runner-integration-scenario1]] -===== Scenario 1 (no input message) +===== Scenario 1 (No Input Message) -To trigger a message via the `return_book_1` label, use the `StubTigger` interface, as +To trigger a message from the `return_book_1` label, use the `StubTigger` interface, as follows: +==== [source,groovy] ---- include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_trigger,indent=0] ---- +==== -To listen to the output of the message sent to `{output_name}`: +The following listing shows how to listen to the output of the message sent to `{output_name}`: +==== [source,groovy] ---- include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_trigger_receive,indent=0] ---- +==== The received message would pass the following assertions: +==== [source,groovy] ---- include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_trigger_message,indent=0] ---- +==== [[features-messaging-stub-runner-integration-scenario2]] -===== Scenario 2 (output triggered by input) +===== Scenario 2 (Output Triggered by Input) Since the route is set for you, you can send a message to the `{output_name}` -destination: +destination, as follows: +==== [source,groovy] ---- include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_send,indent=0] ---- +==== -To listen to the output of the message sent to `{output_name}`: +The following listing shows how to listen to the output of the message sent to `{output_name}`: +==== [source,groovy] ---- include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_receive,indent=0] ---- +==== The received message passes the following assertions: +==== [source,groovy] ---- include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_receive_message,indent=0] ---- +==== [[features-messaging-stub-runner-integration-scenario3]] -===== Scenario 3 (input with no output) +===== Scenario 3 (Input with No Output) -Since the route is set for you, you can send a message to the `{input_name}` destination: +Since the route is set for you, you can send a message to the `{input_name}` destination, as follows: +==== [source,groovy] ---- include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=trigger_no_output,indent=0] ---- +==== [[features-messaging-stub-runner-stream]] -=== Messaging Consumer Side With Spring Cloud Stream +=== Consumer Side Messaging With Spring Cloud Stream Spring Cloud Contract Stub Runner's messaging module gives you an easy way to integrate with Spring Stream. For the provided artifacts, it automatically downloads the stubs and registers the required routes. -WARNING: If Stub Runner's integration with Stream the `messageFrom` or `sentTo` Strings -are resolved first as a `destination` of a channel and no such `destination` exists, the +WARNING: If Stub Runner's integration with the Stream `messageFrom` or `sentTo` strings +are resolved first as the `destination` of a channel and no such `destination` exists, the destination is resolved as a channel name. -IMPORTANT: If you want to use Spring Cloud Stream remember, to add a dependency on -`org.springframework.cloud:spring-cloud-stream-test-support`. +[IMPORTANT] +===== +If you want to use Spring Cloud Stream, remember to add a dependency on +`org.springframework.cloud:spring-cloud-stream-test-support`, as follows: ==== [source,xml,indent=0,subs="verbatim,attributes",role="primary"] @@ -650,6 +703,7 @@ IMPORTANT: If you want to use Spring Cloud Stream remember, to add a dependency testCompile "org.springframework.cloud:spring-cloud-stream-test-support" ---- ==== +===== [[features-messaging-stub-runner-stream-adding]] ==== Adding the Runner to the Project @@ -658,7 +712,7 @@ You can have both Spring Cloud Stream and Spring Cloud Contract Stub Runner on t classpath. Remember to annotate your test class with `@AutoConfigureStubRunner`. [[features-messaging-stub-runner-stream-disabling]] -==== Disabling the functionality +==== Disabling the Functionality If you need to disable this functionality, set the `stubrunner.stream.enabled=false` property. @@ -666,9 +720,10 @@ property. [[features-messaging-stub-runner-stream-example]] ==== Examples -Assume that you have the following Maven repository with a deployed stubs for the +Assume that you have the following Maven repository with deployed stubs for the `streamService` application: +==== [source,bash,indent=0] ---- └── .m2 @@ -684,9 +739,11 @@ Assume that you have the following Maven repository with a deployed stubs for th │   └── maven-metadata-local.xml └── maven-metadata-local.xml ---- +==== Further assume the stubs contain the following structure: +==== [source,bash,indent=0] ---- ├── META-INF @@ -698,27 +755,30 @@ Further assume the stubs contain the following structure: │   └── bookReturned2.groovy └── mappings ---- +==== -Consider the following contracts (numbered *1*): +Consider the following contracts (numbered 1 and 2): +==== [source,groovy] ---- include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=sample_dsl,indent=0] ---- -Now consider *2*: - [source,groovy] ---- include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=sample_dsl_2,indent=0] ---- +==== Now consider the following Spring configuration: +==== [source,yaml] ---- include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/resources/application.yml[] ---- +==== These examples lend themselves to three scenarios: @@ -727,69 +787,83 @@ These examples lend themselves to three scenarios: * <> [[features-messaging-stub-runner-stream-scenario1]] -===== Scenario 1 (no input message) +===== Scenario 1 (No Input Message) -To trigger a message via the `return_book_1` label, use the `StubTrigger` interface as +To trigger a message from the `return_book_1` label, use the `StubTrigger` interface as follows: +==== [source,groovy] ---- include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_trigger,indent=0] ---- +==== -To listen to the output of the message sent to a channel whose `destination` is +The following example shows how to listen to the output of the message sent to a channel whose `destination` is `returnBook`: +==== [source,groovy] ---- include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_trigger_receive,indent=0] ---- +==== The received message passes the following assertions: +==== [source,groovy] ---- include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_trigger_message,indent=0] ---- +==== [[features-messaging-stub-runner-stream-scenario2]] -===== Scenario 2 (output triggered by input) +===== Scenario 2 (Output Triggered by Input) Since the route is set for you, you can send a message to the `bookStorage` -`destination`: +`destination`, as follows: +==== [source,groovy] ---- include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_send,indent=0] ---- +==== -To listen to the output of the message sent to `returnBook`: +The following example shows how to listen to the output of the message sent to `returnBook`: +==== [source,groovy] ---- include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_receive,indent=0] ---- +==== The received message passes the following assertions: +==== [source,groovy] ---- include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_receive_message,indent=0] ---- +==== [[features-messaging-stub-runner-stream-scenario3]] -===== Scenario 3 (input with no output) +===== Scenario 3 (Input with No Output) Since the route is set for you, you can send a message to the `{output_name}` -destination: +destination, as follows: +==== [source,groovy] ---- include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=trigger_no_output,indent=0] ---- +==== [[features-messaging-stub-runner-amqp]] -=== Messaging Consumer Side With Spring AMQP +=== Consumer Side Messaging With Spring AMQP Spring Cloud Contract Stub Runner's messaging module provides an easy way to integrate with Spring AMQP's Rabbit Template. For the provided artifacts, it @@ -797,7 +871,7 @@ automatically downloads the stubs and registers the required routes. The integration tries to work standalone (that is, without interaction with a running RabbitMQ message broker). It expects a `RabbitTemplate` on the application context and -uses it as a spring boot test named `@SpyBean`. As a result, it can use the mockito spy +uses it as a spring boot test named `@SpyBean`. As a result, it can use the Mockito spy functionality to verify and inspect messages sent by the application. On the message consumer side, the stub runner considers all `@RabbitListener` annotated @@ -807,11 +881,11 @@ As messages are usually sent to exchanges in AMQP, the message contract contains exchange name as the destination. Message listeners on the other side are bound to queues. Bindings connect an exchange to a queue. If message contracts are triggered, the Spring AMQP stub runner integration looks for bindings on the application context that -match this exchange. Then it collects the queues from the Spring exchanges and tries to +matches this exchange. Then it collects the queues from the Spring exchanges and tries to find message listeners bound to these queues. The message is triggered for all matching message listeners. -If you need to work with routing keys, it's enough to pass them via the `amqp_receivedRoutingKey` +If you need to work with routing keys, you can pass them by using the `amqp_receivedRoutingKey` messaging header. [[features-messaging-stub-runner-amqp-adding]] @@ -829,8 +903,9 @@ to disable them explicitly by setting the `stubrunner.stream.enabled=false` and ==== Examples Assume that you have the following Maven repository with a deployed stubs for the -`spring-cloud-contract-amqp-test` application. +`spring-cloud-contract-amqp-test` application: +==== [source,bash,indent=0] ---- └── .m2 @@ -844,9 +919,11 @@ Assume that you have the following Maven repository with a deployed stubs for th │   └── maven-metadata-local.xml └── maven-metadata-local.xml ---- +==== Further assume that the stubs contain the following structure: +==== [source,bash,indent=0] ---- ├── META-INF @@ -854,53 +931,67 @@ Further assume that the stubs contain the following structure: └── contracts └── shouldProduceValidPersonData.groovy ---- +==== -Consider the following contract: +Then consider the following contract: +==== [source,groovy] ---- include::{tests_path}/spring-cloud-contract-stub-runner-amqp/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpStubRunnerSpec.groovy[tags=amqp_contract,indent=0] ---- +==== Now consider the following Spring configuration: +==== [source,yaml] ---- include::{tests_path}/spring-cloud-contract-stub-runner-amqp/src/test/resources/application.yml[] ---- +==== [[features-messaging-stub-runner-amqp-triggering]] -===== Triggering the message +===== Triggering the Message -To trigger a message using the contract above, use the `StubTrigger` interface as +To trigger a message using the contract in the preceding section, use the `StubTrigger` interface as follows: +==== [source,groovy] ---- include::{tests_path}/spring-cloud-contract-stub-runner-amqp/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpStubRunnerSpec.groovy[tags=client_trigger,indent=0] ---- +==== The message has a destination of `contract-test.exchange`, so the Spring AMQP stub runner -integration looks for bindings related to this exchange. +integration looks for bindings related to this exchange, as the following example shows: +==== [source,java] ---- include::{tests_path}/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpMessagingApplication.java[tags=amqp_binding,indent=0] ---- +==== -The binding definition binds the queue `test.queue`. As a result, the following listener -definition is matched and invoked with the contract message. +The binding definition binds the queue called `test.queue`. As a result, the following listener +definition is matched and invoked with the contract message: +==== [source,java] ---- include::{tests_path}/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpMessagingApplication.java[tags=amqp_listener,indent=0] ---- +==== Also, the following annotated listener matches and is invoked: + +==== [source,java] ---- include::{tests_path}/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/MessageSubscriberRabbitListener.java[tags=amqp_annotated_listener,indent=0] ---- +==== NOTE: The message is directly handed over to the `onMessage` method of the `MessageListener` associated with the matching `SimpleMessageListenerContainer`. @@ -908,15 +999,17 @@ NOTE: The message is directly handed over to the `onMessage` method of the [[features-messaging-stub-runner-amqp-configuration]] ===== Spring AMQP Test Configuration -In order to avoid Spring AMQP trying to connect to a running broker during our tests +In order to avoid Spring AMQP trying to connect to a running broker during our tests, we configure a mock `ConnectionFactory`. -To disable the mocked ConnectionFactory, set the following property: -`stubrunner.amqp.mockConnection=false` +To disable the mocked `ConnectionFactory`, set the following property: +`stubrunner.amqp.mockConnection=false`, as follows: +==== [source,yaml] ---- stubrunner: amqp: mockConnection: false ----- \ No newline at end of file +---- +==== diff --git a/docs/src/main/asciidoc/_project-features-stubrunner.adoc b/docs/src/main/asciidoc/_project-features-stubrunner.adoc index cfa0ff4a4b..35d9f47b55 100644 --- a/docs/src/main/asciidoc/_project-features-stubrunner.adoc +++ b/docs/src/main/asciidoc/_project-features-stubrunner.adoc @@ -10,10 +10,10 @@ question. That is why we introduced Spring Cloud Contract Stub Runner. It can automatically download and run the stubs for you. [[features-stub-runner-snapshot-versions]] -=== Snapshot versions +=== Snapshot Versions -Add the additional snapshot repository to your `build.gradle` file to use snapshot -versions, which are automatically uploaded after every successful build: +You can add the additional snapshot repository to your `build.gradle` file to use snapshot +versions, which are automatically uploaded after every successful build, as follows: ==== [source,xml,indent=0,subs="verbatim,attributes",role="primary"] @@ -32,12 +32,14 @@ include::{standalone_samples_path}/http-server/build.gradle[tags=repos,indent=0] [[features-stub-runner-publishing-stubs-as-jars]] === Publishing Stubs as JARs -The easiest approach would be to centralize the way stubs are kept. For example, you can -keep them as jars in a Maven repository. +The easiest approach to publishing stubs as jars is to centralize the way stubs are kept. +For example, you can keep them as jars in a Maven repository. TIP: For both Maven and Gradle, the setup comes ready to work. However, you can customize it if you want to. +The following example shows how to publish stubs as jars: + ==== [source,xml,indent=0,subs="verbatim,attributes",role="primary"] .Maven @@ -62,47 +64,52 @@ include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/resources/f [[features-stub-runner-core]] === Stub Runner Core -Runs stubs for service collaborators. Treating stubs as contracts of services allows to use stub-runner as an implementation of -https://martinfowler.com/articles/consumerDrivenContracts.html[Consumer Driven Contracts]. +The stub runner core runs stubs for service collaborators. Treating stubs as contracts of +services lets you use stub-runner as an implementation of +https://martinfowler.com/articles/consumerDrivenContracts.html[Consumer-driven Contracts]. -Stub Runner allows you to automatically download the stubs of the provided dependencies (or pick those from the classpath), start WireMock servers for them and feed them with proper stub definitions. -For messaging, special stub routes are defined. +Stub Runner lets you automatically download the stubs of the provided dependencies (or +pick those from the classpath), start WireMock servers for them, and feed them with proper +stub definitions. For messaging, special stub routes are defined. [[features-stub-runner-retrieving]] ==== Retrieving stubs -You can pick the following options of acquiring stubs +You can pick from the following options of acquiring stubs: -- Aether based solution that downloads JARs with stubs from Artifactory / Nexus -- Classpath scanning solution that searches classpath via pattern to retrieve stubs -- Write your own implementation of the `org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder` for full customization +- Aether-based solution that downloads JARs with stubs from Artifactory or Nexus +- Classpath-scanning solution that searches the classpath with a pattern to retrieve stubs +- Writing your own implementation of the `org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder` for full customization The latter example is described in the <> section. [[features-stub-runner-downloading-stub]] -===== Stub downloading +===== Downloading Stubs -You can control the stub downloading via the `stubsMode` switch. It picks value from the -`StubRunnerProperties.StubsMode` enum. You can use the following options +You can control the downloading of stubs with the `stubsMode` switch. It picks value from the +`StubRunnerProperties.StubsMode` enumeration. You can use the following options: -- `StubRunnerProperties.StubsMode.CLASSPATH` (default value) - will pick stubs from the classpath -- `StubRunnerProperties.StubsMode.LOCAL` - will pick stubs from a local storage (e.g. `.m2`) -- `StubRunnerProperties.StubsMode.REMOTE` - will pick stubs from a remote location +- `StubRunnerProperties.StubsMode.CLASSPATH` (default value): Picks stubs from the classpath +- `StubRunnerProperties.StubsMode.LOCAL`: Picks stubs from a local storage (for example, `.m2`) +- `StubRunnerProperties.StubsMode.REMOTE`: Picks stubs from a remote location -Example: +The following example picks stubs from a local location: +==== [source,java] ---- @AutoConfigureStubRunner(repositoryRoot="https://foo.bar", ids = "com.example:beer-api-producer:+:stubs:8095", stubsMode = StubRunnerProperties.StubsMode.LOCAL) ---- +==== [[features-stub-runner-classpath-scanning]] ===== Classpath scanning If you set the `stubsMode` property to `StubRunnerProperties.StubsMode.CLASSPATH` -(or set nothing since `CLASSPATH` is the default value) then classpath will get scanned. -Let's look at the following example: +(or set nothing since `CLASSPATH` is the default value), the classpath is scanned. +Consider the following example: +==== [source,java] ---- @AutoConfigureStubRunner(ids = { @@ -110,8 +117,9 @@ Let's look at the following example: "com.example.foo:bar:1.0.0:superstubs:8096" }) ---- +==== -If you've added the dependencies to your classpath +You can add the dependencies to your classpath, as follows: ==== [source,xml,indent=0,subs="verbatim,attributes",role="primary"] @@ -131,8 +139,8 @@ If you've added the dependencies to your classpath - com.example.foo - bar + com.example.thing1 + thing2 superstubs 1.0.0 test @@ -151,29 +159,31 @@ If you've added the dependencies to your classpath testCompile("com.example:beer-api-producer-restdocs:0.0.1-SNAPSHOT:stubs") { transitive = false } -testCompile("com.example.foo:bar:1.0.0:superstubs") { +testCompile("com.example.thing1:thing2:1.0.0:superstubs") { transitive = false } ---- ==== -Then the following locations on your classpath will get scanned. For `com.example:beer-api-producer-restdocs` +Then the specified locations on your classpath get scanned. For `com.example:beer-api-producer-restdocs`, +the following locations are scanned: - /META-INF/com.example/beer-api-producer-restdocs/**/*.* - /contracts/com.example/beer-api-producer-restdocs/**/*.* - /mappings/com.example/beer-api-producer-restdocs/**/*.* -and `com.example.foo:bar` +For `com.example.thing1:thing2`, the following locations are scanned: -- /META-INF/com.example.foo/bar/**/*.* -- /contracts/com.example.foo/bar/**/*.* -- /mappings/com.example.foo/bar/**/*.* +- /META-INF/com.example.thing1/thing2/**/*.* +- /contracts/com.example.thing1/thing2/**/*.* +- /mappings/com.example.thing1/thing2/**/*.* -TIP: As you can see you have to explicitly provide the group and artifact ids when packaging the +TIP: You have to explicitly provide the group and artifact IDs when you package the producer stubs. -The producer would setup the contracts like this: +To achieve proper stub packaging, the producer would set up the contracts as follows: +==== [source,bash] ---- └── src @@ -186,13 +196,13 @@ The producer would setup the contracts like this:       └── contract3.groovy ---- +==== -To achieve proper stub packaging. - -Or using the https://github.com/spring-cloud-samples/spring-cloud-contract-samples/blob/{samples_branch}/producer_with_restdocs/pom.xml[Maven `assembly` plugin] or -https://github.com/spring-cloud-samples/spring-cloud-contract-samples/blob/{samples_branch}/producer_with_restdocs/build.gradle[Gradle Jar] task you have to create the following -structure in your stubs jar. +By using the https://github.com/spring-cloud-samples/spring-cloud-contract-samples/blob/{samples_branch}/producer_with_restdocs/pom.xml[Maven `assembly` plugin] or +https://github.com/spring-cloud-samples/spring-cloud-contract-samples/blob/{samples_branch}/producer_with_restdocs/build.gradle[Gradle Jar] task, you have to create the following +structure in your stubs jar: +==== [source,bash] ---- └── META-INF @@ -206,52 +216,68 @@ structure in your stubs jar.    └── mapping.json ---- +==== -By maintaining this structure classpath gets scanned and you can profit from the messaging / +By maintaining this structure, the classpath gets scanned and you can profit from the messaging or HTTP stubs without the need to download artifacts. [[features-stub-runner-configuring-http-server-stubs]] ===== Configuring HTTP Server Stubs -Stub Runner has a notion of a `HttpServerStub` that abstracts the underlaying -concrete implementation of the HTTP server (e.g. WireMock is one of the implementations). -Sometimes, you need to perform some additional tuning of the stub servers, -that is concrete for the given implementation. To do that, Stub Runner gives you -the `httpServerStubConfigurer` property that is available in the annotation, -JUnit rule, and is accessible via system properties, where you can provide -your implementation of the `org.springframework.cloud.contract.stubrunner.HttpServerStubConfigurer` interface. The implementations can alter +Stub Runner has a notion of a `HttpServerStub` that abstracts the underlying +concrete implementation of the HTTP server (for example, WireMock is one of the implementations). +Sometimes, you need to perform some additional tuning (which is concrete for the given implementation) of the stub servers. +To do that, Stub Runner gives you +the `httpServerStubConfigurer` property that is available in the annotation and the +JUnit rule and is accessible through system properties, where you can provide +your implementation of the `org.springframework.cloud.contract.stubrunner.HttpServerStubConfigurer` +interface. The implementations can alter the configuration files for the given HTTP server stub. Spring Cloud Contract Stub Runner comes with an implementation that you -can extend, for WireMock - `org.springframework.cloud.contract.stubrunner.provider.wiremock.WireMockHttpServerStubConfigurer`. In the `configure` method -you can provide your own, custom configuration for the given stub. The use -case might be starting WireMock for the given artifact id, on an HTTPs port. Example: +can extend for WireMock: +`org.springframework.cloud.contract.stubrunner.provider.wiremock.WireMockHttpServerStubConfigurer`. +In the `configure` method, +you can provide your own custom configuration for the given stub. The use +case might be starting WireMock for the given artifact ID, on an HTTPS port. The following +example shows how to do so: .WireMockHttpServerStubConfigurer implementation +==== [source,groovy,indent=0] ---- include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/StubRunnerConfigurationSpec.groovy[tags=wireMockHttpServerStubConfigurer] ---- +==== -You can then reuse it via the annotation +You can then reuse it with the `@AutoConfigureStubRunner` annotation, as follows: +==== [source,groovy,indent=0] ---- include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/StubRunnerConfigurationSpec.groovy[tags=annotation] ---- +==== -Whenever an https port is found, it will take precedence over the http one. +Whenever an HTTPS port is found, it takes precedence over the HTTP port. [[features-stub-runner-running-stubs]] ==== Running stubs +This section describes how to run stubs. It contains the following topics: + +* <> +* <> +* <> + [[features-stub-runner-http-stubs]] ===== HTTP Stubs Stubs are defined in JSON documents, whose syntax is defined in http://wiremock.org/stubbing.html[WireMock documentation] -Example: +The following example defines a stub in JSON: +==== [source,javascript,indent=0] ---- { @@ -268,23 +294,27 @@ Example: } } ---- +==== [[features-stub-runner-viewing]] -===== Viewing registered mappings +===== Viewing Registered Mappings -Every stubbed collaborator exposes list of defined mappings under `__/admin/` endpoint. +Every stubbed collaborator exposes a list of defined mappings under the `__/admin/` endpoint. You can also use the `mappingsOutputFolder` property to dump the mappings to files. - For annotation based approach it would look like this +For the annotation-based approach, it would resembling the following example: +==== [source,java] ---- @AutoConfigureStubRunner(ids="a.b.c:loanIssuance,a.b.c:fraudDetectionServer", mappingsOutputFolder = "target/outputmappings/") ---- +==== -and for the JUnit approach like this: +For the JUnit approach, it resembles the following example: +==== [source,java] ---- @ClassRule @Shared StubRunnerRule rule = new StubRunnerRule() @@ -293,20 +323,24 @@ and for the JUnit approach like this: .downloadStub("a.b.c:fraudDetectionServer") .withMappingsOutputFolder("target/outputmappings") ---- +==== -Then if you check out the folder `target/outputmappings` you would see the following structure +Then, if you check out the `target/outputmappings` folder, you would see the following structure; +==== [source,bash] ---- . ├── fraudDetectionServer_13705 └── loanIssuance_12255 ---- +==== That means that there were two stubs registered. `fraudDetectionServer` was registered at port `13705` -and `loanIssuance` at port `12255`. If we take a look at one of the files we would see (for WireMock) -mappings available for the given server: +and `loanIssuance` at port `12255`. If we take a look at one of the files, we would see (for WireMock) +the mappings available for the given server: +==== [source,json] ---- [{ @@ -324,42 +358,53 @@ mappings available for the given server: ... ] ---- +==== [[features-stub-runner-messaging]] ===== Messaging Stubs -Depending on the provided Stub Runner dependency and the DSL the messaging routes are automatically set up. +Depending on the provided Stub Runner dependency and the DSL, the messaging routes are automatically set up. [[features-stub-runner-junit]] === Stub Runner JUnit Rule and Stub Runner JUnit5 Extension -Stub Runner comes with a JUnit rule thanks to which you can very easily download and run stubs for given group and artifact id: +Stub Runner comes with a JUnit rule that lets you can download and run stubs for a given +group and artifact ID, as the following example shows: +==== [source,java,indent=0] ---- include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleJUnitTest.java[tags=classrule] ---- +==== -There's also a `StubRunnerExtension` available for JUnit 5. `StubRunnerRule` and `StubRunnerExtension` work in a very -similar fashion. After the rule/ extension is executed, Stub Runner connects to your Maven repository and for the given list of dependencies tries to: +A `StubRunnerExtension` is also available for JUnit 5. `StubRunnerRule` and +`StubRunnerExtension` work in a very similar fashion. After the rule or extension is +executed, Stub Runner connects to your Maven repository and, for the given list of +dependencies, tries to: -- download them -- cache them locally -- unzip them to a temporary folder -- start a WireMock server for each Maven dependency on a random port from the provided range of ports / provided port -- feed the WireMock server with all JSON files that are valid WireMock definitions -- can also send messages (remember to pass an implementation of `MessageVerifier` interface) +- Download them +- Cache them locally +- Unzip them to a temporary folder +- Start a WireMock server for each Maven dependency on a random port from the provided +range of ports or the provided port +- Feed the WireMock server with all JSON files that are valid WireMock definitions +- Send messages (remember to pass an implementation of `MessageVerifier` interface) -Stub Runner uses https://wiki.eclipse.org/Aether[Eclipse Aether] mechanism to download the Maven dependencies. +Stub Runner uses the https://wiki.eclipse.org/Aether[Eclipse Aether] mechanism to download the Maven dependencies. Check their https://wiki.eclipse.org/Aether[docs] for more information. -Since the `StubRunnerRule` and `StubRunnerExtension` implement the `StubFinder` they allow you to find the started stubs: +Since the `StubRunnerRule` and `StubRunnerExtension` implement the `StubFinder` they let +you find the started stubs, as the following example shows: +==== [source,groovy,indent=0] ---- include::{stubrunner_core_path}/src/main/java/org/springframework/cloud/contract/stubrunner/StubFinder.java[lines=16..-1] ---- +==== +The following examples provide more detail about using Stub Runner: ==== [source,groovy,indent=0,subs="verbatim,attributes",role="primary"] @@ -381,66 +426,78 @@ include::{stubrunner_core_path}/src/test/java/org/springframework/cloud/contract ---- ==== -Check the <> for more information on how to apply global configuration of Stub Runner. +See the <> for more information on +how to apply global configuration of Stub Runner. IMPORTANT: To use the JUnit rule or JUnit 5 extension together with messaging, you have to provide an implementation of the -`MessageVerifier` interface to the rule builder (e.g. `rule.messageVerifier(new MyMessageVerifier())`). -If you don't do this, then whenever you try to send a message an exception will be thrown. +`MessageVerifier` interface to the rule builder (for example, `rule.messageVerifier(new MyMessageVerifier())`). +If you do not do this, then, whenever you try to send a message, an exception is thrown. [[features-stub-runner-rule-maven-settings]] -==== Maven settings +==== Maven Settings The stub downloader honors Maven settings for a different local repository folder. -Authentication details for repositories and profiles are currently not taken into account, so you need to specify it using the properties mentioned above. +Authentication details for repositories and profiles are currently not taken into account, +so you need to specify it by using the properties mentioned above. [[features-stub-runner-rule-fixed-ports]] -==== Providing fixed ports +==== Providing Fixed Ports -You can also run your stubs on fixed ports. You can do it in two different ways. One is to pass it in the properties, and the other via fluent API of +You can also run your stubs on fixed ports. You can do it in two different ways. +One is to pass it in the properties, and the other is to use the fluent API of JUnit rule. [[features-stub-runner-rule-fluent-api]] ==== Fluent API -When using the `StubRunnerRule` or `StubRunnerExtension` you can add a stub to download and then pass the port for the last downloaded stub. +When using the `StubRunnerRule` or `StubRunnerExtension`, you can add a stub to download +and then pass the port for the last downloaded stub. The following example shows how to do so: +==== [source,java,indent=0] ---- include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleCustomPortJUnitTest.java[tags=classrule_with_port] ---- +==== -You can see that for this example the following test is valid: +For the preceding example, the following test is valid: +==== [source,java,indent=0] ---- include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleCustomPortJUnitTest.java[tags=test_with_port] ---- +==== [[features-stub-runner-rule-spring]] ==== Stub Runner with Spring -Sets up Spring configuration of the Stub Runner project. +Stub Runner with Spring sets up Spring configuration of the Stub Runner project. -By providing a list of stubs inside your configuration file the Stub Runner automatically downloads +By providing a list of stubs inside your configuration file, Stub Runner automatically downloads and registers in WireMock the selected stubs. -If you want to find the URL of your stubbed dependency you can autowire the `StubFinder` interface and use -its methods as presented below: +If you want to find the URL of your stubbed dependency, you can autowire the `StubFinder` interface and use +its methods, as follows: +==== [source,groovy,indent=0] ---- include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/StubRunnerConfigurationSpec.groovy[tags=test] ---- +==== -for the following configuration file: +Doing so depends on the following configuration file: +==== [source,yml,indent=0] ---- include::{stubrunner_core_path}/src/test/resources/application-test.yml[tags=test] ---- +==== -Instead of using the properties you can also use the properties inside the `@AutoConfigureStubRunner`. -Below you can find an example of achieving the same result by setting values on the annotation. +Instead of using the properties, you can also use the properties inside the `@AutoConfigureStubRunner`. +The following example achieves the same result by setting values on the annotation: [source,groovy,indent=0] ---- @@ -448,74 +505,85 @@ include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contra ---- Stub Runner Spring registers environment variables in the following manner -for every registered WireMock server. Example for Stub Runner ids - `com.example:foo`, `com.example:bar`. +for every registered WireMock server. The following example shows Stub Runner IDs for +`com.example:thing1` and `com.example:thing2`: -- `stubrunner.runningstubs.foo.port` -- `stubrunner.runningstubs.com.example.foo.port` -- `stubrunner.runningstubs.bar.port` -- `stubrunner.runningstubs.com.example.bar.port` +- `stubrunner.runningstubs.thing1.port` +- `stubrunner.runningstubs.com.example.thing1.port` +- `stubrunner.runningstubs.thing2.port` +- `stubrunner.runningstubs.com.example.thing2.port` -Which you can reference in your code. +You can reference these values in your code. You can also use the `@StubRunnerPort` annotation to inject the port of a running stub. -Value of the annotation can be the `groupid:artifactid` or just the `artifactid`. Example for Stub Runner ids -`com.example:foo`, `com.example:bar`. +The value of the annotation can be the `groupid:artifactid` or just the `artifactid`. +The following example works shows Stub Runner IDs for +`com.example:thing1` and `com.example:thing2`. +==== [source,java,indent=0] ---- -@StubRunnerPort("foo") -int fooPort; -@StubRunnerPort("com.example:bar") -int barPort; +@StubRunnerPort("thing1") +int thing1Port; +@StubRunnerPort("com.example:thing2") +int thing2Port; ---- +==== [[features-stub-runner-cloud]] === Stub Runner Spring Cloud Stub Runner can integrate with Spring Cloud. -For real life examples you can check the +For real life examples, see: - - https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/producer[producer app sample] - - https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/consumer_with_discovery[consumer app sample] +- https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/producer[The producer app sample] +- https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/consumer_with_discovery[The consumer app sample] [[features-stub-runner-cloud-stubbing-discovery]] ==== Stubbing Service Discovery -The most important feature of `Stub Runner Spring Cloud` is the fact that it's stubbing +The most important feature of `Stub Runner Spring Cloud` is the fact that it stubs: - `DiscoveryClient` - `Ribbon` `ServerList` -that means that regardless of the fact whether you're using Zookeeper, Consul, Eureka or anything else, you don't need that in your tests. -We're starting WireMock instances of your dependencies and we're telling your application whenever you're using `Feign`, load balanced `RestTemplate` -or `DiscoveryClient` directly, to call those stubbed servers instead of calling the real Service Discovery tool. +That means that, regardless of whether you use Zookeeper, Consul, Eureka, or anything +else, you do not need that in your tests. We are starting WireMock instances of your +dependencies and we are telling your application, whenever you use `Feign`, to load a +balanced `RestTemplate` or `DiscoveryClient` directly, to call those stubbed servers +instead of calling the real Service Discovery tool. -For example this test will pass +For example, the following test passes: +==== [source,groovy,indent=0] ---- include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerSpringCloudAutoConfigurationSpec.groovy[tags=test] ---- +==== -for the following configuration file +Note that the preceding example requires the following configuration file: +==== [source,yml,indent=0] ---- include::{stubrunner_core_path}/src/test/resources/application.yml[tags=ids] ---- +==== [[features-stub-runner-cloud-stubbing-profiles]] -===== Test profiles and service discovery +===== Test Profiles and Service Discovery -In your integration tests you typically don't want to call neither a discovery service (e.g. Eureka) -or Config Server. That's why you create an additional test configuration in which you want to disable +In your integration tests, you typically do not want to call either a discovery service (such as Eureka) +or Config Server. That is why you create an additional test configuration in which you want to disable these features. -Due to certain limitations of https://github.com/spring-cloud/spring-cloud-commons/issues/156[`spring-cloud-commons`] to achieve this you have disable these properties -via a static block like presented below (example for Eureka) +Due to certain limitations of https://github.com/spring-cloud/spring-cloud-commons/issues/156[`spring-cloud-commons`], +to achieve this, you have to disable these properties +in a static block such as the following example (for Eureka): +==== [source,java] ---- //Hack to work around https://github.com/spring-cloud/spring-cloud-commons/issues/156 @@ -524,75 +592,80 @@ via a static block like presented below (example for Eureka) System.setProperty("spring.cloud.config.failFast", "false"); } ---- +==== [[features-stub-runner-additional-config]] ==== Additional Configuration -You can match the artifactId of the stub with the name of your app by using the `stubrunner.idsToServiceIds:` map. -You can disable Stub Runner Ribbon support by providing: `stubrunner.cloud.ribbon.enabled` equal to `false` -You can disable Stub Runner support by providing: `stubrunner.cloud.enabled` equal to `false` +You can match the `artifactId` of the stub with the name of your application by using the `stubrunner.idsToServiceIds:` map. +You can disable Stub Runner Ribbon support by setting `stubrunner.cloud.ribbon.enabled` to `false` +You can disable Stub Runner support by setting `stubrunner.cloud.enabled` to `false` -TIP: By default all service discovery will be stubbed. That means that regardless of the fact if you have -an existing `DiscoveryClient` its results will be ignored. However, if you want to reuse it, just set - `stubrunner.cloud.delegate.enabled` to `true` and then your existing `DiscoveryClient` results will be +TIP: By default, all service discovery is stubbed. This means that, regardless of whether you have +an existing `DiscoveryClient`, its results are ignored. However, if you want to reuse it, you can set + `stubrunner.cloud.delegate.enabled` to `true`, and then your existing `DiscoveryClient` results are merged with the stubbed ones. The default Maven configuration used by Stub Runner can be tweaked either -via the following system properties or environment variables +by setting the following system properties or by setting the corresponding environment variables: -- `maven.repo.local` - path to the custom maven local repository location -- `org.apache.maven.user-settings` - path to custom maven user settings location -- `org.apache.maven.global-settings` - path to maven global settings location +- `maven.repo.local`: Path to the custom maven local repository location +- `org.apache.maven.user-settings`: Path to custom maven user settings location +- `org.apache.maven.global-settings`: Path to maven global settings location [[features-stub-runner-boot]] -=== Stub Runner Boot Application +=== Using the Stub Runner Boot Application Spring Cloud Contract Stub Runner Boot is a Spring Boot application that exposes REST endpoints to -trigger the messaging labels and to access started WireMock servers. +trigger the messaging labels and to access WireMock servers. -One of the use-cases is to run some smoke (end to end) tests on a deployed application. +One of the use cases is to run some smoke (end-to-end) tests on a deployed application. You can check out the https://github.com/spring-cloud/spring-cloud-pipelines[Spring Cloud Pipelines] project for more information. -[[features-stub-runner-boot-how]] -==== How to use it? - [[features-stub-runner-boot-server]] ===== Stub Runner Server -Just add the +To use the Stub Runner Server, add the following dependency: +==== [source,groovy,indent=0] ---- compile "org.springframework.cloud:spring-cloud-starter-stub-runner" ---- +==== -Annotate a class with `@EnableStubRunnerServer`, build a fat-jar and you're ready to go! +Then annotate a class with `@EnableStubRunnerServer`, build a fat jar, and it is ready to work. -For the properties check the *Stub Runner Spring* section. +For the properties, see the <> section. [[features-stub-runner-boot-how-fat-jar]] ===== Stub Runner Server Fat Jar -You can download a standalone JAR from Maven (e.g. for version 2.0.1.RELEASE), as follows: +You can download a standalone JAR from Maven (for example, for version 2.0.1.RELEASE) +by running the following commands: +==== [source,bash,indent=0] ---- $ wget -O stub-runner.jar 'https://search.maven.org/remotecontent?filepath=org/springframework/cloud/spring-cloud-contract-stub-runner-boot/2.0.1.RELEASE/spring-cloud-contract-stub-runner-boot-2.0.1.RELEASE.jar' $ java -jar stub-runner.jar --stubrunner.ids=... --stubrunner.repositoryRoot=... ---- +==== [[features-stub-runner-boot-how-cli]] ===== Spring Cloud CLI -Starting from `1.4.0.RELEASE` version of the https://cloud.spring.io/spring-cloud-cli[Spring Cloud CLI] -project you can start Stub Runner Boot by executing `spring cloud stubrunner`. +Starting from the `1.4.0.RELEASE` version of the https://cloud.spring.io/spring-cloud-cli[Spring Cloud CLI] +project, you can start Stub Runner Boot by running `spring cloud stubrunner`. + +In order to pass the configuration, you can create a `stubrunner.yml` file in the current working directory, +in a subdirectory called `config`, or in `~/.spring-cloud`. The file could resemble the following +example for running stubs installed locally: -In order to pass the configuration just create a `stubrunner.yml` file in the current working directory -or a subdirectory called `config` or in `~/.spring-cloud`. The file could look like this -(example for running stubs installed locally) .stubrunner.yml +==== [source,yml,indent=0] ---- stubrunner: @@ -600,31 +673,42 @@ stubrunner: ids: - com.example:beer-api-producer:+:9876 ---- +==== -and then just call `spring cloud stubrunner` from your terminal window to start -the Stub Runner server. It will be available at port `8750`. +Then you can call `spring cloud stubrunner` from your terminal window to start +the Stub Runner server. It is available at port `8750`. [[features-stub-runner-boot-endpoints]] ==== Endpoints +Stub Runner Boot offers two endpoints: + +* <> +* <> + [[features-stub-runner-boot-endpoints-http]] ===== HTTP -- GET `/stubs` - returns a list of all running stubs in `ivy:integer` notation -- GET `/stubs/{ivy}` - returns a port for the given `ivy` notation (when calling the endpoint `ivy` can also be `artifactId` only) +For HTTP, Stub Runner Boot makes the following endpoints available: + +- GET `/stubs`: Returns a list of all running stubs in `ivy:integer` notation +- GET `/stubs/{ivy}`: Returns a port for the given `ivy` notation (when calling the endpoint `ivy` can also be `artifactId` only) [[features-stub-runner-boot-endpoints-messaging]] ===== Messaging -For Messaging +For Messaging, Stub Runner Boot makes the following endpoints available: -- GET `/triggers` - returns a list of all running labels in `ivy : [ label1, label2 ...]` notation -- POST `/triggers/{label}` - executes a trigger with `label` -- POST `/triggers/{ivy}/{label}` - executes a trigger with `label` for the given `ivy` notation (when calling the endpoint `ivy` can also be `artifactId` only) +- GET `/triggers`: Returns a list of all running labels in `ivy : [ label1, label2 ...]` notation +- POST `/triggers/{label}`: Runs a trigger with `label` +- POST `/triggers/{ivy}/{label}`: Runs a trigger with a `label` for the given `ivy` notation +(when calling the endpoint, `ivy` can also be `artifactId` only) [[features-stub-runner-boot-endpoints-example]] ==== Example +The following example shows typical usage of Stub Runner Boot: + [source,groovy,indent=0] ---- include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/server/StubRunnerBootSpec.groovy[tags=boot_usage] @@ -633,55 +717,59 @@ include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contra [[features-stub-runner-boot-service-discovery]] ==== Stub Runner Boot with Service Discovery -One of the possibilities of using Stub Runner Boot is to use it as a feed of stubs for "smoke-tests". What does it mean? - Let's assume that you don't want to deploy 50 microservice to a test environment in order - to check if your application is working fine. You've already executed a suite of tests during the build process - but you would also like to ensure that the packaging of your application is fine. What you can do - is to deploy your application to an environment, start it and run a couple of tests on it to see if - it's working fine. We can call those tests smoke-tests since their idea is to check only a handful - of testing scenarios. +One way to use Stub Runner Boot is to use it as a feed of stubs for "`smoke tests`". What does that mean? +Assume that you do not want to deploy 50 microservices to a test environment in order +to see whether your application works. You have already executed a suite of tests during the build process, +but you would also like to ensure that the packaging of your application works. You can +deploy your application to an environment, start it, and run a couple of tests on it to see whether +it works. We can call those tests "`smoke tests`", because their purpose is to check only a handful +of testing scenarios. -The problem with this approach is such that if you're doing microservices most likely you're - using a service discovery tool. Stub Runner Boot allows you to solve this issue by starting the - required stubs and register them in a service discovery tool. Let's take a look at an example of - such a setup with Eureka. Let's assume that Eureka was already running. +The problem with this approach is thatm if you use microservices, you most likely also +use a service discovery tool. Stub Runner Boot lets you solve this issue by starting the +required stubs and registering them in a service discovery tool. Consider the following example of +such a setup with Eureka (assume that Eureka is already running): +==== [source,java,indent=0] ---- include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/serverexamples/StubRunnerBootEurekaExample.java[tags=stubrunnereureka] ---- +==== -As you can see we want to start a Stub Runner Boot server `@EnableStubRunnerServer`, enable Eureka client `@EnableEurekaClient` -and we want to have the stub runner feature turned on `@AutoConfigureStubRunner`. +We want to start a Stub Runner Boot server (`@EnableStubRunnerServer`), enable the Eureka client (`@EnableEurekaClient`), +and have the stub runner feature turned on (`@AutoConfigureStubRunner`). -Now let's assume that we want to start this application so that the stubs get automatically registered. - We can do it by running the app `java -jar ${SYSTEM_PROPS} stub-runner-boot-eureka-example.jar` where - `${SYSTEM_PROPS}` would contain the following list of properties +Now assume that we want to start this application so that the stubs get automatically registered. +We can do so by running the application with `java -jar ${SYSTEM_PROPS} stub-runner-boot-eureka-example.jar`, where +`${SYSTEM_PROPS}` contains the following list of properties: +==== [source,bash,indent=0] ---- include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/serverexamples/StubRunnerBootEurekaExample.java[tags=stubrunnereureka_args] ---- +==== -That way your deployed application can send requests to started WireMock servers via the service -discovery. Most likely points 1-3 could be set by default in `application.yml` cause they are not -likely to change. That way you can provide only the list of stubs to download whenever you start +That way, your deployed application can send requests to started WireMock servers through service +discovery. Most likely, points 1 through 3 could be set by default in `application.yml`, because they are not +likely to change. That way, you can provide only the list of stubs to download whenever you start the Stub Runner Boot. [[features-stub-runner-stubs-per-consumer]] === Consumer-Driven Contracts: Stubs Per Consumer -There are cases in which 2 consumers of the same endpoint want to have 2 different responses. +There are cases in which two consumers of the same endpoint want to have two different responses. -TIP: This approach also allows you to immediately know which consumer is using which part of your API. -You can remove part of a response that your API produces and you can see which of your autogenerated tests -fails. If none fails then you can safely delete that part of the response cause nobody is using it. +TIP: This approach also lets you immediately know which consumer uses which part of your API. +You can remove part of a response that your API produces and see which of your autogenerated tests +fails. If none fails, you can safely delete that part of the response, because nobody uses it. -Let's look at the following example for contract defined for the producer called `producer`. -There are 2 consumers: `foo-consumer` and `bar-consumer`. - -*Consumer `foo-service`* +Consider the following example of a contract defined for the producer called `producer`, +which has two consumers (`foo-consumer` and `bar-consumer`): +==== +.Consumer `foo-service` [source,groovy] ---- request { @@ -696,12 +784,11 @@ response { } ---- -*Consumer `bar-service`* - +.Consumer `bar-service` [source,groovy] ---- request { - url '/foo' + url '/bar' method GET() } response { @@ -711,14 +798,15 @@ response { } } ---- +==== -You can't produce for the same request 2 different responses. That's why you can properly package the +You cannot produce two different responses for the same request. That is why you can properly package the contracts and then profit from the `stubsPerConsumer` feature. -On the producer side the consumers can have a folder that contains contracts related only to them. -By setting the `stubrunner.stubs-per-consumer` flag to `true` we no longer register all stubs but only those that -correspond to the consumer application's name. In other words we'll scan the path of every stub and -if it contains the subfolder with name of the consumer in the path only then will it get registered. +On the producer side, the consumers can have a folder that contains contracts related only to them. +By setting the `stubrunner.stubs-per-consumer` flag to `true`, we no longer register all stubs but only those that +correspond to the consumer application's name. In other words, we scan the path of every stub and, +if it contains a subfolder with name of the consumer in the path, only then is it registered. On the `foo` producer side the contracts would look like this @@ -734,36 +822,40 @@ On the `foo` producer side the contracts would look like this └── shouldCallFoo.groovy ---- -Being the `bar-consumer` consumer you can either set the `spring.application.name` or the `stubrunner.consumer-name` to `bar-consumer` -Or set the test as follows: +The `bar-consumer` consumer can either set the `spring.application.name` or the `stubrunner.consumer-name` to `bar-consumer` +Alternatively, you can set the test as follows: +==== [source,groovy] ---- include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerStubsPerConsumerSpec.groovy[tags=test] ... } ---- +==== -Then only the stubs registered under a path that contains the `bar-consumer` in its name (i.e. those from the -`src/test/resources/contracts/bar-consumer/some/contracts/...` folder) will be allowed to be referenced. +Then only the stubs registered under a path that contains `bar-consumer` in its name (that is, those from the +`src/test/resources/contracts/bar-consumer/some/contracts/...` folder) are allowed to be referenced. -Or set the consumer name explicitly +You can also set the consumer name explicitly, as follows: +==== [source,groovy] ---- include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerStubsPerConsumerWithConsumerNameSpec.groovy[tags=test] ... } ---- +==== -Then only the stubs registered under a path that contains the `foo-consumer` in its name (i.e. those from the -`src/test/resources/contracts/foo-consumer/some/contracts/...` folder) will be allowed to be referenced. +Then only the stubs registered under a path that contains the `foo-consumer` in its name (that is, those from the +`src/test/resources/contracts/foo-consumer/some/contracts/...` folder) are allowed to be referenced. -You can check out https://github.com/spring-cloud/spring-cloud-contract/issues/224[issue 224] for more +See https://github.com/spring-cloud/spring-cloud-contract/issues/224[issue 224] for more information about the reasons behind this change. [[features-stub-runner-common]] -=== Common +=== Common Properties This section briefly describes common properties, including: @@ -774,14 +866,14 @@ This section briefly describes common properties, including: ==== Common Properties for JUnit and Spring You can set repetitive properties by using system properties or Spring configuration -properties. Here are their names with their default values: +properties. The following table shows their names with their default values: [frame="topbot",options="header"] |=============== | Property name | Default value | Description |stubrunner.minPort|10000| Minimum value of a port for a started WireMock with stubs. |stubrunner.maxPort|15000| Maximum value of a port for a started WireMock with stubs. -|stubrunner.repositoryRoot|| Maven repo URL. If blank, then call the local maven repo. +|stubrunner.repositoryRoot|| Maven repo URL. If blank, then call the local Maven repo. |stubrunner.classifier|stubs| Default classifier for the stub artifacts. |stubrunner.stubsMode|CLASSPATH| The way you want to fetch and register the stubs |stubrunner.ids|| Array of Ivy notation stubs to download. @@ -789,29 +881,31 @@ properties. Here are their names with their default values: stubs. |stubrunner.password|| Optional password to access the tool that stores the JARs with stubs. -|stubrunner.stubsPerConsumer|false| Set to `true` if you want to use different stubs for +|stubrunner.stubsPerConsumer|`false`| Set to `true` if you want to use different stubs for each consumer instead of registering all stubs for every consumer. |stubrunner.consumerName|| If you want to use a stub for each consumer and want to -override the consumer name just change this value. +override the consumer name, change this value. |=============== [[features-stub-runner-stub-runner-stub-ids]] ==== Stub Runner Stubs IDs -You can provide the stubs to download via the `stubrunner.ids` system property. They -follow this pattern: +You can set the stubs to download in the `stubrunner.ids` system property. They +use the following pattern: +==== [source,java,indent=0] ---- groupId:artifactId:version:classifier:port ---- +==== -Note that `version`, `classifier` and `port` are optional. +Note that `version`, `classifier`, and `port` are optional. -* If you do not provide the `port`, a random one will be picked. +* If you do not provide the `port`, a random one is picked. * If you do not provide the `classifier`, the default is used. (Note that you can pass an empty classifier this way: `groupId:artifactId:version:`). -* If you do not provide the `version`, then the `+` will be passed and the latest one is +* If you do not provide the `version`, then `+` is passed, and the latest one is downloaded. `port` means the port of the WireMock server. @@ -819,4 +913,4 @@ downloaded. IMPORTANT: Starting with version 1.0.4, you can provide a range of versions that you would like the Stub Runner to take into consideration. You can read more about the https://wiki.eclipse.org/Aether/New_and_Noteworthy#Version_Ranges[Aether versioning -ranges here]. \ No newline at end of file +ranges here]. diff --git a/docs/src/main/asciidoc/_project-features-wiremock.adoc b/docs/src/main/asciidoc/_project-features-wiremock.adoc index 3a8477ce0b..c2813dbfc6 100644 --- a/docs/src/main/asciidoc/_project-features-wiremock.adoc +++ b/docs/src/main/asciidoc/_project-features-wiremock.adoc @@ -8,34 +8,38 @@ https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples[samp for more details. If you have a Spring Boot application that uses Tomcat as an embedded server (which is -the default with `spring-boot-starter-web`), you can add -`spring-cloud-starter-contract-stub-runner` to your classpath and add `@AutoConfigureWireMock` in -order to be able to use Wiremock in your tests. Wiremock runs as a stub server and you -can register stub behavior using a Java API or via static JSON declarations as part of +the default with `spring-boot-starter-web`), you can add +`spring-cloud-starter-contract-stub-runner` to your classpath and add `@AutoConfigureWireMock` +to use Wiremock in your tests. Wiremock runs as a stub server, and you +can register stub behavior by using a Java API or by using static JSON declarations as part of your test. The following code shows an example: +==== [source,java,indent=0] ---- include::{doc_samples}/src/test/java/com/example/WiremockForDocsTests.java[tags=wiremock_test1] include::{doc_samples}/src/test/java/com/example/WiremockForDocsTests.java[tags=wiremock_test2] ---- +==== -To start the stub server on a different port use (for example), +To start the stub server on a different port, use (for example), `@AutoConfigureWireMock(port=9999)`. For a random port, use a value of `0`. The stub server port can be bound in the test application context with the "wiremock.server.port" property. Using `@AutoConfigureWireMock` adds a bean of type `WiremockConfiguration` to -your test application context, where it will be cached in between methods and classes -having the same context, the same as for Spring integration tests. Also you can inject a bean of type `WireMockServer` into your test. +your test application context, where it is cached between methods and classes +having the same context. The same is true for Spring integration tests. Also, you can +inject a bean of type `WireMockServer` into your test. [[features-wiremock-registering-stubs]] === Registering Stubs Automatically If you use `@AutoConfigureWireMock`, it registers WireMock JSON stubs from the file system or classpath (by default, from `file:src/test/resources/mappings`). You can -customize the locations using the `stubs` attribute in the annotation, which can be an +customize the locations byusing the `stubs` attribute in the annotation, which can be an Ant-style resource pattern or a directory. In the case of a directory, `**/*.json` is appended. The following code shows an example: +==== ---- @RunWith(SpringRunner.class) @SpringBootTest @@ -52,35 +56,40 @@ public class WiremockImportApplicationTests { } ---- +==== NOTE: Actually, WireMock always loads mappings from `src/test/resources/mappings` *as -well as* the custom locations in the stubs attribute. To change this behavior, you can -also specify a files root as described in the next section of this document. +well as* the custom locations in the `stubs` attribute. To change this behavior, you can +also specify a files root, as described in the next section of this document. -If you're using Spring Cloud Contract's default stub jars, then your -stubs are stored under `/META-INF/group-id/artifact-id/versions/mappings/` folder. If you want to register all stubs from that location, from all embedded JARs, then it's enough to use the following syntax. +If you use Spring Cloud Contract's default stub jars, your +stubs are stored in the `/META-INF/group-id/artifact-id/versions/mappings/` folder. +If you want to register all stubs from that location, from all embedded JARs, you can use +the following syntax: +==== [source,java,indent=0] ---- include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockFilesApplicationWithUrlResourceTests.java[tags=load_all_stubs] ---- +==== [[features-wiremock-using-files]] === Using Files to Specify the Stub Bodies -WireMock can read response bodies from files on the classpath or the file system. In that -case, you can see in the JSON DSL that the response has a `bodyFileName` instead of a +WireMock can read response bodies from files on the classpath or the file system. In the +case of the file system, you can see in the JSON DSL that the response has a `bodyFileName` instead of a (literal) `body`. The files are resolved relative to a root directory (by default, -`src/test/resources/\__files`). To customize this location you can set the `files` +`src/test/resources/\__files`). To customize this location, you can set the `files` attribute in the `@AutoConfigureWireMock` annotation to the location of the parent directory (in other words, `__files` is a subdirectory). You can use Spring resource notation to refer to `file:...` or `classpath:...` locations. Generic URLs are not -supported. A list of values can be given, in which case WireMock resolves the first file +supported. A list of values can be given -- in which case, WireMock resolves the first file that exists when it needs to find a response body. NOTE: When you configure the `files` root, it also affects the automatic loading of stubs, because they come from the root location -in a subdirectory called "mappings". The value of `files` has no +in a subdirectory called `mappings`. The value of `files` has no effect on the stubs loaded explicitly from the `stubs` attribute. [[features-wiremock-junit-rule]] @@ -88,13 +97,15 @@ effect on the stubs loaded explicitly from the `stubs` attribute. For a more conventional WireMock experience, you can use JUnit `@Rules` to start and stop the server. To do so, use the `WireMockSpring` convenience class to obtain an `Options` -instance, as shown in the following example: +instance, as the following example shows: +==== [source,java,indent=0] ---- include::{doc_samples}/src/test/java/com/example/WiremockForDocsClassRuleTests.java[tags=wiremock_test1] include::{doc_samples}/src/test/java/com/example/WiremockForDocsClassRuleTests.java[tags=wiremock_test2] ---- +==== The `@ClassRule` means that the server shuts down after all the methods in this class have been run. @@ -102,16 +113,17 @@ have been run. [[features-wiremock-relaxed-ssl]] === Relaxed SSL Validation for Rest Template -WireMock lets you stub a "secure" server with an "https" URL protocol. If your +WireMock lets you stub a "`secure`" server with an `https` URL protocol. If your application wants to contact that stub server in an integration test, it will find that the SSL certificates are not valid (the usual problem with self-installed certificates). -The best option is often to re-configure the client to use "http". If that's not an +The best option is often to re-configure the client to use `http`. If that is not an option, you can ask Spring to configure an HTTP client that ignores SSL validation errors (do so only for tests, of course). -To make this work with minimum fuss, you need to be using the Spring Boot -`RestTemplateBuilder` in your app, as shown in the following example: +To make this work with minimum fuss, you need to use the Spring Boot +`RestTemplateBuilder` in your application, as the following example shows: +==== [source,java,indent=0] ---- @Bean @@ -119,13 +131,15 @@ To make this work with minimum fuss, you need to be using the Spring Boot return builder.build(); } ---- +==== You need `RestTemplateBuilder` because the builder is passed through callbacks to initialize it, so the SSL validation can be set up in the client at that point. This -happens automatically in your test if you are using the `@AutoConfigureWireMock` +happens automatically in your test if you use the `@AutoConfigureWireMock` annotation or the stub runner. If you use the JUnit `@Rule` approach, you need to add the -`@AutoConfigureHttpClient` annotation as well, as shown in the following example: +`@AutoConfigureHttpClient` annotation as well, as the following example shows: +==== [source,java,indent=0] ---- @RunWith(SpringRunner.class) @@ -139,11 +153,12 @@ public class WiremockHttpsServerApplicationTests { ... } ---- +==== -If you are using `spring-boot-starter-test`, you have the Apache HTTP client on the -classpath and it is selected by the `RestTemplateBuilder` and configured to ignore SSL +If you use `spring-boot-starter-test`, you have the Apache HTTP client on the +classpath, and it is selected by the `RestTemplateBuilder` and configured to ignore SSL errors. If you use the default `java.net` client, you do not need the annotation (but it -won't do any harm). There is no support currently for other clients, but it may be added +does no harm). There is currently no support for other clients, but it may be added in future releases. To disable the custom `RestTemplateBuilder`, set the `wiremock.rest-template-ssl-enabled` @@ -155,21 +170,23 @@ property to `false`. Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into a Spring `MockRestServiceServer`. The following code shows an example: +==== [source,java,indent=0] ---- include::{doc_samples}/src/test/java/com/example/WiremockForDocsMockServerApplicationTests.java[tags=wiremock_test] ---- +==== The `baseUrl` value is prepended to all mock calls, and the `stubs()` method takes a stub path resource pattern as an argument. In the preceding example, the stub defined at `/stubs/resource.json` is loaded into the mock server. If the `RestTemplate` is asked to visit `https://example.org/`, it gets the responses as being declared at that URL. More than one stub pattern can be specified, and each one can be a directory (for a recursive -list of all ".json"), a fixed filename (as in the example above), or an Ant-style -pattern. The JSON format is the normal WireMock format, which you can read about in the +list of all `.json`), a fixed filename (as in the preceding example), or an Ant-style +pattern. The JSON format is the normal WireMock format, which you can read about at the https://wiremock.org/docs/stubbing/[WireMock website]. Currently, the Spring Cloud Contract Verifier supports Tomcat, Jetty, and Undertow as -Spring Boot embedded servers, and Wiremock itself has "native" support for a particular +Spring Boot embedded servers, and Wiremock itself has "`native`" support for a particular version of Jetty (currently 9.2). To use the native Jetty, you need to add the native -Wiremock dependencies and exclude the Spring Boot container (if there is one). \ No newline at end of file +Wiremock dependencies and exclude the Spring Boot container (if there is one). diff --git a/docs/src/main/asciidoc/advanced.adoc b/docs/src/main/asciidoc/advanced.adoc index 805a1e63c7..7886420490 100644 --- a/docs/src/main/asciidoc/advanced.adoc +++ b/docs/src/main/asciidoc/advanced.adoc @@ -2,12 +2,12 @@ = Spring Cloud Contract customization include::_attributes.adoc[] -In this section we describe how to customize various parts of Spring Cloud Contract. +In this section, we describe how to customize various parts of Spring Cloud Contract. [[customization-customization]] == DSL Customization -IMPORTANT: This section is valid only for Groovy DSL +IMPORTANT: This section is valid only for the Groovy DSL You can customize the Spring Cloud Contract Verifier by extending the DSL, as shown in the remainder of this section. @@ -29,35 +29,45 @@ https://github.com/spring-cloud-samples/spring-cloud-contract-samples[here]. The following examples show three classes that can be reused in the DSLs. -*PatternUtils* contains functions used by both the **consumer** and the **producer**. +`PatternUtils` contains functions used by both the consumer and the producer. +The following listing shows the `PatternUtils` class: +==== [source,java] ---- include::{samples_url}/common/src/main/java/com/example/PatternUtils.java[] ---- +==== -*ConsumerUtils* contains functions used by the **consumer**. +`ConsumerUtils` contains functions used by the consumer. +The following listing shows the `ConsumerUtils` class: +==== [source,java] ---- include::{samples_url}/common/src/main/java/com/example/ConsumerUtils.java[] ---- +==== -*ProducerUtils* contains functions used by the **producer**. +`ProducerUtils` contains functions used by the producer. +The following listing shows the `ProducerUtils` class: +==== [source,java] ---- include::{samples_url}/common/src/main/java/com/example/ProducerUtils.java[] ---- +==== [[customization-test-dep]] -=== Add a test dependency in the Project's Dependencies +=== Adding a Test Dependency in the Project's Dependencies -First, add the common jar dependency as a test dependency. Because your contracts files +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 examples show how to test the dependency: -== +==== [source,xml,indent=0,subs="verbatim,attributes",role="primary"] .Maven ---- @@ -69,15 +79,15 @@ include::{samples_url}/producer/pom.xml[tags=test_dep,indent=0] ---- include::{samples_url}/producer/build.gradle[tags=test_dep,indent=0] ---- -== +==== [[customization-plugin-dep]] -=== Add a test dependency in the Plugin's Dependencies +=== Adding a Test Dependency in the Plugin's Dependencies -Now, you must add the dependency for the plugin to reuse at runtime, as shown in the -following example: +Now, you must add the dependency for the plugin to reuse at runtime, as the +following example shows: -== +==== [source,xml,indent=0,subs="verbatim,attributes",role="primary"] .Maven ---- @@ -89,24 +99,28 @@ include::{samples_url}/producer/pom.xml[tags=test_dep_in_plugin,indent=0] ---- include::{samples_url}/producer/build.gradle[tags=test_dep_in_plugin,indent=0] ---- -== +==== [[customization-referencing]] -=== Referencing classes in DSLs +=== Referencing Classes in DSLs -You can now reference your classes in your DSL, as shown in the following example: +You can now reference your classes in your DSL, as the following example shows: +==== [source,groovy] ---- include::{samples_url}/producer/src/test/resources/contracts/beer/rest/shouldGrantABeerIfOldEnough.groovy[indent=0] ---- +==== -IMPORTANT: You can set the Spring Cloud Contract plugin up by setting `convertToYaml` to `true`. That way you will NOT have to add the dependency with the extended functionality to the consumer side, since the consumer side will be using YAML contracts instead of Groovy ones. +IMPORTANT: 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. [[customization-wiremock]] -== WireMock customization +== WireMock Customization -In this section you will learn how to customize the way you work with https://wiremock.org[WireMock]. +In this section, we show how to customize the way you work with https://wiremock.org[WireMock]. [[customization-wiremock-extension]] === Registering Your Own WireMock Extension @@ -115,44 +129,50 @@ WireMock lets you register custom extensions. By default, Spring Cloud Contract the transformer, which lets you reference a request from a response. If you want to provide your own extensions, you can register an implementation of the `org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions` interface. -Since we use the spring.factories extension approach, you can create an entry in +Since we use the `spring.factories` extension approach, you can create an entry in `META-INF/spring.factories` file similar to the following: +==== [source,groovy,indent=0] ---- include::{stubrunner_core_path}/src/test/resources/META-INF/spring.factories[indent=0] ---- +==== -The following is an example of a custom extension: +The following example shows a custom extension: .TestWireMockExtensions.groovy +==== [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/dsl/wiremock/TestWireMockExtensions.groovy[indent=0] ---- +==== IMPORTANT: Remember to override the `applyGlobally()` method and set it to `false` if you want the transformation to be applied only for a mapping that explicitly requires it. [[customization-wiremock-configuration]] -=== Customization of WireMock configuration +=== Customization of WireMock Configuration -You can register a bean of `org.springframework.cloud.contract.wiremock.WireMockConfigurationCustomizer` type -in order to customize the WireMock configuration (e.g. add custom transformers). -Example: +You can register a bean of type `org.springframework.cloud.contract.wiremock.WireMockConfigurationCustomizer` +to customize the WireMock configuration (for example, to add custom transformers). +The following example shows how to do so: +==== [source,java,indent=0] ---- include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockConfigurationCustomizerTests.java[tags=customizer_1] // perform your customization here include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockConfigurationCustomizerTests.java[tags=customizer_2] ---- +==== [[customization-pluggable-architecture]] == Using the Pluggable Architecture -You may encounter cases where you have your contracts have been defined in other formats, -such as YAML, RAML or PACT. In those cases, you still want to benefit from the automatic +You may encounter cases where your contracts have been defined in other formats, +such as YAML, RAML, or PACT. In those cases, you still want to benefit from the automatic generation of tests and stubs. You can add your own implementation for generating both tests and stubs. Also, you can customize the way tests are generated (for example, you can generate tests for other languages) and the way stubs are generated (for example, you @@ -164,10 +184,12 @@ can generate stubs for other HTTP server implementations). The `ContractConverter` interface lets you register your own implementation of a contract structure converter. The following code listing shows the `ContractConverter` interface: +==== [source,java] ---- include::{contract_spec_path}/src/main/java/org/springframework/cloud/contract/spec/ContractConverter.java[indent=0,lines=17..-1] ---- +==== Your implementation must define the condition on which it should start the conversion. Also, you must define how to perform that conversion in both directions. @@ -178,11 +200,13 @@ implementation. The following example shows a typical `spring.factories` file: +==== [source] ---- org.springframework.cloud.contract.spec.ContractConverter=\ org.springframework.cloud.contract.verifier.converter.YamlContractConverter ---- +==== [[customization-custom-test-generator]] === Using the Custom Test Generator @@ -193,19 +217,23 @@ way the verifier builds Java tests, you can register your own implementation. The `SingleTestGenerator` interface lets you register your own implementation. The following code listing shows the `SingleTestGenerator` interface: +==== [source,groovy] ---- include::{verifier_core_path}/src/main/groovy/org/springframework/cloud/contract/verifier/builder/SingleTestGenerator.java[indent=0,lines=17..-1] ---- +==== Again, you must provide a `spring.factories` file, such as the one shown in the following example: +==== [source] ---- org.springframework.cloud.contract.verifier.builder.SingleTestGenerator=/ com.example.MyGenerator ---- +==== [[customization-custom-stub-generator]] === Using the Custom Stub Generator @@ -214,18 +242,22 @@ If you want to generate stubs for stub servers other than WireMock, you can plug own implementation of the `StubGenerator` interface. The following code listing shows the `StubGenerator` interface: +==== [source,groovy] ---- include::{converters_path}/src/main/groovy/org/springframework/cloud/contract/verifier/converter/StubGenerator.groovy[indent=0,lines=16..-1] ---- +==== Again, you must provide a `spring.factories` file, such as the one shown in the following example: +==== [source] ---- include::{converters_path}/src/main/resources/META-INF/spring.factories[indent=0] ---- +==== The default implementation is the WireMock stub generation. @@ -244,31 +276,36 @@ you have written a stub generator and placed your stubs in a JAR file. In order for Stub Runner to know how to run your stubs, you have to define a custom HTTP Stub server implementation, which might resemble the following example: +==== [source,groovy] ---- include::{tests_path}/spring-cloud-contract-stub-runner-moco/src/test/groovy/org/springframework/cloud/contract/stubrunner/provider/moco/MocoHttpServerStub.groovy[indent=0,lines=16..-1] ---- +==== -Then, you can register it in your `spring.factories` file, as shown in the following -example: +Then you can register it in your `spring.factories` file, as the following +example shows: +==== [source] ---- org.springframework.cloud.contract.stubrunner.HttpServerStub=\ org.springframework.cloud.contract.stubrunner.provider.moco.MocoHttpServerStub ---- +==== Now you can run stubs with Moco. -IMPORTANT: If you do not provide any implementation, then the default (WireMock) +IMPORTANT: If you do not provide any implementation, the default (WireMock) implementation is used. If you provide more than one, the first one on the list is used. [[customization-custom-stub-downloader]] === Using the Custom Stub Downloader You can customize the way your stubs are downloaded by creating an implementation of the -`StubDownloaderBuilder` interface, as shown in the following example: +`StubDownloaderBuilder` interface, as the following example shows: +==== [source,java] ---- package com.example; @@ -292,36 +329,39 @@ class CustomStubDownloaderBuilder implements StubDownloaderBuilder { } } ---- +==== -Then you can register it in your `spring.factories` file, as shown in the following -example: +Then you can register it in your `spring.factories` file, as the following +example shows: +==== [source] ---- # Example of a custom Stub Downloader Provider org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder=\ com.example.CustomStubDownloaderBuilder ---- +==== Now you can pick a folder with the source of your stubs. -IMPORTANT: If you do not provide any implementation, then the default is used (scan classpath). +IMPORTANT: If you do not provide any implementation, the default (scanning the classpath) is used. If you provide the `stubsMode = StubRunnerProperties.StubsMode.LOCAL` or -`, stubsMode = StubRunnerProperties.StubsMode.REMOTE` then the Aether implementation will be used -If you provide more than one, then the first one on the list is used. +`stubsMode = StubRunnerProperties.StubsMode.REMOTE`, the Aether implementation is used +If you provide more than one, the first one on the list is used. [[scm-stub-downloader]] === Using the SCM Stub Downloader Whenever the `repositoryRoot` starts with a SCM protocol -(currently we support only `git://`), the stub downloader will try +(currently, we support only `git://`), the stub downloader tries to clone the repository and use it as a source of contracts to generate tests or stubs. -Either via environment variables, system properties, properties set -inside the plugin or contracts repository configuration you can -tweak the downloader's behaviour. Below you can find the list of -properties +Through environment variables, system properties, or properties set +inside the plugin or the contracts repository configuration, you can +tweak the downloader's behavior. The following table describes the available +properties: .SCM Stub Downloader properties |==== @@ -369,5 +409,5 @@ properties * `STUBRUNNER_PROPERTIES_GIT_WAIT_BETWEEN_ATTEMPTS` (env prop) |1000 -|Number of millis to wait between attempts to push the commits to `origin` +|Number of milliseconds to wait between attempts to push the commits to `origin` |==== diff --git a/docs/src/main/asciidoc/docker-project.adoc b/docs/src/main/asciidoc/docker-project.adoc index 3d29cff4ce..55c3a899c9 100644 --- a/docs/src/main/asciidoc/docker-project.adoc +++ b/docs/src/main/asciidoc/docker-project.adoc @@ -2,139 +2,151 @@ = Docker Project include::_attributes.adoc[] -We're publishing a `springcloud/spring-cloud-contract` Docker image -that contains a project that will generate tests and execute them in `EXPLICIT` mode +In this section, we publish a `springcloud/spring-cloud-contract` Docker image +that contains a project that generates tests and runs them in `EXPLICIT` mode against a running application. -TIP: The `EXPLICIT` mode means that the tests generated from contracts will send +TIP: The `EXPLICIT` mode means that the tests generated from contracts send real requests and not the mocked ones. -We're also publishing a `spring-cloud/spring-cloud-contract-stub-runner` Docker image -that will start the standalone version of Stub Runner. +We also publish a `spring-cloud/spring-cloud-contract-stub-runner` Docker image +that starts the standalone version of Stub Runner. [[docker-intro]] -== Short intro to Maven, JARs and Binary storage +== A Short Introduction to Maven, JARs and Binary storage -Since the Docker image can be used by non JVM projects, it's good to +Since non-JVM projects can use the Docker image, it is good to explain the basic terms behind Spring Cloud Contract packaging defaults. -Part of the following definitions were taken from the https://maven.apache.org/glossary.html[Maven Glossary] +Parts of the following definitions were taken from the https://maven.apache.org/glossary.html[Maven Glossary]: -- `Project`: Maven thinks in terms of projects. Everything that you -will build are projects. Those projects follow a well defined +- `Project`: Maven thinks in terms of projects. Projects +are all you build. Those projects follow a well defined “Project Object Model”. Projects can depend on other projects, in which case the latter are called “dependencies”. A project may -consistent of several subprojects, however these subprojects are still +consistent of several subprojects. However, these subprojects are still treated equally as projects. - `Artifact`: An artifact is something that is either produced or used by a project. Examples of artifacts produced by Maven for a project -include: JARs, source and binary distributions. Each artifact -is uniquely identified by a group id and an artifact ID which is +include JAR files and source and binary distributions. Each artifact +is uniquely identified by a group ID and an artifact ID that is unique within a group. -- `JAR`: JAR stands for Java ARchive. It's a format based on +- `JAR`: JAR stands for Java ARchive. Its format is based on the ZIP file format. Spring Cloud Contract packages the contracts and generated stubs in a JAR file. - `GroupId`: A group ID is a universally unique identifier for a project. -While this is often just the project name (eg. commons-collections), +While this is often just the project name (for example, `commons-collections`), it is helpful to use a fully-qualified package name to distinguish it -from other projects with a similar name (eg. org.apache.maven). -Typically, when published to the Artifact Manager, the `GroupId` will get -slash separated and form part of the URL. E.g. for group id `com.example` -and artifact id `application` would be `/com/example/application/`. +from other projects with a similar name (for example, `org.apache.maven`). +Typically, when published to the Artifact Manager, the `GroupId` gets +slash separated and forms part of the URL. For example, for a group ID of `com.example` +and an artifact ID of `application`, the result would be `/com/example/application/`. - `Classifier`: The Maven dependency notation looks as follows: -`groupId:artifactId:version:classifier`. The classifier is additional suffix -passed to the dependency. E.g. `stubs`, `sources`. The same dependency -e.g. `com.example:application` can produce multiple artifacts that +`groupId:artifactId:version:classifier`. The classifier is an additional suffix +passed to the dependency -- for example, `stubs` or `sources`. The same dependency +(for example, `com.example:application`) can produce multiple artifacts that differ from each other with the classifier. -- `Artifact manager`: When you generate binaries / sources / packages, you would -like them to be available for others to download / reference or reuse. In case -of the JVM world those artifacts would be JARs, for Ruby these are gems -and for Docker those would be Docker images. You can store those artifacts -in a manager. Examples of such managers can be https://jfrog.com/artifactory/[Artifactory] +- `Artifact manager`: When you generate binaries, sources, or packages, you would +like them to be available for others to download, reference, or reuse. In the case +of the JVM world, those artifacts are generally JARs. For Ruby, those artifacts are gems. +For Docker, those artifacts are Docker images. You can store those artifacts +in a manager. Examples of such managers include https://jfrog.com/artifactory/[Artifactory] or https://www.sonatype.org/nexus/[Nexus]. [[docker-how-it-works]] -== Generating tests on the producer side +== Generating Tests on the Producer Side The image searches for contracts under the `/contracts` folder. -The output from running the tests will be available under -`/spring-cloud-contract/build` folder (it's useful for debugging +The output from running the tests is available in the +`/spring-cloud-contract/build` folder (useful for debugging purposes). -It's enough for you to mount your contracts, pass the environment variables - and the image will: +You can mount your contracts and pass the environment variables. +The image then: -- generate the contract tests -- execute the tests against the provided URL -- generate the https://github.com/tomakehurst/wiremock[WireMock] stubs -- (optional - turned on by default) publish the stubs to a Artifact Manager +- Generates the contract tests +- Runs the tests against the provided URL +- Generates the https://github.com/tomakehurst/wiremock[WireMock] stubs +- Publishes the stubs to a Artifact Manager (optional - turned on by default) [[docker-env-vars]] === Environment Variables The Docker image requires some environment variables to point to -your running application, to the Artifact manager instance etc. +your running application, to the Artifact manager instance, and so on. +The following list describes the environment variables: -- `PROJECT_GROUP` - your project's group id. Defaults to `com.example` -- `PROJECT_VERSION` - your project's version. Defaults to `0.0.1-SNAPSHOT` -- `PROJECT_NAME` - artifact id. Defaults to `example` -- `PRODUCER_STUBS_CLASSIFIER` - archive classifier used for generated producer stubs, defaults to `stubs`. -- `REPO_WITH_BINARIES_URL` - URL of your Artifact Manager. Defaults to `http://localhost:8081/artifactory/libs-release-local` -which is the default URL of https://jfrog.com/artifactory/[Artifactory] running locally -- `REPO_WITH_BINARIES_USERNAME` - (optional) username when the Artifact Manager is secured, defaults to `admin`. -- `REPO_WITH_BINARIES_PASSWORD` - (optional) password when the Artifact Manager is secured, defaults to `password`. -- `PUBLISH_ARTIFACTS` - if set to `true` then will publish artifact to binary storage. Defaults to `true`. +- `PROJECT_GROUP`: Your project's group ID. Defaults to `com.example`. +- `PROJECT_VERSION`: Your project's version. Defaults to `0.0.1-SNAPSHOT`. +- `PROJECT_NAME`: Your project's artifact id. Defaults to `example`. +- `PRODUCER_STUBS_CLASSIFIER`: Archive classifier used for generated producer stubs. Defaults to `stubs`. +- `REPO_WITH_BINARIES_URL`: URL of your Artifact Manager. Defaults to `http://localhost:8081/artifactory/libs-release-local`, +which is the default URL of https://jfrog.com/artifactory/[Artifactory] running locally. +- `REPO_WITH_BINARIES_USERNAME`: (optional) Username when the Artifact Manager is secured. Defaults to `admin`. +- `REPO_WITH_BINARIES_PASSWORD`: (optional) Password when the Artifact Manager is secured. Defaults to `password`. +- `PUBLISH_ARTIFACTS`: If set to `true`, publishes the artifact to binary storage. Defaults to `true`. These environment variables are used when contracts lay in an external repository. To enable -this feature you must set the `EXTERNAL_CONTRACTS_ARTIFACT_ID` environment variable. +this feature, you must set the `EXTERNAL_CONTRACTS_ARTIFACT_ID` environment variable. -- `EXTERNAL_CONTRACTS_GROUP_ID` - group id of the project with contracts. Defaults to `com.example` -- `EXTERNAL_CONTRACTS_ARTIFACT_ID`- artifact id of the project with contracts. -- `EXTERNAL_CONTRACTS_CLASSIFIER`- classifier of the project with contracts. Empty by default -- `EXTERNAL_CONTRACTS_VERSION` - version of the project with contracts. Defaults to `+`, equivalent to picking the latest -- `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL` - URL of your Artifact Manager. Defaults to value of `REPO_WITH_BINARIES_URL` env var. -If that's not set, defaults to `http://localhost:8081/artifactory/libs-release-local` -which is the default URL of https://jfrog.com/artifactory/[Artifactory] running locally -- `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_USERNAME` - (optional) username if the `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL` -requires authentication, defaults to `REPO_WITH_BINARIES_USERNAME`. If that's not set defaults to `admin`. -- `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_PASSWORD` - (optional) password if the `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL` -requires authentication, defaults to `REPO_WITH_BINARIES_PASSWORD`. If that's not set defaults to `password`. -- `EXTERNAL_CONTRACTS_PATH` - path to contracts for the given project, inside the project with contracts. -Defaults to slash separated `EXTERNAL_CONTRACTS_GROUP_ID` concatenated with `/` and `EXTERNAL_CONTRACTS_ARTIFACT_ID`. E.g. -for group id `foo-server-side.bar` and artifact id `baz`, would result in `foo/bar/baz` contracts path. -- `EXTERNAL_CONTRACTS_WORK_OFFLINE` - if set to `true` then will retrieve artifact with contracts +- `EXTERNAL_CONTRACTS_GROUP_ID`: Group ID of the project with contracts. Defaults to `com.example` +- `EXTERNAL_CONTRACTS_ARTIFACT_ID`: Artifact ID of the project with contracts. +- `EXTERNAL_CONTRACTS_CLASSIFIER`: Classifier of the project with contracts. Empty by default. +- `EXTERNAL_CONTRACTS_VERSION`: Version of the project with contracts. Defaults to `+`, equivalent to picking the latest. +- `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL`: URL of your Artifact Manager. It defaults to +the value of `REPO_WITH_BINARIES_URL` environment variable. +If that is not set, it defaults to `http://localhost:8081/artifactory/libs-release-local`, +which is the default URL of https://jfrog.com/artifactory/[Artifactory] running locally. +- `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_USERNAME`: (optional) Username if the `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL` +requires authentication. It defaults to `REPO_WITH_BINARIES_USERNAME`. If that is not set, it defaults to `admin`. +- `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_PASSWORD`: (optional) Password if the `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL` +requires authentication. It defaults to `REPO_WITH_BINARIES_PASSWORD`. If that is not set, it defaults to `password`. +- `EXTERNAL_CONTRACTS_PATH`: Path to contracts for the given project, inside the project with contracts. +Defaults to slash-separated `EXTERNAL_CONTRACTS_GROUP_ID` concatenated with `/` and `EXTERNAL_CONTRACTS_ARTIFACT_ID`. For example, +for group id `cat-server-side.dog` and artifact id `fish`, would result in `cat/dog/fish` for the contracts path. +- `EXTERNAL_CONTRACTS_WORK_OFFLINE`; If set to `true`, retrieves the artifact with contracts from the container's `.m2`. Mount your local `.m2` as a volume available at the container's `/root/.m2` path. -You must not set both `EXTERNAL_CONTRACTS_WORK_OFFLINE` and `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL`. -These environment variables are used when tests are executed: +WARNING: You must not set both `EXTERNAL_CONTRACTS_WORK_OFFLINE` and `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL`. -- `APPLICATION_BASE_URL` - url against which tests should be executed. -Remember that it has to be accessible from the Docker container (e.g. `localhost` -will not work) -- `APPLICATION_USERNAME` - (optional) username for basic authentication to your application -- `APPLICATION_PASSWORD` - (optional) password for basic authentication to your application +The following environment variables are used when tests are executed: + +- `APPLICATION_BASE_URL`: URL against which tests should be run. +Remember that it has to be accessible from the Docker container (for example, `localhost` +does not work) +- `APPLICATION_USERNAME`: (optional) Username for basic authentication to your application. +- `APPLICATION_PASSWORD`: (optional) Password for basic authentication to your application. [[docker-example-of-usage]] -=== Example of usage +=== Example of Usage -Let's take a look at a simple MVC application +In this section, we explore a simple MVC application. To get started, clone the following +git repository and cd to the resulting directory, by running the following commands: -```bash +==== +[source,bash] +---- $ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs $ cd bookstore -``` +---- +==== -The contracts are available under `/contracts` folder. +The contracts are available in the `/contracts` folder. -Since we want to run tests, we could just execute: +Since we want to run tests, we can run the following command: -```bash +==== +[source,bash] +---- $ npm test -``` +---- +==== -however, for learning purposes, let's split it into pieces: +However, for learning purposes, we split it into pieces, as follows: -```bash +==== +[source,bash] +---- # Stop docker infra (nodejs, artifactory) $ ./stop_infra.sh # Start docker infra (nodejs, artifactory) @@ -160,61 +172,68 @@ $ docker run --rm -e "APPLICATION_BASE_URL=${APPLICATION_BASE_URL}" -e "PUBLISH # Kill app $ pkill -f "node app" -``` +---- +==== -What will happen is that via bash scripts: +Through bash scripts, the following happens: -- infrastructure will be set up (MongoDb, Artifactory). -In real life scenario you would just run the NodeJS application -with mocked database. In this example we want to show how we can -benefit from Spring Cloud Contract in no time. -- due to those constraints the contracts also represent the -stateful situation -** first request is a `POST` that causes data to get inserted to the database -** second request is a `GET` that returns a list of data with 1 previously inserted element -- the NodeJS application will be started (on port `3000`) -- contract tests will be generated via Docker and tests -will be executed against the running application -** the contracts will be taken from `/contracts` folder. -** the output of the test execution is available under +- The infrastructure (MongoDb and Artifactory) is set up. +In a real-life scenario, you would run the NodeJS application +with a mocked database. In this example, we want to show how we can +benefit from Spring Cloud Contract in very little time. +- Due to those constraints, the contracts also represent the +stateful situation. +** The first request is a `POST` that causes data to get inserted to the database. +** The second request is a `GET` that returns a list of data with 1 previously inserted element. +- The NodeJS application is started (on port `3000`). +- The contract tests are generated through Docker, and tests +are run against the running application. +** The contracts are taken from `/contracts` folder. +** The output of the test execution is available under `node_modules/spring-cloud-contract/output`. -- the stubs will be uploaded to Artifactory. You can check them out -under http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/ . -The stubs will be here http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar. +- The stubs are uploaded to Artifactory. You can find them in +http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/ . +The stubs are at http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar. [[docker-stubrunner]] -== Running stubs on the consumer side +== Running Stubs on the Consumer Side -This section describes hot to use Docker on the consumer side to fetch and run stubs. +This section describes how to use Docker on the consumer side to fetch and run stubs. -We're publishing a `spring-cloud/spring-cloud-contract-stub-runner` Docker image -that will start the standalone version of Stub Runner. +We publish a `spring-cloud/spring-cloud-contract-stub-runner` Docker image +that starts the standalone version of Stub Runner. [[docker-stubrunner-env-vars]] -=== Environment variables +=== Environment Variables -Just execute the docker image. You can pass any of the <> +You can run the docker image and pass any of the <> as environment variables. The convention is that all the -letters should be upper case. The camel case notation should -and the dot (`.`) should be separated via underscore (`_`). E.g. - the `stubrunner.repositoryRoot` property should be represented - as a `STUBRUNNER_REPOSITORY_ROOT` environment variable. +letters should be upper case. +The dot (`.`) should be replaced with underscore (`_`) characters. For example, +the `stubrunner.repositoryRoot` property should be represented +as a `STUBRUNNER_REPOSITORY_ROOT` environment variable. [[docker-stubrunner-example]] -=== Example of usage +=== Example of Usage -We'd like to use the stubs created in this <> step. -Let's assume that we want to run the stubs on port `9876`. The NodeJS code -is available here: +We want to use the stubs created in this <> step. +Assume that we want to run the stubs on port `9876`. You can see the NodeJS code +by cloning the repository and changing to the directory indicated in the following commands: -```bash +==== +[source,bash] +---- $ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs $ cd bookstore -``` +---- +==== -Let's run the Stub Runner Boot application with the stubs. +Now we can run the Stub Runner Boot application with the stubs, by running the following +commands: -```bash +==== +[source,bash] +---- # Provide the Spring Cloud Contract Docker version $ SC_CONTRACT_DOCKER_VERSION="..." # The IP at which the app is running and Docker container can reach it @@ -226,27 +245,31 @@ $ STUBRUNNER_IDS="com.example:bookstore:0.0.1.RELEASE:stubs:9876" $ STUBRUNNER_REPOSITORY_ROOT="http://${APP_IP}:8081/artifactory/libs-release-local" # Run the docker with Stub Runner Boot $ docker run --rm -e "STUBRUNNER_IDS=${STUBRUNNER_IDS}" -e "STUBRUNNER_REPOSITORY_ROOT=${STUBRUNNER_REPOSITORY_ROOT}" -e "STUBRUNNER_STUBS_MODE=REMOTE" -p "${STUBRUNNER_PORT}:${STUBRUNNER_PORT}" -p "9876:9876" springcloud/spring-cloud-contract-stub-runner:"${SC_CONTRACT_DOCKER_VERSION}" -``` +---- +==== -What's happening is that +When the preceding commands run, -- a standalone Stub Runner application got started -- it downloaded the stub with coordinates `com.example:bookstore:0.0.1.RELEASE:stubs` on port `9876` -- it got downloaded from Artifactory running at `http://192.168.0.100:8081/artifactory/libs-release-local` -- after a while Stub Runner will be running on port `8083` -- and the stubs will be running at port `9876` +- A standalone Stub Runner application gets started. +- It downloads the stub with coordinates `com.example:bookstore:0.0.1.RELEASE:stubs` on port `9876`. +- It gets downloads from Artifactory running at `http://192.168.0.100:8081/artifactory/libs-release-local`. +- After a whil, Stub Runner is running on port `8083`. +- The stubs are running at port `9876`. -On the server side we built a stateful stub. Let's use curl to assert -that the stubs are setup properly. +On the server side, we built a stateful stub. We can use curl to assert +that the stubs are setup properly. To do so, run the following commands: -```bash +==== +[source,bash] +---- # let's execute the first request (no response is returned) $ curl -H "Content-Type:application/json" -X POST --data '{ "title" : "Title", "genre" : "Genre", "description" : "Description", "author" : "Author", "publisher" : "Publisher", "pages" : 100, "image_url" : "https://d213dhlpdb53mu.cloudfront.net/assets/pivotal-square-logo-41418bd391196c3022f3cd9f3959b3f6d7764c47873d858583384e759c7db435.svg", "buy_url" : "https://pivotal.io" }' http://localhost:9876/api/books # Now time for the second request $ curl -X GET http://localhost:9876/api/books # You will receive contents of the JSON -``` +---- +==== IMPORTANT: If you want use the stubs that you have built locally, on your host, -then you should pass the environment variable `-e STUBRUNNER_STUBS_MODE=LOCAL` and mount -the volume of your local m2 `-v "${HOME}/.m2/:/root/.m2:ro"` +you should set the `-e STUBRUNNER_STUBS_MODE=LOCAL` environment variable and mount +the volume of your local m2 (`-v "${HOME}/.m2/:/root/.m2:ro"`). diff --git a/docs/src/main/asciidoc/documentation-overview.adoc b/docs/src/main/asciidoc/documentation-overview.adoc index 2db0e9eb79..397b3b9628 100644 --- a/docs/src/main/asciidoc/documentation-overview.adoc +++ b/docs/src/main/asciidoc/documentation-overview.adoc @@ -9,10 +9,11 @@ as a map for the rest of the document. [[contract-documentation-about]] == About the Documentation + The {project-full-name} reference guide is available as * {docs-url}/html[Multi-page HTML] -* {docs-url}/htmlsingle[Single page HTML] +* {docs-url}/htmlsingle[Single-page HTML] * {docs-url}/pdf/{project-name}.pdf[PDF] Copies of this document may be made for your own use and for distribution to others, @@ -50,9 +51,9 @@ If you are getting started with {project-full-name} or 'Spring' in general, star <> * *Tutorial:* <> | -<> | +<> | <> | -<> +<> @@ -62,9 +63,9 @@ you covered>>: * *Provider contract testing:* -** <> +** <> ** <> -** <> +** <> ** <> ** <> @@ -73,14 +74,14 @@ you covered>>: ** <> ** <> -TIP: We talk about *Provider Contracts* when it's the producer of the API that defines the contracts and -publishes it for all its consumers to use. This approach is useful for producers that can't -directly collaborate with their consumers; for example, when there are too many consumers, -the consumers are external (don't work within the same company). +TIP: We talk about *Provider Contracts* when it is the producer of the API that defines the contracts and +publishes it for all its consumers to use. This approach is useful for producers that cannot +directly collaborate with their consumers -- for example, when there are too many consumers or +the consumers are external (do not work within the same company). -TIP: We use the term *Consumer-Driven Contracts* to refer to workflows where the consumers of an API -play a vital role in the process of creating the contracts; it's the recommended approach, easy -to implement when both producer and consumer teams work for the same organisations and the number +TIP: We use the term, *Consumer-Driven Contracts*, to refer to workflows where the consumers of an API +play a vital role in the process of creating the contracts. We recommended this approach, because it is easy +to implement when both producer and consumer teams work for the same organizations and the number of consumers is not extremely large. == Learning about {project-full-name} Features @@ -109,20 +110,19 @@ link:docker-project.html[Docker] == Advanced Topics Finally, we have a few topics for more advanced users: -* *Customizing DSL:* -<> | +* *Customizing the DSL:* +<> | <> | -<> | -<> | -<> +<> | +<> | +<> * *Customizing WireMock:* <> | <> * *Customizing {project-full-name}:* -<> | +<> | <> | <> | <> | <> | <> - diff --git a/docs/src/main/asciidoc/getting-started.adoc b/docs/src/main/asciidoc/getting-started.adoc index b10b6972c1..10959c3aab 100644 --- a/docs/src/main/asciidoc/getting-started.adoc +++ b/docs/src/main/asciidoc/getting-started.adoc @@ -2,9 +2,7 @@ = Getting Started include::_attributes.adoc[] -include::_attributes.adoc[] - -If you are getting started with {project-full-name}, or "`Spring`" in general, start by reading +If you are getting started with {project-full-name}, or Spring in general, start by reading this section. It answers the basic "`what?`", "`how?`" and "`why?`" questions. It includes an introduction to {project-full-name}, along with installation instructions. We then walk you through building your first {project-full-name} application, discussing some core @@ -13,7 +11,8 @@ principles as we go. [[getting-started-introducing-spring-cloud-contract]] == Introducing Spring Cloud Contract -Spring Cloud Contract moves TDD to the level of software architecture. It allows to perform consumer-driven and producer-driven contract testing. +Spring Cloud Contract moves TDD to the level of software architecture. +It lets you perform consumer-driven and producer-driven contract testing. [[getting-started-introducing-spring-cloud-contract-history]] === History @@ -25,20 +24,22 @@ from (https://github.com/Codearte[Codearte]). The `0.1.0` release took place on 26 Jan 2015 and it became stable with `1.0.0` release on 29 Feb 2016. [[getting-started-introducing-spring-cloud-contract-why]] -==== Why would you need it? +==== Why Do You Need It? -Assume that we have a system consisting of multiple microservices: +Assume that we have a system that consists of multiple microservices, as the following +image shows: image::Deps.png[Microservices Architecture] [[getting-started-introducing-spring-cloud-contract-testing-issues]] -==== Testing issues +==== Testing Issues -If we wanted to test the application in top left corner to determine whether it can -communicate with other services, we could do one of two things: +If we want to test the application in the top left corner of the image in the preceding +section to determine whether it can communicate with other services, we could do one of +two things: - Deploy all microservices and perform end-to-end tests. -- Mock other microservices in unit/integration tests. +- Mock other microservices in unit and integration tests. Both have their advantages but also a lot of disadvantages. @@ -51,15 +52,15 @@ Advantages: Disadvantages: -- To test one microservice, we have to deploy 6 microservices, a couple of databases, -etc. +- To test one microservice, we have to deploy six microservices, a couple of databases, +and other items. - The environment where the tests run is locked for a single suite of tests (nobody else would be able to run the tests in the meantime). - They take a long time to run. - The feedback comes very late in the process. - They are extremely hard to debug. -*Mock other microservices in unit/integration tests* +*Mock other microservices in unit and integration tests* Advantages: @@ -72,14 +73,16 @@ Disadvantages: reality. - You can go to production with passing tests and failing production. -To solve the aforementioned issues, Spring Cloud Contract was created. The main idea is to give you very fast feedback, without the need to set up the +To solve the aforementioned issues, Spring Cloud Contract was created. The main idea is to +give you very fast feedback, without the need to set up the whole world of microservices. If you work on stubs, then the only applications you need -are those that your application directly uses. +are those that your application directly uses. The following image shows the relationship +of stubs to an application: image::Stubs2.png[Stubbed Services] Spring Cloud Contract gives you the certainty that the stubs that you use were -created by the service that you're calling. Also, if you can use them, it means that they +created by the service that you call. Also, if you can use them, it means that they were tested against the producer's side. In short, you can trust those stubs. [[getting-started-introducing-spring-cloud-contract-purposes]] @@ -87,29 +90,31 @@ were tested against the producer's side. In short, you can trust those stubs. The main purposes of Spring Cloud Contract are: -- To ensure that HTTP / Messaging stubs (used when developing the client) do exactly +- To ensure that HTTP and Messaging stubs (used when developing the client) do exactly what the actual server-side implementation does. -- To promote ATDD (acceptance test driven developement) method and Microservices architectural style. +- To promote the ATDD (acceptance test-driven developement) method and the microservices architectural style. - To provide a way to publish changes in contracts that are immediately visible on both sides. - To generate boilerplate test code to be used on the server side. -By default Spring Cloud Contract integrates with http://wiremock.org[Wiremock] as the HTTP server stub. +By default, Spring Cloud Contract integrates with http://wiremock.org[Wiremock] as the HTTP server stub. IMPORTANT: Spring Cloud Contract's purpose is NOT to start writing business features in the contracts. Assume that we have a business use case of fraud check. If a -user can be a fraud for 100 different reasons, we would assume that you would create 2 +user can be a fraud for 100 different reasons, we would assume that you would create two contracts, one for the positive case and one for the negative case. Contract tests are used to test contracts between applications and not to simulate full behavior. [[getting-started-what-is-a-contract]] -=== What is a contract? +=== What Is a Contract? As consumers of services, we need to define what exactly we want to achieve. We need to -formulate our expectations. That is why we write contracts. In other words a contract is an agreement on how the API / message communication should look like. Let's look at the following example +formulate our expectations. That is why we write contracts. In other words, a contract is +an agreement on how the API or message communication should look. Consider the following example: -Assume that you want to send a request containing the ID of a client company and the -amount it wants to borrow from us. You also want to send it to the `/fraudcheck` url via -the `PUT` method. +Assume that you want to send a request that contains the ID of a client company and the +amount it wants to borrow from us. You also want to send it to the `/fraudcheck` URL via +the `PUT` method. The following listing shows a contract to check whether a client should +be marked as a fraud in both Groovy and YAML: ==== [source,groovy,indent=0,role="primary"] @@ -128,7 +133,8 @@ include::{introduction_url}/samples/standalone/yml/http-server/src/test/resource [[getting-started-three-second-tour]] == A Three-second Tour -This very brief tour walks through using Spring Cloud Contract: +This very brief tour walks through using Spring Cloud Contract. It consists of the +following topics: * <> * <> @@ -136,6 +142,8 @@ This very brief tour walks through using Spring Cloud Contract: You can find a somewhat longer tour <>. +The following UML diagram shows the relationship of the parts within Spring Cloud Contract: + [plantuml, getting-started-three-second, png] ---- "API Producer"->"API Producer": add Spring Cloud \nContract (SCC) plugin @@ -157,21 +165,24 @@ You can find a somewhat longer tour [[getting-started-three-second-tour-producer]] === On the Producer Side -To start working with Spring Cloud Contract, add files with REST/messaging contracts +To start working with Spring Cloud Contract, you can add files with REST or messaging contracts expressed in either Groovy DSL or YAML to the contracts directory, which is set by the `contractsDslDir` property. By default, it is `$rootDir/src/test/resources/contracts`. -Then add the Spring Cloud Contract Verifier dependency and plugin to your build file, as -shown in the following example: +Then you can add the Spring Cloud Contract Verifier dependency and plugin to your build file, as +the following example shows: +==== [source,xml,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] ---- +==== The following listing shows how to add the plugin, which should go in the build/plugins portion of the file: +==== [source,xml,indent=0] ---- @@ -181,6 +192,7 @@ portion of the file: true ---- +==== Running `./mvnw clean install` automatically generates tests that verify the application compliance with the added contracts. By default, the tests get generated under @@ -192,27 +204,29 @@ present, the tests fail. To make them pass, you must add the correct implementation of either handling HTTP requests or messages. Also, you must add a correct base test class for auto-generated tests to the project. This class is extended by all the auto-generated tests, and it -should contain all the setup necessary to run them (for example `RestAssuredMockMvc` +should contain all the setup information necessary to run them (for example `RestAssuredMockMvc` controller setup or messaging test setup). Once the implementation and the test base class are in place, the tests pass, and both the application and the stub artifacts are built and installed in the local Maven repository. -The changes can now be merged, and both the application and the stub artifacts may be -published in an online repository. +You can now merge the changes, and you can publish both the application and the stub artifacts +in an online repository. [[getting-started-three-second-tour-consumer]] === On the Consumer Side -`Spring Cloud Contract Stub Runner` can be used in the integration tests to get a running +You can use `Spring Cloud Contract Stub Runner` in the integration tests to get a running WireMock instance or messaging route that simulates the actual service. -To do so, add the dependency to `Spring Cloud Contract Stub Runner`, as shown in the -following example: +To do so, add the dependency to `Spring Cloud Contract Stub Runner`, as the +following example shows: +==== [source,xml,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] ---- +==== You can get the Producer-side stubs installed in your Maven repository in either of two ways: @@ -220,26 +234,31 @@ ways: * By checking out the Producer side repository and adding contracts and generating the stubs by running the following commands: + +==== [source,bash,indent=0] ---- $ cd local-http-server-repo $ ./mvnw clean install -DskipTests ---- -TIP: The tests are being skipped because the Producer-side contract implementation is not +==== +TIP: The tests are being skipped because the producer-side contract implementation is not in place yet, so the automatically-generated contract tests fail. * By getting already-existing producer service stubs from a remote repository. To do so, pass the stub artifact IDs and artifact repository URL as `Spring Cloud Contract -Stub Runner` properties, as shown in the following example: +Stub Runner` properties, as the following example shows: + +==== [source,yaml,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ---- +==== Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, provide the `group-id` and `artifact-id` values for `Spring Cloud Contract Stub Runner` to -run the collaborators' stubs for you, as shown in the following example: +run the collaborators' stubs for you, as the following example shows: +==== [source,java, indent=0] ---- @RunWith(SpringRunner.class) @@ -248,6 +267,7 @@ run the collaborators' stubs for you, as shown in the following example: stubsMode = StubRunnerProperties.StubsMode.LOCAL) public class LoanApplicationServiceTests { ---- +==== TIP: Use the `REMOTE` `stubsMode` when downloading stubs from an online repository and `LOCAL` for offline work. @@ -256,9 +276,9 @@ Now, in your integration test, you can receive stubbed versions of HTTP response messages that are expected to be emitted by the collaborator service. [[getting-started-first-application]] -== Developing Your First Spring Cloud Contract based application +== Developing Your First Spring Cloud Contract-based Application -This brief tour walks through using Spring Cloud Contract: +This brief tour walks through using Spring Cloud Contract. It consists of the following topics: * <> * <> @@ -266,24 +286,29 @@ This brief tour walks through using Spring Cloud Contract: You can find an even more brief tour <>. -For the sake of this example the `Stub Storage` will be Nexus / Artifactory. +For the sake of this example, the `Stub Storage` is Nexus/Artifactory. + +The following UML diagram shows the relationship of the parts of Spring Cloud Contract: image::getting-started-three-second.png[Getting started first application] [[getting-started-first-application-producer]] === On the Producer Side -To start working with `Spring Cloud Contract`, add Spring Cloud Contract Verifier dependency and plugin to your build file, -as shown in the following example: +To start working with `Spring Cloud Contract`, you can add Spring Cloud Contract Verifier +dependency and plugin to your build file, as the following example shows: +==== [source,xml,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] ---- +==== The following listing shows how to add the plugin, which should go in the build/plugins portion of the file: +==== [source,xml,indent=0] ---- @@ -293,14 +318,15 @@ portion of the file: true ---- +==== -Now let's add files with `REST/` messaging contracts +Now you can add files with `REST/` messaging contracts expressed in either Groovy DSL or YAML to the contracts directory, which is set by the `contractsDslDir` property. By default, it is `$rootDir/src/test/resources/contracts`. For the HTTP stubs, a contract defines what kind of response should be returned for a given request (taking into account the HTTP methods, URLs, headers, status codes, and so -on). The following example shows how an HTTP stub contract: +on). The following example shows an HTTP stub contract in both Groovy and YAML: ==== [source,groovy,indent=0,role="primary"] @@ -361,7 +387,7 @@ response: In the case of messaging, you can define: -* The input and the output messages can be defined (taking into account from and where it +* The input and output messages (taking into account from and where it was sent, the message body, and the header). * The methods that should be called after the message is received. * The methods that, when called, should trigger a message. @@ -386,14 +412,17 @@ Running `./mvnw clean install` automatically generates tests that verify the app compliance with the added contracts. By default, the generated tests are under `org.springframework.cloud.contract.verifier.tests.`. -The generated tests will differ, depending on which framework and test type you've setup in your plugin. +The generated tests may differ, depending on which framework and test type you have setup in your plugin. -In the samples below you'll find: +In the next listing, you can find: -- the default test mode for HTTP contracts via `MockMvc` -- JAX-RS client via the `JAXRS` test mode -- `WebTestClient` based test (this is particularly recommended while working with Reactive, `Web-Flux`-based applications) set via `WEBTESTCLIENT` test mode -- Spock based test via the `testFramework` property set to `SPOCK` +- The default test mode for HTTP contracts in `MockMvc` +- A JAX-RS client with the `JAXRS` test mode +- A `WebTestClient`-based test (this is particularly recommended while working with +Reactive, `Web-Flux`-based applications) set with the `WEBTESTCLIENT` test mode +- A Spock-based test with the `testFramework` property set to `SPOCK` + +The following listing shows all these samples: ==== [source,java,indent=0,role="primary"] @@ -504,14 +533,15 @@ present, the tests fail. To make them pass, you must add the correct implementation of handling either HTTP requests or messages. Also, you must add a correct base test class for auto-generated tests to the project. This class is extended by all the auto-generated tests and should -contain all the setup necessary to run them (for example, `RestAssuredMockMvc` controller -setup or messaging test setup). +contain all the setup necessary information needed to run them (for example, +`RestAssuredMockMvc` controller setup or messaging test setup). Once the implementation and the test base class are in place, the tests pass, and both the application and the stub artifacts are built and installed in the local Maven repository. Information about installing the stubs jar to the local repository appears in the logs, as -shown in the following example: +the following example shows: +==== [source,bash,indent=0] ---- [INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server --- @@ -527,6 +557,7 @@ shown in the following example: [INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom [INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar ---- +==== You can now merge the changes and publish both the application and the stub artifacts in an online repository. @@ -534,15 +565,17 @@ in an online repository. [[getting-started-first-application-consumer]] === On the Consumer Side -`Spring Cloud Contract Stub Runner` can be used in the integration tests to get a running +You can use Spring Cloud Contract Stub Runner in the integration tests to get a running WireMock instance or messaging route that simulates the actual service. -To get started, add the dependency to `Spring Cloud Contract Stub Runner`: +To get started, add the dependency to `Spring Cloud Contract Stub Runner`, as follows: +==== [source,xml,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] ---- +==== You can get the Producer-side stubs installed in your Maven repository in either of two ways: @@ -550,26 +583,31 @@ ways: * By checking out the Producer side repository and adding contracts and generating the stubs by running the following commands: + +==== [source,bash,indent=0] ---- $ cd local-http-server-repo $ ./mvnw clean install -DskipTests ---- +==== NOTE: The tests are skipped because the Producer-side contract implementation is not yet in place, so the automatically-generated contract tests fail. * Getting already existing producer service stubs from a remote repository. To do so, pass the stub artifact IDs and artifact repository URl as `Spring Cloud Contract Stub -Runner` properties, as shown in the following example: +Runner` properties, as the following example shows: + +==== [source,yaml,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ---- +==== Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation, provide the `group-id` and `artifact-id` for `Spring Cloud Contract Stub Runner` to run -the collaborators' stubs for you, as shown in the following example: +the collaborators' stubs for you, as the following example shows: +==== [source,java, indent=0] ---- @RunWith(SpringRunner.class) @@ -578,6 +616,7 @@ the collaborators' stubs for you, as shown in the following example: stubsMode = StubRunnerProperties.StubsMode.LOCAL) public class LoanApplicationServiceTests { ---- +==== TIP: Use the `REMOTE` `stubsMode` when downloading stubs from an online repository and `LOCAL` for offline work. @@ -586,6 +625,7 @@ In your integration test, you can receive stubbed versions of HTTP responses or that are expected to be emitted by the collaborator service. You can see entries similar to the following in the build logs: +==== [source,bash,indent=0] ---- 2016-07-19 14:22:25.403 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Desired version is + - will try to resolve the latest version @@ -596,45 +636,45 @@ to the following in the build logs: 2016-07-19 14:22:25.475 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265] 2016-07-19 14:22:27.737 INFO 41050 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}] ---- +==== [[getting-started-cdc]] -== Step-by-step Guide to Consumer Driven Contracts (CDC) with contracts laying on the producer side +== Step-by-step Guide to Consumer Driven Contracts (CDC) with Contracts on the Producer Side -Consider an example of Fraud Detection and the Loan Issuance process. The business +Consider an example of fraud detection and the loan issuance process. The business scenario is such that we want to issue loans to people but do not want them to steal from us. The current implementation of our system grants loans to everybody. Assume that `Loan Issuance` is a client to the `Fraud Detection` server. In the current -sprint, we must develop a new feature: if a client wants to borrow too much money, then +sprint, we must develop a new feature: if a client wants to borrow too much money, we mark the client as a fraud. Technical remarks -* Fraud Detection has an `artifact-id` of `http-server`, -* Loan -Issuance has an artifact-id of `http-client` -* both have a `group-id` of `com.example` -* For the sake of this example the `Stub Storage` will be Nexus / Artifactory +* Fraud Detection has an `artifact-id` of `http-server` +* Loan Issuance has an artifact-id of `http-client` +* Both have a `group-id` of `com.example` +* For the sake of this example the `Stub Storage` is Nexus/Artifactory Social remarks -* both client and server development teams need to communicate directly and +* Both the client and the server development teams need to communicate directly and discuss changes while going through the process -* CDC is all about communication. +* CDC is all about communication -The https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-server[server -side code is available here] and https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-client[the -client code here]. +The https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-server[server-side +code is available here] and https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-client[the client code is available here]. -TIP: In this case, the producer owns the contracts. Physically, all the contract are +TIP: In this case, the producer owns the contracts. Physically, all of the contracts are in the producer's repository. [[getting-started-cdc-technical-note]] -=== Technical note +=== Technical Note -If using the *SNAPSHOT* / *Milestone* / *Release Candidate* versions please add the +If you use the SNAPSHOT, Milestone, or Release Candidate versions you need to add the following section to your build: +==== [source,xml,indent=0,subs="verbatim,attributes",role="primary"] .Maven ---- @@ -646,22 +686,23 @@ include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=repo ---- include::{introduction_url}/samples/standalone/dsl/http-server/build.gradle[tags=deps_repos,indent=0] ---- +==== -For simplicity we will use the following acronyms: +For simplicity, we use the following acronyms: -- Loan Issuance - LI - the http client -- Fraud Detection - FD - the http server -- Spring Cloud Contract - SCC +- Loan Issuance (LI): The HTTP client +- Fraud Detection (FD): The HTTP server +- Spring Cloud Contract (SCC) [[getting-started-cdc-consumer]] -=== Consumer side (Loan Issuance) +=== The Consumer Side (Loan Issuance) As a developer of the Loan Issuance service (a consumer of the Fraud Detection server), you might do the following steps: . Start doing TDD by writing a test for your feature. . Write the missing implementation. . Clone the Fraud Detection service repository locally. -. Define the contract locally in the repo of Fraud Detection service. +. Define the contract locally in the repo of the fraud detection service. . Add the Spring Cloud Contract (SCC) plugin. . Run the integration tests. . File a pull request. @@ -671,7 +712,7 @@ As a developer of the Loan Issuance service (a consumer of the Fraud Detection s . Deploy your app. . Work online. -Let's start with the Loan Issuance flow: +We start with the loan issuance flow, which the following UML diagram shows: [plantuml, getting-started-cdc-client, png] ---- @@ -702,54 +743,66 @@ Let's start with the Loan Issuance flow: ---- [[getting-started-cdc-consumer-start]] -==== Start doing TDD by writing a test for your feature +==== Start Doing TDD by Writing a Test for Your Feature +The following listing shows a test that we might use to check whether a loan amount is too +large: + +==== [source,groovy,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=client_tdd,indent=0] ---- +==== Assume that you have written a test of your new feature. If a loan application for a big amount is received, the system should reject that loan application with some description. [[getting-started-cdc-consumer-write]] -==== Write the missing implementation +==== Write the Missing Implementation At some point in time, you need to send a request to the Fraud Detection service. Assume that you need to send the request containing the ID of the client and the amount the -client wants to borrow. You want to send it to the `/fraudcheck` url via the `PUT` method. +client wants to borrow. You want to send it to the `/fraudcheck` URL by using the `PUT` method. +To do so, you might use code similar to the following: +==== [source,groovy,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-client/src/main/java/com/example/loan/LoanApplicationService.java[tags=client_call_server,indent=0] ---- +==== For simplicity, the port of the Fraud Detection service is set to `8080`, and the application runs on `8090`. -If you start the test at this point, it breaks, because no service currently runs on port +NOTE: If you start the test at this point, it breaks, because no service currently runs on port `8080`. [[getting-started-cdc-consumer-clone]] ==== Clone the Fraud Detection service repository locally You can start by playing around with the server side contract. To do so, you must first -clone it. +clone it, by running the following command: +==== [source,bash,indent=0] ---- $ git clone https://your-git-server.com/server-side.git local-http-server-repo ---- +==== [[getting-started-cdc-consumer-define]] -==== Define the contract locally in the repo of Fraud Detection service +==== Define the Contract Locally in the Repository of the Fraud Detection Service As a consumer, you need to define what exactly you want to achieve. You need to formulate your expectations. To do so, write the following contract: -IMPORTANT: Place the contract under `src/test/resources/contracts/fraud` folder. The `fraud` folder +IMPORTANT: Place the contract in the `src/test/resources/contracts/fraud` folder. The `fraud` folder is important because the producer's test base class name references that folder. +The following example shows our contract, in both Groovy and YAML: + ==== [source,groovy,indent=0,role="primary"] .groovy @@ -764,69 +817,76 @@ include::{introduction_url}/samples/standalone/yml/http-server/src/test/resource ---- ==== -The YML contract is quite straight-forward. However when you take a look at the Contract -written using a statically typed Groovy DSL - you might wonder what the +The YML contract is quite straightforward. However, when you take a look at the Contract +written with a statically typed Groovy DSL, you might wonder what the `value(client(...), server(...))` parts are. By using this notation, Spring Cloud -Contract lets you define parts of a JSON block, a URL, etc., which are dynamic. In case +Contract lets you define parts of a JSON block, a URL, or other structure that is dynamic. In case of an identifier or a timestamp, you need not hardcode a value. You want to allow some different ranges of values. To enable ranges of values, you can set regular expressions -matching those values for the consumer side. You can provide the body by means of either -a map notation or String with interpolations. We highly recommend using the map notation! +that match those values for the consumer side. You can provide the body by means of either +a map notation or String with interpolations. We highly recommend using the map notation. -TIP: You must understand the map notation in order to set up contracts. Please read the +TIP: You must understand the map notation in order to set up contracts. See the https://groovy-lang.org/json.html[Groovy docs regarding JSON]. The previously shown contract is an agreement between two sides that: -- if an HTTP request is sent with all of -** a `PUT` method on the `/fraudcheck` endpoint, -** a JSON body with a `client.id` that matches the regular expression `[0-9]{10}` and +- If an HTTP request is sent with all of +** A `PUT` method on the `/fraudcheck` endpoint +** A JSON body with a `client.id` that matches the regular expression `[0-9]{10}` and `loanAmount` equal to `99999`, -** and a `Content-Type` header with a value of `application/vnd.fraud.v1+json`, -- then an HTTP response is sent to the consumer that -** has status `200`, -** contains a JSON body with the `fraudCheckStatus` field containing a value `FRAUD` and -the `rejectionReason` field having value `Amount too high`, -** and a `Content-Type` header with a value of `application/vnd.fraud.v1+json`. +** A `Content-Type` header with a value of `application/vnd.fraud.v1+json` +- Then an HTTP response is sent to the consumer that +** Has status `200` +** Contains a JSON body with the `fraudCheckStatus` field containing a value of `FRAUD` and +the `rejectionReason` field having a value of `Amount too high` +** Has a `Content-Type` header with a value of `application/vnd.fraud.v1+json` Once you are ready to check the API in practice in the integration tests, you need to install the stubs locally. [[getting-started-cdc-consumer-add]] -==== Add the Spring Cloud Contract Verifier plugin +==== Add the Spring Cloud Contract Verifier Plugin -We can add either a Maven or a Gradle plugin. In this example, you see how to add Maven. -First, add the `Spring Cloud Contract` BOM. +We can add either a Maven or a Gradle plugin. In this example, we show how to add Maven. +First, we add the `Spring Cloud Contract` BOM, as the following example shows: +==== [source,xml,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_bom,indent=0] ---- +==== -Next, add the `Spring Cloud Contract Verifier` Maven plugin +Next, add the `Spring Cloud Contract Verifier` Maven plugin, as the following example shows: +==== [source,xml,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0] ---- +==== -Since the plugin was added, you get the `Spring Cloud Contract Verifier` features which, +Since the plugin was added, you get the `Spring Cloud Contract Verifier` features, which, from the provided contracts: -- generate and run tests -- produce and install stubs +- Generate and run tests +- Produce and install stubs -You do not want to generate tests since you, as the consumer, want only to play with the -stubs. You need to skip the test generation and execution. When you execute: +You do not want to generate tests, since you, as the consumer, want only to play with the +stubs. You need to skip the test generation and execution. To do so, run the following commands: +==== [source,bash,indent=0] ---- $ cd local-http-server-repo $ ./mvnw clean install -DskipTests ---- +==== -In the logs, you see something like this: +Once you run those commands, you should you see something like the following content in the logs: +==== [source,bash,indent=0] ---- [INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server --- @@ -842,50 +902,60 @@ In the logs, you see something like this: [INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom [INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar ---- +==== The following line is extremely important: +==== [source,bash,indent=0] ---- [INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar ---- +==== It confirms that the stubs of the `http-server` have been installed in the local repository. [[getting-started-cdc-consumer-run]] -==== Run the integration tests +==== Running the Integration Tests In order to profit from the Spring Cloud Contract Stub Runner functionality of automatic stub downloading, you must do the following in your consumer side project (`Loan Application service`): -Add the `Spring Cloud Contract` BOM: - +. Add the `Spring Cloud Contract` BOM, as follows: ++ +==== [source,xml,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=contract_bom,indent=0] ---- +==== -Add the dependency to `Spring Cloud Contract Stub Runner`: - +. Add the dependency to `Spring Cloud Contract Stub Runner`, as follows: ++ +==== [source,xml,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] ---- +==== -Annotate your test class with `@AutoConfigureStubRunner`. In the annotation, provide the +. Annotate your test class with `@AutoConfigureStubRunner`. In the annotation, provide the `group-id` and `artifact-id` for the Stub Runner to download the stubs of your -collaborators. (Optional step) Because you're playing with the collaborators offline, you +collaborators. (Optional step) Because you are playing with the collaborators offline, you can also provide the offline work switch (`StubRunnerProperties.StubsMode.LOCAL`). - ++ +==== [source,groovy,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=autoconfigure_stubrunner,indent=0] ---- +==== -Now, when you run your tests, you see something like this: +Now, when you run your tests, you see something like the following output in the logs: +==== [source,bash,indent=0] ---- 2016-07-19 14:22:25.403 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Desired version is + - will try to resolve the latest version @@ -896,31 +966,33 @@ Now, when you run your tests, you see something like this: 2016-07-19 14:22:25.475 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265] 2016-07-19 14:22:27.737 INFO 41050 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}] ---- +==== -This output means that Stub Runner has found your stubs and started a server for your app -with group id `com.example`, artifact id `http-server` with version `0.0.1-SNAPSHOT` of -the stubs and with `stubs` classifier on port `8080`. +This output means that Stub Runner has found your stubs and started a server for your application +with a group ID of `com.example` and an artifact ID of `http-server` with version `0.0.1-SNAPSHOT` of +the stubs and with the `stubs` classifier on port `8080`. [[getting-started-cdc-consumer-file]] -==== File a pull request +==== Filing a Pull Request What you have done until now is an iterative process. You can play around with the contract, install it locally, and work on the consumer side until the contract works as you wish. -Once you are satisfied with the results and the test passes, publish a pull request to +Once you are satisfied with the results and the test passes, you can publish a pull request to the server side. Currently, the consumer side work is done. [[getting-started-cdc-producer]] -=== Producer side (Fraud Detection server) +=== The Producer Side (Fraud Detection server) -As a developer of the Fraud Detection server (a server to the Loan Issuance service) I would like to: +As a developer of the Fraud Detection server (a server to the Loan Issuance service), you +might want to do the following -- take over the pull request -- write the missing implementation -- deploy the application +- Take over the pull request +- Write the missing implementation +- Deploy the application -Let's look at the Fraud Detection flow: +The following UML diagram shows the fraud detection flow: [plantuml, getting-started-cdc-server, png] ---- @@ -943,38 +1015,48 @@ Let's look at the Fraud Detection flow: ---- [[getting-started-cdc-producer-pr]] -==== Take over the pull request +==== Taking over the Pull Request -As a reminder, you can see the initial implementation here: +As a reminder, the following listing shows the initial implementation: +==== [source,java,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=server_api,indent=0] include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=initial_impl,indent=0] } ---- +==== +Then you can run the following commands: + +==== [source,bash,indent=0] ---- $ git checkout -b contract-change-pr master $ git pull https://your-git-server.com/server-side-fork.git contract-change-pr ---- +==== -You must add the dependencies needed by the autogenerated tests: +You must add the dependencies needed by the autogenerated tests, as follows: +==== [source,xml,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] ---- +==== -In the configuration of the Maven plugin, pass the `packageWithBaseClasses` property +In the configuration of the Maven plugin, you must pass the `packageWithBaseClasses` property, as follows: +==== [source,xml,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0] ---- +==== -IMPORTANT: This example uses "convention based" naming by setting the +IMPORTANT: This example uses "`convention-based`" naming by setting the `packageWithBaseClasses` property. Doing so means that the two last packages combine to make the name of the base test class. In our case, the contracts were placed under `src/test/resources/contracts/fraud`. Since you do not have two packages starting from @@ -982,16 +1064,20 @@ the `contracts` folder, pick only one, which should be `fraud`. Add the `Base` s capitalize `fraud`. That gives you the `FraudBase` test class name. All the generated tests extend that class. Over there, you can set up your Spring Context -or whatever is necessary. In this case, use https://github.com/rest-assured/rest-assured[Rest Assured MVC] to -start the server side `FraudDetectionController`. +or whatever is necessary. In this case, you should use https://github.com/rest-assured/rest-assured[Rest Assured MVC] to +start the server side `FraudDetectionController`. The following listing shows the +`FraudBase` class: +==== [source,java,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-server/src/test/java/com/example/fraud/FraudBase.java[] ---- +==== -Now, if you run the `./mvnw clean install`, you get something like this: +Now, if you run the `./mvnw clean install`, you get something like the following output: +==== [source,bash,indent=0] ---- Results : @@ -999,11 +1085,13 @@ Results : Tests in error: ContractVerifierTest.validate_shouldMarkClientAsFraud:32 » IllegalState Parsed... ---- +==== This error occurs because you have a new contract from which a test was generated and it failed since you have not implemented the feature. The auto-generated test would look -like this: +like the following test method: +==== [source,java,indent=0] ---- @Test @@ -1026,23 +1114,25 @@ public void validate_shouldMarkClientAsFraud() throws Exception { assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high"); } ---- +==== -If you used the Groovy DSL, you can see, all the `producer()` parts of the Contract that were present in the +If you used the Groovy DSL, you can see that all of the `producer()` parts of the Contract that were present in the `value(consumer(...), producer(...))` blocks got injected into the test. In case of using YAML, the same applied for the `matchers` sections of the `response`. Note that, on the producer side, you are also doing TDD. The expectations are expressed in the form of a test. This test sends a request to our own application with the URL, -headers, and body defined in the contract. It also is expecting precisely defined values +headers, and body defined in the contract. It is also expecting precisely defined values in the response. In other words, you have the `red` part of `red`, `green`, and `refactor`. It is time to convert the `red` into the `green`. [[getting-started-cdc-producer-impl]] -==== Write the missing implementation +==== Write the Missing Implementation Because you know the expected input and expected output, you can write the missing -implementation: +implementation as follows: +==== [source,java,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=server_api,indent=0] @@ -1050,33 +1140,39 @@ include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=initial_impl,indent=0] } ---- +==== -When you execute `./mvnw clean install` again, the tests pass. Since the `Spring Cloud +When you run `./mvnw clean install` again, the tests pass. Since the `Spring Cloud Contract Verifier` plugin adds the tests to the `generated-test-sources`, you can actually run those tests from your IDE. [[getting-started-cdc-producer-deploy]] -==== Deploy your app +==== Deploying Your Application -Once you finish your work, you can deploy your change. First, merge the branch: +Once you finish your work, you can deploy your changes. To do so, you must first merge the +branch by running the following commands: +==== [source,bash,indent=0] ---- $ git checkout master $ git merge --no-ff contract-change-pr $ git push origin master ---- +==== -Your CI might run something like `./mvnw clean deploy`, which would publish both the +Your CI might run something a command such as `./mvnw clean deploy`, which would publish both the application and the stub artifacts. [[getting-started-cdc-consumer-final]] -=== Consumer Side (Loan Issuance) Final Step +=== Consumer Side (Loan Issuance), Final Step -As a developer of the Loan Issuance service (a consumer of the Fraud Detection server) I will want to: +As a developer of the loan issuance service (a consumer of the Fraud Detection server), I want to: -- merge our feature branch to `master` -- switch to online mode of working +- Merge our feature branch to `master` +- Switch to online mode of working + +The following UML diagram shows the final state of the process: [plantuml, getting-started-cdc-client-final, png] ---- @@ -1095,42 +1191,49 @@ As a developer of the Loan Issuance service (a consumer of the Fraud Detection s ---- [[getting-started-cdc-consumer-final-merge]] -==== Merge branch to master +==== Merging a Branch to Master +The following commands show one way to merge a branch into master with Git: + +==== [source,bash,indent=0] ---- $ git checkout master $ git merge --no-ff contract-change-pr ---- +==== [[getting-started-cdc-consumer-final-online]] -==== Work online +==== Working Online Now you can disable the offline work for Spring Cloud Contract Stub Runner and indicate -where the repository with your stubs is located. At this moment the stubs of the server +where the repository with your stubs is located. At this moment, the stubs of the server side are automatically downloaded from Nexus/Artifactory. You can set the value of `stubsMode` to `REMOTE`. The following code shows an example of -achieving the same thing by changing the properties. +achieving the same thing by changing the properties: +==== [source,yaml,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ---- +==== -That's it! +That's it. You have finished the tutorial. [[getting-started-whats-next]] == Next Steps + Hopefully, this section provided some of the {project-full-name} basics and got you on your way to writing your own applications. If you are a task-oriented type of developer, you might want to jump over to https://spring.io and check out some of the https://spring.io/guides/[getting started] guides that solve specific "`How do I do that with Spring?`" problems. We also have {project-full-name}-specific -"`<>`" reference documentation. +"`<>`" reference documentation. -Otherwise, the next logical step is to read _<>_. If +Otherwise, the next logical step is to read <>. If you are really impatient, you could also jump ahead and read about -_<>_. +<>. In addition to that you can check out the following videos: @@ -1149,4 +1252,4 @@ video::TvpkZu1e2Dc[youtube,start=6262,width=640,height=480] You can find the default project samples at https://github.com/spring-cloud-samples/spring-cloud-contract-samples[samples]. -You can find the Spring Cloud Contract workshops https://cloud-samples.spring.io/spring-cloud-contract-samples/[over here]. \ No newline at end of file +You can find the Spring Cloud Contract workshops https://cloud-samples.spring.io/spring-cloud-contract-samples/[here]. diff --git a/docs/src/main/asciidoc/gradle-project.adoc b/docs/src/main/asciidoc/gradle-project.adoc index 75b89045fa..e12a4b8e1d 100644 --- a/docs/src/main/asciidoc/gradle-project.adoc +++ b/docs/src/main/asciidoc/gradle-project.adoc @@ -21,18 +21,19 @@ following sections: [[gradle-prerequisites]] == Prerequisites -In order to use Spring Cloud Contract Verifier with WireMock, you muse use either a +In order to use Spring Cloud Contract Verifier with WireMock, you must use either a Gradle or a Maven plugin. -WARNING: If you want to use Spock in your projects, you must add separately the -`spock-core` and `spock-spring` modules. Check https://spockframework.github.io/[Spock -docs for more information] +WARNING: If you want to use Spock in your projects, you must separately add the +`spock-core` and `spock-spring` modules. See https://spockframework.github.io/[Spock's +documnetation for more information] [[gradle-add-gradle-plugin]] == Add Gradle Plugin with Dependencies -To add a Gradle plugin with dependencies, use code similar to this: +To add a Gradle plugin with dependencies, you can use code similar to the following: +==== [source,groovy,indent=0] ---- buildscript { @@ -62,13 +63,15 @@ dependencies { testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier' } ---- +==== [[gradle-and-rest-assured]] == Gradle and Rest Assured 2.0 By default, Rest Assured 3.x is added to the classpath. However, to use Rest Assured 2.x -you can add it to the plugins classpath, as shown here: +you can add it to the plugins classpath, as the following listing shows: +==== [source,groovy,indent=0] ---- buildscript { @@ -90,6 +93,7 @@ depenendencies { testCompile "com.jayway.restassured:spring-mock-mvc:2.5.0" } ---- +==== That way, the plugin automatically sees that Rest Assured 2.x is present on the classpath and modifies the imports accordingly. @@ -97,43 +101,48 @@ and modifies the imports accordingly. [[gradle-snapshot-versions]] == Snapshot Versions for Gradle -Add the additional snapshot repository to your build.gradle to use snapshot versions, -which are automatically uploaded after every successful build, as shown here: +You can add the additional snapshot repository to your `build.gradle` to use snapshot versions, +which are automatically uploaded after every successful build, as the following listing shows: +==== [source,groovy,indent=0] ---- include::{standalone_samples_path}/http-server/build.gradle[tags=repos,indent=0] } ---- +==== + [[gradle-add-stubs]] == Add stubs -By default, Spring Cloud Contract Verifier is looking for stubs in the +By default, Spring Cloud Contract Verifier looks for stubs in the `src/test/resources/contracts` directory. -The directory containing stub definitions is treated as a class name, and each stub +The directory that contains stub definitions is treated as a class name, and each stub definition is treated as a single test. Spring Cloud Contract Verifier assumes that it contains at least one level of directories that are to be used as the test class name. If more than one level of nested directories is present, all except the last one is used -as the package name. For example, with following structure: +as the package name. Consider the following structure: +==== [source,groovy,indent=0] ---- src/test/resources/contracts/myservice/shouldCreateUser.groovy src/test/resources/contracts/myservice/shouldReturnUser.groovy ---- +==== -Spring Cloud Contract Verifier creates a test class named `defaultBasePackage.MyService` -with two methods: +Given the preceding structure, Spring Cloud Contract Verifier creates a test class named +`defaultBasePackage.MyService` with two methods: - - `shouldCreateUser()` - - `shouldReturnUser()` +- `shouldCreateUser()` +- `shouldReturnUser()` [[gradle-run-plugin]] -== Run the Plugin +== Running the Plugin The plugin registers itself to be invoked before a `check` task. If you want it to be -part of your build process, you need to do nothing more. If you just want to generate +part of your build process, you need do nothing more. If you just want to generate tests, invoke the `generateContractTests` task. [[gradle-default-setup]] @@ -142,6 +151,7 @@ tests, invoke the `generateContractTests` task. The default Gradle Plugin setup creates the following Gradle part of the build (in pseudocode): +==== [source,groovy,indent=0] ---- contracts { @@ -190,13 +200,15 @@ publishing { } } ---- +==== [[gradle-configure-plugin]] -== Configure Plugin +== Configuring the Plugin -To change the default configuration, add a `contracts` snippet to your Gradle config, as -shown here: +To change the default configuration, you can add a `contracts` snippet to your Gradle +configuration, as the following listing shows: +==== [source,groovy,indent=0] ---- contracts { @@ -205,79 +217,85 @@ contracts { generatedTestSourcesDir = project.file('src/generatedContract') } ---- +==== [[gradle-configuration-options]] == Configuration Options -* *testMode*: Defines the mode for acceptance tests. By default, the mode is MockMvc, -which is based on Spring's MockMvc. It can also be changed to *WebTestClient*, *JaxRsClient* or to -*Explicit* for real HTTP calls. -* *imports*: Creates an array with imports that should be included in generated tests -(for example ['org.myorg.Matchers']). By default, it creates an empty array. -* *staticImports*: Creates an array with static imports that should be included in -generated tests(for example ['org.myorg.Matchers.*']). By default, it creates an empty +* `testMode`: Defines the mode for acceptance tests. By default, the mode is MockMvc, +which is based on Spring's MockMvc. It can also be changed to WebTestClient, JaxRsClient, or +Explicit (for real HTTP calls). +* `imports`: Creates an array with imports that should be included in the generated tests +(for example, `['org.myorg.Matchers']`). By default, it creates an empty array. +* `staticImports`: Creates an array with static imports that should be included in +generated tests(for example, `['org.myorg.Matchers.*']`). By default, it creates an empty array. -* *basePackageForTests*: Specifies the base package for all generated tests. If not set, -the value is picked from `baseClassForTests`'s package and from `packageWithBaseClasses`. -If neither of these values are set, then the value is set to +* `basePackageForTests`: Specifies the base package for all generated tests. If not set, +the value is picked from the package of `baseClassForTests` and from `packageWithBaseClasses`. +If neither of these values are set, the value is set to `org.springframework.cloud.contract.verifier.tests`. -* *baseClassForTests*: Creates a base class for all generated tests. By default, if you +* `baseClassForTests`: Creates a base class for all generated tests. By default, if you use Spock classes, the class is `spock.lang.Specification`. -* *packageWithBaseClasses*: Defines a package where all the base classes reside. This -setting takes precedence over *baseClassForTests*. -* *baseClassMappings*: Explicitly maps a contract package to a FQN of a base class. This -setting takes precedence over *packageWithBaseClasses* and *baseClassForTests*. -* *ruleClassForTests*: Specifies a rule that should be added to the generated test +* `packageWithBaseClasses`: Defines a package where all the base classes reside. This +setting takes precedence over `baseClassForTests`. +* `baseClassMappings`: Explicitly maps a contract package to a FQN of a base class. This +setting takes precedence over `packageWithBaseClasses` and `baseClassForTests`. +* `ruleClassForTests`: Specifies a rule that should be added to the generated test classes. -* *ignoredFiles*: Uses an `Antmatcher` to allow defining stub files for which processing +* `ignoredFiles`: Uses an `Antmatcher` to allow defining stub files for which processing should be skipped. By default, it is an empty array. -* *contractsDslDir*: Specifies the directory containing contracts written using the +* `contractsDslDir`: Specifies the directory that contains contracts written by using the GroovyDSL. By default, its value is `$rootDir/src/test/resources/contracts`. -* *generatedTestSourcesDir*: Specifies the test source directory where tests generated -from the Groovy DSL should be placed. By default its value is +* `generatedTestSourcesDir`: Specifies the test source directory where tests generated +from the Groovy DSL should be placed. By default, its value is `$buildDir/generated-test-sources/contracts`. -* *generatedTestResourcesDir*: Specifies the test resource directory where resources used by the tests generated -from the Groovy DSL should be placed. By default its value is +* `generatedTestResourcesDir`: Specifies the test resource directory where resources used by the tests generated +from the Groovy DSL should be placed. By default, its value is `$buildDir/generated-test-resources/contracts`. -* *stubsOutputDir*: Specifies the directory where the generated WireMock stubs from +* `stubsOutputDir`: Specifies the directory where the generated WireMock stubs from the Groovy DSL should be placed. -* *testFramework*: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (`TestFramework.JUNIT`) and -JUnit 5 are supported with JUnit 4 being the default framework. -* *contractsProperties*: a map containing properties to be passed to Spring Cloud Contract -components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders. +* `testFramework`: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (`TestFramework.JUNIT`), and +JUnit 5 are supported, with JUnit 4 being the default framework. +* `contractsProperties`: A map that contains properties to be passed to Spring Cloud Contract +components. Those properties might be used by (for example) built-in or custom Stub Downloaders. -The following properties are used when you want to specify the location of the JAR -containing the contracts: +You can use the following properties when you want to specify the location of the JAR +that contains the contracts: -* *contractDependency*: Specifies the Dependency that provides +* `contractDependency`: Specifies the Dependency that provides `groupid:artifactid:version:classifier` coordinates. You can use the `contractDependency` closure to set it up. -* *contractsPath*: Specifies the path to the jar. If contract dependencies are +* `contractsPath`: Specifies the path to the jar. If contract dependencies are downloaded, the path defaults to `groupid/artifactid` where `groupid` is slash separated. Otherwise, it scans contracts under the provided directory. -* *contractsMode*: Specifies the mode of downloading contracts (whether the -JAR is available offline, remotely etc.) -* *deleteStubsAfterTest*: If set to `false` will not remove any downloaded -contracts from temporary directories +* `contractsMode`: Specifies the mode for downloading contracts (whether the +JAR is available offline, remotely, and so on). +* `deleteStubsAfterTest`: If set to `false`, do not remove any downloaded +contracts from temporary directories. -Below you can find a list of experimental features you can turn on via the plugin: +You can also turn on the following experimental features in the plugin: -* *convertToYaml*: converts all DSLs to the declarative, YAML format. This can be extremely useful when you're using external libraries in your Groovy DSLs. By turning this feature on (by setting it to `true`) you will not need to add the library dependency on the consumer side. -* *assertJsonSize*: You can check the size of JSON arrays in the generated tests. This feature is disabled by default. +* `convertToYaml`: Converts all DSLs to the declarative YAML format. This can be extremely +useful when you use external libraries in your Groovy DSLs. By turning this feature on +(by setting it to `true`) you need not add the library dependency on the consumer side. +* `assertJsonSize`: You can check the size of JSON arrays in the generated tests. This +feature is disabled by default. [[gradle-single-base-class]] == Single Base Class for All Tests When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base specification for all generated acceptance tests. In this class, you need to point to an -endpoint, which should be verified. +endpoint, which should be verified. The following example shows how to do so: +==== [source,groovy,indent=0] ---- include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/resources/functionalTest/bootSimple/src/test/groovy/org/springframework/cloud/contract/verifier/twitter/places/BaseMockMvcSpec.groovy[tags=base_class,indent=0] ---- +==== -If you use `Explicit` mode, you can use a base class to initialize the whole tested app +If you use `Explicit` mode, you can use a base class to initialize the whole tested application, as you might see in regular integration tests. If you use the `JAXRSCLIENT` mode, this base class should also contain a `protected WebTarget webTarget` field. Right now, the only option to test the JAX-RS API is to start a web server. @@ -289,40 +307,44 @@ If your base classes differ between contracts, you can tell the Spring Cloud Con plugin which class should get extended by the autogenerated tests. You have two options: * Follow a convention by providing the `packageWithBaseClasses` -* Provide explicit mapping via `baseClassMappings` +* Provide explicit mapping by using `baseClassMappings` -*By Convention* +=== By Convention -The convention is such that if you have a contract under (for example) +The convention is such that if you have a contract in (for example) `src/test/resources/contract/foo/bar/baz/` and set the value of the `packageWithBaseClasses` property to `com.example.base`, then Spring Cloud Contract Verifier assumes that there is a `BarBazBase` class under the `com.example.base` package. In other words, the system takes the last two parts of the package, if they exist, and -forms a class with a `Base` suffix. This rule takes precedence over *baseClassForTests*. -Here is an example of how it works in the `contracts` closure: +forms a class with a `Base` suffix. This rule takes precedence over `baseClassForTests`. +The following example shows how it works in the `contracts` closure: +==== [source,groovy,indent=0] ---- include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/groovy/org/springframework/cloud/contract/verifier/plugin/ContractVerifierSpec.groovy[tags=package_with_base_classes,indent=0] ---- +==== -*By Mapping* +=== By Mapping -You can manually map a regular expression of the contract's package to fully qualified +You can manually map a regular expression of the contract's package to the fully qualified name of the base class for the matched contract. You have to provide a list called -`baseClassMappings` that consists `baseClassMapping` objects that takes a +`baseClassMappings` that consists of `baseClassMapping` objects that take a `contractPackageRegex` to `baseClassFQN` mapping. Consider the following example: +==== [source,groovy,indent=0] ---- include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/groovy/org/springframework/cloud/contract/verifier/plugin/ContractVerifierSpec.groovy[tags=base_class_mappings,indent=0] ---- +==== -Let's assume that you have contracts under +Let's assume that you have contracts in the following directories: - `src/test/resources/contract/com/` - `src/test/resources/contract/foo/` -By providing the `baseClassForTests`, we have a fallback in case mapping did not succeed. +By providing `baseClassForTests`, we have a fallback in case mapping did not succeed. (You could also provide the `packageWithBaseClasses` as a fallback.) That way, the tests generated from `src/test/resources/contract/com/` contracts extend the `com.example.ComBase`, whereas the rest of the tests extend `com.example.FooBase`. @@ -330,49 +352,58 @@ generated from `src/test/resources/contract/com/` contracts extend the [[gradle-invoking-generated-tests]] == Invoking Generated Tests -To ensure that the provider side is compliant with defined contracts, you need to invoke: +To ensure that the provider side is compliant with your defined contracts, you need to run +the following command: +==== [source,bash,indent=0] ---- ./gradlew generateContractTests test ---- +==== [[gradle-pushing-stubs-to-scm]] -== Pushing stubs to SCM +== Pushing Stubs to SCM -If you're using the SCM repository to keep the contracts and +If you use the SCM repository to keep the contracts and stubs, you might want to automate the step of pushing stubs to -the repository. To do that, it's enough to call the `pushStubsToScm` -task. Example: +the repository. To do that, you can call the `pushStubsToScm` +task by running the following command: +==== [source,bash,indent=0] ---- $ ./gradlew pushStubsToScm ---- +==== Under <> you can find all possible -configuration options that you can pass either via -the `contractsProperties` field e.g. `contracts { contractsProperties = [foo:"bar"] }`, -via `contractsProperties` method e.g. `contracts { contractsProperties([foo:"bar"]) }`, -a system property or an environment variable. +configuration options that you can pass either through +the `contractsProperties` field (for example, `contracts { contractsProperties = [foo:"bar"] }`), +through the `contractsProperties` method (for example, `contracts { contractsProperties([foo:"bar"]) }`), +or through a system property or an environment variable. [[gradle-consumer]] == Spring Cloud Contract Verifier on the Consumer Side In a consuming service, you need to configure the Spring Cloud Contract Verifier plugin -in exactly the same way as in case of provider. If you do not want to use Stub Runner -then you need to copy contracts stored in `src/test/resources/contracts` and generate -WireMock JSON stubs using: +in exactly the same way as in the case of a provider. If you do not want to use Stub Runner, +you need to copy the contracts stored in `src/test/resources/contracts` and generate +WireMock JSON stubs by using the following command: +==== [source,bash,indent=0] ---- ./gradlew generateClientStubs ---- +==== NOTE: The `stubsOutputDir` option has to be set for stub generation to work. -When present, JSON stubs can be used in automated tests of consuming a service. +When present, JSON stubs can be used in automated tests to consume a service. The +following example shows how to do so: +==== [source,groovy,indent=0] ---- @ContextConfiguration(loader == SpringApplicationContextLoader, classes == Application) @@ -397,6 +428,8 @@ class LoanApplicationServiceSpec extends Specification { } } ---- +==== -`LoanApplication` makes a call to `FraudDetection` service. This request is handled by a -WireMock server configured with stubs generated by Spring Cloud Contract Verifier. \ No newline at end of file +In the preceding example, `LoanApplication` makes a call to the `FraudDetection` service. +This request is handled by a WireMock server configured with stubs that were generated by +Spring Cloud Contract Verifier. diff --git a/docs/src/main/asciidoc/howto.adoc b/docs/src/main/asciidoc/howto.adoc index 9094dfa857..059a55a9c7 100644 --- a/docs/src/main/asciidoc/howto.adoc +++ b/docs/src/main/asciidoc/howto.adoc @@ -2,47 +2,50 @@ = "`How-to`" Guides include::_attributes.adoc[] -This section provides answers to some common '`how do I do that...`' questions +This section provides answers to some common "`how do I do that...`" questions that often arise when using {project-full-name}. Its coverage is not exhaustive, but it does cover quite a lot. If you have a specific problem that we do not cover here, you might want to check out https://stackoverflow.com/tags/{project-name}[stackoverflow.com] to see if someone has -already provided an answer. This is also a great place to ask new questions (please use +already provided an answer. Stack Overflow is also a great place to ask new questions (please use the `{project-name}` tag). -We are also more than happy to extend this section. If you want to add a '`how-to`', +We are also more than happy to extend this section. If you want to add a "`how-to`", send us a {github-code}[pull request]. [[why-spring-cloud-contract]] -== Why use Spring Cloud Contract and not X ? +== Why use Spring Cloud Contract? -Spring Cloud Contract works great in a polyglot environment. This project has a lot of really interesting features but especially quite a few of them definitely make -Spring Cloud Contract Verifier stand out on the "market" of Consumer Driven Contract (CDC) tooling. Out of many the most interesting are: +Spring Cloud Contract works great in a polyglot environment. This project has a lot of +really interesting features. Quite a few of these features definitely make +Spring Cloud Contract Verifier stand out on the market of Consumer Driven Contract +(CDC) tooling. The most interesting features include the following: -- Possibility to do CDC with messaging -- Clear and easy to use, statically typed DSL -- Possibility to copy paste your current JSON file to the contract and only edit its elements -- Automatic generation of tests from the defined Contract -- Stub Runner functionality - the stubs are automatically downloaded at runtime from Nexus / Artifactory -- Spring Cloud integration - no discovery service is needed for integration tests -- Spring Cloud Contract integrates with Pact out of the box and provides easy hooks to extend its functionality -- Via Docker adds support for any language & framework used +- Ability to do CDC with messaging. +- Clear and easy to use, statically typed DSL. +- Ability to copy-paste your current JSON file to the contract and only edit its elements. +- Automatic generation of tests from the defined Contract. +- Stub Runner functionality: The stubs are automatically downloaded at runtime from Nexus/Artifactory. +- Spring Cloud integration: No discovery service is needed for integration tests. +- Spring Cloud Contract integrates with Pact and provides easy hooks to extend its functionality. +- Ability to add support for any language & framework through Docker. [[how-to-not-write-contracts-in-groovy]] -== How can I write contracts in a language different than Groovy? +== How Can I Write Contracts in a Language Other than Groovy? -No problem. You can write a contract in YAML! Check <> for more information. +You can write a contract in YAML. See <> for more information. We are working on allowing more ways of describing the contracts. You can check the {github-issues}[github-issues] for more information. [[how-to-provide-dynamic-values]] -== How can I provide dynamic values for a contract? +== How Can I Provide Dynamic Values to a Contract? -One of the biggest challenges related to stubs is their reusability. Only if they can be vastly used, will they serve their purpose. -What typically makes that difficult are the hard-coded values of request / response elements. For example dates or ids. -Imagine the following JSON request +One of the biggest challenges related to stubs is their reusability. Only if they can be widely used can they serve their purpose. +The hard-coded values (such as dates and IDs) of request and response elements generally make that difficult. +Consider the following JSON request: +==== [source,json,indent=0] ---- { @@ -51,9 +54,11 @@ Imagine the following JSON request "body" : "foo" } ---- +==== -and JSON response +Now consider the following JSON response: +==== [source,json,indent=0] ---- { @@ -62,16 +67,18 @@ and JSON response "body" : "bar" } ---- +==== -Imagine the pain required to set proper value of the `time` field (let's assume that this content is generated by the -database) by changing the clock in the system or providing stub implementations of data providers. The same is related -to the field called `id`. Will you create a stubbed implementation of UUID generator? Makes little sense... +Imagine the pain required to set the proper value of the `time` field (assume that this content is generated by the +database) by changing the clock in the system or by providing stub implementations of data providers. The same is related +to the field called `id`. You could create a stubbed implementation of UUID generator, but doing so makes little sense. -So as a consumer you would like to send a request that matches any form of a time or any UUID. That way your system -will work as usual - will generate data and you won't have to stub anything out. Let's assume that in case of the aforementioned -JSON the most important part is the `body` field. You can focus on that and provide matching for other fields. In other words -you would like the stub to work like this: +So, as a consumer, you want to send a request that matches any form of a time or any UUID. That way, your system +works as usual, generating data without you having to stub out anything. Assume that, in case of the aforementioned +JSON, the most important part is the `body` field. You can focus on that and provide matching for other fields. In other words, +you would like the stub to work as follows: +==== [source,json,indent=0] ---- { @@ -80,9 +87,12 @@ you would like the stub to work like this: "body" : "foo" } ---- +==== -As far as the response goes as a consumer you need a concrete value that you can operate on. So such a JSON is valid +As far as the response goes, as a consumer, you need a concrete value on which you can operate. +Consequently, the following JSON is valid: +==== [source,json,indent=0] ---- { @@ -91,12 +101,14 @@ As far as the response goes as a consumer you need a concrete value that you can "body" : "bar" } ---- +==== -As you could see in the previous sections we generate tests from contracts. So from the producer's side the situation looks -much different. We're parsing the provided contract and in the test we want to send a real request to your endpoints. -So for the case of a producer for the request we can't have any sort of matching. We need concrete values that the -producer's backend can work on. Such a JSON would be a valid one: +In the previous sections, we generated tests from contracts. So, from the producer's side, the situation looks +much different. We parse the provided contract, and, in the test, we want to send a real request to your endpoints. +So, for the case of a producer for the request, we cannot have any sort of matching. We need concrete values on which the +producer's backend can work. Consequently, the following JSON would be valid: +==== [source,json,indent=0] ---- { @@ -105,12 +117,14 @@ producer's backend can work on. Such a JSON would be a valid one: "body" : "foo" } ---- +==== -On the other hand from the point of view of the validity of the contract the response doesn't necessarily have to -contain concrete values of `time` or `id`. Let's say that you generate those on the producer side - again, you'd -have to do a lot of stubbing to ensure that you always return the same values. That's why from the producer's side -what you might want is the following response: +On the other hand, from the point of view of the validity of the contract, the response does not necessarily have to +contain concrete values for `time` or `id`. Suppose you generate those on the producer side. Again, you +have to do a lot of stubbing to ensure that you always return the same values. That is why, from the producer's side +you might want the following response: +==== [source,json,indent=0] ---- { @@ -119,109 +133,134 @@ what you might want is the following response: "body" : "bar" } ---- +==== -How can you then provide one time a matcher for the consumer and a concrete value for the producer and vice versa? -In Spring Cloud Contract we're allowing you to provide a *dynamic value*. That means that it can differ for both +How can you then provide a matcher for the consumer and a concrete value for the producer (and the opposite at some other time)? +Spring Cloud Contract lets you provide a dynamic value. That means that it can differ for both sides of the communication. You can read more about this in the <> section. -IMPORTANT: Please read the https://groovy-lang.org/json.html[Groovy docs related to JSON] to understand how to -properly structure the request / response bodies. +IMPORTANT: Read the https://groovy-lang.org/json.html[Groovy docs related to JSON] to understand how to +properly structure the request and response bodies. [[how-to-do-stubs-versioning]] -== How to do Stubs versioning? +== How to Do Stubs versioning? + +This section covers version of the stubs, which you can handle in a number of different ways: + +* <> +* <> +* <> [[how-to-api-versioning]] === API Versioning -Let's try to answer a question what versioning really means. If you're referring to the API version then there are -different approaches. +What does versioning really mean? If you refer to the API version, there are +different approaches: -- use Hypermedia, links and do not version your API by any means -- pass versions through headers / urls +- Use hypermedia links and do not version your API by any means +- Pass the version through headers and URLs -We will not try to answer a question which approach is better. Whatever suits your needs and allows you to generate -business value should be picked. +We do not try to answer the question of which approach is better. You should pick whatever +suits your needs and lets you generate business value. -Let's assume that you do version your API. In that case you should provide as many contracts as many versions you support. -You can create a subfolder for every version or append it to the contract name - whatever suits you more. +Assume that you do version your API. In that case, you should provide as many contracts with as many versions as you support. +You can create a subfolder for every version or append it to the contract name -- whatever suits you best. [[how-to-jar-versioning]] === JAR versioning -If by versioning you mean the version of the JAR that contains the stubs then there are essentially two main approaches. +If, by versioning, you mean the version of the JAR that contains the stubs, then there are essentially two main approaches. -Let's assume that you're doing Continuous Delivery / Deployment which means that you're generating a new version of -the jar each time you go through the pipeline and that jar can go to production at any time. For example your jar version -looks like this (it got built on the 20.10.2016 at 20:15:21) : +Assume that you do continuous delivery and deployment, which means that you generate a new version of +the jar each time you go through the pipeline and that the jar can go to production at any time. For example, your jar version +looks like the following (because it got built on the 20.10.2016 at 20:15:21) : +==== [source,groovy,indent=0] ---- 1.0.0.20161020-201521-RELEASE ---- +==== -In that case your generated stub jar will look like this. +In that case your, generated stub jar should look like the following: +==== [source,groovy,indent=0] ---- 1.0.0.20161020-201521-RELEASE-stubs.jar ---- +==== -In this case you should inside your `application.yml` or `@AutoConfigureStubRunner` when referencing stubs provide the - latest version of the stubs. You can do that by passing the `+` sign. Example +In this case, you should, inside your `application.yml` or `@AutoConfigureStubRunner` when +referencing stubs, provide the latest version of the stubs. You can do that by passing the +`+` sign. the following example shows how to do so: +==== [source,java,indent=0] ---- @AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"}) ---- +==== -If the versioning however is fixed (e.g. `1.0.4.RELEASE` or `2.1.1`) then you have to set the concrete value of the jar -version. Example for 2.1.1. +If the versioning, however, is fixed (for example, `1.0.4.RELEASE` or `2.1.1`), you have to set the concrete value of the jar +version. The following example shows how to do so for version 2.1.1: +==== [source,java,indent=0] ---- @AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:2.1.1:stubs:8080"}) ---- +==== [[how-to-dev-or-prod-stubs]] -=== Dev or prod stubs +=== Development or Production Stubs -You can manipulate the classifier to run the tests against current development version of the stubs of other services - or the ones that were deployed to production. If you alter your build to deploy the stubs with the `prod-stubs` classifier - once you reach production deployment then you can run tests in one case with dev stubs and one with prod stubs. +You can manipulate the classifier to run the tests against current the development version +of the stubs of other services or the ones that were deployed to production. If you alter +your build to deploy the stubs with the `prod-stubs` classifier once you reach production +deployment, you can run tests in one case with development stubs and one with production stubs. -Example of tests using development version of stubs +The following example works for tests that use the development version of the stubs: +==== [source,java,indent=0] ---- @AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"}) ---- +==== -Example of tests using production version of stubs +The following example works for tests that use the production version of stubs: +==== [source,java,indent=0] ---- @AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:prod-stubs:8080"}) ---- +==== -You can pass those values also via properties from your deployment pipeline. +You can also pass those values also in properties from your deployment pipeline. [[how-to-common-repo-with-contracts]] -== How can I use a common repo with contracts instead of storing them with the producer? +== How Can I use a Common Repository with Contracts Instead of Storing Them with the Producer? -Another way of storing contracts other than having them with the producer is keeping them in a common place. -It can be related to security issues where the consumers can't clone the producer's code. Also if you keep -contracts in a single place then you, as a producer, will know how many consumers you have and which -consumer you will break with your local changes. +Another way of storing contracts, rather than having them with the producer, is to keep +them in a common place. This situation can be related to security issues (where the +consumers cannot clone the producer's code). Also if you keep contracts in a single place, +then you, as a producer, know how many consumers you have and which consumer you may break +with your local changes. [[how-to-repo-structure]] -=== Repo structure +=== Repo Structure -Let's assume that we have a producer with coordinates `com.example:server` and 3 consumers: `client1`, -`client2`, `client3`. Then in the repository with common contracts you would have the following setup -(which you can checkout https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/contracts[here]): +Assume that we have a producer with coordinates of `com.example:server` and three +consumers: `client1`, `client2`, and `client3`. Then, in the repository with common +contracts, you could have the following setup (which you can check out +https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/contracts[here]). +The following listing shows such a structure: +==== [source,bash,indent=0] ---- ├── com @@ -241,41 +280,53 @@ Let's assume that we have a producer with coordinates `com.example:server` and 3 └── assembly └── contracts.xml ---- +==== -As you can see under the slash-delimited groupid `/` artifact id folder (`com/example/server`) you have -expectations of the 3 consumers (`client1`, `client2` and `client3`). Expectations are the standard Groovy DSL -contract files as described throughout this documentation. This repository has to produce a JAR file that maps -one to one to the contents of the repo. +As you can see under the slash-delimited `groupid/artifact id` folder (`com/example/server`) you have +expectations of the three consumers (`client1`, `client2`, and `client3`). Expectations are the standard Groovy DSL +contract files, as described throughout this documentation. This repository has to produce a JAR file that maps +one-to-one to the contents of the repository. -Example of a `pom.xml` inside the `server` folder. +The following example shows a `pom.xml` inside the `server` folder: +==== [source,xml,indent=0] ---- include::{introduction_url}/samples/standalone/contracts/com/example/server/pom.xml[indent=0] ---- +==== -As you can see there are no dependencies other than the Spring Cloud Contract Maven Plugin. -Those poms are necessary for the consumer side to run `mvn clean install -DskipTests` to locally install - stubs of the producer project. +There are no dependencies other than the Spring Cloud Contract Maven Plugin. +Those pom files are necessary for the consumer side to run `mvn clean install -DskipTests` to locally install +the stubs of the producer project. -The `pom.xml` in the root folder can look like this: +The `pom.xml` in the root folder can look like the following: +==== [source,xml,indent=0] ---- include::{introduction_url}/samples/standalone/contracts/pom.xml[indent=0] ---- +==== -It's using the assembly plugin in order to build the JAR with all the contracts. Example of such setup is here: +It uses the assembly plugin to build the JAR with all the contracts. The following example +shows such a setup: +==== [source,xml,indent=0] ---- include::{introduction_url}/samples/standalone/contracts/src/assembly/contracts.xml[indent=0] ---- +==== [[how-to-workflow]] === Workflow -The workflow assumes that Spring Cloud Contract is setup both on the consumer and the producer side. There is also the proper plugin setup in the common repo with contracts. The CI jobs are set for common repo to build an artifact of all contracts and upload it to Nexus / Artifactory. +The workflow assumes that Spring Cloud Contract is set up both on the consumer and on the +producer side. There is also the proper plugin setup in the common repository with +contracts. The CI jobs are set for a common repository to build an artifact of all +contracts and upload it to Nexus/Artifactory. The following image shows the UML for this +workflow: [plantuml, how-to-common-repo, png] ---- @@ -314,46 +365,53 @@ The workflow assumes that Spring Cloud Contract is setup both on the consumer an [[how-to-workflow-consumer]] === Consumer -When the *consumer* wants to work on the contracts offline, instead of cloning the producer code, the -consumer team clones the common repository, goes to the required producer's folder (e.g. `com/example/server`) -and runs `mvn clean install -DskipTests` to install locally the stubs converted from the contracts. +When the consumer wants to work on the contracts offline, instead of cloning the producer +code, the consumer team clones the common repository, goes to the required producer's +folder (for example, `com/example/server`) and runs `mvn clean install -DskipTests` to +locally install the stubs converted from the contracts. TIP: You need to have https://maven.apache.org/download.cgi[Maven installed locally] [[how-to-workflow-producer]] === Producer -As a *producer* it's enough to alter the Spring Cloud Contract Verifier to provide the URL and the dependency -of the JAR containing the contracts: +As a producer, you can to alter the Spring Cloud Contract Verifier to provide the URL and +the dependency of the JAR that contains the contracts, as follows: +==== [source,xml,indent=0] ---- include::{introduction_url}/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/test/projects/basic-remote-contracts/pom-with-repo.xml[tags=remote_config,indent=0] ---- +==== -With this setup the JAR with groupid `com.example.standalone` and artifactid `contracts` will be downloaded -from `https://link/to/your/nexus/or/artifactory/or/sth`. It will be then unpacked in a local temporary folder -and contracts present under the `com/example/server` will be picked as the ones used to generate the -tests and the stubs. Due to this convention the producer team will know which consumer teams will be broken -when some incompatible changes are done. +With this setup, the JAR with a groupid of `com.example.standalone` and artifactid +`contracts` is downloaded from `https://link/to/your/nexus/or/artifactory/or/sth`. It is +then unpacked in a local temporary folder, and the contracts present in +`com/example/server` are picked as the ones used to generate the tests and the stubs. Due +to this convention, the producer team can know which consumer teams will be broken when +some incompatible changes are made. The rest of the flow looks the same. [[how-to-define-messaging-contracts-per-topic]] -=== How can I define messaging contracts per topic not per producer? +=== How Can I Define Messaging Contracts per Topic Rather than per Producer? -To avoid messaging contracts duplication in the common repo, when few producers writing messages to one topic, -we could create the structure when the rest contracts would be placed in a folder per producer and messaging -contracts in the folder per topic. +To avoid messaging contracts duplication in the common repository, when a few producers write messages to one topic, +we could create a structure in which the REST contracts are placed in a folder per producer and messaging +contracts are placed in the folder per topic. [[how-to-define-messaging-contracts-per-topic-maven]] -==== For Maven Project - -To make it possible to work on the producer side we should specify an inclusion pattern for -filtering common repository jar by messaging topics we are interested in. ```includedFiles``` property of ```Maven Spring Cloud Contract plugin``` -allows us to do that. Also ```contractsPath``` need to be specified since the default path would be the common repository ```groupid/artifactid```. +==== For Maven Projects +To make it possible to work on the producer side, we should specify an inclusion pattern for +filtering common repository jar files by messaging topics we are interested in. The +`includedFiles` property of the Maven Spring Cloud Contract plugin +lets us do so. Also, `contractsPath` need to be specified, since the default path would be +the common repository `groupid/artifactid`. The following example shows a Maven +plugin for Spring Cloud Contract: +==== [source,xml,indent=0] ---- @@ -387,12 +445,19 @@ allows us to do that. Also ```contractsPath``` need to be specified since the de ---- +==== + +NOTE: Many of the values in the preceding Maven plugin can be changed. We included it for +illustration purposes rather than trying to provide a "`typical`" example. [[how-to-define-messaging-contracts-per-topic-gradle]] -==== For Gradle Project +==== For Gradle Projects -- Add a custom configuration for the common-repo dependency: +To work with a Gradle project: +. Add a custom configuration for the common repository dependency, as follows: ++ +==== [source,groovy,indent=0] ---- ext { @@ -407,9 +472,11 @@ configurations { } } ---- +==== -- Add the common-repo dependency to your classpath: - +. Add the common repository dependency to your classpath, as follows: ++ +==== [source,groovy,indent=0] ---- dependencies { @@ -417,9 +484,11 @@ dependencies { testCompile "${conractsGroupId}:${contractsArtifactId}:${contractsVersion}" } ---- +==== -- Download the dependency to an appropriate folder: - +. Download the dependency to an appropriate folder, as follows: ++ +==== [source,groovy,indent=0] ---- task getContracts(type: Copy) { @@ -427,9 +496,11 @@ task getContracts(type: Copy) { into new File(project.buildDir, "downloadedContracts") } ---- +==== -- Unzip JAR: - +. Unzip the JAR, as follows: ++ +==== [source,groovy,indent=0] ---- task unzipContracts(type: Copy) { @@ -440,9 +511,11 @@ task unzipContracts(type: Copy) { into outputDir } ---- +==== -- Cleanup unused contracts: - +. Cleanup unused contracts, as follows: ++ +==== [source,groovy,indent=0] ---- task deleteUnwantedContracts(type: Delete) { @@ -454,36 +527,43 @@ task deleteUnwantedContracts(type: Delete) { "**/${second-topic}/**"]) } ---- +==== -- Create task dependencies: - +. Create task dependencies, as follows: ++ +==== [source,groovy,indent=0] ---- unzipContracts.dependsOn("getContracts") deleteUnwantedContracts.dependsOn("unzipContracts") build.dependsOn("deleteUnwantedContracts") ---- +==== -- Configure plugin by specifying the directory containing contracts using `contractsDslDir` property - +. Configure the plugin by specifying the directory that contains the contracts, by setting +the `contractsDslDir` property, as follows: ++ +==== [source,groovy,indent=0] ---- contracts { contractsDslDir = new File("${buildDir}/unpackedContracts") } ---- +==== [[how-to-use-git-as-storage]] -== How can I use Git as the storage for contracts and stubs? +== How Can I Use Git as the Storage for Contracts and Stubs? -In the polyglot world, there are languages that don't use binary storages like -Artifactory or Nexus. Starting from Spring Cloud Contract version 2.0.0 we provide -mechanisms to store contracts and stubs in a SCM repository. Currently the +In the polyglot world, there are languages that do not use binary storages, as +Artifactory or Nexus do. Starting from Spring Cloud Contract version 2.0.0, we provide +mechanisms to store contracts and stubs in a SCM (Source Control Management) repository. Currently, the only supported SCM is Git. -The repository would have to the following setup -(which you can checkout https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/contracts_git/[here]): +The repository would have to have the following setup +(which you can checkout from https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/contracts_git/[here]): +==== [source,indent=0] ---- . @@ -505,59 +585,71 @@ The repository would have to the following setup ├── shouldGrantABeerIfOldEnough.json └── shouldRejectABeerIfTooYoung.json ---- +==== -Under `META-INF` folder: +Under the `META-INF` folder: -* we group applications via `groupId` (e.g. `com.example`) -* then each application is represented via the `artifactId` (e.g. `beer-api-producer-git`) -* next, the version of the application (e.g. `0.0.1-SNAPSHOT`). Starting from Spring Cloud Contract version `2.1.0`, you can specify the versions as follows (assuming that your versions follow the semantic versioning) -** `+` or `latest` - to find the latest version of your stubs (assuming that the snapshots are always the latest artifact for a given revision number). That means: -*** if you have a version `1.0.0.RELEASE`, `2.0.0.BUILD-SNAPSHOT` and `2.0.0.RELEASE` we will assume that the latest is `2.0.0.BUILD-SNAPSHOT` -*** if you have a version `1.0.0.RELEASE` and `2.0.0.RELEASE` we will assume that the latest is `2.0.0.RELEASE` -*** if you have a version called `latest` or `+` we will pick that folder -** `release` - to find the latest release version of your stubs. That means: -*** if you have a version `1.0.0.RELEASE`, `2.0.0.BUILD-SNAPSHOT` and `2.0.0.RELEASE` we will assume that the latest is `2.0.0.RELEASE` -*** if you have a version called `release` we will pick that folder -* finally, there are two folders: -** `contracts` - the good practice is to store the contracts required by each -consumer in the folder with the consumer name (e.g. `beer-api-consumer`). That way you +* We group applications by `groupId` (such as `com.example`). +* Each application is represented by its `artifactId` (for example, `beer-api-producer-git`). +* Next, each application is organized by its version (such as `0.0.1-SNAPSHOT`). Starting +from Spring Cloud Contract version `2.1.0`, you can specify the versions as follows +(assuming that your versions follow semantic versioning): +** `+` or `latest`: To find the latest version of your stubs (assuming that the snapshots +are always the latest artifact for a given revision number). That means: +*** If you have `1.0.0.RELEASE`, `2.0.0.BUILD-SNAPSHOT`, and `2.0.0.RELEASE`, we assume +that the latest is `2.0.0.BUILD-SNAPSHOT`. +*** If you have `1.0.0.RELEASE` and `2.0.0.RELEASE`, we assume that the latest is `2.0.0.RELEASE`. +*** If you have a version called `latest` or `+`, we will pick that folder. +** `release`: To find the latest release version of your stubs. That means: +*** If you have `1.0.0.RELEASE`, `2.0.0.BUILD-SNAPSHOT`, and `2.0.0.RELEASE` we assume +that the latest is `2.0.0.RELEASE`. +*** If you have a version called `release`, we pick that folder. + +Finally, there are two folders: + +* `contracts`: The good practice is to store the contracts required by each +consumer in the folder with the consumer name (such as `beer-api-consumer`). That way, you can use the `stubs-per-consumer` feature. Further directory structure is arbitrary. -** `mappings` - in this folder the Maven / Gradle Spring Cloud Contract plugins will push -the stub server mappings. On the consumer side, Stub Runner will scan this folder -to start stub servers with stub definitions. The folder structure will be a copy +* `mappings`: The Maven or Gradle Spring Cloud Contract plugins push +the stub server mappings in this folder. On the consumer side, Stub Runner scans this folder +to start stub servers with stub definitions. The folder structure is a copy of the one created in the `contracts` subfolder. [[how-to-protocol-convention]] -=== Protocol convention +=== Protocol Convention -In order to control the type and location of the source of contracts (whether it's -a binary storage or an SCM repository), you can use the protocol in the URL of +To control the type and location of the source of contracts (whether +binary storage or an SCM repository), you can use the protocol in the URL of the repository. Spring Cloud Contract iterates over registered protocol resolvers -and tries to fetch the contracts (via a plugin) or stubs (via Stub Runner). +and tries to fetch the contracts (by using a plugin) or stubs (from Stub Runner). For the SCM functionality, currently, we support the Git repository. To use it, -in the property, where the repository URL needs to be placed you just have to prefix -the connection URL with `git://`. Here you can find a couple of examples: +in the property where the repository URL needs to be placed, you have to prefix +the connection URL with `git://`. The following listing shows some examples: +==== [source,indent=0] ---- git://file:///foo/bar git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git ---- +==== [[how-to-protocol-convention-producer]] === Producer -For the producer, to use the SCM approach, we can reuse the +For the producer, to use the SCM (Source Control Management) approach, we can reuse the same mechanism we use for external contracts. We route Spring Cloud Contract -to use the SCM implementation via the URL that starts with +to use the SCM implementation from the URL that starts with the `git://` protocol. IMPORTANT: You have to manually add the `pushStubsToScm` goal in Maven or execute (bind) the `pushStubsToScm` task in -Gradle. We don't push stubs to `origin` of your git -repository out of the box. +Gradle. We do not push stubs to the `origin` of your git +repository. + +The following listing includes the relevant parts both Maven and Gradle build files: ==== [source,xml,indent=0,role="primary"] @@ -630,19 +722,21 @@ publish.dependsOn("publishStubsToScm") With such a setup: -* Git project will be cloned to a temporary directory -* The SCM stub downloader will go to `META-INF/groupId/artifactId/version/contracts` folder -to find contracts. E.g. for `com.example:foo:1.0.0` the path would be -`META-INF/com.example/foo/1.0.0/contracts` -* Tests will be generated from the contracts -* Stubs will be created from the contracts -* Once the tests pass, the stubs will be committed in the cloned repository -* Finally, a push will be done to that repo's `origin` +* A git project is cloned to a temporary directory +* The SCM stub downloader goes to `META-INF/groupId/artifactId/version/contracts` folder +to find contracts. For example, for `com.example:foo:1.0.0`, the path would be +`META-INF/com.example/foo/1.0.0/contracts`. +* Tests are generated from the contracts. +* Stubs are created from the contracts. +* Once the tests pass, the stubs are committed in the cloned repository. +* Finally, a push is sent to that repo's `origin`. [[how-to-protocol-convention-producer-with-contracts-stored-locally]] -=== Producer with contracts stored locally +=== Producer with Contracts Stored Locally -Another option to use the SCM as the destination for stubs and contracts is to store the contracts locally, with the producer, and only push the contracts and the stubs to SCM. Below, you can find the setup required to achieve this using Maven and Gradle. +Another option to use the SCM as the destination for stubs and contracts is to store the +contracts locally, with the producer, and only push the contracts and the stubs to SCM. +The following listing shows the setup required to achieve this with Maven and Gradle: ==== [source,xml,indent=0,role="primary"] @@ -660,32 +754,33 @@ include::{samples_url}/producer_with_empty_git/build.gradle[tags=plugin,indent=0 With such a setup: -* Contracts from the default `src/test/resources/contracts` directory will be picked -* Tests will be generated from the contracts -* Stubs will be created from the contracts -* Once the tests pass -** Git project will be cloned to a temporary directory -** The stubs and contracts will be committed in the cloned repository -* Finally, a push will be done to that repo's `origin` +* Contracts from the default `src/test/resources/contracts` directory are picked. +* Tests are generated from the contracts. +* Stubs are created from the contracts. +* Once the tests pass: +** The git project is cloned to a temporary directory. +** The stubs and contracts are committed in the cloned repository. +* Finally, a push is done to that repository's `origin`. [[how-to-protocol-convention-contracts-producer-stubs-external]] -=== Keeping contracts with the producer and stubs in an external repository +=== Keeping Contracts with the Producer and Stubs in an External Repository -It is also possible to keep the contracts in the producer repository, but keep the stubs in an external git repo. -This is most useful when you want to use the base consumer-producer collaboration flow, but do not have a possibility to -use an artifact repository for storing the stubs. +You can also keep the contracts in the producer repository but keep the stubs in an external git repository. +This is most useful when you want to use the base consumer-producer collaboration flow but cannot +use an artifact repository to store the stubs. -In order to do that, use the usual producer setup, and then add the `pushStubsToScm` goal and set +To do so, use the usual producer setup and then add the `pushStubsToScm` goal and set `contractsRepositoryUrl` to the repository where you want to keep the stubs. [[how-to-protocol-convention-contracts-producer-stubs-external-consumer]] === Consumer -On the consumer side when passing the `repositoryRoot` parameter, +On the consumer side, when passing the `repositoryRoot` parameter, either from the `@AutoConfigureStubRunner` annotation, the -JUnit rule, JUnit 5 extension or properties, it's enough to pass the URL of the -SCM repository, prefixed with the protocol. For example +JUnit rule, JUnit 5 extension, or properties, you can pass the URL of the +SCM repository, prefixed with the `git://` protocol. The following example shows how to do so: +==== [source,java,indent=0] ---- @AutoConfigureStubRunner( @@ -694,71 +789,74 @@ SCM repository, prefixed with the protocol. For example ids="com.example:bookstore:0.0.1.RELEASE" ) ---- +==== With such a setup: -* Git project will be cloned to a temporary directory -* The SCM stub downloader will go to `META-INF/groupId/artifactId/version/` folder -to find stub definitions and contracts. E.g. for `com.example:foo:1.0.0` the path would be -`META-INF/com.example/foo/1.0.0/` -* Stub servers will be started and fed with mappings -* Messaging definitions will be read and used in the messaging tests +* The git project is cloned to a temporary directory. +* The SCM stub downloader goes to thje `META-INF/groupId/artifactId/version/` folder +to find stub definitions and contracts. For example, for `com.example:foo:1.0.0`, the path would be +`META-INF/com.example/foo/1.0.0/`. +* Stub servers are started and fed with mappings. +* Messaging definitions are read and used in the messaging tests. [[how-to-use-pact-broker]] -== How can I use the Pact Broker? +== How Can I Use the Pact Broker? -When using https://pact.io/[Pact] you can use the https://github.com/pact-foundation/pact_broker[Pact Broker] +When using https://pact.io/[Pact], you can use the https://github.com/pact-foundation/pact_broker[Pact Broker] to store and share Pact definitions. Starting from Spring Cloud Contract -2.0.0 one can fetch Pact files from the Pact Broker to generate +2.0.0, you can fetch Pact files from the Pact Broker to generate tests and stubs. -IMPORTANT: Pact follows the Consumer Contract convention. That means -that the Consumer creates the Pact definitions first, then +IMPORTANT: Pact follows the consumer contract convention. That means +that the consumer creates the Pact definitions first and then shares the files with the Producer. Those expectations are generated from the Consumer's code and can break the Producer if the expectations are not met. [[how-to-use-pact-broker-pact]] -=== How to work with Pact +=== How to Work with Pact -Spring Cloud Contract includes support for https://docs.pact.io/[Pact] representation of -contracts up until v4. Instead of using the DSL, you can use Pact files. In this section, we -present how to add Pact support for your project. Note however that not all functionality is supported. -Starting with v3 you can combine multiple matcher for the same element; +Spring Cloud Contract includes support for the https://docs.pact.io/[Pact] representation of +contracts up until version 4. Instead of using the DSL, you can use Pact files. In this section, we +show how to add Pact support for your project. Note, however, that not all functionality is supported. +Starting with version 3, you can combine multiple matchers for the same element; you can use matchers for the body, headers, request and path; and you can use value generators. -Spring Cloud Contract currently only supports multiple matchers that are combined using the AND rule logic. -Next to that the request and path matchers are skipped during the conversion. -When using a date, time or datetime value generator with a given format, -the given format will be skipped and the ISO format will be used. +Spring Cloud Contract currently only supports multiple matchers that are combined by using the `AND` rule logic. +Next to that, the request and path matchers are skipped during the conversion. +When using a date, time, or datetime value generator with a given format, +the given format is skipped and the ISO format is used. [[how-to-use-pact-broker-pact-converter]] === Pact Converter In order to properly support the Spring Cloud Contract way of doing messaging -with Pact you'll have to provide some additional meta data entries. Below you can find a list of such entries: +with Pact, you have to provide some additional meta data entries. -* to define the destination to which a message gets sent, you have to -set -** `metaData` entry in the Pact file -*** with key `sentTo` equal to the destination to which a message is to be sent. -*** E.g. `"metaData": { "sentTo": "activemq:output" }` +To define the destination to which a message gets sent, you have to +set a `metaData` entry in the Pact file with the `sentTo` key equal to the destination to + which a message is to be sent (for example, `"metaData": { "sentTo": "activemq:output" }`). [[how-to-use-pact-broker-pact-contract]] === Pact Contract -Spring Cloud Contract can read the Pact JSON definition out of the box. It's enough to place the file under `src/test/resources/contracts` folder. An example of such a Pact contract can look like this: +Spring Cloud Contract can read the Pact JSON definition. You can place the file in the +`src/test/resources/contracts` folder. The following example shows such a Pact contract: +==== [source,javascript,indent=0] ---- include::{standalone_pact_path}/pact-http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.json[indent=0] ---- +==== [[how-to-use-pact-broker-pact-for-producers]] === Pact for Producers On the producer side, you must add two additional dependencies to your plugin configuration. One is the Spring Cloud Contract Pact support, and the other represents -the current Pact version that you use. +the current Pact version that you use. The following listing shows how to do so for both +Maven and Gradle: ==== [source,xml,indent=0,subs="verbatim,attributes",role="primary"] @@ -774,7 +872,8 @@ include::{standalone_pact_path}/pact-http-server/build.gradle[tags=pact_dependen ---- ==== -When you execute the build of your application, a test and stub will be generated. +When you execute the build of your application, a test and stub is generated. The following +example shows a test and stub that came from this process: ==== [source,java,indent=0,subs="verbatim,attributes",role="primary"] @@ -839,7 +938,8 @@ When you execute the build of your application, a test and stub will be generate On the producer side, you must add two additional dependencies to your project dependencies. One is the Spring Cloud Contract Pact support, and the other represents the -current Pact version that you use. +current Pact version that you use. The following listing shows how to do so for both +Maven and Gradle: ==== [source,xml,indent=0,subs="verbatim,attributes",role="primary"] @@ -858,15 +958,15 @@ include::{standalone_pact_path}/pact-http-client/build.gradle[tags=pact_dependen [[pact-stub-downloader]] === Communicating with the Pact Broker -Whenever the `repositoryRoot` starts with a Pact protocol -(starts with `pact://`), the stub downloader will try +Whenever the `repositoryRoot` property starts with a Pact protocol +(starts with `pact://`), the stub downloader tries to fetch the Pact contract definitions from the Pact Broker. -Whatever is set after `pact://` will be parsed as the Pact Broker URL. +Whatever is set after `pact://` is parsed as the Pact Broker URL. -Either via environment variables, system properties, properties set -inside the plugin or contracts repository configuration you can -tweak the downloader's behaviour. Below you can find the list of -properties +By setting environment variables, system properties, or properties set +inside the plugin or contracts repository configuration, you can +tweak the downloader's behavior. The following table describes the +properties: .Pact Stub Downloader properties |==== @@ -878,7 +978,7 @@ properties * `STUBRUNNER_PROPERTIES_PACTBROKER_HOST` (env prop) |Host from URL passed to `repositoryRoot` -|What is the URL of Pact Broker +|The URL of the Pact Broker. | * `pactbroker.port` (plugin prop) @@ -887,7 +987,7 @@ properties * `STUBRUNNER_PROPERTIES_PACTBROKER_PORT` (env prop) |Port from URL passed to `repositoryRoot` -|What is the port of Pact Broker +|The port of Pact Broker. | * `pactbroker.protocol` (plugin prop) @@ -896,7 +996,7 @@ properties * `STUBRUNNER_PROPERTIES_PACTBROKER_PROTOCOL` (env prop) |Protocol from URL passed to `repositoryRoot` -|What is the protocol of Pact Broker +|The protocol of Pact Broker. | * `pactbroker.tags` (plugin prop) @@ -905,7 +1005,7 @@ properties * `STUBRUNNER_PROPERTIES_PACTBROKER_TAGS` (env prop) |Version of the stub, or `latest` if version is `+` -|What tags should be used to fetch the stub +|The tags that should be used to fetch the stub. | * `pactbroker.auth.scheme` (plugin prop) @@ -914,7 +1014,7 @@ properties * `STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_SCHEME` (env prop) |`Basic` -|What kind of authentication should be used to connect to the Pact Broker +|The kind of authentication that should be used to connect to the Pact Broker. | * `pactbroker.auth.username` (plugin prop) @@ -923,7 +1023,7 @@ properties * `STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_USERNAME` (env prop) |The username passed to `contractsRepositoryUsername` (maven) or `contractRepository.username` (gradle) -|Username used to connect to the Pact Broker +|The username to use when connecting to the Pact Broker. | * `pactbroker.auth.password` (plugin prop) @@ -932,7 +1032,7 @@ properties * `STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_PASSWORD` (env prop) |The password passed to `contractsRepositoryPassword` (maven) or `contractRepository.password` (gradle) -|Password used to connect to the Pact Broker +|The password to use when connecting to the Pact Broker. | * `pactbroker.provider-name-with-group-id` (plugin prop) @@ -941,24 +1041,26 @@ properties * `STUBRUNNER_PROPERTIES_PACTBROKER_PROVIDER_NAME_WITH_GROUP_ID` (env prop) |false -|When `true`, the provider name will be a combination of `groupId:artifactId`. If `false`, just `artifactId` is used +|When `true`, the provider name is a combination of `groupId:artifactId`. If `false`, only `artifactId` is used. |==== [[how-to-pact-consumer]] === Flow: Consumer Contract approach with Pact Broker | Consumer Side -The consumer uses Pact framework to generate Pact files. The -Pact files are sent to the Pact Broker. An example of such -setup can be found https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/consumer_pact[here]. +The consumer uses the Pact framework to generate Pact files. The +Pact files are sent to the Pact Broker. You can find an example of such a setup +https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/consumer_pact[here]. [[how-to-pact-producer]] -=== Flow: Consumer Contract approach with Pact Broker | Producer Side +=== Flow: Consumer Contract Approach with Pact Broker on the Producer Side -For the producer, to use the Pact files from the Pact Broker, we can reuse the +For the producer to use the Pact files from the Pact Broker, we can reuse the same mechanism we use for external contracts. We route Spring Cloud Contract -to use the Pact implementation via the URL that contains -the `pact://` protocol. It's enough to pass the URL to the -Pact Broker. An example of such setup can be found https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/producer_pact[here]. +to use the Pact implementation with the URL that contains +the `pact://` protocol. You can pass the URL to the +Pact Broker. You can find an example of such a setup +https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/producer_pact[here]. +The following listing shows the configuration details for both Maven and Gradle: ==== [source,xml,indent=0,role="primary"] @@ -1031,22 +1133,25 @@ contracts { With such a setup: -* Pact files will be downloaded from the Pact Broker -* Spring Cloud Contract will convert the Pact files into tests and stubs -* The JAR with the stubs gets automatically created as usual +* Pact files are downloaded from the Pact Broker. +* Spring Cloud Contract converts the Pact files into tests and stubs. +* The JAR with the stubs gets automatically created, as usual. [[how-to-pact-consumer-producer-contract]] -=== Flow: Producer Contract approach with Pact | Consumer Side +=== Flow: Producer Contract approach with Pact on the Consumer Side -In the scenario where you don't want to do Consumer Contract approach -(for every single consumer define the expectations) but you'd prefer -to do Producer Contracts (the producer provides the contracts and -publishes stubs), it's enough to use Spring Cloud Contract with -Stub Runner option. An example of such setup can be found https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/consumer_pact_stubrunner[here]. +In the scenario where you do not want to do the consumer contract approach +(for every single consumer, define the expectations) but you prefer +to do producer contracts (the producer provides the contracts and +publishes stubs), you can use Spring Cloud Contract with the +Stub Runner option. You can find an example of such a setup +https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/consumer_pact_stubrunner[here]. -First, remember to add Stub Runner and Spring Cloud Contract Pact module +Remember to add the Stub Runner and Spring Cloud Contract Pact modules as test dependencies. +The following listing shows the configuration details for both Maven and Gradle: + ==== [source,xml,indent=0,role="primary"] .maven @@ -1097,9 +1202,11 @@ dependencies { ---- ==== -Next, just pass the URL of the Pact Broker to `repositoryRoot`, prefixed -with `pact://` protocol. E.g. `pact://http://localhost:8085` +Next, you can pass the URL of the Pact Broker to `repositoryRoot`, prefixed +with `pact://` protocol (for example, `pact://http://localhost:8085`), as the following +example shows: +==== [source,java,indent=0] ---- @RunWith(SpringRunner.class) @@ -1113,63 +1220,80 @@ public class BeerControllerTest { //... } ---- +==== With such a setup: -* Pact files will be downloaded from the Pact Broker -* Spring Cloud Contract will convert the Pact files into stub definitions -* The stub servers will be started and fed with stubs +* Pact files are downloaded from the Pact Broker. +* Spring Cloud Contract converts the Pact files into stub definitions. +* The stub servers are started and fed with stubs. [[how-to-debug]] -== How can I debug the request/response being sent by the generated tests client? +== How Can I Debug the Request/Response Being Sent by the Generated Tests Client? -The generated tests all boil down to RestAssured in some form or fashion which relies on https://hc.apache.org/httpcomponents-client-ga/[Apache HttpClient]. HttpClient has a facility called https://hc.apache.org/httpcomponents-client-ga/logging.html#Wire_Logging[wire logging] which logs the entire request and response to HttpClient. Spring Boot has a logging https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html[common application property] for doing this sort of thing, just add this to your application properties +The generated tests all boil down to RestAssured in some form or fashion. RestAssured +relies on the https://hc.apache.org/httpcomponents-client-ga/[Apache HttpClient]. +HttpClient has a facility called +https://hc.apache.org/httpcomponents-client-ga/logging.html#Wire_Logging[wire logging], +which logs the entire request and response to HttpClient. Spring Boot has a logging +https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html[common application property] +for doing this sort of thing. To use it, add this to your application properties, as follows: + +==== [source,properties,indent=0] ---- logging.level.org.apache.http.wire=DEBUG ---- +==== [[how-to-debug-wiremock]] -== How can I debug the mapping/request/response being sent by WireMock? +== How Can I Debug the Mapping, Request, or Response Being Sent by WireMock? -Starting from version `1.2.0` we turn on WireMock logging to -info and the WireMock notifier to being verbose. Now you will -exactly know what request was received by WireMock server and which +Starting from version `1.2.0`, we turn on WireMock logging to +`info` and set the WireMock notifier to being verbose. Now you can +exactly know what request was received by the WireMock server and which matching response definition was picked. -To turn off this feature just bump WireMock logging to `ERROR` +To turn off this feature, set WireMock logging to `ERROR`, as follows: +==== [source,properties,indent=0] ---- logging.level.com.github.tomakehurst.wiremock=ERROR ---- +==== [[how-to-see-registered-stubs]] -== How can I see what got registered in the HTTP server stub? +== How Can I See What Got Registered in the HTTP Server Stub? -You can use the `mappingsOutputFolder` property on `@AutoConfigureStubRunner`, `StubRunnerRule` or -`StubRunnerExtension`to dump all mappings per artifact id. Also the port at which the given stub server -was started will be attached. +You can use the `mappingsOutputFolder` property on `@AutoConfigureStubRunner`, `StubRunnerRule`, or +`StubRunnerExtension`to dump all mappings per artifact ID. Also the port at which the given stub server +was started is attached. [[how-to-reference-text-from-file]] -== How can I reference text from file? +== How Can I Reference Text from File? -Yes! With version 1.2.0 we've added such a possibility. It's enough to call `file(...)` method in the -DSL and provide a path relative to where the contract lays. -If you're using YAML just use the `bodyFromFile` property. +In version 1.2.0, we added this ability. You can call a `file(...)` method in the +DSL and provide a path relative to where the contract lies. +If you use YAML, you can use the `bodyFromFile` property. [[how-to-generate-pact-from-scc]] -== How can I generate Pact / YAML / X files from Spring Cloud Contract Contracts? +== How Can I Generate Pact, YAML, or X files from Spring Cloud Contract Contracts? -Spring Cloud Contract comes with a `ToFileContractsTransformer` class that allows you to dump contracts as files for the given `ContractConverter`. It contains a `static void main` method, that allows you to execute the transformer as an executable. It takes the following arguments: +Spring Cloud Contract comes with a `ToFileContractsTransformer` class that lets you dump +contracts as files for the given `ContractConverter`. It contains a `static void main` +method that lets you execute the transformer as an executable. It takes the following +arguments: -- argument 1 : *FQN* - fully qualified name of the `ContractConverter` (e.g. the `PactContractConverter`) *REQUIRED* -- argument 2 : *path* - path where the dumped files should be stored *OPTIONAL* - defaults to `target/converted-contracts` -- argument 3 : *path* - path were the contracts should be searched for *OPTIONAL* - defaults to `src/test/resources/contracts` +- argument 1 : `FQN`: Fully qualified name of the `ContractConverter` (for example, `PactContractConverter`). *REQUIRED*. +- argument 2 : `path`: Path where the dumped files should be stored. *OPTIONAL* -- defaults to `target/converted-contracts`. +- argument 3 : `path`: Path were the contracts should be searched for. *OPTIONAL* -- defaults to `src/test/resources/contracts`. -After executing the transformer, the Spring Cloud Contract files will be processed and depending on the provided FQN of the `ContractTransformer`, the contracts will be transformed to the required format and dumped to the provided folder. +After executing the transformer, the Spring Cloud Contract files are processed and, +depending on the provided FQN of the `ContractTransformer`, the contracts are transformed +to the required format and dumped to the provided folder. -Below you can find an example for Pact integration: +The following example shows how to configure Pact integration for both Maven and Gradle: ==== [source,xml,indent=0,role="primary"] @@ -1221,13 +1345,14 @@ test.dependsOn("convertContracts") ==== [[how-to-work-with-transitivie]] -== How can I work with transitive dependencies? +== How Can I Work with Transitive Dependencies? The Spring Cloud Contract plugins add the tasks that create the stubs jar for you. One problem that arises is that, when reusing the stubs, you can mistakenly import all of that stub's dependencies. When building a Maven artifact, even though you have a couple -of different jars, all of them share one pom: +of different jars, all of them share one pom, as the following listing shows: +==== [source,bash,indent=0] ---- ├── producer-0.0.1.BUILD-20160903.075506-1-stubs.jar @@ -1240,6 +1365,7 @@ of different jars, all of them share one pom: ├── ... └── ... ---- +==== There are three possibilities of working with those dependencies so as not to have any issues with transitive dependencies: @@ -1249,30 +1375,30 @@ issues with transitive dependencies: * Exclude dependencies on the consumer side [[how-to-work-with-transitivie-optional]] -=== Mark all application dependencies as optional +=== How Can I Mark All Application Dependencies as Optional? If, in the `producer` application, you mark all of your dependencies as optional, when you include the `producer` stubs in another application (or when that dependency gets downloaded by Stub Runner) then, since all of the dependencies are -optional, they will not get downloaded. +optional, they do not get downloaded. [[how-to-work-with-transitivie-separate]] -=== Create a separate `artifactid` for the stubs +=== How can I Create a Separate `artifactid` for the Stubs? -If you create a separate `artifactid`, then you can set it up in whatever way you wish. +If you create a separate `artifactid`, you can set it up in whatever way you wish. For example, you might decide to have no dependencies at all. [[how-to-work-with-transitivie-exclude]] -=== Exclude dependencies on the consumer side +=== How can I Exclude Dependencies on the Consumer Side? As a consumer, if you add the stub dependency to your classpath, you can explicitly exclude the unwanted dependencies. [[contract-dsl-rest-docs]] -== Generating Spring REST Docs snippets from the contracts +== How can I Generate Spring REST Docs Snippets from the Contracts? -When you want to include the requests and responses of your API using Spring REST Docs, +When you want to include the requests and responses of your API by using Spring REST Docs, you only need to make some minor changes to your setup if you are using MockMvc and RestAssuredMockMvc. -Simply include the following dependencies if you haven't already. +To do so, include the following dependencies (if you have not already done so): ==== [source,xml,indent=0,subs="verbatim,attributes",role="primary"] @@ -1288,7 +1414,8 @@ include::{standalone_restdocs_path}/http-server/build.gradle[tags=dependencies,i ---- ==== -Next you need to make some changes to your base class. Below you can find examples for using `WebAppContext` and the standalone option when using RestAssured. +Next, you need to make some changes to your base class. The following examples use +`WebAppContext` and the standalone option with RestAssured: ==== [source,java,indent=0,subs="verbatim,attributes",role="primary"] @@ -1304,4 +1431,4 @@ include::{standalone_restdocs_path}/http-server/src/test/java/com/example/fraud/ ---- ==== -TIP: You don't need to specify the output directory for the generated snippets since version 1.2.0.RELEASE of Spring REST Docs. \ No newline at end of file +TIP: You need not specify the output directory for the generated snippets (since version 1.2.0.RELEASE of Spring REST Docs). diff --git a/docs/src/main/asciidoc/index.htmladoc b/docs/src/main/asciidoc/index.htmladoc index 4ee1bab1c8..21d7b4ffb7 100644 --- a/docs/src/main/asciidoc/index.htmladoc +++ b/docs/src/main/asciidoc/index.htmladoc @@ -9,8 +9,8 @@ The reference documentation consists of the following sections: [horizontal] <> :: Legal information. <> :: About the Documentation, Getting Help, First Steps, and more. -<> :: Introducing {project-full-name}, Developing Your First {project-full-name} based Application +<> :: Introducing {project-full-name}, Developing Your First {project-full-name}-based Application <> :: {project-full-name} usage examples and workflows -<> :: Contract DSL, Messaging, Spring Cloud Contract Stub Runner, Spring Cloud Contract WireMock -<> :: Maven Plugin, Gradle Plugin, Docker +<> :: Contract DSL, Messaging, Spring Cloud Contract Stub Runner, and Spring Cloud Contract WireMock. +<> :: Maven Plugin, Gradle Plugin, and Docker. <> :: Stubs versioning, Pact integration, Debugging, and more. diff --git a/docs/src/main/asciidoc/index.htmlpdfadoc b/docs/src/main/asciidoc/index.htmlpdfadoc index 46603b6857..7beef6b1ef 100644 --- a/docs/src/main/asciidoc/index.htmlpdfadoc +++ b/docs/src/main/asciidoc/index.htmlpdfadoc @@ -1,7 +1,6 @@ [[spring-cloud-contract-reference-documentation]] = Spring Cloud Contract Reference Documentation Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak, Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer, Jay Bryant -:docinfo: shared include::_attributes.adoc[] include::legal.adoc[leveloffset=+1] @@ -9,4 +8,4 @@ include::documentation-overview.adoc[leveloffset=+1] include::getting-started.adoc[leveloffset=+1] include::using.adoc[leveloffset=+1] include::project-features.adoc[leveloffset=+1] -include::howto.adoc[leveloffset=+1] \ No newline at end of file +include::howto.adoc[leveloffset=+1] diff --git a/docs/src/main/asciidoc/maven-project.adoc b/docs/src/main/asciidoc/maven-project.adoc index ffc5e36735..dce7ec1c6e 100644 --- a/docs/src/main/asciidoc/maven-project.adoc +++ b/docs/src/main/asciidoc/maven-project.adoc @@ -18,32 +18,37 @@ following sections: * <> [[maven-add-plugin]] -== Add maven plugin +== Adding the Maven Plugin -Add the Spring Cloud Contract BOM in a fashion similar to this: +Add the Spring Cloud Contract BOM in a fashion similar to the following: +==== [source,xml,indent=0] ---- include::{standalone_samples_path}/http-server/pom.xml[tags=contract_bom,indent=0] ---- +==== -Next, add the `Spring Cloud Contract Verifier` Maven plugin: +Next, add the `Spring Cloud Contract Verifier` Maven plugin, as follows: +==== [source,xml,indent=0] ---- include::{standalone_samples_path}/http-server/pom.xml[tags=contract_maven_plugin,indent=0] ---- +==== You can read more in the spring-cloud-contract-maven-plugin/index.html[Spring -Cloud Contract Maven Plugin Documentation. +Cloud Contract Maven Plugin Documentation]. [[maven-rest-assured]] == Maven and Rest Assured 2.0 By default, Rest Assured 3.x is added to the classpath. However, you can use Rest -Assured 2.x by adding it to the plugins classpath, as shown here: +Assured 2.x by adding it to the plugins classpath, as follows: +==== [source,groovy,indent=0] ---- @@ -92,39 +97,44 @@ Assured 2.x by adding it to the plugins classpath, as shown here: ---- +==== -That way, the plugin automatically sees that Rest Assured 3.x is present on the classpath +That way, the plugin automatically sees that Rest Assured 2.x is present on the classpath and modifies the imports accordingly. [[maven-snapshot-versions]] -== Snapshot versions for Maven +== Using Snapshot and Milestone Versions for Maven -For Snapshot and Milestone versions, you have to add the following section to your -`pom.xml`, as shown here: +To use Snapshot and Milestone versions, you have to add the following section to your +`pom.xml`: +==== [source,xml,indent=0] ---- include::{standalone_samples_path}/http-server/pom.xml[tags=repos,indent=0] ---- +==== [[maven-add-stubs]] -== Add stubs +== Adding stubs -By default, Spring Cloud Contract Verifier is looking for stubs in the +By default, Spring Cloud Contract Verifier looks for stubs in the `src/test/resources/contracts` directory. The directory containing stub definitions is treated as a class name, and each stub definition is treated as a single test. We assume -that it contains at least one directory to be used as test class name. If there is more -than one level of nested directories, all except the last one is used as package name. -For example, with following structure: +that it contains at least one directory to be used as the test class name. If there is more +than one level of nested directories, all except the last one is used as the package name. +Consider the following structure: +==== [source,groovy,indent=0] ---- src/test/resources/contracts/myservice/shouldCreateUser.groovy src/test/resources/contracts/myservice/shouldReturnUser.groovy ---- +==== -Spring Cloud Contract Verifier creates a test class named `defaultBasePackage.MyService` -with two methods +Given that structure, Spring Cloud Contract Verifier creates a test class named +`defaultBasePackage.MyService` with two methods: * `shouldCreateUser()` * `shouldReturnUser()` @@ -132,16 +142,17 @@ with two methods [[maven-run-plugin]] == Run plugin -The plugin goal `generateTests` is assigned to be invoked in the phase called +The `generateTests` plugin goal is assigned to be invoked in the phase called `generate-test-sources`. If you want it to be part of your build process, you need not do -anything. If you just want to generate tests, invoke the `generateTests` goal. +anything. If you want only to generate tests, invoke the `generateTests` goal. [[maven-configure-plugin]] == Configure plugin -To change the default configuration, just add a `configuration` section to the plugin -definition or the `execution` definition, as shown here: +To change the default configuration, you can add a `configuration` section to the plugin +definition or the `execution` definition, as follows: +==== [source,xml,indent=0] ---- @@ -162,78 +173,80 @@ definition or the `execution` definition, as shown here: ---- +==== [[maven-configuration-options]] == Configuration Options -* *testMode*: Defines the mode for acceptance tests. By default, the mode is MockMvc, -which is based on Spring's MockMvc. It can also be changed to *WebTestClient*, *JaxRsClient* or to -*Explicit* for real HTTP calls. -* *basePackageForTests*: Specifies the base package for all generated tests. If not set, -the value is picked from `baseClassForTests`'s package and from `packageWithBaseClasses`. -If neither of these values are set, then the value is set to +* `testMode`: Defines the mode for acceptance tests. By default, the mode is `MockMvc`, +which is based on Spring's MockMvc. You can also change it to `WebTestClient`, `JaxRsClient`, or +`Explicit` (for real HTTP calls). +* `basePackageForTests`: Specifies the base package for all generated tests. If not set, +the value is picked from the package of `baseClassForTests` and from `packageWithBaseClasses`. +If neither of these values are set, the value is set to `org.springframework.cloud.contract.verifier.tests`. -* *ruleClassForTests*: Specifies a rule that should be added to the generated test +* `ruleClassForTests`: Specifies a rule that should be added to the generated test classes. -* *baseClassForTests*: Creates a base class for all generated tests. By default, if you +* `baseClassForTests`: Creates a base class for all generated tests. By default, if you use Spock classes, the class is `spock.lang.Specification`. -* *contractsDirectory*: Specifies a directory containing contracts written with the -GroovyDSL. The default directory is `/src/test/resources/contracts`. -* *generatedTestSourcesDir*: Specifies the test source directory where tests generated -from the Groovy DSL should be placed. By default its value is +* contractsDirectory: Specifies a directory that contains contracts written with the +Groovyn DSL. The default directory is `/src/test/resources/contracts`. +* `generatedTestSourcesDir`: Specifies the test source directory where tests generated +from the Groovy DSL should be placed. By default, its value is `$buildDir/generated-test-sources/contracts`. -* *generatedTestResourcesDir*: Specifies the test resource directory where resources used by the tests generated -* *testFramework*: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (`TestFramework.JUNIT`) and -JUnit 5 are supported with JUnit 4 being the default framework. -* *packageWithBaseClasses*: Defines a package where all the base classes reside. This -setting takes precedence over *baseClassForTests*. The convention is such that, if you +* `generatedTestResourcesDir`: Specifies the test resource directory for resources used by the generated tests. +* `testFramework`: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (`TestFramework.JUNIT`), and +JUnit 5 are supported, with JUnit 4 being the default framework. +* `packageWithBaseClasses`: Defines a package where all the base classes reside. This +setting takes precedence over `baseClassForTests`. The convention is such that, if you have a contract under (for example) `src/test/resources/contract/foo/bar/baz/` and set -the value of the `packageWithBaseClasses` property to `com.example.base`, then Spring +the value of the `packageWithBaseClasses` property to `com.example.base`, Spring Cloud Contract Verifier assumes that there is a `BarBazBase` class under the `com.example.base` package. In other words, the system takes the last two parts of the -package, if they exist, and forms a class with a `Base` suffix. -* *baseClassMappings*: Specifies a list of base class mappings that provide -`contractPackageRegex`, which is checked against the package where the contract is -located, and `baseClassFQN`, which maps to the fully qualified name of the base class for -the matched contract. For example, if you have a contract under -`src/test/resources/contract/foo/bar/baz/` and map the property -`.* -> com.example.base.BaseClass`, then the test class generated from these contracts +package, if they exist, and forms a class with `Base` as a suffix. +* `baseClassMappings`: Specifies a list of base class mappings that provide +`contractPackageRegex` (which is checked against the package where the contract is +located) and `baseClassFQN`( which maps to the fully qualified name of the base class for +the matched contract). For example, if you have a contract under +`src/test/resources/contract/foo/bar/baz/` and map the +`.* -> com.example.base.BaseClass` property, the test class generated from these contracts extends `com.example.base.BaseClass`. This setting takes precedence over -*packageWithBaseClasses* and *baseClassForTests*. -* *contractsProperties*: a map containing properties to be passed to Spring Cloud Contract -components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders. +`packageWithBaseClasses` and `baseClassForTests`. +* `contractsProperties`: A map that contains properties to be passed to Spring Cloud Contract +components. Those properties might be used by (for example) built-in or custom Stub Downloaders. If you want to download your contract definitions from a Maven repository, you can use the following options: -* *contractDependency*: The contract dependency that contains all the packaged contracts. -* *contractsPath*: The path to the concrete contracts in the JAR with packaged contracts. +* `contractDependency`: The contract dependency that contains all the packaged contracts. +* `contractsPath`: The path to the concrete contracts in the JAR with packaged contracts. Defaults to `groupid/artifactid` where `gropuid` is slash separated. -* *contractsMode*: Picks the mode in which stubs will be found and registered -* *deleteStubsAfterTest*: If set to `false` will not remove any downloaded -contracts from temporary directories -* *contractsRepositoryUrl*: URL to a repo with the artifacts that have contracts. If it is not provided, +* `contractsMode`: Picks the mode in which stubs are found and registered. +* `deleteStubsAfterTest`: If set to `false` will not remove any downloaded +contracts from temporary directories. +* `contractsRepositoryUrl`: URL to a repository with the artifacts that have contracts. If it is not provided, use the current Maven ones. -* *contractsRepositoryUsername*: The user name to be used to connect to the repo with contracts. -* *contractsRepositoryPassword*: The password to be used to connect to the repo with contracts. -* *contractsRepositoryProxyHost*: The proxy host to be used to connect to the repo with contracts. -* *contractsRepositoryProxyPort*: The proxy port to be used to connect to the repo with contracts. +* `contractsRepositoryUsername`: The user name to be used to connect to the repo with contracts. +* `contractsRepositoryPassword`: The password to be used to connect to the repo with contracts. +* `contractsRepositoryProxyHost`: The proxy host to be used to connect to the repo with contracts. +* `contractsRepositoryProxyPort`: The proxy port to be used to connect to the repo with contracts. We cache only non-snapshot, explicitly provided versions (for example -`+` or `1.0.0.BUILD-SNAPSHOT` won't get cached). By default, this feature is turned on. +`+` or `1.0.0.BUILD-SNAPSHOT` do not get cached). By default, this feature is turned on. -Below you can find a list of experimental features you can turn on via the plugin: +The following list describes experimental features that you can turn on in the plugin: -* *convertToYaml*: converts all DSLs to the declarative, YAML format. This can be extremely useful when you're using external libraries in your Groovy DSLs. By turning this feature on (by setting it to `true`) you will not need to add the library dependency on the consumer side. -* *assertJsonSize*: You can check the size of JSON arrays in the generated tests. This feature is disabled by default. +* `convertToYaml`: Converts all DSLs to the declarative YAML format. This can be extremely useful when you use external libraries in your Groovy DSLs. By turning this feature on (by setting it to `true`) you need not add the library dependency on the consumer side. +* `assertJsonSize`: You can check the size of JSON arrays in the generated tests. This feature is disabled by default. [[maven-single-base]] == Single Base Class for All Tests -When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base +When using Spring Cloud Contract Verifier in the default (`MockMvc`), you need to create a base specification for all generated acceptance tests. In this class, you need to point to an -endpoint, which should be verified. +endpoint, which should be verified. The following example shows how to do so: +==== [source,groovy,indent=0] ---- package org.mycompany.tests @@ -248,9 +261,11 @@ class MvcSpec extends Specification { } } ---- +==== -You can also setup the whole context if necessary. +You can also setup the whole context if necessary, as the following example shows: +==== [source,java,indent=0] ---- import io.restassured.module.mockmvc.RestAssuredMockMvc; @@ -274,10 +289,13 @@ public abstract class BaseTestClass { } } ---- +==== -If you use `EXPLICIT` mode, you can use a base class to initialize the whole tested app -similarly, as you might find in regular integration tests. +If you use `EXPLICIT` mode, you can use a base class to initialize the whole tested app, +similar to what you might do in regular integration tests. The following example shows +how to do so: +==== [source,java,indent=0] ---- import io.restassured.RestAssured; @@ -302,45 +320,50 @@ public abstract class BaseTestClass { } } ---- +==== If you use the `JAXRSCLIENT` mode, this base class should also contain a `protected WebTarget webTarget` field. Right -now, the only option to test the JAX-RS API is to start a web server. +now, the only way to test the JAX-RS API is to start a web server. [[maven-different-base]] -== Different base classes for contracts +== Using Different Base Classes for Contracts If your base classes differ between contracts, you can tell the Spring Cloud Contract plugin which class should get extended by the autogenerated tests. You have two options: -* Follow a convention by providing the `packageWithBaseClasses` -* provide explicit mapping via `baseClassMappings` +* Follow a convention by providing a value for `packageWithBaseClasses` +* Provide explicit mapping with `baseClassMappings` -*By Convention* +=== By Convention The convention is such that if you have a contract under (for example) `src/test/resources/contract/foo/bar/baz/` and set the value of the `packageWithBaseClasses` property to `com.example.base`, then Spring Cloud Contract Verifier assumes that there is a `BarBazBase` class under the `com.example.base` package. In other words, the system takes the last two parts of the package, if they exist, and -forms a class with a `Base` suffix. This rule takes precedence over *baseClassForTests*. -Here is an example of how it works in the `contracts` closure: +forms a class with a `Base` suffix. This rule takes precedence over `baseClassForTests`. +The following example shows how it works in the `contracts` closure: +==== [source,xml,indent=0] ---- include::{plugins_path}/spring-cloud-contract-maven-plugin/src/test/projects/basic-generated-baseclass/pom.xml[tags=convention,indent=0] ---- +==== -*By Mapping* +=== By Mapping -You can manually map a regular expression of the contract's package to fully qualified +You can manually map a regular expression of the contract's package to the fully qualified name of the base class for the matched contract. You have to provide a list called -`baseClassMappings` that consists `baseClassMapping` objects that takes a +`baseClassMappings` that consists of `baseClassMapping` objects that each take a `contractPackageRegex` to `baseClassFQN` mapping. Consider the following example: +==== [source,xml,indent=0] ---- include::{plugins_path}/spring-cloud-contract-maven-plugin/src/test/projects/basic-baseclass-from-mappings/pom.xml[tags=mapping,indent=0] ---- +==== Assume that you have contracts under these two locations: * `src/test/resources/contract/com/` @@ -352,14 +375,15 @@ generated from `src/test/resources/contract/com/` contracts extend the `com.example.ComBase`, whereas the rest of the tests extend `com.example.FooBase`. [[maven-invoking-generated-tests]] -== Invoking generated tests +== Invoking Generated Tests The Spring Cloud Contract Maven Plugin generates verification code in a directory called `/generated-test-sources/contractVerifier` and attaches this directory to `testCompile` goal. -For Groovy Spock code, use the following: +For Groovy Spock code, you can use the following: +==== [source,xml,indent=0] ---- @@ -391,18 +415,20 @@ For Groovy Spock code, use the following: ---- +==== -To ensure that provider side is compliant with defined contracts, you need to invoke +To ensure that the provider side is compliant with defined contracts, you need to invoke `mvn generateTest test`. [[maven-pushing-stubs-to-scm]] -== Pushing stubs to SCM +== Pushing Stubs to SCM -If you're using the SCM repository to keep the contracts and +If you use the SCM (Source Control Management) repository to keep the contracts and stubs, you might want to automate the step of pushing stubs to -the repository. To do that, it's enough to add the `pushStubsToScm` -goal. Example: +the repository. To do that, you can add the `pushStubsToScm` +goal. The following example shows how to do so: +==== [source,xml,indent=0] ---- @@ -440,21 +466,23 @@ goal. Example: ---- +==== -Under <> you can find all possible -configuration options that you can pass either via -the `` map, a system property +Under <>, you can find all possible +configuration options that you can pass through +the `` map, a system property, or an environment variable. [[maven-sts]] == Maven Plugin and STS -If you see the following exception while using STS: +The following image shows an exception that you may see when you use STS: image::{github-raw}/docs/src/main/asciidoc/images/sts_exception.png[STS Exception] -When you click on the error marker you should see something like this: +When you click on the error marker you should see something like the following: +==== [source,bash] ---- plugin:1.1.0.M1:convert:default-convert:process-test-resources) org.apache.maven.plugin.PluginExecutionException: Execution default-convert of goal org.springframework.cloud:spring- @@ -465,9 +493,11 @@ When you click on the error marker you should see something like this: org.eclipse.m2e.core.internal.builder.plexusbuildapi.EclipseIncrementalBuildContext.hasDelta(EclipseIncrementalBuildContext.java:53) at org.sonatype.plexus.build.incremental.ThreadBuildContext.hasDelta(ThreadBuildContext.java:59) at ---- +==== In order to fix this issue, provide the following section in your `pom.xml`: +==== [source,xml] ---- @@ -503,27 +533,32 @@ In order to fix this issue, provide the following section in your `pom.xml`: ---- +==== == Maven Plugin with Spock Tests -You can select the http://spockframework.org/[Spock Framework] for creating and executing the auto-generated contract -verification tests with both Maven and Gradle plugin. However, whereas with Gradle its really straightforward, -in Maven you will require some additional setup in order to make the tests compile and execute properly. +You can select the http://spockframework.org/[Spock Framework] for creating and running the auto-generated contract +verification tests with both Maven and Gradle. However, whereas using Gradle is straightforward, +in Maven, you will require some additional setup in order to make the tests compile and execute properly. -First of all, you will have to use a plugin, such as https://github.com/groovy/GMavenPlus[GMavenPlus] plugin, -to add Groovy to your project. In GMavenPlus plugin, you will need to explicitly set test sources, including both the +First of all, you must use a plugin, such as the https://github.com/groovy/GMavenPlus[GMavenPlus] plugin, +to add Groovy to your project. In GMavenPlus plugin, you need to explicitly set test sources, including both the path where your base test classes are defined and the path were the generated contract tests are added. -Please refer to the example below: +The following example shows how to do so: +==== [source,xml,indent=0] ---- include::{samples_url}/producer_with_spock/pom.xml[tags=gmavenplus-setup,indent=0] ---- +==== -If you uphold to the Spock convention of ending the test class names with `Spec`, you will also need to adjust your Maven -Surefire plugin setup, like in the following example: +If you uphold the Spock convention of ending the test class names with `Spec`, you also need to adjust your Maven +Surefire plugin setup, as the following example shows: +==== [source,xml,indent=0] ---- include::{samples_url}/producer_with_spock/pom.xml[tags=spock-surefire-setup,indent=0] ----- \ No newline at end of file +---- +==== diff --git a/docs/src/main/asciidoc/project-features.adoc b/docs/src/main/asciidoc/project-features.adoc index 8666a0fff6..6b30c36718 100644 --- a/docs/src/main/asciidoc/project-features.adoc +++ b/docs/src/main/asciidoc/project-features.adoc @@ -19,9 +19,10 @@ include::_project-features-stubrunner.adoc[] include::_project-features-wiremock.adoc[] [[features-build-tools]] -== Build Tools integration +== Build Tools Integration -You can run test generation / stub execution in various ways. The most common ones are +You can run test generation and stub execution in various ways. The most common ones are +as follows: * link:maven-project.html[Maven] * link:gradle-project.html[Gradle] @@ -29,10 +30,11 @@ You can run test generation / stub execution in various ways. The most common on [[features-whats-next]] == What to Read Next + If you want to learn more about any of the classes discussed in this section, you can browse the -{github-code}[source code directly]. If you have specific questions, take a look at the +{github-code}[source code directly]. If you have specific questions, see the <> section. If you are comfortable with {project-full-name}'s core features, you can continue on and read about -_<>_. +<>. diff --git a/docs/src/main/asciidoc/sagan-boot.adoc b/docs/src/main/asciidoc/sagan-boot.adoc index b1f37c3c30..98fc275c51 100644 --- a/docs/src/main/asciidoc/sagan-boot.adoc +++ b/docs/src/main/asciidoc/sagan-boot.adoc @@ -1,8 +1,15 @@ -Add Sleuth to your classpath: +== Adding Sleuth to Your Classpath: -Maven +This section details how to add Sleuth to your class path for both Maven and Gradle -```xml +=== Maven + +To add Sleuth to your classpath with Maven, add the following elements +to your `pom.xml` file: + +==== +[source,xml] +---- @@ -20,11 +27,17 @@ Maven spring-cloud-starter-sleuth -``` +---- +==== -Gradle +=== Gradle -```groovy +To add Sleuth to your classpath with Gradle, add the following +to your `build.gradle` file: + +==== +[src,groovy] +---- buildscript { dependencies { classpath "io.spring.gradle:dependency-management-plugin:0.5.2.RELEASE" @@ -41,11 +54,15 @@ dependencyManagement { dependencies { compile 'org.springframework.cloud:spring-cloud-starter-sleuth' } -``` +---- +==== -As long as Spring Cloud Sleuth is on the classpath any Spring Boot application will generate trace data: +As long as Spring Cloud Sleuth is on the classpath, any Spring Boot application can +generate trace data. The following example shows how to do so: -```java +==== +[src,java] +---- @SpringBootApplication @RestController public class Application { @@ -63,12 +80,21 @@ public class Application { } } -``` +---- +==== -Run this app and then hit the home page. You will see traceId and spanId populated in the logs. If this app calls out to another one (e.g. with `RestTemplate`) it will send the trace data in headers and if the receiver is another Sleuth app you will see the trace continue there. +Now you can run this application and visit the home page. In the logs, you can see +`traceId` and `spanId` populated. If this application calls out to another one (for +example, with `RestTemplate`), it sends the trace data in headers, and, if the receiver is +another Sleuth application, you can see the trace continue there. -IMPORTANT: instead of logging the request in the handler explicitly, you could set `logging.level.org.springframework.web.servlet.DispatcherServlet=DEBUG` +IMPORTANT: instead of logging the request in the handler explicitly, you could set +`logging.level.org.springframework.web.servlet.DispatcherServlet=DEBUG` -IMPORTANT: If you use Zipkin, configure the probability of spans exported by setting (for `2.0.x`) `spring.sleuth.sampler.probability` or (up till `2.0.x`)`spring.sleuth.sampler.percentage` (default: 0.1, which is 10 percent). Otherwise, you might think that Sleuth is not working because it omits some spans. +IMPORTANT: If you use Zipkin, you can configure the probability of spans being exported by +setting (for `2.0.x`) `spring.sleuth.sampler.probability` or (up till `2.0.x`) +`spring.sleuth.sampler.percentage` (default: 0.1, which is 10 percent). Otherwise, you +might think that Sleuth is not working because it omits some spans. -IMPORTANT: Set `spring.application.name=bar` (for instance) to see the service name as well as the trace and span ids. \ No newline at end of file +IMPORTANT: Set `spring.application.name=bar` (for instance) to see the service name as +well as the trace and span IDs. diff --git a/docs/src/main/asciidoc/sagan-index.adoc b/docs/src/main/asciidoc/sagan-index.adoc index 2c4b64d55e..73f429223c 100644 --- a/docs/src/main/asciidoc/sagan-index.adoc +++ b/docs/src/main/asciidoc/sagan-index.adoc @@ -1,12 +1,30 @@ -Spring Cloud Sleuth implements a distributed tracing solution for Spring Cloud, borrowing heavily from https://research.google.com/pubs/pub36356.html[Dapper], https://github.com/openzipkin/zipkin[Zipkin] and HTrace. For most users Sleuth should be invisible, and all your interactions with external systems should be instrumented automatically. You can capture data simply in logs, or by sending it to a remote collector service. +Spring Cloud Sleuth implements a distributed tracing solution for Spring Cloud, borrowing +heavily from https://research.google.com/pubs/pub36356.html[Dapper], +https://github.com/openzipkin/zipkin[Zipkin], and HTrace. For most users, Sleuth should be +invisible, and all your interactions with external systems should be instrumented +automatically. You can capture data in logs or by sending it to a remote collector service. ## Features -A Span is the basic unit of work. For example, sending an RPC is a new span, as is sending a response to an RPC. Span’s are identified by a unique 64-bit ID for the span and another 64-bit ID for the trace the span is a part of. Spans also have other data, such as descriptions, key-value annotations, the ID of the span that caused them, and process ID’s (normally IP address). Spans are started and stopped, and they keep track of their timing information. Once you create a span, you must stop it at some point in the future. A set of spans forming a tree-like structure called a Trace. For example, if you are running a distributed big-data store, a trace might be formed by a put request. +A span is the basic unit of work. For example, sending an RPC is a new span, as is sending +a response to an RPC. Spans are identified by a unique 64-bit ID for the span and another +64-bit ID for the trace of which the span is a part. Spans also have other data, such as +descriptions, key-value annotations, the ID of the span that caused them, and process IDs +(normally IP addresses). Spans are started and stopped, and they keep track of their +timing information. Once you create a span, you must stop it at some point in the future. +A set of spans (which form a tree-like structure) is called a trace. For example, if you +run a distributed big-data store, a trace might be formed by a `PUT` request. -Spring Cloud Sleuth features: +Spring Cloud Sleuth: -* Adds trace and span ids to the Slf4J MDC, so you can extract all the logs from a given trace or span in a log aggregator. -* Provides an abstraction over common distributed tracing data models: traces, spans (forming a DAG), annotations, key-value annotations. Loosely based on HTrace, but Zipkin (Dapper) compatible. -* Instruments common ingress and egress points from Spring applications (servlet filter, rest template, scheduled actions, message channels, zuul filters, feign client). -* If `spring-cloud-sleuth-zipkin` is available then the app will generate and collect Zipkin-compatible traces via HTTP. By default it sends them to a Zipkin collector service on localhost (port 9411). Configure the location of the service using `spring.zipkin.baseUrl`. \ No newline at end of file +* Adds trace and span IDs to the Slf4J MDC so that you can extract all the logs from a +given trace or span in a log aggregator. +* Provides an abstraction over common distributed tracing data models: traces, spans +(forming a DAG), annotations, and key-value annotations. This is loosely based on HTrace +but is Zipkin (Dapper) compatible. +* Instruments common ingress and egress points from Spring applications (servlet filter, +rest template, scheduled actions, message channels, zuul filters, and the feign client). +* If `spring-cloud-sleuth-zipkin` is available, the app generates and collects +Zipkin-compatible traces over HTTP. By default, it sends them to a Zipkin collector +service on localhost (port 9411). You can configure the location of the service using +`spring.zipkin.baseUrl`. diff --git a/docs/src/main/asciidoc/using.adoc b/docs/src/main/asciidoc/using.adoc index 9fa0e8ab80..a3e6ddeadf 100644 --- a/docs/src/main/asciidoc/using.adoc +++ b/docs/src/main/asciidoc/using.adoc @@ -3,34 +3,35 @@ include::_attributes.adoc[] This section goes into more detail about how you should use {project-full-name}. It covers topics -such as description of flows of how to work with {project-full-name}. We also +such as flows of how to work with {project-full-name}. We also cover some {project-full-name} best practices. If you are starting out with {project-full-name}, you should probably read the -_<>_ guide before diving into this +<> guide before diving into this section. [[flows-provider-nexus]] -== Provider contract testing with stubs in Nexus / Artifactory +== Provider Contract Testing with Stubs in Nexus or Artifactory -You can check the <> link to see the provider contract testing with stubs in Nexus / Artifactory flow. +You can check the <> link to see the provider contract testing with stubs in the Nexus or Artifactory flow. -You can also check the https://cloud-samples.spring.io/spring-cloud-contract-samples/tutorials/contracts_on_the_producer_side.html[workshop page] for a step by step instruction on how to do this flow. +You can also check the https://cloud-samples.spring.io/spring-cloud-contract-samples/tutorials/contracts_on_the_producer_side.html[workshop page] for a step-by-step instruction on how to do this flow. [[flows-provider-git]] -== Provider contract testing with stubs in Git +== Provider Contract Testing with Stubs in Git -In this flow, we will perform the provider contract testing (producer has no knowledge of how consumers use their API). The stubs will be uploaded to a separate repository (they will not be uploaded to Artifactory / Nexus). +In this flow, we perform the provider contract testing (the producer has no knowledge of how consumers use their API). The stubs are uploaded to a separate repository (they are not uploaded to Artifactory or Nexus). -Prerequisites: +=== Prerequisites -* Git repository that -** will contain all the stubs for each producer -** for an example of such a project you can check the samples -{samples_code}/contract_git[check the samples ] or {samples_code}/contract_git[check the samples here] -** as a result of pushing stubs there, the repository will have the following structure -+ -``` +Before testing provider contracts with stubs in git, you must provide a git repository +that contains all the stubs for each producer. For an example of such a project, see +{samples_code}/contract_git[this samples ] or {samples_code}/contract_git[this sample]. +As a result of pushing stubs there, the repository has the following structure: + +==== +[src, bash] +---- $ tree . └── META-INF    └── folder.with.group.id.as.its.name @@ -40,24 +41,33 @@ $ tree .    ├── contractB.yml    └── contractC.groovy -``` -* Consumer code that has Spring Cloud Contract Stub Runner setup -** for an example of such a project you can {samples_code}/consumer[check the samples] and search for a `BeerControllerGitTest` test -* Producer code that has Spring Cloud Contract setup together with a plugin -** for an example of such a project you can {samples_code}/producer_with_empty_git[check the samples] +---- +==== + +You must also provide consumer code that has Spring Cloud Contract Stub Runner set up. For +an example of such a project, see {samples_code}/consumer[this sample] and search for a +`BeerControllerGitTest` test. You must also provide producer code that has Spring Cloud +Contract set up, together with a plugin. For an example of such a project, see +{samples_code}/producer_with_empty_git[this sample]. [[flows-provider-git-flow]] -=== The flow +=== The Flow -The flow looks exactly as the one presented in he <> section, but the `Stub Storage` implementation will be a git repository. +The flow looks exactly as the one presented in +<>, +but the `Stub Storage` implementation is a git repository. -You can read more about setting up git repository as a git storage and setting consumer and producer side in the <> of the documentation. +You can read more about setting up a git repository and setting consumer and producer side +in the <> of the documentation. [[flows-provider-git-consumer]] === Consumer setup -In order to fetch the stubs from a git repository instead of Nexus / Artifactory, you need to use the `git` protocol in the URL of the `repositoryRoot` property in Stub Runner. Below you have an example of how to set it up. +In order to fetch the stubs from a git repository instead of Nexus or Artifactory, you +need to use the `git` protocol in the URL of the `repositoryRoot` property in Stub Runner. +The following example shows how to set it up: +==== [source,java,indent=0,subs="verbatim,attributes",role="primary"] .Annotation ---- @@ -86,11 +96,15 @@ stubsMode = StubRunnerProperties.StubsMode.REMOTE, .repoRoot("git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git") .stubsMode(StubRunnerProperties.StubsMode.REMOTE); ---- +==== [[flows-provider-git-producer]] -=== Producer setup +=== Setting up the Producer -In order to push the stubs to a git repository instead of Nexus / Artifactory, you need to use the `git` protocol in the URL of the plugin setup. Also you need to explicitly tell the plugin to push the stubs at the end of the build process. +In order to push the stubs to a git repository instead of Nexus or Artifactory, you need +to use the `git` protocol in the URL of the plugin setup. Also you need to explicitly tell +the plugin to push the stubs at the end of the build process. The following example shows +how to do so: ==== [source,xml,indent=0,role="primary"] @@ -161,69 +175,94 @@ publish.dependsOn("publishStubsToScm") ---- ==== -You can read more about setting up git repository as a git storage in the <> of the documentation. +You can read more about setting up a git repository in the +<> of the documentation. [[flows-cdc-contracts-producer]] -== Consumer Driven Contracts with contracts on the producer side +== Consumer Driven Contracts with Contracts on the Producer Side -You can check the <> link to see the Consumer Driven Contracts with contracts on the producer side flow. +See <> to see the Consumer Driven Contracts +with contracts on the producer side flow. [[flows-cdc-contracts-external]] -== Consumer Driven Contracts with contracts in external repo +== Consumer Driven Contracts with Contracts in an External Repository -In this flow, we will perform Consumer Driven Contract testing. The contract definitions will be stored in a separate repository. +In this flow, we perform Consumer Driven Contract testing. The contract definitions are +stored in a separate repository. -You can check the https://cloud-samples.spring.io/spring-cloud-contract-samples/tutorials/contracts_on_the_producer_side.html[workshop page] for a step by step instruction on how to do this flow. +See the https://cloud-samples.spring.io/spring-cloud-contract-samples/tutorials/contracts_on_the_producer_side.html[workshop page] +for step-by-step instructions on how to do this flow. -Prerequisites: +=== Prerequisites -* Git repository that -** will contain all the contract definitions for each producer -** can package the contract definitions in a JAR -** for each contract producer contains a way (e.g. `pom.xml`) to install stubs locally via the Spring Cloud Contract Plugin (SCC Plugin) -** for more information please visit the <> where we describe how to set up such a repository -** for an example of such a project you can {samples_code}/beer_contracts[check the samples] -* Consumer code that has Spring Cloud Contract Stub Runner setup -** for an example of such a project you can {samples_code}/consumer[check the samples] -* Producer code that has Spring Cloud Contract setup together with a plugin -** for an example of such a project you can {samples_code}/producer_with_external_contracts[check the samples] -* The `Stub Storage` will be Nexus / Artifactory +To use consumer-driven contracts with the contracts held in an external repository, you need to set up a git repository that: -At a high level the flow looks as follows: +* Contains all the contract definitions for each producer. +* Can package the contract definitions in a JAR. +* For each contract producer, contains a way (for example, `pom.xml`) to install stubs +locally through the Spring Cloud Contract Plugin (SCC Plugin) -* Consumer works with the contract definitions from the separate repository -* Once the consumer's work is done, a branch with working code is done on the consumer side and a pull request is made to the separate repository with contract definitions -* Producer takes over the pull request to the separate repository with contract definitions and installs the JAR with all contracts locally -* Producer generates tests from the locally stored JAR and writes the missing implementation to make the tests pass -* Once the producer's work is done, the pull request to the repository with contract definitions is merged. -* After the CI tool builds the repository with contract definitions and the JAR with contract definitions gets uploaded to Nexus / Artifactory, the producer can merge their branch -* Finally the consumer can switch to working online to fetch stubs of the producer from a remote location and the branch can be merged to master +For more information, see the <>, +where we describe how to set up such a repository +For an example of such a project, see {samples_code}/beer_contracts[this sample]. + +You also need consumer code that has Spring Cloud Contract Stub Runner set up. +For an example of such a project, see {samples_code}/consumer[this sample]. +You also need producer code that has Spring Cloud Contract set up, together with a plugin. +For an example of such a project, see {samples_code}/producer_with_external_contracts[this sample]. +The stub storage is Nexus or Artifactory + +At a high level, the flow looks as follows: + +. The consumer works with the contract definitions from the separate repository +. Once the consumer's work is done, a branch with working code is done on the consumer +side and a pull request is made to the separate repository that holds the contract definitions. +. The producer takes over the pull request to the separate repository with contract +definitions and installs the JAR with all contracts locally. +. The producer generates tests from the locally stored JAR and writes the missing +implementation to make the tests pass. +. Once the producer's work is done, the pull request to the repository that holds the +contract definitions is merged. +. After the CI tool builds the repository with the contract definitions and the JAR with +contract definitions gets uploaded to Nexus or Artifactory, the producer can merge its branch. +. Finally, the consumer can switch to working online to fetch stubs of the producer from a +remote location, and the branch can be merged to master. [[flows-cdc-contracts-external-consumer]] === Consumer Flow -As a consumer +The consumer: -* write a test that would send a request to the producer -** the test will fail due to no server being present -* clone the repository with contract definitions -* set up the your requirements as contract under the folder with your consumer name as a subfolder of the producer. E.g. for a producer `producer` and consumer `consumer` the contracts would be stored under `src/main/resources/contracts/producer/consumer/`) -* once the contracts are defined, install the producer stubs to your local storage e.g. +. Writes a test that would send a request to the producer. + -``` +The test fails due to no server being present. +. Clones the repository that holds the contract definitions. +. Set up the requirements as contracts under the folder with the consumer name as a subfolder of the producer. ++ +For example, for a producer named `producer` and a consumer named `consumer`, the contracts would be stored under `src/main/resources/contracts/producer/consumer/`) +. Once the contracts are defined, installs the producer stubs to local storage, as the following example shows: ++ +==== +[src,bash] +---- $ cd src/main/resource/contracts/producer $ ./mvnw clean install -``` -* setup Spring Cloud Contract (SCC) Stub Runner in your tests -** to fetch the producer stubs from your local storage -** to work in the `stubs per consumer` mode (this enables Consumer Driven Contracts mode) -* SCC Stub Runner will -** fetch the producer stubs -** run an in memory HTTP server stub with the producer stubs +---- +==== +. Sets up Spring Cloud Contract (SCC) Stub Runner in the consumer tests, to: +* Fetch the producer stubs from local storage. +* Work in the stubs-per-consumer mode (this enables consumer driven contracts mode). ++ +The SCC Stub Runner: +* Fetches the producer stubs. +* Runs an in-memory HTTP server stub with the producer stubs. * Now your test communicates with the HTTP server stub and your tests pass * Create a pull request to the repository with contract definitions, with the new contracts for the producer * Branch your consumer code, until the producer team has merged their code +The following UML diagram shows the consumer flow: + [plantuml, flow-overview-consumer-cdc-external-consumer, png] ---- "Consumer"->"Repo\nwith\ncontracts": clone @@ -245,20 +284,30 @@ $ ./mvnw clean install [[flows-cdc-contracts-external-producer]] === Producer Flow -As a producer +The producer: -* take over the pull request to the repository with contract definitions. You can do it from the command line +. Takes over the pull request to the repository with contract definitions. You can do it +from the command line, as follows + -```bash +==== +[src,bash] +---- $ git checkout -b the_branch_with_pull_request master git pull https://github.com/user_id/project_name.git the_branch_with_pull_request -``` -* Install the contract definitions e.g. -```bash -$ ./mvnw clean install -``` -* Setup your plugin to fetch the contract definitions from a JAR instead of from `src/test/resources/contracts` +---- +==== +. Installs the contract definitions, as follows + +==== +[src,bash] +---- +$ ./mvnw clean install +---- +==== +. Sets up the plugin to fetch the contract definitions from a JAR instead of from +`src/test/resources/contracts`, as follows: ++ +==== [source,xml,indent=0,subs="verbatim,attributes",role="primary"] .Maven ---- @@ -279,7 +328,7 @@ $ ./mvnw clean install ---- -+ + [source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] .Gradle ---- @@ -294,34 +343,41 @@ contracts { // Additional configuration } ---- -* Run the build, generate tests and stubs +==== +. Runs the build to generate tests and stubs, as follows: + +==== [source,bash,indent=0,subs="verbatim,attributes",role="primary"] .Maven ---- ./mvnw clean install ---- -+ + [source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] .Gradle ---- ./gradlew clean build ---- -* Write the missing implementation, make the tests pass -* Once done -** merge the pull request to the repository with contract definitions -** you can do it from the command line +==== +. Writes the missing implementation, to make the tests pass. +. Merges the pull request to the repository with contract definitions, as follows: + -```bash +==== +[src,bash] +---- $ git commit -am "Finished the implementation to make the contract tests pass" $ git checkout master $ git merge --no-ff the_branch_with_pull_request $ git push origin master -``` -* Now, the CI system will build the project with contract definitions and upload the JAR with contract definitions to Nexus / Artifactory -* The producer can switch to working remotely -** Setup the plugin so that the contract definitions are no longer taken from the local storage but from a remote location +---- +==== +. The CI system builds the project with the contract definitions and uploads the JAR with +the contract definitions to Nexus or Artifactory. +. Switches to working remotely. +. Sets up the plugin so that the contract definitions are no longer taken from the local +storage but from a remote location, as follows: + +==== [source,xml,indent=0,subs="verbatim,attributes",role="primary"] .Maven ---- @@ -342,7 +398,7 @@ $ git push origin master ---- -+ + [source,groovy,indent=0,subs="verbatim,attributes",role="secondary"] .Gradle ---- @@ -357,8 +413,14 @@ contracts { // Additional configuration } ---- -** merge the producer code with the new implementation -* Now, the CI system will build the project, generate tests, stubs, stub JAR and upload the artifact with the application and the stubs to Nexus / Artifactory +==== +. Merges the producer code with the new implementation. +. The CI system: +* Builds the project +* Generates tests, stubs, and the stub JAR +* Uploads the artifact with the application and the stubs to Nexus or Artifactory. + +The following UML diagram shows the producer process: [plantuml, flow-overview-consumer-cdc-external-producer, png] ---- @@ -393,27 +455,30 @@ contracts { ---- [[flows-cdc-contracts-stubs-git]] -== Consumer Driven Contracts with contracts on the producer side, pushed to git +== Consumer Driven Contracts with Contracts on the Producer Side, Pushed to Git -You can check the <> link to see the Consumer Driven Contracts with contracts on the producer side flow. +You can check <> to see the consumer driven contracts with contracts on the producer side flow. -The Stub Storage implementation would be the git repository. We describe its setup in the <> section. +The stub storage implementation is a git repository. We describe its setup in the +<> section. -You can read more about setting up git repository as a git storage and setting consumer and producer side in the <> of the documentation. +You can read more about setting up a git repository for the consumer and producer sides in +the <> of the documentation. [[flows-provider-non-spring]] -== Provider contract testing with stubs in Artifactory for a non Spring application +== Provider Contract Testing with Stubs in Artifactory for a non-Spring Application [[flows-provider-non-spring-flow]] -=== The flow +=== The Flow -You can check the <> link to see the provider contract testing with stubs in Nexus / Artifactory flow. +You can check <> to see the flow for provider contract testing with stubs in Nexus or Artifactory. [[flows-provider-non-spring-consumer]] -=== Consumer setup +=== Setting up the Consumer -For the consumer side, it's enough to use a JUnit rule. That way you don't even start a Spring context. +For the consumer side, you can use a JUnit rule. That way, you need not start a Spring context. The follwoing listing shows such a rule (in JUnit4 and JUnit 5); +==== [source,java,indent=0,subs="verbatim,attributes",role="primary"] .JUnit 4 Rule ---- @@ -433,16 +498,21 @@ For the consumer side, it's enough to use a JUnit rule. That way you don't even .repoRoot("git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git") .stubsMode(StubRunnerProperties.StubsMode.REMOTE); ---- +==== [[flows-provider-non-spring-producer]] -=== Producer setup +=== Setting up the Producer -By default, the Spring Cloud Contract Plugin will use the Rest Assured's `MockMvc` setup for the generated tests. Since non Spring applications don't use `MockMvc`, it's enough to change the `testMode` to `EXPLICIT` to send a real request to an application bound at a specific port. ' +By default, the Spring Cloud Contract Plugin uses Rest Assured's `MockMvc` setup for the +generated tests. Since non-Spring applications do not use `MockMvc`, you can change the +`testMode` to `EXPLICIT` to send a real request to an application bound at a specific port. -In this example we will use a framework called https://javalin.io[Javalin] to start a non Spring HTTP server. +In this example, we use a framework called https://javalin.io[Javalin] to start a +non-Spring HTTP server. -Let us assume that we have the following application +Assume that we have the following application: +==== [source,java,indent=0] ---- package com.example.demo; @@ -469,8 +539,10 @@ public class DemoApplication { } ---- +==== -Setup the plugin to use the `EXPLICIT` mode (i.e. to send out requests to a real port). +Given that application, we can set up the plugin to use the `EXPLICIT` mode (that is, to +send out requests to a real port), as follows: ==== [source,xml,indent=0,role="primary"] @@ -500,8 +572,9 @@ contracts { ---- ==== -The base class could look like this +The base class might resemble the following: +==== [source,java,indent=0] ---- import io.javalin.Javalin; @@ -536,45 +609,57 @@ public class BaseClass { } } ---- +==== -With such a setup +With such a setup: -* we've setup the Spring Cloud Contract plugin that it uses the `EXPLICIT` mode to send real requests instead of mocked ones -* we've defined a base class that -** starts the HTTP server on a random port for each test -** sets Rest Assured to send requests to that port -** closes the HTTP server after each test +* We have setup the Spring Cloud Contract plugin to use the `EXPLICIT` mode to send real +requests instead of mocked ones. +* We have defined a base class that: +** Starts the HTTP server on a random port for each test. +** Sets Rest Assured to send requests to that port. +** Closes the HTTP server after each test. [[flows-provider-non-jvm]] -== Provider contract testing with stubs in Artifactory in non JVM world +== Provider Contract Testing with Stubs in Artifactory in a non-JVM World -In this flow we assume that +In this flow, we assume that: -* the API Producer and API Consumer are non JVM applications. -* the contract definitions are written in YAML -* the Stub Storage is Artifactory / Nexus -* Spring Cloud Contract Docker (SCC Docker) and Spring Cloud Contract Stub Runner Docker (SCC Stub Runner Docker) images will be used +* The API Producer and API Consumer are non-JVM applications. +* The contract definitions are written in YAML. +* The Stub Storage is Artifactory or Nexus. +* Spring Cloud Contract Docker (SCC Docker) and Spring Cloud Contract Stub Runner Docker +(SCC Stub Runner Docker) images are used. -You can read more about how to use Spring Cloud Contract with Docker <>. +You can read more about how to use Spring Cloud Contract with Docker +<>. -Over https://spring.io/blog/2018/02/13/spring-cloud-contract-in-a-polyglot-world[here] you can read a blog post about how to use Spring Cloud Contract in a polyglot world. +https://spring.io/blog/2018/02/13/spring-cloud-contract-in-a-polyglot-world[Here], you can +read a blog post about how to use Spring Cloud Contract in a polyglot world. -https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs/[Here] you can find a sample of a NodeJS application using Spring Cloud Contract both as a producer and a consumer. +https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs/[Here], you can find +a sample of a NodeJS application that uses Spring Cloud Contract both as a producer and a +consumer. [[flows-provider-non-jvm-producer]] === Producer Flow -At a high level the producer +At a high level, the producer: -* writes contract definitions e.g. in YAML -* sets up the build tool to -** start the application with mocked services on a given port X -** in case when mocking is not possible you can setup the infrastructure and define tests in a stateful way -** run the Spring Cloud Contract Docker image and pass the port of a running application as an environment variable -* The SCC Docker image -** generates the tests from the attached volume -** runs the tests against the running application -** upon test completion, stubs will get uploaded to a Stub Storage (e.g. Artifactory, Git) +. Writes contract definitions (for example, in YAML). +. Sets up the build tool to: +.. Start the application with mocked services on a given port. ++ +If mocking is not possible, you can setup the infrastructure and define tests in a stateful way. +.. Run the Spring Cloud Contract Docker image and pass the port of a running application as an environment variable. + +The SCC Docker image: +* Generates the tests from the attached volume. +* Runs the tests against the running application. + +Upon test completion, stubs get uploaded to a stub storage site (such as Artifactory or Git). + +The following UML diagram shows the producer flow: [plantuml, flows-provider-non-jvm-producer, png] ---- @@ -599,16 +684,21 @@ At a high level the producer [[flows-provider-non-jvm-consumer]] === Consumer Flow -At a high level the consumer +At a high level, the consumer: -* sets up the build tool to -** start the Spring Cloud Contract Stub Runner Docker image and start the stubs -*** the environment variables passed will configure -**** the stubs to fetch -**** location of the repositories -*** to use the local storage you can also attach it as a volume -*** the ports at which the stubs are running need to be exposed -** run your application tests against the running stubs +. Sets up the build tool to: +* Start the Spring Cloud Contract Stub Runner Docker image and start the stubs. ++ +The environment variables configure: +* The stubs to fetch. +* The location of the repositories. ++ +Note that: +* To use the local storage, you can also attach it as a volume. +* The ports at which the stubs are running need to be exposed. +. Run the application tests against the running stubs. + +The following UML diagram shows the consumer flow: [plantuml, flows-provider-non-jvm-consumer, png] ---- @@ -627,19 +717,19 @@ At a high level the consumer ---- [[flows-provider-rest-docs]] -== Provider contract testing with REST Docs and stubs in Nexus / Artifactory +== Provider Contract Testing with REST Docs and Stubs in Nexus or Artifactory -In this flow, we will not use a Spring Cloud Contract Plugin to generate tests and stubs. We will write https://spring.io/projects/spring-restdocs[Spring RESTDocs] and from them we will automatically generate stubs. Finally, we will setup our builds to package the stubs and upload them to the Stub Storage - in our case Nexus / Artifactory. +In this flow, we do not use a Spring Cloud Contract plugin to generate tests and stubs. We write https://spring.io/projects/spring-restdocs[Spring RESTDocs] and, from them, we automatically generate stubs. Finally, we set up our builds to package the stubs and upload them to the stub storage site -- in our case, Nexus or Artifactory. -You can also check the https://cloud-samples.spring.io/spring-cloud-contract-samples/tutorials/rest_docs.html[workshop page] for a step by step instruction on how to do this flow. +See the https://cloud-samples.spring.io/spring-cloud-contract-samples/tutorials/rest_docs.html[workshop page] for a step-by-step instruction on how to use this flow. [[flows-provider-rest-docs-producer]] -=== Producer flow +=== Producer Flow -As a producer +As a producer, we: -* we write RESTDocs tests of our API -* we add Spring Cloud Contract Stub Runner starter to our build (`spring-cloud-starter-contract-stub-runner`) +. We write RESTDocs tests of our API. +. We add Spring Cloud Contract Stub Runner starter to our build (`spring-cloud-starter-contract-stub-runner`), as follows + ==== [source,xml,indent=0,role="primary"] @@ -680,7 +770,7 @@ dependencyManagement { } ---- ==== -* we setup the build tool to package our stubs +. We set up the build tool to package our stubs, as follows: + ==== [source,xml,indent=0,role="primary"] @@ -747,7 +837,10 @@ stubsJar.dependsOn(test) bootJar.dependsOn(stubsJar) ---- ==== -* now, when we run the tests, stubs will be automatically published and packaged + +Now, when we run the tests, stubs are automatically published and packaged. + +The following UML diagram shows the producer flow: [plantuml, flows-provider-rest-docs-producer, png] ---- @@ -769,13 +862,14 @@ bootJar.dependsOn(stubsJar) ---- [[flows-provider-rest-docs-consumer]] -=== Consumer flow +=== Consumer Flow -Since the consumer flow isn't affected by the tool used to generate the stubs, you can check the <> link to see the consumer side of the provider contract testing with stubs in Nexus / Artifactory flow. +Since the consumer flow is not affected by the tool used to generate the stubs, you can check <> to see the flow for consumer side of the provider contract testing with stubs in Nexus or Artifactory. [[using-whats-next]] == What to Read Next + You should now understand how you can use {project-full-name} and some best practices that you should follow. You can now go on to learn about specific -_<>_ in depth, or you could -skip ahead and read about the _link:advanced.html[advanced features of {project-full-name}]_. +<>, or you could +skip ahead and read about the link:advanced.html[advanced features of {project-full-name}]. From 21318efa8d7bb5a36be687114510064c764b159b Mon Sep 17 00:00:00 2001 From: Marcin Grzejszczak Date: Wed, 7 Aug 2019 10:45:32 +0200 Subject: [PATCH 18/18] Polish --- docs/src/main/asciidoc/_attributes.adoc | 2 +- docs/src/main/asciidoc/_project-features-contract.adoc | 2 +- docs/src/main/asciidoc/_project-features-flows.adoc | 2 +- docs/src/main/asciidoc/index.adoc | 1 - 4 files changed, 3 insertions(+), 4 deletions(-) delete mode 120000 docs/src/main/asciidoc/index.adoc diff --git a/docs/src/main/asciidoc/_attributes.adoc b/docs/src/main/asciidoc/_attributes.adoc index 868f5ebdea..99a2353223 100644 --- a/docs/src/main/asciidoc/_attributes.adoc +++ b/docs/src/main/asciidoc/_attributes.adoc @@ -16,7 +16,7 @@ // project-specific attributes :core_path: {project-root} -:plugins_path: {github-raw}/spring-cloud-contract-tools +:plugins_path: {project-root}/spring-cloud-contract-tools :converters_path: {plugins_path}/spring-cloud-contract-converters :verifier_root_path: {core_path}/spring-cloud-contract-verifier :contract_spec_path: {core_path}/specs/spring-cloud-contract-spec-java diff --git a/docs/src/main/asciidoc/_project-features-contract.adoc b/docs/src/main/asciidoc/_project-features-contract.adoc index 76ac7db7ad..45a90de82f 100644 --- a/docs/src/main/asciidoc/_project-features-contract.adoc +++ b/docs/src/main/asciidoc/_project-features-contract.adoc @@ -190,7 +190,7 @@ include::{verifier_core_path}/src/test/resources/classpath/response.json[indent= ---- ==== -When test or stub generation takes place, the contents of the `readFromFile.groovy` file is passed to the body +When test or stub generation takes place, the contents of the `request.json` and `response.json` files are passed to the body of a request or a response. The name of the file needs to be a file with location relative to the folder in which the contract lays. diff --git a/docs/src/main/asciidoc/_project-features-flows.adoc b/docs/src/main/asciidoc/_project-features-flows.adoc index 177794758a..1f146abc60 100644 --- a/docs/src/main/asciidoc/_project-features-flows.adoc +++ b/docs/src/main/asciidoc/_project-features-flows.adoc @@ -352,7 +352,7 @@ methods to create request matchers, but you cannot use both approaches. On the consumer side, you can make the `resource.json` generated earlier in this section available on the classpath (by -<>, for example). After that, you can create a stub that uses WireMock in a number of different ways, including by using `@AutoConfigureWireMock(stubs="classpath:resource.json")`, as described earlier in this document. diff --git a/docs/src/main/asciidoc/index.adoc b/docs/src/main/asciidoc/index.adoc deleted file mode 120000 index 3abe7caccd..0000000000 --- a/docs/src/main/asciidoc/index.adoc +++ /dev/null @@ -1 +0,0 @@ -spring-cloud-contract.adoc \ No newline at end of file