From 0e906dc6e231e44ea79105f6789dd3891ef7fff1 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Thu, 3 Feb 2022 15:01:30 -0800 Subject: [PATCH] Use convention based code imports Closes gh-29647 --- .../docs/asciidoc/actuator/cloud-foundry.adoc | 5 +- .../src/docs/asciidoc/actuator/endpoints.adoc | 35 +-- .../src/docs/asciidoc/actuator/metrics.adoc | 60 +---- .../src/docs/asciidoc/attributes.adoc | 4 +- .../other-build-systems.adoc | 5 +- .../annotation-processor.adoc | 15 +- .../configuration-metadata/format.adoc | 5 +- .../configuration-metadata/manual-hints.adoc | 5 +- .../src/docs/asciidoc/data.adoc | 2 +- .../src/docs/asciidoc/data/nosql.adoc | 65 +---- .../src/docs/asciidoc/data/sql.adoc | 50 +--- .../src/docs/asciidoc/deployment.adoc | 2 +- .../src/docs/asciidoc/deployment/cloud.adoc | 5 +- .../src/docs/asciidoc/documentation.adoc | 2 +- .../developing-auto-configuration.adoc | 40 +-- .../asciidoc/features/external-config.adoc | 85 ++---- .../src/docs/asciidoc/features/profiles.adoc | 5 +- .../asciidoc/features/spring-application.adoc | 45 +--- .../src/docs/asciidoc/features/testing.adoc | 255 ++++-------------- .../getting-started/first-application.adoc | 5 +- .../src/docs/asciidoc/howto/actuator.adoc | 5 +- .../src/docs/asciidoc/howto/application.adoc | 5 +- .../src/docs/asciidoc/howto/data-access.adoc | 70 +---- .../src/docs/asciidoc/howto/http-clients.adoc | 5 +- .../src/docs/asciidoc/howto/jersey.adoc | 10 +- .../src/docs/asciidoc/howto/messaging.adoc | 5 +- .../howto/properties-and-configuration.adoc | 10 +- .../src/docs/asciidoc/howto/security.adoc | 5 +- .../src/docs/asciidoc/howto/spring-mvc.adoc | 10 +- .../src/docs/asciidoc/howto/testing.adoc | 15 +- .../howto/traditional-deployment.adoc | 25 +- .../src/docs/asciidoc/howto/webserver.adoc | 35 +-- .../src/docs/asciidoc/io/caching.adoc | 20 +- .../src/docs/asciidoc/io/jta.adoc | 15 +- .../src/docs/asciidoc/io/quartz.adoc | 5 +- .../src/docs/asciidoc/io/rest-client.adoc | 20 +- .../src/docs/asciidoc/io/validation.adoc | 5 +- .../src/docs/asciidoc/io/webservices.adoc | 10 +- .../src/docs/asciidoc/io/whats-next.adoc | 2 +- .../src/docs/asciidoc/messaging/amqp.adoc | 20 +- .../src/docs/asciidoc/messaging/jms.adoc | 20 +- .../src/docs/asciidoc/messaging/kafka.adoc | 25 +- .../src/docs/asciidoc/messaging/rsocket.adoc | 5 +- .../docs/asciidoc/messaging/whats-next.adoc | 2 +- .../src/docs/asciidoc/upgrading.adoc | 2 +- .../src/docs/asciidoc/upgrading/cli.adoc | 2 +- .../src/docs/asciidoc/upgrading/from-1x.adoc | 2 +- .../docs/asciidoc/upgrading/whats-next.adoc | 2 +- .../asciidoc/using/auto-configuration.adoc | 5 +- .../src/docs/asciidoc/using/devtools.adoc | 5 +- ...spring-beans-and-dependency-injection.adoc | 10 +- .../asciidoc/using/structuring-your-code.adoc | 5 +- ...-the-springbootapplication-annotation.adoc | 10 +- .../src/docs/asciidoc/web/reactive.adoc | 40 +-- .../src/docs/asciidoc/web/servlet.adoc | 75 ++---- .../src/docs/asciidoc/web/spring-graphql.adoc | 5 +- .../docs/asciidoc/web/spring-security.adoc | 10 +- 57 files changed, 250 insertions(+), 967 deletions(-) diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/cloud-foundry.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/cloud-foundry.adoc index f6032fba95..0e90877e58 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/cloud-foundry.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/cloud-foundry.adoc @@ -47,7 +47,4 @@ If you expect the Cloud Foundry endpoints to always be available at `/cloudfound The configuration differs, depending on the web server in use. For Tomcat, you can add the following configuration: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/actuator/cloudfoundry/customcontextpath/MyCloudFoundryConfiguration.java[] ----- +include::code:MyCloudFoundryConfiguration[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/endpoints.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/endpoints.adoc index b7ee3fd026..378be58e43 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/endpoints.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/endpoints.adoc @@ -328,10 +328,7 @@ If you wish to configure custom security for HTTP endpoints (for example, to all A typical Spring Security configuration might look something like the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/actuator/endpoints/security/typical/MySecurityConfiguration.java[] ----- +include::code:typical/MySecurityConfiguration[] The preceding example uses `EndpointRequest.toAnyEndpoint()` to match a request to any endpoint and then ensures that all have the `ENDPOINT_ADMIN` role. Several other matcher methods are also available on `EndpointRequest`. @@ -351,10 +348,7 @@ You can do so by changing the configprop:management.endpoints.web.exposure.inclu Additionally, if Spring Security is present, you would need to add custom security configuration that allows unauthenticated access to the endpoints, as the following example shows: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/actuator/endpoints/security/exposeall/MySecurityConfiguration.java[] ----- +include::code:exposeall/MySecurityConfiguration[] NOTE: In both of the preceding examples, the configuration applies only to the actuator endpoints. Since Spring Boot's security configuration backs off completely in the presence of any `SecurityFilterChain` bean, you need to configure an additional `SecurityFilterChain` bean with rules that apply to the rest of the application. @@ -443,10 +437,7 @@ If both Jersey and Spring MVC are available, Spring MVC is used. The following example exposes a read operation that returns a custom object: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/actuator/endpoints/implementingcustom/MyEndpoint.java[tag=read] ----- +include::code:MyEndpoint[tag=read] You can also write technology-specific endpoints by using `@JmxEndpoint` or `@WebEndpoint`. These endpoints are restricted to their respective technologies. @@ -480,10 +471,7 @@ Consider the following JSON request body: You can use this to invoke a write operation that takes `String name` and `int counter` parameters, as the following example shows: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/actuator/endpoints/implementingcustom/input/../MyEndpoint.java[tag=write] ----- +include::code:../MyEndpoint[tag=write] TIP: Because endpoints are technology agnostic, only simple types can be specified in the method signature. In particular, declaring a single parameter with a `CustomData` type that defines a `name` and `counter` properties is not supported. @@ -759,10 +747,7 @@ You need to provide an implementation of the `health()` method and return a `Hea The `Health` response should include a status and can optionally include additional details to be displayed. The following code shows a sample `HealthIndicator` implementation: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/actuator/endpoints/health/writingcustomhealthindicators/MyHealthIndicator.java[] ----- +include::code:MyHealthIndicator[] NOTE: The identifier for a given `HealthIndicator` is the name of the bean without the `HealthIndicator` suffix, if it exists. In the preceding example, the health information is available in an entry named `my`. @@ -837,10 +822,7 @@ If you need to register a regular `HealthContributor`, you should wrap it with ` To provide custom health information from a reactive API, you can register Spring beans that implement the {spring-boot-actuator-module-code}/health/ReactiveHealthIndicator.java[`ReactiveHealthIndicator`] interface. The following code shows a sample `ReactiveHealthIndicator` implementation: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/actuator/endpoints/health/reactivehealthindicators/MyReactiveHealthIndicator.java[] ----- +include::code:MyReactiveHealthIndicator[] TIP: To handle the error automatically, consider extending from `AbstractReactiveHealthIndicator`. @@ -1283,10 +1265,7 @@ To provide custom application information, you can register Spring beans that im The following example contributes an `example` entry with a single value: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/actuator/endpoints/info/writingcustominfocontributors/MyInfoContributor.java[] ----- +include::code:MyInfoContributor[] If you reach the `info` endpoint, you should see a response that contains the following additional entry: diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/metrics.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/metrics.adoc index ac09e5a5a5..962db60b80 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/metrics.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/metrics.adoc @@ -65,17 +65,11 @@ Spring Boot also adds any auto-configured registries to the global static compos You can register any number of `MeterRegistryCustomizer` beans to further configure the registry, such as applying common tags, before any meters are registered with the registry: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/actuator/metrics/gettingstarted/commontags/MyMeterRegistryConfiguration.java[] ----- +include::code:commontags/MyMeterRegistryConfiguration[] You can apply customizations to particular registry implementations by being more specific about the generic type: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/actuator/metrics/gettingstarted/specifictype/MyMeterRegistryConfiguration.java[] ----- +include::code:specifictype/MyMeterRegistryConfiguration[] Spring Boot also <> that you can control through configuration or dedicated annotation markers. @@ -308,10 +302,7 @@ Micrometer provides a default `HierarchicalNameMapper` that governs how a dimens To take control over this behavior, define your `GraphiteMeterRegistry` and supply your own `HierarchicalNameMapper`. An auto-configured `GraphiteConfig` and `Clock` beans are provided unless you define your own: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/actuator/metrics/export/graphite/MyGraphiteConfiguration.java[] ----- +include::code:MyGraphiteConfiguration[] ==== @@ -384,10 +375,7 @@ Micrometer provides a default `HierarchicalNameMapper` that governs how a dimens To take control over this behavior, define your `JmxMeterRegistry` and supply your own `HierarchicalNameMapper`. An auto-configured `JmxConfig` and `Clock` beans are provided unless you define your own: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/actuator/metrics/export/jmx/MyJmxConfiguration.java[] ----- +include::code:MyJmxConfiguration[] ==== @@ -1045,10 +1033,7 @@ Each metric is tagged with the following information by default: To replace the default metric tags, define a `MongoCommandTagsProvider` bean, as the following example shows: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/actuator/metrics/supported/mongodb/command/MyCommandTagsProviderConfiguration.java[] ----- +include::code:MyCommandTagsProviderConfiguration[] To disable the auto-configured command metrics, set the following property: @@ -1086,10 +1071,7 @@ Each metric is tagged with the following information by default: To replace the default metric tags, define a `MongoConnectionPoolTagsProvider` bean: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/actuator/metrics/supported/mongodb/connectionpool/MyConnectionPoolTagsProviderConfiguration.java[] ----- +include::code:MyConnectionPoolTagsProviderConfiguration[] To disable the auto-configured connection pool metrics, set the following property: @@ -1118,24 +1100,15 @@ If supported, you can use the annotation at either the class level or the method For example, the following code shows how you can use the annotation to instrument all request mappings in a `@RestController`: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/actuator/metrics/supported/timedannotation/all/MyController.java[] ----- +include::code:all/MyController[] If you want only to instrument a single mapping, you can use the annotation on the method instead of the class: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/actuator/metrics/supported/timedannotation/single/MyController.java[] ----- +include::code:single/MyController[] You can also combine class-level and method-level annotations if you want to change the timing details for a specific method: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/actuator/metrics/supported/timedannotation/change/MyController.java[] ----- +include::code:change/MyController[] NOTE: A `@Timed` annotation with `longTask = true` enables a long task timer for the method. Long task timers require a separate metric name and can be stacked with a short task timer. @@ -1153,17 +1126,11 @@ For more detail, see the {lettuce-docs}#command.latency.metrics.micrometer[Micro === Registering Custom Metrics To register custom metrics, inject `MeterRegistry` into your component: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/actuator/metrics/registeringcustom/MyBean.java[] ----- +include::code:MyBean[] If your metrics depend on other beans, we recommend that you use a `MeterBinder` to register them: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/actuator/metrics/registeringcustom/MyMeterBinderConfiguration.java[] ----- +include::code:MyMeterBinderConfiguration[] Using a `MeterBinder` ensures that the correct dependency relationships are set up and that the bean is available when the metric's value is retrieved. A `MeterBinder` implementation can also be useful if you find that you repeatedly instrument a suite of metrics across components or applications. @@ -1178,10 +1145,7 @@ If you need to apply customizations to specific `Meter` instances, you can use t For example, if you want to rename the `mytag.region` tag to `mytag.area` for all meter IDs beginning with `com.example`, you can do the following: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/actuator/metrics/customizing/MyMetricsFilterConfiguration.java[] ----- +include::code:MyMetricsFilterConfiguration[] NOTE: By default, all `MeterFilter` beans are automatically bound to the Spring-managed `MeterRegistry`. Make sure to register your metrics by using the Spring-managed `MeterRegistry` and not any of the static methods on `Metrics`. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/attributes.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/attributes.adoc index 04210649a2..7911dc0b63 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/attributes.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/attributes.adoc @@ -18,8 +18,8 @@ :github-raw: https://raw.githubusercontent.com/{github-repo}/{github-tag} :github-issues: https://github.com/{github-repo}/issues/ :github-wiki: https://github.com/{github-repo}/wiki -:docs-java: ../../main/java/org/springframework/boot/docs -:docs-groovy: ../../main/groovy/org/springframework/boot/docs +:docs-java: {docdir}/../main/java/org/springframework/boot/docs +:docs-groovy: {docdir}/../main/groovy/org/springframework/boot/docs :docs-resources: ../../main/resources :spring-boot-code: https://github.com/{github-repo}/tree/{github-tag} :spring-boot-api: https://docs.spring.io/spring-boot/docs/{spring-boot-version}/api diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/build-tool-plugins/other-build-systems.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/build-tool-plugins/other-build-systems.adoc index 7c5d6a360b..579d7f0b2f 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/build-tool-plugins/other-build-systems.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/build-tool-plugins/other-build-systems.adoc @@ -37,7 +37,4 @@ An exception is thrown if more than one candidate is found. === Example Repackage Implementation The following example shows a typical repackage implementation: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/buildtoolplugins/otherbuildsystems/examplerepackageimplementation/MyBuildTool.java[] ----- +include::code:MyBuildTool[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/configuration-metadata/annotation-processor.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/configuration-metadata/annotation-processor.adoc index 5219c77c14..e2526bcf22 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/configuration-metadata/annotation-processor.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/configuration-metadata/annotation-processor.adoc @@ -69,10 +69,7 @@ The annotation processor also supports the use of the `@Data`, `@Value`, `@Gette Consider the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/configurationmetadata/annotationprocessor/automaticmetadatageneration/MyServerProperties.java[] ----- +include::code:MyServerProperties[] This exposes three properties where `my.server.name` has no default and `my.server.ip` and `my.server.port` defaults to `"127.0.0.1"` and `9797` respectively. The Javadoc on fields is used to populate the `description` attribute. For instance, the description of `my.server.ip` is "IP address to listen to.". @@ -86,10 +83,7 @@ Also, the annotation processor cannot auto-detect default values for ``Enum``s a For cases where the default value could not be detected, <> should be provided. Consider the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/configurationmetadata/annotationprocessor/automaticmetadatageneration/MyMessagingProperties.java[] ----- +include::code:MyMessagingProperties[] In order to document default values for properties in the class above, you could add the following content to <>: @@ -117,10 +111,7 @@ The annotation processor automatically considers inner classes as nested propert Rather than documenting the `ip` and `port` at the root of the namespace, we could create a sub-namespace for it. Consider the updated example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/configurationmetadata/annotationprocessor/automaticmetadatageneration/nestedproperties/MyServerProperties.java[] ----- +include::code:MyServerProperties[] The preceding example produces metadata information for `my.server.name`, `my.server.host.ip`, and `my.server.host.port` properties. You can use the `@NestedConfigurationProperty` annotation on a field to indicate that a regular (non-inner) class should be treated as if it were nested. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/configuration-metadata/format.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/configuration-metadata/format.adoc index 2e4c55a4df..af6d80f858 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/configuration-metadata/format.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/configuration-metadata/format.adoc @@ -208,10 +208,7 @@ Deprecation can also be specified declaratively in code by adding the `@Deprecat For instance, assume that the `my.app.target` property was confusing and was renamed to `my.app.name`. The following example shows how to handle that situation: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/configurationmetadata/format/property/MyProperties.java[] ----- +include::code:MyProperties[] NOTE: There is no way to set a `level`. `warning` is always assumed, since code is still handling the property. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/configuration-metadata/manual-hints.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/configuration-metadata/manual-hints.adoc index 4df1946045..f5b0ed44d5 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/configuration-metadata/manual-hints.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/configuration-metadata/manual-hints.adoc @@ -18,10 +18,7 @@ The special `.keys` and `.values` suffixes must refer to the keys and the values Assume a `my.contexts` maps magic `String` values to an integer, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/configurationmetadata/manualhints/valuehint/MyProperties.java[] ----- +include::code:MyProperties[] The magic values are (in this example) are `sample1` and `sample2`. In order to offer additional content assistance for the keys, you could add the following JSON to <>: diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data.adoc index 0ff5e60b96..3015216815 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data.adoc @@ -8,4 +8,4 @@ include::data/sql.adoc[] include::data/nosql.adoc[] -include::data/whats-next.adoc[] \ No newline at end of file +include::data/whats-next.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data/nosql.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data/nosql.adoc index 2c01cffebc..cfddb9cd07 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data/nosql.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data/nosql.adoc @@ -36,10 +36,7 @@ You can inject an auto-configured `RedisConnectionFactory`, `StringRedisTemplate 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,subs="verbatim"] ----- -include::{docs-java}/data/nosql/redis/connecting/MyBean.java[] ----- +include::code:MyBean[] TIP: You can also register an arbitrary number of beans that implement `LettuceClientConfigurationBuilderCustomizer` for more advanced customizations. `ClientResources` can also be customized using `ClientResourcesBuilderCustomizer`. @@ -65,10 +62,7 @@ To access MongoDB databases, you can inject an auto-configured `org.springframew 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,subs="verbatim"] ----- -include::{docs-java}/data/nosql/mongodb/connecting/MyBean.java[] ----- +include::code:MyBean[] If you have defined your own `MongoClient`, it will be used to auto-configure a suitable `MongoDatabaseFactory`. @@ -119,10 +113,7 @@ The auto-configuration configures this factory automatically if Netty is availab {spring-data-mongodb}[Spring Data MongoDB] provides a {spring-data-mongodb-api}/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,subs="verbatim"] ----- -include::{docs-java}/data/nosql/mongodb/template/MyBean.java[] ----- +include::code:MyBean[] See the {spring-data-mongodb-api}/core/MongoOperations.html[`MongoOperations` Javadoc] for complete details. @@ -136,10 +127,7 @@ As with the JPA repositories discussed earlier, the basic principle is that quer 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 MongoDB data class rather than a JPA `@Entity`, it works in the same way, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/data/nosql/mongodb/repositories/CityRepository.java[] ----- +include::code:CityRepository[] TIP: You can customize document scanning locations by using the `@EntityScan` annotation. @@ -181,10 +169,7 @@ To access a Neo4j server, you can inject an auto-configured `org.neo4j.driver.Dr 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 `Driver` that gives you access, amongst other things, to a `Session`: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/data/nosql/neo4j/connecting/MyBean.java[] ----- +include::code:MyBean[] You can configure various aspects of the driver using `spring.neo4j.*` properties. The following example shows how to configure the uri and credentials to use: @@ -213,10 +198,7 @@ For complete details of Spring Data Neo4j, see the {spring-data-neo4j-docs}[refe 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 Spring Data Neo4j `@Node` rather than JPA `@Entity` and the repository abstraction works in the same way, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/data/nosql/neo4j/repositories/CityRepository.java[] ----- +include::code:CityRepository[] The `spring-boot-starter-data-neo4j` "`Starter`" enables the repository support as well as transaction management. Spring Boot supports both classic and reactive Neo4j repositories, using the `Neo4jTemplate` or `ReactiveNeo4jTemplate` beans. @@ -229,10 +211,7 @@ You can customize the locations to look for repositories and entities by using ` In an application using the reactive style, a `ReactiveTransactionManager` is not auto-configured. To enable transaction management, the following bean must be defined in your configuration: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/data/nosql/neo4j/repositories/MyNeo4jConfiguration.java[] ----- +include::code:MyNeo4jConfiguration[] ==== @@ -250,10 +229,7 @@ You can inject an auto-configured `SolrClient` instance as you would any other S 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,subs="verbatim"] ----- -include::{docs-java}/data/nosql/solr/connecting/MyBean.java[] ----- +include::code:MyBean[] If you add your own `@Bean` of type `SolrClient`, it replaces the default. @@ -342,10 +318,7 @@ 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,subs="verbatim"] ----- -include::{docs-java}/data/nosql/elasticsearch/connectingusingspringdata/MyBean.java[] ----- +include::code:MyBean[] 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. @@ -435,10 +408,7 @@ NOTE: If you use `CqlSessionBuilder` to create multiple `CqlSession` beans, keep The following code listing shows how to inject a Cassandra bean: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/data/nosql/cassandra/connecting/MyBean.java[] ----- +include::code:MyBean[] If you add your own `@Bean` of type `CassandraTemplate`, it replaces the default. @@ -514,10 +484,7 @@ This happens when a `Cluster` is available, as described above, and a bucket nam The following examples shows how to inject a `CouchbaseTemplate` bean: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/data/nosql/couchbase/repositories/MyBean.java[] ----- +include::code:MyBean[] There are a few beans that you can define in your own configuration to override those provided by the auto-configuration: @@ -528,10 +495,7 @@ There are a few beans that you can define in your own configuration to override 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,subs="verbatim"] ----- -include::{docs-java}/data/nosql/couchbase/repositories/MyCouchbaseConfiguration.java[] ----- +include::code:MyCouchbaseConfiguration[] @@ -575,10 +539,7 @@ For complete details of Spring Data LDAP, see the https://docs.spring.io/spring- 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,subs="verbatim"] ----- -include::{docs-java}/data/nosql/ldap/repositories/MyBean.java[] ----- +include::code:MyBean[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data/sql.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data/sql.adoc index daf322fd23..cdf909d1ed 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data/sql.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data/sql.adoc @@ -158,10 +158,7 @@ For example, the following section in `application.properties` shows how you can === 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,subs="verbatim"] ----- -include::{docs-java}/data/sql/jdbctemplate/MyBean.java[] ----- +include::code:MyBean[] You can customize some properties of the template by using the `spring.jdbc.template.*` properties, as shown in the following example: @@ -202,10 +199,7 @@ By default, all packages below your main configuration class (the one annotated Any classes annotated with `@Entity`, `@Embeddable`, or `@MappedSuperclass` are considered. A typical entity class resembles the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/data/sql/jpaandspringdata/entityclasses/City.java[] ----- +include::code:City[] TIP: You can customize entity scanning locations by using the `@EntityScan` annotation. See the "`<>`" how-to. @@ -225,10 +219,7 @@ If you use auto-configuration, repositories are searched from the package contai The following example shows a typical Spring Data repository interface definition: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/data/sql/jpaandspringdata/repositories/CityRepository.java[] ----- +include::code:CityRepository[] Spring Data JPA repositories support three different modes of bootstrapping: default, deferred, and lazy. To enable deferred or lazy bootstrapping, set the configprop:spring.data.jpa.repositories.bootstrap-mode[] property to `deferred` or `lazy` respectively. @@ -253,10 +244,7 @@ If {spring-data-envers}[Spring Data Envers] is available, JPA repositories are a To use Spring Data Envers, make sure your repository extends from `RevisionRepository` as show in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/data/sql/jpaandspringdata/enversrepositories/CountryRepository.java[] ----- +include::code:CountryRepository[] NOTE: For more details, check the {spring-data-envers-doc}[Spring Data Envers reference documentation]. @@ -387,19 +375,13 @@ The fluent API offered by jOOQ is initiated through the `org.jooq.DSLContext` in Spring Boot auto-configures a `DSLContext` as a Spring Bean and connects it to your application `DataSource`. To use the `DSLContext`, you can inject it, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/data/sql/jooq/dslcontext/MyBean.java[tag=!method] ----- +include::code:MyBean[tag=!method] 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,subs="verbatim"] ----- -include::{docs-java}/data/sql/jooq/dslcontext/MyBean.java[tag=method] ----- +include::code:MyBean[tag=method] @@ -449,17 +431,11 @@ TIP: The "`How-to`" section includes a <> for details. @@ -814,10 +793,7 @@ Doing so can be particularly useful when you want to bind properties to third-pa To configure a bean from the `Environment` properties, add `@ConfigurationProperties` to its bean registration, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/thirdpartyconfiguration/ThirdPartyConfiguration.java[] ----- +include::code:ThirdPartyConfiguration[] Any JavaBean property defined with the `another` prefix is mapped onto that `AnotherComponent` bean in manner similar to the preceding `SomeProperties` example. @@ -830,10 +806,7 @@ Common examples where this is useful include dash-separated environment properti As an example, consider the following `@ConfigurationProperties` class: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/relaxedbinding/MyPersonProperties.java[] ----- +include::code:MyPersonProperties[] With the preceding code, the following properties names can all be used: @@ -949,10 +922,7 @@ When lists are configured in more than one place, overriding works by replacing 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 `MyProperties`: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/mergingcomplextypes/list/MyProperties.java[] ----- +include::code:list/MyProperties[] Consider the following configuration: @@ -1004,10 +974,7 @@ For `Map` properties, you can bind with property values drawn from multiple sour However, for the same property in multiple sources, the one with the highest priority is used. The following example exposes a `Map` from `MyProperties`: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/mergingcomplextypes/map/MyProperties.java[] ----- +include::code:map/MyProperties[] Consider the following configuration: @@ -1061,10 +1028,7 @@ If you expose a `java.time.Duration` property, the following formats in applicat Consider the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/conversion/durations/javabeanbinding/MyProperties.java[] ----- +include::code:javabeanbinding/MyProperties[] 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`. @@ -1084,10 +1048,7 @@ The default unit is milliseconds and can be overridden using `@DurationUnit` as If you prefer to use constructor binding, the same properties can be exposed, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/conversion/durations/constructorbinding/MyProperties.java[] ----- +include::code:constructorbinding/MyProperties[] TIP: If you are upgrading a `Long` property, make sure to define the unit (using `@DurationUnit`) if it is not milliseconds. @@ -1125,10 +1086,7 @@ If you expose a `DataSize` property, the following formats in application proper Consider the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/conversion/datasizes/javabeanbinding/MyProperties.java[] ----- +include::code:javabeanbinding/MyProperties[] 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`. @@ -1146,10 +1104,7 @@ The default unit is bytes and can be overridden using `@DataSizeUnit` as illustr If you prefer to use constructor binding, the same properties can be exposed, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/conversion/datasizes/constructorbinding/MyProperties.java[] ----- +include::code:constructorbinding/MyProperties[] TIP: If you are upgrading a `Long` property, make sure to define the unit (using `@DataSizeUnit`) if it is not bytes. Doing so gives a transparent upgrade path while supporting a much richer format. @@ -1162,20 +1117,14 @@ Spring Boot attempts to validate `@ConfigurationProperties` classes whenever the 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,subs="verbatim"] ----- -include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/validation/MyProperties.java[] ----- +include::code:MyProperties[] TIP: You can also trigger validation by annotating the `@Bean` method that creates the configuration properties with `@Validated`. To ensure that validation is always triggered for nested properties, even when no properties are found, the associated field must be annotated with `@Valid`. The following example builds on the preceding `MyProperties` example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/validation/nested/MyProperties.java[] ----- +include::code:nested/MyProperties[] You can also add a custom Spring `Validator` by creating a bean definition called `configurationPropertiesValidator`. The `@Bean` method should be declared `static`. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/profiles.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/profiles.adoc index 219e336d3b..2ca39daf0e 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/profiles.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/profiles.adoc @@ -3,10 +3,7 @@ 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] ----- -include::{docs-java}/features/profiles/ProductionConfiguration.java[] ----- +include::code:ProductionConfiguration[] NOTE: If `@ConfigurationProperties` beans are registered through `@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. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/spring-application.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/spring-application.adoc index 118636ed4e..64e08acf30 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/spring-application.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/spring-application.adoc @@ -3,10 +3,7 @@ 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,subs="verbatim"] ----- -include::{docs-java}/features/springapplication/MyApplication.java[] ----- +include::code:MyApplication[] When your application starts, you should see something similar to the following output: @@ -165,10 +162,7 @@ This will initialize the `application.*` banner variables before building the cl 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,subs="verbatim"] ----- -include::{docs-java}/features/springapplication/customizingspringapplication/MyApplication.java[] ----- +include::code:MyApplication[] 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 direct references `@Component` classes. @@ -186,10 +180,7 @@ If you need to build an `ApplicationContext` hierarchy (multiple contexts with a 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,subs="verbatim"] ----- -include::{docs-java}/features/springapplication/fluentbuilderapi/MyApplication.java[tag=*] ----- +include::code:MyApplication[tag=*] 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. @@ -240,17 +231,11 @@ More often, applications will want to listen to state updates or update the stat For example, we can export the "Readiness" state of the application to a file so that a Kubernetes "exec Probe" can look at this file: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/springapplication/applicationavailability/managing/MyReadinessStateExporter.java[] ----- +include::code:MyReadinessStateExporter[] We can also update the state of the application, when the application breaks and cannot recover: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/springapplication/applicationavailability/managing/MyLocalCacheVerifier.java[] ----- +include::code:MyLocalCacheVerifier[] Spring Boot provides <>. You can get more guidance about <>. @@ -332,10 +317,7 @@ TIP: It is often desirable to call `setWebApplicationType(WebApplicationType.NON 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,subs="verbatim"] ----- -include::{docs-java}/features/springapplication/applicationarguments/MyBean.java[] ----- +include::code:MyBean[] TIP: Spring Boot also registers a `CommandLinePropertySource` with the Spring `Environment`. This lets you also inject single application arguments by using the `@Value` annotation. @@ -353,10 +335,7 @@ NOTE: This contract is well suited for tasks that should run after application s The `CommandLineRunner` interfaces provides access to application arguments as a 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,subs="verbatim"] ----- -include::{docs-java}/features/springapplication/commandlinerunner/MyCommandLineRunner.java[] ----- +include::code:MyCommandLineRunner[] 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. @@ -370,10 +349,7 @@ All the standard Spring lifecycle callbacks (such as the `DisposableBean` interf 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,subs="verbatim"] ----- -include::{docs-java}/features/springapplication/applicationexit/MyApplication.java[] ----- +include::code:MyApplication[] 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. @@ -401,10 +377,7 @@ This data can be collected for profiling purposes, or just to have a better unde You can choose an `ApplicationStartup` implementation when setting up the `SpringApplication` instance. For example, to use the `BufferingApplicationStartup`, you could write: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/springapplication/startuptracking/MyApplication.java[] ----- +include::code:MyApplication[] The first available implementation, `FlightRecorderApplicationStartup` is provided by Spring Framework. It adds Spring-specific startup events to a Java Flight Recorder session and is meant for profiling applications and correlating their Spring context lifecycle with JVM events (such as allocations, GCs, class loading...). diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/testing.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/testing.adoc index 7e7e084460..fdd4731ae7 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/testing.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/testing.adoc @@ -105,10 +105,7 @@ If you have only Spring WebFlux, we will detect that and configure a WebFlux-bas If both are present, Spring MVC takes precedence. If you want to test a reactive web application in this scenario, you must set the configprop:spring.main.web-application-type[] property: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/detectingwebapptype/MyWebFluxTests.java[] ----- +include::code:MyWebFluxTests[] @@ -148,10 +145,7 @@ As we <>, you can have `@SpringBootTest` inject them using the `args` attribute. -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/usingapplicationarguments/MyApplicationArgumentTests.java[] ----- +include::code:MyApplicationArgumentTests[] @@ -176,19 +167,13 @@ By default, `@SpringBootTest` does not start the server but instead sets up a mo With Spring MVC, we can query our web endpoints using {spring-framework-docs}/testing.html#spring-mvc-test-framework[`MockMvc`] or `WebTestClient`, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/withmockenvironment/MyMockMvcTests.java[] ----- +include::code:MyMockMvcTests[] TIP: If you want to focus only on the web layer and not start a complete `ApplicationContext`, consider <>. With Spring WebFlux endpoints, you can use {spring-framework-docs}/testing.html#webtestclient-tests[`WebTestClient`] as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/withmockenvironment/MyMockWebTestClientTests.java[] ----- +include::code:MyMockWebTestClientTests[] [TIP] ==== @@ -210,20 +195,14 @@ If you use `@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)`, an avai 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-framework-docs}/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,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/withrunningserver/MyRandomPortWebTestClientTests.java[] ----- +include::code:MyRandomPortWebTestClientTests[] TIP: `WebTestClient` can be used against both live servers and <>. This setup requires `spring-webflux` on the classpath. If you can not or will not add webflux, Spring Boot also provides a `TestRestTemplate` facility: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/withrunningserver/MyRandomPortTestRestTemplateTests.java[] ----- +include::code:MyRandomPortTestRestTemplateTests[] @@ -239,10 +218,7 @@ Any such beans are called with the `WebTestClient.Builder` that is used to creat 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,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/jmx/MyJmxTests.java[] ----- +include::code:MyJmxTests[] @@ -271,19 +247,13 @@ Mock beans are automatically reset after each test method. 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, listeners must be explicitly added, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/mockingbeans/listener/MyTests.java[] ----- +include::code:listener/MyTests[] ==== The following example replaces an existing `RemoteService` bean with a mock implementation: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/mockingbeans/bean/MyTests.java[] ----- +include::code:bean/MyTests[] NOTE: `@MockBean` cannot be used to mock the behavior of a bean that is 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. @@ -346,10 +316,7 @@ The `JacksonTester`, `GsonTester`, `JsonbTester`, and `BasicJsonTester` classes 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,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/jsontests/MyJsonTests.java[] ----- +include::code:MyJsonTests[] 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`. @@ -358,10 +325,7 @@ If you use Spring Boot's AssertJ-based helpers to assert on a number value at a 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,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/jsontests/MyJsonAssertJTests.java[tag=*] ----- +include::code:MyJsonAssertJTests[tag=*] @@ -384,20 +348,14 @@ Mock MVC offers a powerful way to quickly test MVC controllers without needing t 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,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/springmvctests/MyControllerTests.java[] ----- +include::code:MyControllerTests[] 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 and Selenium, auto-configuration also provides an HtmlUnit `WebClient` bean and/or a Selenium `WebDriver` bean. The following example uses HtmlUnit: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/springmvctests/MyHtmlUnitTests.java[] ----- +include::code:MyHtmlUnitTests[] 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. @@ -431,10 +389,7 @@ Often, `@WebFluxTest` is limited to a single controller and used in combination 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,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/springwebfluxtests/MyControllerTests.java[] ----- +include::code:MyControllerTests[] TIP: This setup is only supported by WebFlux applications as using `WebTestClient` in a mocked web application only works with WebFlux at the moment. @@ -495,10 +450,7 @@ TIP: If you need to register extra components, such as Jackson `Module`, you can Often, `@GraphQlTest` is limited to a set of controllers and used in combination with the `@MockBean` annotation to provide mock implementations for required collaborators. -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/springgraphqltests/GreetingControllerTests.java[] ----- +include::code:GreetingControllerTests[] TIP: You can also auto-configure `WebGraphQlTester` in a non-`@GraphQlTest` (such as `@SpringBootTest`) by annotating it with `@AutoConfigureWebGraphQlTester`. @@ -516,10 +468,7 @@ TIP: A list of the auto-configuration settings that are enabled by `@DataCassand The following example shows a typical setup for using Cassandra tests in Spring Boot: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdatacassandra/MyDataCassandraTests.java[] ----- +include::code:MyDataCassandraTests[] @@ -540,10 +489,7 @@ By default, data JPA tests are transactional and roll back at the end of each te See the {spring-framework-docs}/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,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdatajpa/MyNonTransactionalTests.java[] ----- +include::code:MyNonTransactionalTests[] Data JPA tests may also inject a {spring-boot-test-autoconfigure-module-code}/orm/jpa/TestEntityManager.java[`TestEntityManager`] bean, which provides an alternative to the standard JPA `EntityManager` that is specifically designed for tests. @@ -553,18 +499,12 @@ When doing so, make sure that your test is running in a transaction, for instanc A `JdbcTemplate` is also available if you need that. The following example shows the `@DataJpaTest` annotation in use: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdatajpa/withoutdb/MyRepositoryTests.java[] ----- +include::code:withoutdb/MyRepositoryTests[] 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,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdatajpa/withdb/MyRepositoryTests.java[] ----- +include::code:withdb/MyRepositoryTests[] @@ -581,10 +521,7 @@ By default, JDBC tests are transactional and roll back at the end of each test. See the {spring-framework-docs}/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,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/autoconfiguredjdbc/MyTransactionalTests.java[] ----- +include::code:MyTransactionalTests[] 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 "<>".) @@ -623,10 +560,7 @@ TIP: A list of the auto-configurations that are enabled by `@JooqTest` can be << `@JooqTest` configures a `DSLContext`. The following example shows the `@JooqTest` annotation in use: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/autoconfiguredjooq/MyJooqTests.java[] ----- +include::code:MyJooqTests[] 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 <>. @@ -645,18 +579,12 @@ TIP: A list of the auto-configuration settings that are enabled by `@DataMongoTe The following class shows the `@DataMongoTest` annotation in use: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdatamongodb/withoutdb/MyDataMongoDbTests.java[] ----- +include::code:withoutdb/MyDataMongoDbTests[] 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,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdatamongodb/withdb/MyDataMongoDbTests.java[] ----- +include::code:withdb/MyDataMongoDbTests[] @@ -672,19 +600,13 @@ TIP: A list of the auto-configuration settings that are enabled by `@DataNeo4jTe The following example shows a typical setup for using Neo4J tests in Spring Boot: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdataneo4j/propagation/MyDataNeo4jTests.java[] ----- +include::code:propagation/MyDataNeo4jTests[] By default, Data Neo4j tests are transactional and roll back at the end of each test. See the {spring-framework-docs}/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,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdataneo4j/nopropagation/MyDataNeo4jTests.java[] ----- +include::code:nopropagation/MyDataNeo4jTests[] NOTE: Transactional tests are not supported with reactive access. If you are using this style, you must configure `@DataNeo4jTest` tests as described above. @@ -703,10 +625,7 @@ TIP: A list of the auto-configuration settings that are enabled by `@DataRedisTe The following example shows the `@DataRedisTest` annotation in use: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdataredis/MyDataRedisTests.java[] ----- +include::code:MyDataRedisTests[] @@ -722,18 +641,12 @@ TIP: A list of the auto-configuration settings that are enabled by `@DataLdapTes The following example shows the `@DataLdapTest` annotation in use: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdataldap/inmemory/MyDataLdapTests.java[] ----- +include::code:inmemory/MyDataLdapTests[] 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,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdataldap/server/MyDataLdapTests.java[] ----- +include::code:server/MyDataLdapTests[] @@ -748,10 +661,7 @@ TIP: A list of the auto-configuration settings that are enabled by `@RestClientT 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,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/autoconfiguredrestclient/MyRestClientTests.java[] ----- +include::code:MyRestClientTests[] @@ -770,26 +680,17 @@ It can also be used to configure the host, scheme, and port that appears in any `@AutoConfigureRestDocs` customizes the `MockMvc` bean to use Spring REST Docs when testing servlet-based web applications. 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,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withmockmvc/MyUserDocumentationTests.java[] ----- +include::code:MyUserDocumentationTests[] 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,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withmockmvc/MyRestDocsConfiguration.java[] ----- +include::code:MyRestDocsConfiguration[] 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,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withmockmvc/MyResultHandlerConfiguration.java[] ----- +include::code:MyResultHandlerConfiguration[] @@ -798,25 +699,16 @@ include::{docs-java}/features/testing/springbootapplications/autoconfiguredsprin `@AutoConfigureRestDocs` can also be used with `WebTestClient` when testing reactive web applications. 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,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withwebtestclient/MyUsersDocumentationTests.java[] ----- +include::code:MyUsersDocumentationTests[] 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,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withwebtestclient/MyRestDocsConfiguration.java[] ----- +include::code:MyRestDocsConfiguration[] If you want to make use of Spring REST Docs support for a parameterized output directory, you can use a `WebTestClientBuilderCustomizer` to configure a consumer for every entity exchange result. The following example shows such a `WebTestClientBuilderCustomizer` being defined: -[source,java,indent=0] ----- -include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withwebtestclient/MyWebTestClientBuilderCustomizerConfiguration.java[] ----- +include::code:MyWebTestClientBuilderCustomizerConfiguration[] @@ -825,17 +717,11 @@ include::{docs-java}/features/testing/springbootapplications/autoconfiguredsprin `@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,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withrestassured/MyUserDocumentationTests.java[] ----- +include::code:MyUserDocumentationTests[] 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,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withrestassured/MyRestDocsConfiguration.java[] ----- +include::code:MyRestDocsConfiguration[] @@ -855,10 +741,7 @@ TIP: A list of the auto-configuration settings that are enabled by `@WebServiceC The following example shows the `@WebServiceClientTest` annotation in use: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/autoconfiguredwebservices/client/MyWebServiceClientTests.java[] ----- +include::code:MyWebServiceClientTests[] @@ -873,10 +756,7 @@ TIP: A list of the auto-configuration settings that are enabled by `@WebServiceS The following example shows the `@WebServiceServerTest` annotation in use: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/autoconfiguredwebservices/server/MyWebServiceServerTests.java[] ----- +include::code:MyWebServiceServerTests[] @@ -885,10 +765,7 @@ include::{docs-java}/features/testing/springbootapplications/autoconfiguredwebse 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 on a test-by-test basis by creating a custom `@AutoConfigure...` annotation or by adding `@ImportAutoConfiguration` to the test as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/additionalautoconfigurationandslicing/MyJdbcTests.java[] ----- +include::code:MyJdbcTests[] 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. @@ -912,18 +789,12 @@ It then becomes important not to litter the application's main class with config 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,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/userconfigurationandslicing/MyApplication.java[] ----- +include::code:MyApplication[] 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,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/userconfigurationandslicing/MyBatchConfiguration.java[] ----- +include::code:MyBatchConfiguration[] 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. @@ -931,26 +802,17 @@ The latter approach lets you enable it in one of your tests, if necessary, with 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,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/userconfigurationandslicing/MyWebConfiguration.java[] ----- +include::code:MyWebConfiguration[] The configuration below will, however, cause the custom `WebMvcConfigurer` to be loaded by the test slice. -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/userconfigurationandslicing/MyWebMvcConfigurer.java[] ----- +include::code:MyWebMvcConfigurer[] 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,subs="verbatim"] ----- -include::{docs-java}/features/testing/springbootapplications/userconfigurationandslicing/scan/MyApplication.java[] ----- +include::code:scan/MyApplication[] 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. @@ -981,10 +843,7 @@ A few test utility classes that are generally useful when testing your applicati `ConfigDataApplicationContextInitializer` 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,subs="verbatim"] ----- -include::{docs-java}/features/testing/utilities/configdataapplicationcontextinitializer/MyConfigFileTests.java[] ----- +include::code:MyConfigFileTests[] NOTE: Using `ConfigDataApplicationContextInitializer` alone does not provide support for `@Value("${...}")` injection. Its only job is to ensure that `application.properties` files are loaded into Spring's `Environment`. @@ -997,10 +856,7 @@ For `@Value` support, you need to either additionally configure a `PropertySourc `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,subs="verbatim"] ----- -include::{docs-java}/features/testing/utilities/testpropertyvalues/MyEnvironmentTests.java[] ----- +include::code:MyEnvironmentTests[] @@ -1009,10 +865,7 @@ include::{docs-java}/features/testing/utilities/testpropertyvalues/MyEnvironment `OutputCapture` is a JUnit `Extension` that you can use to capture `System.out` and `System.err` output. To use add `@ExtendWith(OutputCaptureExtension.class)` and inject `CapturedOutput` as an argument to your test class constructor or test method as follows: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/testing/utilities/outputcapture/MyOutputCaptureTests.java[] ----- +include::code:MyOutputCaptureTests[] @@ -1036,16 +889,10 @@ If you do use Apache's HTTP client, some additional test-friendly features are e `TestRestTemplate` can be instantiated directly in your integration tests, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/testing/utilities/testresttemplate/MyTests.java[] ----- +include::code:MyTests[] 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,subs="verbatim"] ----- -include::{docs-java}/features/testing/utilities/testresttemplate/MySpringBootTests.java[] ----- +include::code:MySpringBootTests[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-started/first-application.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-started/first-application.adoc index 8a1ae97b35..c77a2ead8d 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-started/first-application.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-started/first-application.adoc @@ -137,10 +137,7 @@ If you run `mvn dependency:tree` again, you see that there are now a number of a 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 directory structure and then add a file named `src/main/java/MyApplication.java` to contain the following code: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/gettingstarted/firstapplication/code/MyApplication.java[] ----- +include::code:MyApplication[] Although there is not much code here, quite a lot is going on. We step through the important parts in the next few sections. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/actuator.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/actuator.adoc index 0ef8dbb66e..faedaa128d 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/actuator.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/actuator.adoc @@ -67,7 +67,4 @@ To export these, you will need to convert these states to some set of numbers so The following example shows one way to write such an exporter: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/actuator/maphealthindicatorstometrics/MyHealthMetricsExportConfiguration.java[] ----- +include::code:MyHealthMetricsExportConfiguration[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/application.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/application.adoc index 8cab241281..6388647788 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/application.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/application.adoc @@ -78,10 +78,7 @@ Each implementation should be registered in `META-INF/spring.factories`, as show The implementation can load arbitrary files and add them to the `Environment`. For instance, the following example loads a YAML configuration file from the classpath: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/application/customizetheenvironmentorapplicationcontext/MyEnvironmentPostProcessor.java[] ----- +include::code:MyEnvironmentPostProcessor[] TIP: The `Environment` has already been prepared with all the usual property sources that Spring Boot loads by default. It is therefore possible to get the location of the file from the environment. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/data-access.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/data-access.adoc index aba5336884..598af73f67 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/data-access.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/data-access.adoc @@ -13,10 +13,7 @@ If you need to externalize some settings, you can bind your `DataSource` to the The following example shows how to define a data source in a bean: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/dataaccess/configurecustomdatasource/custom/MyDataSourceConfiguration.java[] ----- +include::code:custom/MyDataSourceConfiguration[] The following example shows how to define a data source by setting properties: @@ -37,10 +34,7 @@ It also auto-detects the driver based on the JDBC URL. The following example shows how to create a data source by using a `DataSourceBuilder`: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/dataaccess/configurecustomdatasource/builder/MyDataSourceConfiguration.java[] ----- +include::code:builder/MyDataSourceConfiguration[] To run an app with that `DataSource`, all you need is the connection information. Pool-specific settings can also be provided. @@ -78,20 +72,14 @@ You cannot change the implementation at runtime, but the list of options will be The following example shows how create a `HikariDataSource` with `DataSourceBuilder`: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/dataaccess/configurecustomdatasource/simple/MyDataSourceConfiguration.java[] ----- +include::code:simple/MyDataSourceConfiguration[] You can even go further by leveraging what `DataSourceProperties` does for you -- that is, by providing a default embedded database with a sensible username and password if no URL is provided. You can easily initialize a `DataSourceBuilder` from the state of any `DataSourceProperties` object, so you could also inject the DataSource that Spring Boot creates automatically. However, that would split your configuration into two namespaces: `url`, `username`, `password`, `type`, and `driver` on `spring.datasource` and the rest on your custom namespace (`app.datasource`). To avoid that, you can redefine a custom `DataSourceProperties` on your custom namespace, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/dataaccess/configurecustomdatasource/configurable/MyDataSourceConfiguration.java[] ----- +include::code:configurable/MyDataSourceConfiguration[] This setup puts you _in sync_ with what Spring Boot does for you by default, except that a dedicated connection pool is chosen (in code) and its settings are exposed in the `app.datasource.configuration` sub namespace. Because `DataSourceProperties` is taking care of the `url`/`jdbcUrl` translation for you, you can configure it as follows: @@ -125,10 +113,7 @@ You must, however, mark one of the `DataSource` instances as `@Primary`, because If you create your own `DataSource`, the auto-configuration backs off. In the following example, we provide the _exact_ same feature set as the auto-configuration provides on the primary data source: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/dataaccess/configuretwodatasources/MyDataSourcesConfiguration.java[] ----- +include::code:MyDataSourcesConfiguration[] TIP: `firstDataSourceProperties` has to be flagged as `@Primary` so that the database initializer feature uses your copy (if you use the initializer). @@ -155,10 +140,7 @@ For instance, you could configure them as follows: You can apply the same concept to the secondary `DataSource` as well, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/dataaccess/configuretwodatasources/MyCompleteDataSourcesConfiguration.java[] ----- +include::code:MyCompleteDataSourcesConfiguration[] The preceding example configures two data sources on custom namespaces with the same logic as Spring Boot would use in auto-configuration. Note that each `configuration` sub namespace provides advanced settings based on the chosen implementation. @@ -186,10 +168,7 @@ For more about Spring Data, see the {spring-data}[Spring Data project page]. Spring Boot tries to guess the location of your `@Entity` definitions, based on the `@EnableAutoConfiguration` it finds. To get more control, you can use the `@EntityScan` annotation, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/dataaccess/separateentitydefinitionsfromspringconfiguration/MyApplication.java[] ----- +include::code:MyApplication[] @@ -242,10 +221,7 @@ Alternatively, if `ImplicitNamingStrategy` or `PhysicalNamingStrategy` beans are By default, Spring Boot configures the physical naming strategy with `SpringPhysicalNamingStrategy`. This implementation provides the same table structure as Hibernate 4: all dots are replaced by underscores and camel casing is replaced by underscores as well. Additionally, by default, all table names are generated in lower case. For example, a `TelephoneNumber` entity is mapped to the `telephone_number` table. If your schema requires mixed-case identifiers, define a custom `SpringPhysicalNamingStrategy` bean, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/dataaccess/configurehibernatenamingstrategy/spring/MyHibernateConfiguration.java[] ----- +include::code:spring/MyHibernateConfiguration[] If you prefer to use Hibernate 5's default instead, set the following property: @@ -256,10 +232,7 @@ If you prefer to use Hibernate 5's default instead, set the following property: Alternatively, you can configure the following bean: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/dataaccess/configurehibernatenamingstrategy/standard/MyHibernateConfiguration.java[] ----- +include::code:standard/MyHibernateConfiguration[] See {spring-boot-autoconfigure-module-code}/orm/jpa/HibernateJpaAutoConfiguration.java[`HibernateJpaAutoConfiguration`] and {spring-boot-autoconfigure-module-code}/orm/jpa/JpaBaseConfiguration.java[`JpaBaseConfiguration`] for more details. @@ -273,10 +246,7 @@ Rather than configuring Hibernate to lookup the cache provider again, it is bett To do this with JCache, first make sure that `org.hibernate:hibernate-jcache` is available on the classpath. Then, add a `HibernatePropertiesCustomizer` bean as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/dataaccess/configurehibernatesecondlevelcaching/MyHibernateSecondLevelCacheConfiguration.java[] ----- +include::code:MyHibernateSecondLevelCacheConfiguration[] This customizer will configure Hibernate to use the same `CacheManager` as the one that the application uses. It is also possible to use separate `CacheManager` instances. @@ -306,10 +276,7 @@ If you need to use JPA against multiple data sources, you likely need one `Entit The `LocalContainerEntityManagerFactoryBean` from Spring ORM allows you to configure an `EntityManagerFactory` for your needs. You can also reuse `JpaProperties` to bind settings for each `EntityManagerFactory`, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/dataaccess/usemultipleentitymanagers/MyEntityManagerFactoryConfiguration.java[] ----- +include::code:MyEntityManagerFactoryConfiguration[] The example above creates an `EntityManagerFactory` using a `DataSource` bean named `firstDataSource`. It scans entities located in the same package as `Order`. @@ -325,15 +292,9 @@ Alternatively, you might be able to use a JTA transaction manager that spans bot If you use Spring Data, you need to configure `@EnableJpaRepositories` accordingly, as shown in the following examples: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/dataaccess/usemultipleentitymanagers/OrderConfiguration.java[] ----- +include::code:OrderConfiguration[] -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/dataaccess/usemultipleentitymanagers/CustomerConfiguration.java[] ----- +include::code:CustomerConfiguration[] @@ -390,10 +351,7 @@ For example, when Flyway is auto-configured, Hibernate is configured to depend u If you are configuring a component yourself, you can use an `EntityManagerFactoryDependsOnPostProcessor` subclass as a convenient way of setting up the necessary dependencies. For example, if you use Hibernate Search with Elasticsearch as its index manager, any `EntityManagerFactory` beans must be configured to depend on the `elasticsearchClient` bean, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/dataaccess/configureacomponentthatisusedbyjpa/ElasticsearchEntityManagerFactoryDependsOnPostProcessor.java[] ----- +include::code:ElasticsearchEntityManagerFactoryDependsOnPostProcessor[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/http-clients.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/http-clients.adoc index 36a335975b..7d809dc9d9 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/http-clients.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/http-clients.adoc @@ -20,10 +20,7 @@ When Reactor Netty is on the classpath a Reactor Netty-based `WebClient` is auto To customize the client's handling of network connections, provide a `ClientHttpConnector` bean. The following example configures a 60 second connect timeout and adds a `ReadTimeoutHandler`: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/httpclients/webclientreactornettycustomization/MyReactorNettyClientConfiguration.java[] ----- +include::code:MyReactorNettyClientConfiguration[] TIP: Note the use of `ReactorResourceFactory` for the connection provider and event loop resources. This ensures efficient sharing of resources for the server receiving requests and the client making requests. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/jersey.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/jersey.adoc index ff1246e543..ed5dbf6b12 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/jersey.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/jersey.adoc @@ -11,10 +11,7 @@ This prevents Jersey from committing the response before Spring Security has had The `jersey.config.server.response.setStatusOverSendError` property must be set to `true` on the application's `ResourceConfig` bean, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/jersey/springsecurity/JerseySetStatusOverSendErrorConfig.java[] ----- +include::code:JerseySetStatusOverSendErrorConfig[] @@ -24,7 +21,4 @@ To use Jersey alongside another web framework, such as Spring MVC, it should be First, configure Jersey to use a filter rather than a servlet by configuring the configprop:spring.jersey.type[] application property with a value of `filter`. Second, configure your `ResourceConfig` to forward requests that would have resulted in a 404, as shown in the following example. -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/jersey/alongsideanotherwebframework/JerseyConfig.java[] ----- +include::code:JerseyConfig[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/messaging.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/messaging.adoc index 1b3c5920af..b0e8b91707 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/messaging.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/messaging.adoc @@ -11,9 +11,6 @@ If your JMS broker does not support transacted sessions, you have to disable the If you create your own `JmsListenerContainerFactory`, there is nothing to do, since, by default it cannot be transacted. If you want to use the `DefaultJmsListenerContainerFactoryConfigurer` to reuse Spring Boot's default, you can disable transacted sessions, as follows: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/messaging/disabletransactedjmssession/MyJmsConfiguration.java[] ----- +include::code:MyJmsConfiguration[] The preceding example overrides the default factory, and it should be applied to any other factory that your application defines, if any. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/properties-and-configuration.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/properties-and-configuration.adoc index cd1be837a0..ccd7dfe10f 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/properties-and-configuration.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/properties-and-configuration.adoc @@ -110,17 +110,11 @@ Then the Spring Boot banner is not printed on startup, and the application is no Properties defined in external configuration override and replace the values specified with the Java API, with the notable exception of the primary sources. Primary sources are those provided to the `SpringApplication` constructor: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/propertiesandconfiguration/externalizeconfiguration/application/MyApplication.java[] ----- +include::code:application/MyApplication[] Or to `sources(...)` method of a `SpringApplicationBuilder`: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/propertiesandconfiguration/externalizeconfiguration/builder/MyApplication.java[] ----- +include::code:builder/MyApplication[] Given the examples above, if we have the following configuration: diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/security.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/security.adoc index adf2c75d57..d143ddad44 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/security.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/security.adoc @@ -42,7 +42,4 @@ Alternatively, you can add the `RemoteIpValve` by customizing the `TomcatServlet To configure Spring Security to require a secure channel for all (or some) requests, consider adding your own `SecurityFilterChain` bean that adds the following `HttpSecurity` configuration: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/security/enablehttps/MySecurityConfig.java[] ----- +include::code:MySecurityConfig[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/spring-mvc.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/spring-mvc.adoc index febe30cf00..e24a6a6606 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/spring-mvc.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/spring-mvc.adoc @@ -10,10 +10,7 @@ This section answers common questions about Spring MVC and Spring Boot. === Write a JSON REST Service Any Spring `@RestController` in a Spring Boot application should render JSON response by default as long as Jackson2 is on the classpath, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/springmvc/writejsonrestservice/MyController.java[] ----- +include::code:MyController[] As long as `MyThing` can be serialized by Jackson2 (true for a normal POJO or Groovy object), then `http://localhost:8080/thing` serves a JSON representation of it by default. Note that, in a browser, you might sometimes see XML responses, because browsers tend to send accept headers that prefer XML. @@ -36,10 +33,7 @@ To use the Jackson XML renderer, add the following dependency to your project: If Jackson's XML extension is not available and JAXB is available, XML can be rendered with the additional requirement of having `MyThing` annotated as `@XmlRootElement`, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/springmvc/writexmlrestservice/MyThing.java[] ----- +include::code:MyThing[] JAXB is only available out of the box with Java 8. If you use a more recent Java generation, add the following dependency to your project: diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/testing.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/testing.adoc index ef00e0c74f..95da6a65b4 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/testing.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/testing.adoc @@ -10,10 +10,7 @@ This section answers common questions about testing. Spring Security provides support for running tests as a specific user. For example, the test in the snippet below will run with an authenticated user that has the `ADMIN` role. -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/testing/withspringsecurity/MySecurityTests.java[] ----- +include::code:MySecurityTests[] Spring Security provides comprehensive integration with Spring MVC Test and this can also be used when testing controllers using the `@WebMvcTest` slice and `MockMvc`. @@ -29,19 +26,13 @@ It integrates with JUnit, allowing you to write a test class that can start up a Testcontainers is especially useful for writing integration tests that talk to a real backend service such as MySQL, MongoDB, Cassandra and others. Testcontainers can be used in a Spring Boot test as follows: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/testing/testcontainers/vanilla/MyIntegrationTests.java[] ----- +include::code:vanilla/MyIntegrationTests[] This will start up a docker container running Neo4j (if Docker is running locally) before any of the tests are run. In most cases, you will need to configure the application using details from the running container, such as container IP or port. This can be done with a static `@DynamicPropertySource` method that allows adding dynamic property values to the Spring Environment. -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/testing/testcontainers/dynamicproperties/MyIntegrationTests.java[] ----- +include::code:dynamicproperties/MyIntegrationTests[] The above configuration allows Neo4j-related beans in the application to communicate with Neo4j running inside the Testcontainers-managed Docker container. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/traditional-deployment.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/traditional-deployment.adoc index cc63b6423c..a9a29e7c59 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/traditional-deployment.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/traditional-deployment.adoc @@ -14,10 +14,7 @@ The first step in producing a deployable war file is to provide a `SpringBootSer Doing so makes use of Spring Framework's servlet 3.0 support and lets you configure your application when it is launched by the servlet container. Typically, you should update your application's main class to extend `SpringBootServletInitializer`, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/traditionaldeployment/war/MyApplication.java[] ----- +include::code:MyApplication[] The next step is to update your build configuration such that your project produces a war file rather than a jar file. If you use Maven and `spring-boot-starter-parent` (which configures Maven's war plugin for you), all you need to do is to modify `pom.xml` to change the packaging to war, as follows: @@ -79,10 +76,7 @@ See the https://spring.io/guides/gs/convert-jar-to-war/[Getting Started Guide on To create a deployable war by extending `SpringBootServletInitializer` (for example, in a class called `Application`) and adding the Spring Boot `@SpringBootApplication` annotation, use code similar to that shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/traditionaldeployment/convertexistingapplication/MyApplication.java[tag=!main] ----- +include::code:MyApplication[tag=!main] Remember that, whatever you put in the `sources` is merely a Spring `ApplicationContext`. Normally, anything that already works should work here. @@ -101,19 +95,13 @@ If you have other features in your application (for instance, using other servle Once the war file is working, you can make it executable by adding a `main` method to your `Application`, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/traditionaldeployment/convertexistingapplication/MyApplication.java[tag=main] ----- +include::code:MyApplication[tag=main] [NOTE] ==== If you intend to start your application as a war or as an executable application, you need to share the customizations of the builder in a method that is both available to the `SpringBootServletInitializer` callback and in the `main` method in a class similar to the following: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/traditionaldeployment/convertexistingapplication/both/MyApplication.java[] ----- +include::code:both/MyApplication[] ==== Applications can fall into more than one category: @@ -144,10 +132,7 @@ To deploy a Spring Boot application to WebLogic, you must ensure that your servl A typical initializer for WebLogic should resemble the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/traditionaldeployment/weblogic/MyApplication.java[] ----- +include::code:MyApplication[] If you use Logback, you also need to tell WebLogic to prefer the packaged version rather than the version that was pre-installed with the server. You can do so by adding a `WEB-INF/weblogic.xml` file with the following contents: diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/webserver.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/webserver.adoc index 2451976a78..8850d4d23f 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/webserver.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/webserver.adoc @@ -101,10 +101,7 @@ The best way to get that and be sure it has been initialized is to add a `@Bean` Tests that use `@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)` can also inject the actual port into a field by using the `@LocalServerPort` annotation, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/webserver/discoverport/MyWebIntegrationTests.java[] ----- +include::code:MyWebIntegrationTests[] [NOTE] ==== @@ -244,10 +241,7 @@ You can declare such a component and get access to the server factory relevant t The example below is for Tomcat with the `spring-boot-starter-web` (servlet stack): -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/webserver/configure/MyTomcatWebServerCustomizer.java[] ----- +include::code:MyTomcatWebServerCustomizer[] NOTE: Spring Boot uses that infrastructure internally to auto-configure the server. Auto-configured `WebServerFactoryCustomizer` beans have an order of `0` and will be processed before any user-defined customizers, unless it has an explicit order that states otherwise. @@ -317,10 +311,7 @@ Like any other Spring bean, you can define the order of servlet filter beans; pl As <>, any `Servlet` or `Filter` beans are registered with the servlet container automatically. To disable registration of a particular `Filter` or `Servlet` bean, create a registration bean for it and mark it as disabled, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/webserver/addservletfilterlistener/springbean/disable/MyFilterConfiguration.java[] ----- +include::code:MyFilterConfiguration[] @@ -439,10 +430,7 @@ You can take complete control of the configuration of Tomcat's `RemoteIpValve` b === Enable Multiple Connectors with Tomcat You can add an `org.apache.catalina.connector.Connector` to the `TomcatServletWebServerFactory`, which can allow multiple connectors, including HTTP and HTTPS connectors, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/webserver/enablemultipleconnectorsintomcat/MyTomcatConfiguration.java[] ----- +include::code:MyTomcatConfiguration[] @@ -459,10 +447,7 @@ If at all possible, you should consider updating your code to only store values If, however, you cannot change the way that cookies are written, you can instead configure Tomcat to use a `LegacyCookieProcessor`. To switch to the `LegacyCookieProcessor`, use an `WebServerFactoryCustomizer` bean that adds a `TomcatContextCustomizer`, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/webserver/usetomcatlegacycookieprocessor/MyLegacyCookieProcessorConfiguration.java[] ----- +include::code:MyLegacyCookieProcessorConfiguration[] @@ -486,10 +471,7 @@ server: === Enable Multiple Listeners with Undertow Add an `UndertowBuilderCustomizer` to the `UndertowServletWebServerFactory` and add a listener to the `Builder`, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/webserver/enablemultiplelistenersinundertow/MyUndertowConfiguration.java[] ----- +include::code:MyUndertowConfiguration[] @@ -497,10 +479,7 @@ include::{docs-java}/howto/webserver/enablemultiplelistenersinundertow/MyUnderto === Create WebSocket Endpoints Using @ServerEndpoint If you want to use `@ServerEndpoint` in a Spring Boot application that used an embedded container, you must declare a single `ServerEndpointExporter` `@Bean`, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/webserver/createwebsocketendpointsusingserverendpoint/MyWebSocketConfiguration.java[] ----- +include::code:MyWebSocketConfiguration[] The bean shown in the preceding example registers any `@ServerEndpoint` annotated beans with the underlying WebSocket container. When deployed to a standalone servlet container, this role is performed by a servlet container initializer, and the `ServerEndpointExporter` bean is not required. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/caching.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/caching.adoc index 28aa2d2985..0de2bb1b38 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/caching.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/caching.adoc @@ -9,10 +9,7 @@ NOTE: Check the {spring-framework-docs}/integration.html#cache[relevant section] In a nutshell, to add caching to an operation of your service add the relevant annotation to its method, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/io/caching/MyMathService.java[] ----- +include::code:MyMathService[] 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. @@ -59,10 +56,7 @@ If you add dependencies manually, you must include `spring-context-support` in o 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 not be passed down to the underlying map: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/io/caching/provider/MyCacheManagerConfiguration.java[] ----- +include::code:MyCacheManagerConfiguration[] 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. @@ -175,10 +169,7 @@ For instance, the following configuration creates `cache1` and `cache2` caches w If you need more control over the configuration, consider registering a `CouchbaseCacheManagerBuilderCustomizer` bean. The following example shows a customizer that configures a specific entry expiration for `cache1` and `cache2`: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/io/caching/provider/couchbase/MyCouchbaseCacheManagerConfiguration.java[] ----- +include::code:MyCouchbaseCacheManagerConfiguration[] @@ -206,10 +197,7 @@ This can be useful if you need to customize the default serialization strategy. If you need more control over the configuration, consider registering a `RedisCacheManagerBuilderCustomizer` bean. The following example shows a customizer that configures a specific time to live for `cache1` and `cache2`: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/io/caching/provider/redis/MyRedisCacheManagerConfiguration.java[] ----- +include::code:MyRedisCacheManagerConfiguration[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/jta.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/jta.adoc index 29cdc2779d..4007947d79 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/jta.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/jta.adoc @@ -41,27 +41,18 @@ Spring Boot tries to auto-configure JMS by looking for a `ConnectionFactory` at When using JTA, the primary JMS `ConnectionFactory` bean is XA-aware and participates in distributed transactions. You can inject into your bean without needing to use any `@Qualifier`: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/io/jta/mixingxaandnonxaconnections/primary/MyBean.java[tag=*] ----- +include::code:primary/MyBean[tag=*] 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 the `nonXaJmsConnectionFactory` bean: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/io/jta/mixingxaandnonxaconnections/nonxa/MyBean.java[tag=*] ----- +include::code:nonxa/MyBean[tag=*] For consistency, the `jmsConnectionFactory` bean is also provided by using the bean alias `xaJmsConnectionFactory`: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/io/jta/mixingxaandnonxaconnections/xa/MyBean.java[tag=*] ----- +include::code:xa/MyBean[tag=*] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/quartz.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/quartz.adoc index 052342c34e..285d826d63 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/quartz.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/quartz.adoc @@ -50,7 +50,4 @@ If you need to customize the task executor, consider implementing `SchedulerFact 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,subs="verbatim"] ----- -include::{docs-java}/io/quartz/MySampleJob.java[] ----- +include::code:MySampleJob[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/rest-client.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/rest-client.adoc index a8cc35099a..bf6ffd59d6 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/rest-client.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/rest-client.adoc @@ -11,10 +11,7 @@ The auto-configured `RestTemplateBuilder` ensures that sensible `HttpMessageConv The following code shows a typical example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/io/restclient/resttemplate/MyService.java[] ----- +include::code:MyService[] 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()`. @@ -33,20 +30,14 @@ All such beans are automatically registered with the auto-configured `RestTempla 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,subs="verbatim"] ----- -include::{docs-java}/io/restclient/resttemplate/customization/MyRestTemplateCustomizer.java[] ----- +include::code:MyRestTemplateCustomizer[] Finally, you can define your own `RestTemplateBuilder` bean. Doing so will replace the auto-configured builder. If you want any `RestTemplateCustomizer` beans to be applied to your custom builder, as the auto-configuration would have done, configure it using a `RestTemplateBuilderConfigurer`. The following example exposes a `RestTemplateBuilder` that matches what Spring Boot's auto-configuration would have done, except that custom connect and read timeouts are also specified: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/io/restclient/resttemplate/customization/MyRestTemplateBuilderConfiguration.java[] ----- +include::code:MyRestTemplateBuilderConfiguration[] The most extreme (and rarely used) option is to create your own `RestTemplateBuilder` bean without using a configurer. In addition to replacing the auto-configured builder, this also prevents any `RestTemplateCustomizer` beans from being used. @@ -65,10 +56,7 @@ Spring Boot is configuring that builder to share HTTP resources, reflect codecs The following code shows a typical example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/io/restclient/webclient/MyService.java[] ----- +include::code:MyService[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/validation.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/validation.adoc index 50781c2371..f9561871b8 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/validation.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/validation.adoc @@ -6,10 +6,7 @@ Target classes with such annotated methods need to be annotated with the `@Valid 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,subs="verbatim"] ----- -include::{docs-java}/io/validation/MyBean.java[] ----- +include::code:MyBean[] The application's `MessageSource` is used when resolving `+{parameters}+` in constraint messages. This allows you to use <> for Bean Validation messages. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/webservices.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/webservices.adoc index ebf080fb3f..04b9e5fce2 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/webservices.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/webservices.adoc @@ -25,15 +25,9 @@ It does, however, auto-configure a `WebServiceTemplateBuilder`, which can be use The following code shows a typical example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/io/webservices/template/MyService.java[] ----- +include::code:MyService[] 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,subs="verbatim"] ----- -include::{docs-java}/io/webservices/template/MyWebServiceTemplateConfiguration.java[] ----- +include::code:MyWebServiceTemplateConfiguration[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/whats-next.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/whats-next.adoc index 8c7ccefb26..2a6434165c 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/whats-next.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/whats-next.adoc @@ -3,4 +3,4 @@ You should now have a good understanding of Spring Boot's <> and the various technologies that Spring Boot provides support for via auto-configuration. The next few sections go into detail about deploying applications to cloud platforms. -You can read about <> in the next section or skip to the <> section. \ No newline at end of file +You can read about <> in the next section or skip to the <> section. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/amqp.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/amqp.adoc index 8033e54c05..3eb7b20669 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/amqp.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/amqp.adoc @@ -49,10 +49,7 @@ TIP: See https://spring.io/blog/2010/06/14/understanding-amqp-the-protocol-used- === 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,subs="verbatim"] ----- -include::{docs-java}/messaging/amqp/sending/MyBean.java[] ----- +include::code:MyBean[] NOTE: {spring-amqp-api}/rabbit/core/RabbitMessagingTemplate.html[`RabbitMessagingTemplate`] can be injected in a similar manner. If a `MessageConverter` bean is defined, it is associated automatically to the auto-configured `AmqpTemplate`. @@ -104,10 +101,7 @@ If a `MessageConverter` or a `MessageRecoverer` bean is defined, it is automatic The following sample component creates a listener endpoint on the `someQueue` queue: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/messaging/amqp/receiving/MyBean.java[] ----- +include::code:MyBean[] TIP: See {spring-amqp-api}/rabbit/annotation/EnableRabbit.html[the Javadoc of `@EnableRabbit`] for more details. @@ -118,17 +112,11 @@ 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,subs="verbatim"] ----- -include::{docs-java}/messaging/amqp/receiving/custom/MyRabbitConfiguration.java[] ----- +include::code:custom/MyRabbitConfiguration[] Then you can use the factory in any `@RabbitListener`-annotated method, as follows: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/messaging/amqp/receiving/custom/MyBean.java[] ----- +include::code:custom/MyBean[] 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. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/jms.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/jms.adoc index 7ef7bf19a7..7cbeb8444d 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/jms.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/jms.adoc @@ -140,10 +140,7 @@ You can use the configprop:spring.jms.jndi-name[] property if you need to specif === 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,subs="verbatim"] ----- -include::{docs-java}/messaging/jms/sending/MyBean.java[] ----- +include::code:MyBean[] NOTE: {spring-framework-api}/jms/core/JmsMessagingTemplate.html[`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`. @@ -165,10 +162,7 @@ This also includes sending response messages that have been performed on the sam The following component creates a listener endpoint on the `someQueue` destination: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/messaging/jms/receiving/MyBean.java[] ----- +include::code:MyBean[] TIP: See {spring-framework-api}/jms/annotation/EnableJms.html[the Javadoc of `@EnableJms`] for more details. @@ -176,14 +170,8 @@ If you need to create more `JmsListenerContainerFactory` instances or if you wan For instance, the following example exposes another factory that uses a specific `MessageConverter`: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/messaging/jms/receiving/custom/MyJmsConfiguration.java[] ----- +include::code:custom/MyJmsConfiguration[] Then you can use the factory in any `@JmsListener`-annotated method as follows: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/messaging/jms/receiving/custom/MyBean.java[] ----- +include::code:custom/MyBean[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/kafka.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/kafka.adoc index 0467257565..0f9b319377 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/kafka.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/kafka.adoc @@ -25,10 +25,7 @@ See {spring-boot-autoconfigure-module-code}/kafka/KafkaProperties.java[`KafkaPro === 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,subs="verbatim"] ----- -include::{docs-java}/messaging/kafka/sending/MyBean.java[] ----- +include::code:MyBean[] NOTE: If the property configprop: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`. @@ -42,10 +39,7 @@ If no `KafkaListenerContainerFactory` has been defined, a default one is automat The following component creates a listener endpoint on the `someTopic` topic: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/messaging/kafka/receiving/MyBean.java[] ----- +include::code:MyBean[] If a `KafkaTransactionManager` bean is defined, it is automatically associated to the container factory. Similarly, if a `RecordFilterStrategy`, `ErrorHandler`, `CommonErrorHandler`, `AfterRollbackProcessor` or `ConsumerAwareRebalanceListener` bean is defined, it is automatically associated to the default factory. @@ -71,10 +65,7 @@ See also <> for more information To use the factory bean, wire `StreamsBuilder` into your `@Bean` as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/messaging/kafka/streams/MyKafkaStreamsConfiguration.java[] ----- +include::code:MyKafkaStreamsConfiguration[] By default, the streams managed by the `StreamBuilder` object it creates are started automatically. You can customize this behavior using the configprop:spring.kafka.streams.auto-startup[] property. @@ -156,17 +147,11 @@ There are several ways to do that: * Provide a system property to map embedded broker addresses into configprop:spring.kafka.bootstrap-servers[] in the test class: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/messaging/kafka/embedded/property/MyTest.java[tag=*] ----- +include::code:property/MyTest[tag=*] * Configure a property name on the `@EmbeddedKafka` annotation: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/messaging/kafka/embedded/annotation/MyTest.java[] ----- +include::code:annotation/MyTest[] * Use a placeholder in configuration properties: diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/rsocket.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/rsocket.adoc index 1fb71f22be..e29a3e8270 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/rsocket.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/rsocket.adoc @@ -80,7 +80,4 @@ This is done on purpose since this builder is stateful and you should not create The following code shows a typical example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/messaging/rsocket/requester/MyService.java[] ----- +include::code:MyService[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/whats-next.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/whats-next.adoc index 0a285e0421..36841ba1a1 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/whats-next.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/whats-next.adoc @@ -1,4 +1,4 @@ [[messaging.whats-next]] == What to Read Next The next section describes how to enable <> in your application. -You can read about <>, <>, <>, <> and more in this section. \ No newline at end of file +You can read about <>, <>, <>, <> and more in this section. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading.adoc index 305da05330..1292c64da3 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading.adoc @@ -14,4 +14,4 @@ include::upgrading/to-feature.adoc[] include::upgrading/cli.adoc[] -include::upgrading/whats-next.adoc[] \ No newline at end of file +include::upgrading/whats-next.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading/cli.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading/cli.adoc index 692c238105..b6b3ea2026 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading/cli.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading/cli.adoc @@ -2,4 +2,4 @@ == Upgrading the Spring Boot CLI To upgrade an existing CLI installation, use the appropriate package manager command (for example, `brew upgrade`). -If you manually installed the CLI, follow the <>, remembering to update your `PATH` environment variable to remove any older references. \ No newline at end of file +If you manually installed the CLI, follow the <>, remembering to update your `PATH` environment variable to remove any older references. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading/from-1x.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading/from-1x.adoc index 10b440cac8..f57c9f0862 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading/from-1x.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading/from-1x.adoc @@ -2,4 +2,4 @@ == Upgrading from 1.x If you are upgrading from the `1.x` 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. \ No newline at end of file +Check also the {github-wiki}["`release notes`"] for a list of "`new and noteworthy`" features for each release. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading/whats-next.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading/whats-next.adoc index 5f377b9341..ff0bd6e768 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading/whats-next.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading/whats-next.adoc @@ -2,4 +2,4 @@ == What to Read Next Once you've decided to upgrade your application, you can find detailed information regarding specific features in the rest of the document. -Spring Boot's documentation is specific to that version, so any information that you find in here will contain the most up-to-date changes that are in that version. \ No newline at end of file +Spring Boot's documentation is specific to that version, so any information that you find in here will contain the most up-to-date changes that are in that version. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/auto-configuration.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/auto-configuration.adoc index d96ad65421..c11c9b9504 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/auto-configuration.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/auto-configuration.adoc @@ -25,10 +25,7 @@ Doing so enables debug logs for a selection of core loggers and logs a condition === 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 `@SpringBootApplication` to disable them, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/using/autoconfiguration/disablingspecific/MyApplication.java[] ----- +include::code:MyApplication[] If the class is not on the classpath, you can use the `excludeName` attribute of the annotation and specify the fully qualified name instead. If you prefer to use `@EnableAutoConfiguration` rather than `@SpringBootApplication`, `exclude` and `excludeName` are also available. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/devtools.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/devtools.adoc index eab4a3509b..e32eed8072 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/devtools.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/devtools.adoc @@ -178,10 +178,7 @@ In most cases, you can set this property in your `application.properties` (doing If you need to _completely_ disable restart support (for example, because it does not work with a specific library), you need to set the configprop:spring.devtools.restart.enabled[] `System` property to `false` before calling `SpringApplication.run(...)`, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/using/devtools/restart/disable/MyApplication.java[] ----- +include::code:MyApplication[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/spring-beans-and-dependency-injection.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/spring-beans-and-dependency-injection.adoc index 3ef36daebd..d96903bee3 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/spring-beans-and-dependency-injection.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/spring-beans-and-dependency-injection.adoc @@ -8,16 +8,10 @@ All of your application components (`@Component`, `@Service`, `@Repository`, `@C The following example shows a `@Service` Bean that uses constructor injection to obtain a required `RiskAssessor` bean: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/using/springbeansanddependencyinjection/singleconstructor/MyAccountService.java[] ----- +include::code:singleconstructor/MyAccountService[] If a bean has more than one constructor, you will need to mark the one you want Spring to use with `@Autowired`: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/using/springbeansanddependencyinjection/multipleconstructors/MyAccountService.java[] ----- +include::code:multipleconstructors/MyAccountService[] TIP: Notice how using constructor injection lets the `riskAssessor` field be marked as `final`, indicating that it cannot be subsequently changed. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/structuring-your-code.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/structuring-your-code.adoc index 1fcd5cde27..896651f205 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/structuring-your-code.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/structuring-your-code.adoc @@ -48,7 +48,4 @@ The following listing shows a typical layout: The `MyApplication.java` file would declare the `main` method, along with the basic `@SpringBootApplication`, as follows: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/using/structuringyourcode/locatingthemainclass/MyApplication.java[] ----- +include::code:MyApplication[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/using-the-springbootapplication-annotation.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/using-the-springbootapplication-annotation.adoc index f3edc3df12..04695f1b6c 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/using-the-springbootapplication-annotation.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/using-the-springbootapplication-annotation.adoc @@ -8,10 +8,7 @@ A single `@SpringBootApplication` annotation can be used to enable those three f * `@SpringBootConfiguration`: enable registration of extra beans in the context or the import of additional configuration classes. An alternative to Spring's standard `@Configuration` that aids <> in your integration tests. -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/using/usingthespringbootapplicationannotation/springapplication/MyApplication.java[] ----- +include::code:springapplication/MyApplication[] NOTE: `@SpringBootApplication` also provides aliases to customize the attributes of `@EnableAutoConfiguration` and `@ComponentScan`. @@ -20,10 +17,7 @@ NOTE: `@SpringBootApplication` also provides aliases to customize the attributes 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,subs="verbatim"] ----- -include::{docs-java}/using/usingthespringbootapplicationannotation/individualannotations/MyApplication.java[] ----- +include::code:individualannotations/MyApplication[] In this example, `MyApplication` 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`). ==== diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/reactive.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/reactive.adoc index cb66b692a2..2b646a53c4 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/reactive.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/reactive.adoc @@ -10,22 +10,13 @@ Unlike Spring MVC, it does not require the servlet API, is fully asynchronous an 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,subs="verbatim"] ----- -include::{docs-java}/web/reactive/webflux/MyRestController.java[] ----- +include::code:MyRestController[] "`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,subs="verbatim"] ----- -include::{docs-java}/web/reactive/webflux/MyRoutingConfiguration.java[] ----- +include::code:MyRoutingConfiguration[] -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/web/reactive/webflux/MyUserHandler.java[] ----- +include::code:MyUserHandler[] WebFlux is part of the Spring Framework and detailed information is available in its {spring-framework-docs}/web-reactive.html#webflux-fn[reference documentation]. @@ -41,15 +32,9 @@ You can still enforce your choice by setting the chosen application type to `Spr "`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,subs="verbatim"] ----- -include::{docs-java}/web/reactive/webflux/MyRoutingConfiguration.java[] ----- +include::code:MyRoutingConfiguration[] -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/web/reactive/webflux/MyUserHandler.java[] ----- +include::code:MyUserHandler[] WebFlux is part of the Spring Framework and detailed information is available in its {spring-framework-docs}/web-reactive.html#webflux-fn[reference documentation]. @@ -88,10 +73,7 @@ For example, `+spring.jackson.*+` configuration keys are applied to the Jackson 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,subs="verbatim"] ----- -include::{docs-java}/web/reactive/webflux/httpcodecs/MyCodecsConfiguration.java[] ----- +include::code:MyCodecsConfiguration[] You can also leverage <>. @@ -162,20 +144,14 @@ 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 `ErrorWebExceptionHandler` 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"] ----- -include::{docs-java}/web/reactive/webflux/errorhandling/MyErrorWebExceptionHandler.java[] ----- +include::code:MyErrorWebExceptionHandler[] For a more complete picture, you can also subclass `DefaultErrorWebExceptionHandler` directly and override specific methods. In some cases, errors handled at the controller or handler function level are not recorded by the <>. Applications can ensure that such exceptions are recorded with the request metrics by setting the handled exception as a request attribute: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/web/reactive/webflux/errorhandling/MyExceptionHandlingController.java[] ----- +include::code:MyExceptionHandlingController[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/servlet.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/servlet.adoc index 589b76ab91..f02609f159 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/servlet.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/servlet.adoc @@ -10,10 +10,7 @@ Methods in your controller are mapped to HTTP by using `@RequestMapping` annotat The following code shows a typical `@RestController` that serves JSON data: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/web/servlet/springmvc/MyRestController.java[] ----- +include::code:MyRestController[] Spring MVC is part of the core Spring Framework, and detailed information is available in the {spring-framework-docs}/web.html#mvc[reference documentation]. There are also several guides that cover Spring MVC available at https://spring.io/guides. @@ -60,10 +57,7 @@ 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,subs="verbatim"] ----- -include::{docs-java}/web/servlet/springmvc/messageconverters/MyHttpMessageConvertersConfiguration.java[] ----- +include::code:MyHttpMessageConvertersConfiguration[] 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. @@ -78,10 +72,7 @@ Custom serializers are usually https://github.com/FasterXML/jackson-docs/wiki/Ja 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,subs="verbatim"] ----- -include::{docs-java}/web/servlet/springmvc/json/MyJsonComponent.java[] ----- +include::code:MyJsonComponent[] All `@JsonComponent` beans in the `ApplicationContext` are automatically registered with Jackson. Because `@JsonComponent` is meta-annotated with `@Component`, the usual component-scanning rules apply. @@ -91,10 +82,7 @@ See {spring-boot-module-api}/jackson/JsonObjectSerializer.html[`JsonObjectSerial The example above can be rewritten to use `JsonObjectSerializer`/`JsonObjectDeserializer` as follows: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/web/servlet/springmvc/json/object/MyJsonComponent.java[] ----- +include::code:object/MyJsonComponent[] @@ -340,20 +328,14 @@ To do so, extend `BasicErrorController`, add a public method with a `@RequestMap 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"] ----- -include::{docs-java}/web/servlet/springmvc/errorhandling/MyControllerAdvice.java[] ----- +include::code:MyControllerAdvice[] In the preceding example, if `YourException` is thrown by a controller defined in the same package as `SomeController`, a JSON representation of the `CustomErrorType` POJO is used instead of the `ErrorAttributes` representation. In some cases, errors handled at the controller level are not recorded by the <>. Applications can ensure that such exceptions are recorded with the request metrics by setting the handled exception as a request attribute: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/web/servlet/springmvc/errorhandling/MyController.java[] ----- +include::code:MyController[] @@ -395,10 +377,7 @@ To map all `5xx` errors by using a FreeMarker template, your directory structure 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"] ----- -include::{docs-java}/web/servlet/springmvc/errorhandling/errorpages/MyErrorViewResolver.java[] ----- +include::code:MyErrorViewResolver[] You can also use regular Spring MVC features such as {spring-framework-docs}/web.html#mvc-exceptionhandlers[`@ExceptionHandler` methods] and {spring-framework-docs}/web.html#mvc-ann-controller-advice[`@ControllerAdvice`]. The `ErrorController` then picks up any unhandled exceptions. @@ -410,17 +389,11 @@ The `ErrorController` then picks up any unhandled exceptions. 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"] ----- -include::{docs-java}/web/servlet/springmvc/errorhandling/errorpageswithoutspringmvc/MyErrorPagesConfiguration.java[] ----- +include::code:MyErrorPagesConfiguration[] 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"] ----- -include::{docs-java}/web/servlet/springmvc/errorhandling/errorpageswithoutspringmvc/MyFilterConfiguration.java[] ----- +include::code:MyFilterConfiguration[] Note that the default `FilterRegistrationBean` does not include the `ERROR` dispatcher type. @@ -449,10 +422,7 @@ As of version 4.2, Spring MVC {spring-framework-docs}/web.html#mvc-cors[supports Using {spring-framework-docs}/web.html#mvc-cors-controller[controller method CORS configuration] with {spring-framework-api}/web/bind/annotation/CrossOrigin.html[`@CrossOrigin`] annotations in your Spring Boot application does not require any specific configuration. {spring-framework-docs}/web.html#mvc-cors-global[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,subs="verbatim"] ----- -include::{docs-java}/web/servlet/springmvc/cors/MyCorsConfiguration.java[] ----- +include::code:MyCorsConfiguration[] @@ -465,10 +435,7 @@ Jersey has some native Spring support, so we also provide auto-configuration sup 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"] ----- -include::{docs-java}/web/servlet/jersey/MyJerseyConfig.java[] ----- +include::code:MyJerseyConfig[] 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. @@ -478,10 +445,7 @@ For more advanced customizations, you can also register an arbitrary number of b 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"] ----- -include::{docs-java}/web/servlet/jersey/MyEndpoint.java[] ----- +include::code:MyEndpoint[] 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 `/*`. @@ -614,10 +578,7 @@ The `CookieSameSiteSupplier` is passed a `Cookie` and may return a `SameSite` va There are a number of convenience factory and filter methods that you can use to quickly match specific cookies. For example, adding the following bean will automatically apply a `SameSite` of `Lax` for all cookies with a name that matches the regular expression `myapp.*`. -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/web/servlet/embeddedcontainer/customizing/samesite/MySameSiteConfiguration.java[] ----- +include::code:MySameSiteConfiguration[] @@ -627,18 +588,12 @@ If you need to programmatically configure your embedded servlet container, you c `WebServerFactoryCustomizer` provides access to the `ConfigurableServletWebServerFactory`, which includes numerous customization setter methods. The following example shows programmatically setting the port: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/web/servlet/embeddedcontainer/customizing/programmatic/MyWebServerFactoryCustomizer.java[] ----- +include::code:MyWebServerFactoryCustomizer[] `TomcatServletWebServerFactory`, `JettyServletWebServerFactory` and `UndertowServletWebServerFactory` are dedicated variants of `ConfigurableServletWebServerFactory` that have additional customization setter methods for Tomcat, Jetty and Undertow respectively. The following example shows how to customize `TomcatServletWebServerFactory` that provides access to Tomcat-specific configuration options: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/web/servlet/embeddedcontainer/customizing/programmatic/MyTomcatWebServerFactoryCustomizer.java[] ----- +include::code:MyTomcatWebServerFactoryCustomizer[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-graphql.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-graphql.adoc index dc23080631..b71ec6de2c 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-graphql.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-graphql.adoc @@ -54,10 +54,7 @@ Typically, however, applications will not implement `DataFetcher` directly and w Spring Boot will automatically detect `@Controller` classes with annotated handler methods and register those as `DataFetcher`s. Here's a sample implementation for our greeting query with a `@Controller` class: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/web/graphql/runtimewiring/GreetingController.java[] ----- +include::code:GreetingController[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-security.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-security.adoc index 0a1ea2546e..afa678edff 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-security.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-security.adoc @@ -60,10 +60,7 @@ Spring Boot provides convenience methods that can be used to override access rul For example, you can customize your security configuration by adding something like: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/web/security/springwebflux/MyWebFluxSecurityConfiguration.java[] ----- +include::code:MyWebFluxSecurityConfiguration[] @@ -139,10 +136,7 @@ By default, Spring Security's `OAuth2LoginAuthenticationFilter` only processes U 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 `SecurityFilterChain` that resembles the following: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/web/security/oauth2/client/MyOAuthClientConfiguration.java[] ----- +include::code:MyOAuthClientConfiguration[] TIP: Spring Boot auto-configures an `InMemoryOAuth2AuthorizedClientService` which is used by Spring Security for the management of client registrations. The `InMemoryOAuth2AuthorizedClientService` has limited capabilities and we recommend using it only for development environments.