diff --git a/spring-boot-project/spring-boot-docs/src/main/asciidoc/build-tool-plugins.adoc b/spring-boot-project/spring-boot-docs/src/main/asciidoc/build-tool-plugins.adoc index 27454ec9b76..9b7d70cff32 100644 --- a/spring-boot-project/spring-boot-docs/src/main/asciidoc/build-tool-plugins.adoc +++ b/spring-boot-project/spring-boot-docs/src/main/asciidoc/build-tool-plugins.adoc @@ -67,8 +67,9 @@ as the original jar in the `target` directory: ---- -If you do not include the `` configuration as shown in the prior example, you -can run the plugin on its own (but only if the package goal is used as well). For example: +If you do not include the `` configuration, as shown in the prior example, you +can run the plugin on its own (but only if the package goal is used as well), as shown in +the following example: [indent=0] ---- @@ -78,7 +79,7 @@ can run the plugin on its own (but only if the package goal is used as well). Fo ---- If you use a milestone or snapshot release, you also need to add the appropriate -`pluginRepository` elements as shown in the following listing: +`pluginRepository` elements, as shown in the following listing: [source,xml,indent=0,subs="verbatim,attributes"] ---- @@ -115,7 +116,7 @@ the usual `packaging` element, as shown in the following example: ---- Your existing archive is enhanced by Spring Boot during the `package` phase. The main -class that you want to launch can either be specified by using a configuration option or +class that you want to launch can be specified either by using a configuration option or by adding a `Main-Class` attribute to the manifest in the usual way. If you do not specify a main class, the plugin searches for a class with a `public static void main(String[] args)` method. @@ -229,7 +230,7 @@ attributes are supported by the task: |`start-class` |The main application class to run -|No _(default is first class found declaring a `main` method)_ +|No _(the default is the first class found that declares a `main` method)_ |==== The following nested elements can be used with the task: @@ -252,6 +253,9 @@ of the application. ==== Examples + +This section shows two examples of Ant tasks. + .Specify +start-class+ [source,xml,indent=0] ---- @@ -280,7 +284,7 @@ of the application. [[spring-boot-ant-findmainclass]] === `spring-boot:findmainclass` The `findmainclass` task is used internally by `exejar` to locate a class declaring a -`main`. You can also use this task directly in your build, if needed. The following +`main`. If necessary, you can also use this task directly in your build. The following attributes are supported: [cols="1,2,2"] @@ -303,6 +307,9 @@ attributes are supported: ==== Examples + +This section contains three examples of using `findmainclass`. + .Find and log [source,xml,indent=0] ---- @@ -367,7 +374,7 @@ candidate is found. [[build-tool-plugins-repackage-implementation]] === Example Repackage Implementation -The following listing shows a typical example repackage: +The following example shows a typical repackage implementation: [source,java,indent=0] ---- diff --git a/spring-boot-project/spring-boot-docs/src/main/asciidoc/deployment.adoc b/spring-boot-project/spring-boot-docs/src/main/asciidoc/deployment.adoc index 9df1b0e26b7..eedcc820f4c 100644 --- a/spring-boot-project/spring-boot-docs/src/main/asciidoc/deployment.adoc +++ b/spring-boot-project/spring-boot-docs/src/main/asciidoc/deployment.adoc @@ -17,16 +17,16 @@ This section covers some of the more common deployment scenarios. Spring Boot's executable jars are ready-made for most popular cloud PaaS (Platform-as-a-Service) providers. These providers tend to require that you "`bring your own container`". They manage application processes (not Java applications -specifically), so they need some intermediary layer that adapts _your_ application to the +specifically), so they need an intermediary layer that adapts _your_ application to the _cloud's_ notion of a running process. Two popular cloud providers, Heroku and Cloud Foundry, employ a "`buildpack`" approach. -The buildpack wraps your deployed code in whatever is needed to _start_ your application: -it might be a JDK and a call to `java`, it might be an embedded web server, or it might be -a full-fledged application server. A buildpack is pluggable, but ideally you should be -able to get by with as few customizations to it as possible. This reduces the footprint of -functionality that is not under your control. It minimizes divergence between development -and production environments. +The buildpack wraps your deployed code in whatever is needed to _start_ your application. +It might be a JDK and a call to `java`, an embedded web server, or a full-fledged +application server. A buildpack is pluggable, but ideally you should be able to get by +with as few customizations to it as possible. This reduces the footprint of functionality +that is not under your control. It minimizes divergence between development and production +environments. Ideally, your application, like a Spring Boot executable jar, has everything that it needs to run packaged within it. @@ -148,7 +148,7 @@ extracts them and flattens the data into properties that can be accessed through All Cloud Foundry properties are prefixed with `vcap`. You can use `vcap` properties to access application information (such as the public URL of the application) and service -information (such as database credentials). See +information (such as database credentials). See the {dc-spring-boot}/cloud/CloudFoundryVcapEnvironmentPostProcessor.html['`CloudFoundryVcapEnvironmentPostProcessor`'] Javadoc for complete details. @@ -175,7 +175,7 @@ shows the `Procfile` for our starter REST application: Spring Boot makes `-D` arguments available as properties accessible from a Spring `Environment` instance. The `server.port` configuration property is fed to the embedded -Tomcat, Jetty, or Undertow instance which, then uses the port when it starts up. The `$PORT` +Tomcat, Jetty, or Undertow instance, which then uses the port when it starts up. The `$PORT` environment variable is assigned to us by the Heroku PaaS. This should be everything you need. The most common deployment workflow for Heroku @@ -234,8 +234,7 @@ https://www.openshift.com/[OpenShift] is the Red Hat public (and enterprise) ext the Kubernetes container orchestration platform. Similarly to Kubernetes, OpenShift has many options for installing Spring Boot based applications. -OpenShift has many resources describing how to deploy Spring Boot applications, which -include: +OpenShift has many resources describing how to deploy Spring Boot applications, including: * https://blog.openshift.com/using-openshift-enterprise-grade-spring-boot-deployments/[Using the S2I builder] * https://access.redhat.com/documentation/en-us/reference_architectures/2017/html-single/spring_boot_microservices_on_red_hat_openshift_container_platform_3/[Architecture guide] @@ -255,7 +254,7 @@ server. The options include: * AWS Cloud Formation * AWS Container Registry -Each has different features and pricing model. In this document, we describe only the +Each has different features and pricing models. In this document, we describe only the simplest option: AWS Elastic Beanstalk. @@ -269,8 +268,8 @@ either use the "`Tomcat Platform`" or the "`Java SE platform`". ===== Using the Tomcat Platform -This option applies to Spring Boot projects that produce a war file. There is no any -special configuration required. You need only follow the official guide. +This option applies to Spring Boot projects that produce a war file. No +special configuration is required. You need only follow the official guide. @@ -290,7 +289,7 @@ your `application.properties` file: .Upload binaries instead of sources ==== By default, Elastic Beanstalk uploads sources and compiles them in AWS. However, it is -best to upload the binaries instead. To do so, add the following lines to your +best to upload the binaries instead. To do so, add lines similar to the following to your `.elasticbeanstalk/config.yml` file: @@ -355,11 +354,11 @@ more options. If there is a https://boxfuse.com/docs/commandline/#configuration TIP: By default, Boxfuse activates a Spring profile named `boxfuse` on startup. If your executable jar or war contains an https://boxfuse.com/docs/payloads/springboot.html#configuration -[`application-boxfuse.properties`] file, Boxfuse bases its configuration based on the +[`application-boxfuse.properties`] file, Boxfuse bases its configuration on the properties it contains. At this point, `boxfuse` creates an image for your application, uploads it, and configures -and starts the necessary resources on AWS resulting in output similar to the following +and starts the necessary resources on AWS, resulting in output similar to the following example: [indent=0,subs="verbatim,quotes,attributes"] @@ -405,7 +404,7 @@ it empty and then use the https://cloud.google.com/sdk/downloads[Google Cloud SD push your Spring Boot app into that slot from the command line or CI build. App Engine needs you to create an `app.yaml` file to describe the resources your app -requires. Normally you put this file in `src/main/appengine`, and it should resemble the +requires. Normally, you put this file in `src/main/appengine`, and it should resemble the following file: [source,yaml,indent=0] @@ -464,11 +463,11 @@ can be executed like any other executable binary or it can be <>. This makes it very easy to install and manage Spring Boot applications in common production environments. -WARNING: Fully executable jars work by embedding an extra script at the front of the file. +CAUTION: Fully executable jars work by embedding an extra script at the front of the file. Currently, some tools do not accept this format, so you may not always be able to use this technique. For example, `jar -xf` may silently fail to extract a jar or war that has been -made fully executable. It is recommended that you only make your jar or war fully -executable if you intend to execute it directly, rather than running it with `java -jar` +made fully executable. It is recommended that you make your jar or war fully executable +only if you intend to execute it directly, rather than running it with `java -jar` or deploying it to a servlet container. To create a '`fully executable`' jar with Maven, use the following plugin configuration: @@ -516,7 +515,7 @@ Spring Boot application can be easily started as Unix/Linux services by using ei If you configured Spring Boot's Maven or Gradle plugin to generate a <>, and you do not use a custom `embeddedLaunchScript`, your application can be used as an `init.d` service. To do so, symlink the jar to `init.d` to -support the standard `start`, `stop`, `restart` and `status` commands. +support the standard `start`, `stop`, `restart`, and `status` commands. The script supports the following features: @@ -533,7 +532,7 @@ Spring Boot application as an `init.d` service, create a symlink, as follows: ---- Once installed, you can start and stop the service in the usual way. For example, on a -Debian based system, you could start it with the following command: +Debian-based system, you could start it with the following command: [indent=0,subs="verbatim,quotes,attributes"] ---- @@ -638,7 +637,7 @@ place it in `/etc/systemd/system` directory. The following script offers an exam WantedBy=multi-user.target ---- -IMPORTANT: Remember to change the `Description`, `User` and `ExecStart` fields for your +IMPORTANT: Remember to change the `Description`, `User`, and `ExecStart` fields for your application. NOTE: The `ExecStart` field does not declare the script action command, which means that @@ -666,7 +665,7 @@ Refer to `man systemctl` for more details. The default embedded startup script written by the Maven or Gradle plugin can be customized in a number of ways. For most people, using the default script along with a few customizations is usually enough. If you find you cannot customize something that you need -to, you can always use the `embeddedLaunchScript` option to write your own file entirely. +to, use the `embeddedLaunchScript` option to write your own file entirely. @@ -785,8 +784,8 @@ The following environment properties are supported with the default script: |The name of the log file in the `LOG_FOLDER` (`.log` by default). |`APP_NAME` -|The name of the app. If the jar is run from a symlink, the script guesses the app name if - it is not a symlink or you want to explicitly set the app name, this can be useful. +|The name of the app. If the jar is run from a symlink, the script guesses the app name. +If it is not a symlink or you want to explicitly set the app name, this can be useful. |`RUN_ARGS` |The arguments to pass to the program (the Spring Boot app). @@ -818,10 +817,11 @@ http://www.freedesktop.org/software/systemd/man/systemd.service.html[service uni configuration man page] for more details. [[deployment-script-customization-conf-file]] -With the exception of `JARFILE` and `APP_NAME`, the above settings can be configured by -using a `.conf` file. The file is expected to be next to the jar file and have the same -name but suffixed with `.conf` rather than `.jar`. For example, a jar named -`/var/myapp/myapp.jar` uses the configuration file named `/var/myapp/myapp.conf`. +With the exception of `JARFILE` and `APP_NAME`, the settings listed in the preceding +section can be configured by using a `.conf` file. The file is expected to be next to the +jar file and have the same name but suffixed with `.conf` rather than `.jar`. For example, +a jar named `/var/myapp/myapp.jar` uses the configuration file named +`/var/myapp/myapp.conf`, as shown in the following example: .myapp.conf [indent=0,subs="verbatim,quotes,attributes"] @@ -842,7 +842,7 @@ To learn about securing this file appropriately, see A Spring Boot application can be started as a Windows service by using https://github.com/kohsuke/winsw[`winsw`]. -A sample (https://github.com/snicoll-scratches/spring-boot-daemon[maintained separately]) +A (https://github.com/snicoll-scratches/spring-boot-daemon[separately maintained sample]) describes step-by-step how you can create a Windows service for your Spring Boot application. diff --git a/spring-boot-project/spring-boot-docs/src/main/asciidoc/getting-started.adoc b/spring-boot-project/spring-boot-docs/src/main/asciidoc/getting-started.adoc index 321ad6da090..6c6d9b619cd 100644 --- a/spring-boot-project/spring-boot-docs/src/main/asciidoc/getting-started.adoc +++ b/spring-boot-project/spring-boot-docs/src/main/asciidoc/getting-started.adoc @@ -3,7 +3,7 @@ [partintro] -- -If you are getting started with Spring Boot, or "Spring" in general, start by reading +If you are getting started with Spring Boot, or "`Spring`" in general, start by reading this section. It answers the basic "`what?`", "`how?`" and "`why?`" questions. It includes an introduction to Spring Boot, along with installation instructions. We then walk you through building your first Spring Boot application, discussing some core @@ -14,7 +14,7 @@ principles as we go. [[getting-started-introducing-spring-boot]] == Introducing Spring Boot -Spring Boot makes it easy to create stand-alone, production-grade Spring based +Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applications that you can run. We take an opinionated view of the Spring platform and third-party libraries, so that you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration. @@ -25,7 +25,7 @@ runs "`spring scripts`". Our primary goals are: -* Provide a radically faster and widely accessible getting started experience for all +* Provide a radically faster and widely accessible getting-started experience for all Spring development. * Be opinionated out of the box but get out of the way quickly as requirements start to diverge from the defaults. @@ -38,15 +38,15 @@ configuration). [[getting-started-system-requirements]] == System Requirements -Spring Boot {spring-boot-version} requires http://www.java.com[Java 8] and Spring -Framework {spring-version} or above. Explicit build support is provided for Maven 3.2+ -and Gradle 4. +Spring Boot {spring-boot-version} requires http://www.java.com[Java 8] and +{spring-reference}[Spring Framework {spring-version}] or above. Explicit build support is +provided for Maven 3.2+ and Gradle 4. [[getting-started-system-requirements-servlet-containers]] === Servlet Containers -The following embedded servlet containers are supported out of the box: +Spring Boot supports the following embedded servlet containers: |=== |Name |Servlet Version @@ -78,7 +78,7 @@ begin, you should check your current Java installation by using the following co If you are new to Java development or if you want to experiment with Spring Boot, you might want to try the <> (Command -Line Interface) first, otherwise, read on for "`classic`" installation instructions. +Line Interface) first. Otherwise, read on for "`classic`" installation instructions. @@ -102,8 +102,8 @@ Maven installed, you can follow the instructions at http://maven.apache.org. TIP: On many operating systems, Maven can be installed with a package manager. If you use OSX Homebrew, try `brew install maven`. Ubuntu users can run -`sudo apt-get install maven`. Windows users with Chocolatey can run `choco install maven` -from an elevated (administrator) prompt. +`sudo apt-get install maven`. Windows users with https://chocolatey.org/[Chocolatey] can +run `choco install maven` from an elevated (administrator) prompt. Spring Boot dependencies use the `org.springframework.boot` `groupId`. Typically, your Maven POM file inherits from the `spring-boot-starter-parent` project and declares @@ -298,7 +298,7 @@ commands: Spring Boot v{spring-boot-version} ---- -If you are developing features for the CLI and want easy access to the version you built, +If you develop features for the CLI and want easy access to the version you built, use the following commands: [indent=0,subs="verbatim,quotes,attributes"] @@ -372,8 +372,8 @@ http://en.wikipedia.org/wiki/Zsh[zsh] shells. You can `source` the script (also `spring`) in any shell or put it in your personal or system-wide bash completion initialization. On a Debian system, the system-wide scripts are in `/shell-completion/bash` and all scripts in that directory are executed when a new shell -starts. For example, to run the script manually if you have installed using SDKMAN!, use -the following commands: +starts. For example, to run the script manually if you have installed by using SDKMAN!, +use the following commands: [indent=0] ---- @@ -415,7 +415,7 @@ Then run it from a shell, as follows: NOTE: The first run of your application is slow, as dependencies are downloaded. Subsequent runs are much quicker. -Open http://localhost:8080 in your favorite web browser. You should see the following +Open `http://localhost:8080` in your favorite web browser. You should see the following output: [indent=0] @@ -427,13 +427,13 @@ output: [[getting-started-upgrading-from-an-earlier-version]] === Upgrading from an Earlier Version of Spring Boot -If you are upgrading from an earlier release of Spring Boot check the "`release notes`" -hosted on the {github-wiki}[project wiki]. You'll find upgrade instructions along with a +If you are upgrading from an earlier release of Spring Boot, check the "`release notes`" +hosted on the {github-wiki}[project wiki]. You can find upgrade instructions along with a list of "`new and noteworthy`" features for each release. -To upgrade an existing CLI installation use the appropriate package manager command (for +To upgrade an existing CLI installation, use the appropriate package manager command (for example, `brew upgrade`) or, if you manually installed the CLI, follow the -<> remembering to update +<>, remembering to update your `PATH` environment variable to remove any older references. @@ -477,7 +477,7 @@ valid versions of Java and Maven installed: ---- NOTE: This sample needs to be created in its own folder. Subsequent instructions assume -that you have created a suitable folder and that it is your "`current directory`". +that you have created a suitable folder and that it is your current directory. @@ -646,7 +646,7 @@ accordingly. **** Auto-configuration is designed to work well with "`Starters`", but the two concepts are not directly tied. You are free to pick and choose jar dependencies outside of the -starters and Spring Boot still does its best to auto-configure your application. +starters. Spring Boot still does its best to auto-configure your application. **** @@ -687,7 +687,7 @@ application. You should see output similar to the following: ........ Started Example in 2.222 seconds (JVM running for 6.514) ---- -If you open a web browser to http://localhost:8080, you should see the following output: +If you open a web browser to `http://localhost:8080`, you should see the following output: [indent=0] ---- @@ -718,7 +718,7 @@ can also be problematic if the same filename is used (but with different content multiple jars. Spring Boot takes a <> and allows you to actually nest jars directly. +approach>> and lets you actually nest jars directly. **** To create an executable jar, we need to add the `spring-boot-maven-plugin` to our diff --git a/spring-boot-project/spring-boot-docs/src/main/asciidoc/howto.adoc b/spring-boot-project/spring-boot-docs/src/main/asciidoc/howto.adoc index 72405374e57..185102ef70f 100644 --- a/spring-boot-project/spring-boot-docs/src/main/asciidoc/howto.adoc +++ b/spring-boot-project/spring-boot-docs/src/main/asciidoc/howto.adoc @@ -21,6 +21,9 @@ send us a {github-code}[pull request]. [[howto-spring-boot-application]] == Spring Boot Application +This section includes topics relating directly to Spring Boot applications. + + [[howto-failure-analyzer]] === Create Your Own FailureAnalyzer @@ -49,37 +52,38 @@ The following example registers `ProjectConstraintViolationFailureAnalyzer`: [[howto-troubleshoot-auto-configuration]] === Troubleshoot Auto-configuration -The Spring Boot auto-configuration tries its best to '`do the right thing`', but +The Spring Boot auto-configuration tries its best to "`do the right thing`", but sometimes things fail, and it can be hard to tell why. There is a really useful `ConditionEvaluationReport` available in any Spring Boot `ApplicationContext`. You can see it if you enable `DEBUG` logging output. If you use -the `spring-boot-actuator`, there is also a `conditions` endpoint that renders the report -in JSON. Use that endpoint to debug the application and see what features have been added (and -which not) by Spring Boot at runtime. +the `spring-boot-actuator` (see <>), +there is also a `conditions` endpoint that renders the report in JSON. Use that endpoint +to debug the application and see what features have been added (and which have not been +added) by Spring Boot at runtime. Many more questions can be answered by looking at the source code and the Javadoc. When reading the code, remember the following rules of thumb: -* Look for classes called `+*AutoConfiguration+` and read their sources. Pay special attention to the - `+@Conditional*+` annotations to find out what features they enable and when. Add - `--debug` to the command line or a System property `-Ddebug` to get a log on the - console of all the auto-configuration decisions that were made in your app. In a running - Actuator app, look at the `conditions` endpoint (`/actuator/conditions` or the JMX - equivalent) for the same information. +* Look for classes called `+*AutoConfiguration+` and read their sources. Pay special +attention to the `+@Conditional*+` annotations to find out what features they enable and +when. Add `--debug` to the command line or a System property `-Ddebug` to get a log on the +console of all the auto-configuration decisions that were made in your app. In a running +Actuator app, look at the `conditions` endpoint (`/actuator/conditions` or the JMX +equivalent) for the same information. * Look for classes that are `@ConfigurationProperties` (such as - {sc-spring-boot-autoconfigure}/web/ServerProperties.{sc-ext}[`ServerProperties`]) - and read from there the available external configuration options. The - `@ConfigurationProperties` has a `name` attribute that acts as a prefix to external - properties. Thus, `ServerProperties` has `prefix="server"` and its configuration properties - are `server.port`, `server.address`, and others. In a running Actuator app, look at the - `configprops` endpoint. -* Look for uses of the `bind` method on the `Binder` to pull configuration values explicitly out of the - `Environment` in a relaxed manner. It is often used with a prefix. +{sc-spring-boot-autoconfigure}/web/ServerProperties.{sc-ext}[`ServerProperties`]) +and read from there the available external configuration options. The +`@ConfigurationProperties` annotation has a `name` attribute that acts as a prefix to +external properties. Thus, `ServerProperties` has `prefix="server"` and its configuration +properties are `server.port`, `server.address`, and others. In a running Actuator app, +look at the `configprops` endpoint. +* Look for uses of the `bind` method on the `Binder` to pull configuration values +explicitly out of the `Environment` in a relaxed manner. It is often used with a prefix. * Look for `@Value` annotations that bind directly to the `Environment`. * Look for `@ConditionalOnExpression` annotations that switch features on and off in - response to SpEL expressions, normally evaluated with placeholders resolved from the - `Environment`. +response to SpEL expressions, normally evaluated with placeholders resolved from the +`Environment`. @@ -88,14 +92,14 @@ reading the code, remember the following rules of thumb: A `SpringApplication` has `ApplicationListeners` and `ApplicationContextInitializers` that are used to apply customizations to the context or environment. Spring Boot loads a number of such customizations for use internally from `META-INF/spring.factories`. There is more -than one way to register additional ones: +than one way to register additional customizations: * Programmatically, per application, by calling the `addListeners` and `addInitializers` - methods on `SpringApplication` before you run it. +methods on `SpringApplication` before you run it. * Declaratively, per application, by setting the `context.initializer.classes` or - `context.listener.classes` properties. +`context.listener.classes` properties. * Declaratively, for all applications, by adding a `META-INF/spring.factories` and packaging - a jar file that the applications all use as a library. +a jar file that the applications all use as a library. The `SpringApplication` sends some special `ApplicationEvents` to the listeners (some even before the context is created) and then registers the listeners for events published @@ -123,15 +127,15 @@ include::{code-examples}/context/EnvironmentPostProcessorExample.java[tag=exampl 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. This example adds the `custom-resource` property source at the -end of the list so that a key defined in any of the usual other locations takes -precedence. A custom implementation may define another order. +file from the environment. The preceding example adds the `custom-resource` property +source at the end of the list so that a key defined in any of the usual other locations +takes precedence. A custom implementation may define another order. -CAUTION: While using `@PropertySource` on your `@SpringBootApplication` may seem convenient and -easy enough to load a custom resource in the `Environment`, we do not recommend it as -Spring Boot prepares the `Environment` before the `ApplicationContext` is refreshed. Any -key defined via `@PropertySource` is loaded too late to have any effect on -auto-configuration. +CAUTION: While using `@PropertySource` on your `@SpringBootApplication` may seem to be a +convenient and easy way to load a custom resource in the `Environment`, we do not +recommend it, because Spring Boot prepares the `Environment` before the +`ApplicationContext` is refreshed. Any key defined with `@PropertySource` is loaded too +late to have any effect on auto-configuration. @@ -162,7 +166,8 @@ Application code that you want to run as your business logic can be implemented [[howto-properties-and-configuration]] == Properties and Configuration - +This section includes topics about setting and reading properties and configuration +settings and their interaction with Spring Boot applications. [[howto-automatic-expansion]] === Automatically Expand Properties at Build Time @@ -190,7 +195,7 @@ applied on `src/test/resources`). TIP: If you enable the `addResources` flag, the `spring-boot:run` goal can add `src/main/resources` directly to the classpath (for hot reloading purposes). Doing so circumvents the resource filtering and this feature. Instead, you can use the `exec:java` -goal or customize the plugin's configuration, see the +goal or customize the plugin's configuration. See the {spring-boot-maven-plugin-site}/usage.html[plugin usage page] for more details. If you do not use the starter parent, you need to include the following element inside @@ -241,7 +246,7 @@ Java plugin's `processResources` task to do so, as shown in the following exampl } ---- -You can then refer to your Gradle project's properties via placeholders, as shown in the +You can then refer to your Gradle project's properties by using placeholders, as shown in the following example: [source,properties,indent=0] @@ -259,11 +264,11 @@ the Spring property placeholders as follows: `\${..}`. [[howto-externalize-configuration]] -=== Externalize the Configuration of SpringApplication +=== Externalize the Configuration of `SpringApplication` A `SpringApplication` has bean properties (mainly setters), so you can use its Java API as you create the application to modify its behavior. Alternatively, you can externalize the -configuration using properties in `+spring.main.*+`. For example, in `application.properties`, you -might have the following settings: +configuration by setting properties in `+spring.main.*+`. For example, in +`application.properties`, you might have the following settings: [source,properties,indent=0,subs="verbatim,quotes,attributes"] ---- @@ -277,7 +282,7 @@ not a web application. NOTE: The preceding example also demonstrates how flexible binding allows the use of underscores (`_`) as well as dashes (`-`) in property names. -Properties defined in external configuration overrides the values specified with the Java +Properties defined in external configuration override the values specified with the Java API, with the notable exception of the sources used to create the `ApplicationContext`. Consider the following application: @@ -299,7 +304,7 @@ Now consider the following configuration: The actual application _now_ shows the banner (as overridden by configuration) and uses three sources for the `ApplicationContext` (in the following order): `demo.MyApp`, -`com.acme.Config`, `com.acme.ExtraConfig`. +`com.acme.Config`, and `com.acme.ExtraConfig`. @@ -321,11 +326,11 @@ You can also provide the following System properties (or environment variables) the behavior: * `spring.config.name` (`SPRING_CONFIG_NAME`): Defaults to `application` as the root of - the file name. -* `spring.config.location` (`SPRING_CONFIG_LOCATION`): The file to load (such as a classpath - resource or a URL). A separate `Environment` property source is set up for this document - and it can be overridden by system properties, environment variables, or the - command line. +the file name. +* `spring.config.location` (`SPRING_CONFIG_LOCATION`): The file to load (such as a +classpath resource or a URL). A separate `Environment` property source is set up for this +document and it can be overridden by system properties, environment variables, or the +command line. No matter what you set in the environment, Spring Boot always loads `application.properties` as described above. By default, if YAML is used, then files with @@ -353,12 +358,13 @@ placeholders in `application.properties`, as shown in the following example: TIP: If you inherit from the `spring-boot-starter-parent` POM, the default filter token of the `maven-resources-plugins` has been changed from `+${*}+` to `@` (that is, `@maven.token@` instead of `${maven.token}`) to prevent conflicts with Spring-style -placeholders. If you have enabled maven filtering for the `application.properties` +placeholders. If you have enabled Maven filtering for the `application.properties` directly, you may want to also change the default filter token to use -http://maven.apache.org/plugins/maven-resources-plugin/resources-mojo.html#delimiters[other delimiters]. +http://maven.apache.org/plugins/maven-resources-plugin/resources-mojo.html#delimiters[other +delimiters]. NOTE: In this specific case, the port binding works in a PaaS environment such as Heroku -or Cloud Foundry In those two platforms, the `PORT` environment variable is set +or Cloud Foundry. In those two platforms, the `PORT` environment variable is set automatically and Spring can bind to capitalized synonyms for `Environment` properties. @@ -387,7 +393,7 @@ included if you use the `spring-boot-starter`). A YAML file is parsed to a Java is one level deep and has period-separated keys, as many people are used to with `Properties` files in Java. -The example YAML above corresponds to an `application.properties` file as follows: +The preceding example YAML corresponds to the following `application.properties` file: [source,properties,indent=0,subs="verbatim,quotes,attributes"] ---- @@ -438,7 +444,7 @@ document is parsed separately to a flattened map. If a YAML document contains a `spring.profiles` key, then the profiles value (a comma-separated list of profiles) is fed into the Spring `Environment.acceptsProfiles()` method. If any of those profiles is active, that document -is included in the final merge (otherwise not), as shown in the following example: +is included in the final merge (otherwise, it is not), as shown in the following example: [source,yaml,indent=0,subs="verbatim,quotes,attributes"] ---- @@ -463,8 +469,8 @@ In the preceding example, the default port is 9000. However, if the Spring profi '`development`' is active, then the port is 9001. If '`production`' is active, then the port is 0. -The YAML documents are merged in the order in which they are encountered (so later values -override earlier ones). +NOTE: The YAML documents are merged in the order in which they are encountered. Later +values override earlier values. To do the same thing with properties files, you can use `application-${profile}.properties` to specify profile-specific values. @@ -473,10 +479,10 @@ To do the same thing with properties files, you can use [[howto-discover-build-in-options-for-external-properties]] === Discover Built-in Options for External Properties -Spring Boot binds external properties from `application.properties` (or `.yml`) (and -other places) into an application at runtime. There is not (and technically cannot be) -an exhaustive list of all supported properties in a single location, because -contributions can come from additional jar files on your classpath. +Spring Boot binds external properties from `application.properties` (or `.yml` files and +other places) into an application at runtime. There is not (and technically cannot be) an +exhaustive list of all supported properties in a single location, because contributions +can come from additional jar files on your classpath. A running application with the Actuator features has a `configprops` endpoint that shows all the bound and bindable properties available through `@ConfigurationProperties`. @@ -485,7 +491,8 @@ The appendix includes an <> example with a list of the most common properties supported by Spring Boot. The definitive list comes from searching the source code for `@ConfigurationProperties` and `@Value` annotations as well as the occasional use of -`Binder`. +`Binder`. For more about the exact ordering of loading properties, see +"<>". @@ -500,10 +507,10 @@ configure the embedded server. This section answers those questions. === Use Another Web Server Many Spring Boot starters include default embedded containers. `spring-boot-starter-web` includes Tomcat by including `spring-boot-starter-tomcat`, but you can use -`spring-boot-starter-jetty` and `spring-boot-starter-undertow` instead. +`spring-boot-starter-jetty` or `spring-boot-starter-undertow` instead. `spring-boot-starter-webflux` includes Reactor Netty by including `spring-boot-starter-reactor-netty`, but you can use `spring-boot-starter-tomcat`, -`spring-boot-starter-jetty`, and `spring-boot-starter-undertow` instead. +`spring-boot-starter-jetty`, or `spring-boot-starter-undertow` instead. NOTE: Many starters support only Spring MVC, so they transitively bring `spring-boot-starter-web` into your application classpath. @@ -563,9 +570,11 @@ server. Generally, you can follow the advice from "`<>`" about `@ConfigurationProperties` (`ServerProperties` is the main one here). However, you should -also look at `ServletWebServerFactoryCustomizer`. The Jetty APIs are quite rich, so, once -you have access to the `JettyServletWebServerFactory`, you can modify it in a number of -ways. Alternatively, if you need more control and customization, you can add your own +also look at +{dc-spring-boot}/web/servlet/server/ServletWebServerFactoryCustomizer.html[`ServletWebServerFactoryCustomizer`]. +The Jetty APIs are quite rich, so, once you have access to the +`JettyServletWebServerFactory`, you can modify it in a number of ways. Alternatively, if +you need more control and customization, you can add your own `JettyServletWebServerFactory`. @@ -573,8 +582,10 @@ ways. Alternatively, if you need more control and customization, you can add you [[howto-add-a-servlet-filter-or-listener]] === Add a Servlet, Filter, or Listener to an Application There are two ways to add `Servlet`, `Filter`, `ServletContextListener`, and the other -listeners supported by the Servlet spec to your application. You can either provide -Spring beans for them or enable scanning for Servlet components. +listeners supported by the Servlet spec to your application: + +* <> +* <> @@ -584,9 +595,9 @@ To add a `Servlet`, `Filter`, or Servlet `*Listener` by using a Spring bean, you provide a `@Bean` definition for it. Doing so can be very useful when you want to inject configuration or dependencies. However, you must be very careful that they do not cause eager initialization of too many other beans, because they have to be installed in the -container very early in the application lifecycle (for example, it is not a good idea to -have them depend on your `DataSource` or JPA configuration). You can work around -restrictions like that by initializing the beans lazily when first used instead of on +container very early in the application lifecycle. (For example, it is not a good idea to +have them depend on your `DataSource` or JPA configuration.) You can work around such +restrictions by initializing the beans lazily when first used instead of on initialization. In the case of `Filters` and `Servlets`, you can also add mappings and init parameters by @@ -602,10 +613,10 @@ aligns with the Servlet Specification's default dispatcher type. [[howto-disable-registration-of-a-servlet-or-filter]] ===== Disable Registration of a Servlet or Filter -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: +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,quotes,attributes"] ---- @@ -632,14 +643,15 @@ of the annotated class. [[howto-change-the-http-port]] === Change the HTTP Port In a standalone application, the main HTTP port defaults to `8080` but can be set with -`server.port` (for example, in `application.properties` or as a System property). Thanks to -relaxed binding of `Environment` values, you can also use `SERVER_PORT` (for example, as an OS -environment variable). +`server.port` (for example, in `application.properties` or as a System property). Thanks +to relaxed binding of `Environment` values, you can also use `SERVER_PORT` (for example, +as an OS environment variable). To switch off the HTTP endpoints completely but still create a `WebApplicationContext`, use `server.port=-1`. (Doing so is sometimes useful for testing.) -For more details, see "`<>`" +For more details, see +"`<>`" in the '`Spring Boot features`' section, or the {sc-spring-boot-autoconfigure}/web/ServerProperties.{sc-ext}[`ServerProperties`] source code. @@ -709,11 +721,11 @@ See {sc-spring-boot}/web/server/Ssl.{sc-ext}[`Ssl`] for details of all of the supported properties. Using configuration such as the preceding example means the application no longer supports -a plain HTTP connector at port 8080. Spring Boot does not support the configuration of both -an HTTP connector and an HTTPS connector through `application.properties`. If you want to -have both, you need to configure one of them programmatically. We recommend -using `application.properties` to configure HTTPS, as the HTTP connector is the easier of -the two to configure programmatically. See the +a plain HTTP connector at port 8080. Spring Boot does not support the configuration of +both an HTTP connector and an HTTPS connector through `application.properties`. If you +want to have both, you need to configure one of them programmatically. We recommend using +`application.properties` to configure HTTPS, as the HTTP connector is the easier of the +two to configure programmatically. See the {github-code}/spring-boot-samples/spring-boot-sample-tomcat-multi-connectors[`spring-boot-sample-tomcat-multi-connectors`] sample project for an example. @@ -744,27 +756,27 @@ As of Undertow 1.4.0+, HTTP/2 is supported without any additional requirement on [[howto-configure-http2-tomcat]] ==== HTTP/2 with Tomcat -Spring Boot ships by default with Tomcat 8.5.x; with that version, HTTP/2 is only +Spring Boot ships by default with Tomcat 8.5.x. With that version, HTTP/2 is only supported if the `libtcnative` library and its dependencies are installed on the host operating system. -The library folder must be made available, if not already, to the JVM library path; this -can be done with a JVM argument such as +The library folder must be made available, if not already, to the JVM library path. You +can do so with a JVM argument such as `-Djava.library.path=/usr/local/opt/tomcat-native/lib`. More on this in the http://tomcat.apache.org/tomcat-8.5-doc/apr.html[official Tomcat documentation]. -Starting Tomcat 8.5.x without that native support will log the following error: +Starting Tomcat 8.5.x without that native support logs the following error: [indent=0,subs="attributes"] ---- ERROR 8787 --- [ main] o.a.coyote.http11.Http11NioProtocol : The upgrade handler [org.apache.coyote.http2.Http2Protocol] for [h2] only supports upgrade via ALPN but has been configured for the ["https-jsse-nio-8443"] connector that does not support ALPN. ---- -This error is not fatal, and the application starts with HTTP/1.1 SSL support still. +This error is not fatal, and the application still starts with HTTP/1.1 SSL support. -Running your application with Tomcat 9.0.x and JDK9 doesn't require any native library -installed. To use Tomcat 9, you can override the `tomcat.version` build property with the -version of your choice. +Running your application with Tomcat 9.0.x and JDK9 does not require any native library to +be installed. To use Tomcat 9, you can override the `tomcat.version` build property with +the version of your choice. @@ -789,7 +801,7 @@ fix Tomcat's base directory or use an absolute path for the logs. In the precedi example, the logs are available in `my-tomcat/logs` relative to the working directory of the application. -Access logging for undertow can be configured in a similar fashion, as shown in the +Access logging for Undertow can be configured in a similar fashion, as shown in the following example: [source,properties,indent=0,subs="verbatim,quotes,attributes"] @@ -811,7 +823,7 @@ Finally, access logging for Jetty can also be configured as follows: ---- By default, logs are redirected to `System.err`. For more details, see -{jetty-documentation}/configuring-jetty-request-logs.html[the documentation]. +{jetty-documentation}/configuring-jetty-request-logs.html[the Jetty documentation]. @@ -825,7 +837,7 @@ handled through a contract with the proxy, which adds headers to tell the back e construct links to itself. If the proxy adds conventional `X-Forwarded-For` and `X-Forwarded-Proto` headers (most -proxy server do so), the absolute links should be rendered correctly, provided +proxy servers do so), the absolute links should be rendered correctly, provided `server.use-forward-headers` is set to `true` in your `application.properties`. NOTE: If your application runs in Cloud Foundry or Heroku, the @@ -863,8 +875,8 @@ NOTE: You can trust all proxies by setting the `internal-proxies` to empty (but so in production). You can take complete control of the configuration of Tomcat's `RemoteIpValve` by -switching the automatic one off (to do so, set `server.use-forward-headers=false`) and adding -a new valve instance in a `TomcatServletWebServerFactory` bean. +switching the automatic one off (to do so, set `server.use-forward-headers=false`) and +adding a new valve instance in a `TomcatServletWebServerFactory` bean. @@ -874,8 +886,8 @@ Generally, you can follow the advice from "`<>`" about `@ConfigurationProperties` (`ServerProperties` is the main one here). However, you should also look at `ServletWebServerFactoryCustomizer` and various Tomcat-specific -`+*Customizers+` that you can add. The Tomcat APIs are quite rich, so, once you have -access to the `TomcatServletWebServerFactory`, you can modify it in a number of ways. +`+*Customizers+` that you can add. The Tomcat APIs are quite rich. Consequently, once you +have access to the `TomcatServletWebServerFactory`, you can modify it in a number of ways. Alternatively, if you need more control and customization, you can add your own `TomcatServletWebServerFactory`. @@ -1021,10 +1033,10 @@ performed. You can configure this behavior by setting the By default, responses are compressed only if their content type is one of the following: - - `text/html` - - `text/xml` - - `text/plain` - - `text/css` +* `text/html` +* `text/xml` +* `text/plain` +* `text/css` You can configure this behavior by setting the `server.compression.mime-types` property. @@ -1078,7 +1090,8 @@ work. To use the Jackson XML renderer, add the following dependency to your proj You may also want to add a dependency on Woodstox. It is faster than the default StAX implementation provided by the JDK and also adds pretty-print support and improved -namespace handling. The following listing shows how to include a dependency on Woodstox: +namespace handling. The following listing shows how to include a dependency on +https://github.com/FasterXML/woodstox[Woodstox]: [source,xml,indent=0,subs="verbatim,quotes,attributes"] ---- @@ -1113,13 +1126,13 @@ conversion in an HTTP exchange. If Jackson is on the classpath, you already get default converter(s) provided by `Jackson2ObjectMapperBuilder`, an instance of which is auto-configured for you. -The `ObjectMapper` (or `XmlMapper` for Jackson XML converter) instance (created by default) -has the following customized properties: +The `ObjectMapper` (or `XmlMapper` for Jackson XML converter) instance (created by +default) has the following customized properties: * `MapperFeature.DEFAULT_VIEW_INCLUSION` is disabled * `DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES` is disabled -Spring Boot has also some features to make it easier to customize this behavior. +Spring Boot also has some features to make it easier to customize this behavior. You can configure the `ObjectMapper` and `XmlMapper` instances by using the environment. Jackson provides an extensive suite of simple on/off features that can be used to @@ -1174,7 +1187,7 @@ doing so disables all auto-configuration of the `ObjectMapper`. If you provide any `@Beans` of type `MappingJackson2HttpMessageConverter`, they replace the default value in the MVC configuration. Also, a convenience bean of type -`HttpMessageConverters` is provided (always available if you use the default MVC +`HttpMessageConverters` is provided (and is always available if you use the default MVC configuration). It has some useful methods to access the default and user-enhanced message converters. @@ -1188,12 +1201,13 @@ source code for more details. === Customize the @ResponseBody Rendering Spring uses `HttpMessageConverters` to render `@ResponseBody` (or responses from `@RestController`). You can contribute additional converters by adding beans of the -appropriate type in a Spring Boot context. If a bean you add is of a type that would have been -included by default anyway (such as `MappingJackson2HttpMessageConverter` for JSON -conversions), it replaces the default value. A convenience bean of -type `HttpMessageConverters` is provided and is always available if you use the default MVC configuration. -It has some useful methods to access the default and user-enhanced message converters -(For example, it can be useful if you want to manually inject them into a custom `RestTemplate`). +appropriate type in a Spring Boot context. If a bean you add is of a type that would have +been included by default anyway (such as `MappingJackson2HttpMessageConverter` for JSON +conversions), it replaces the default value. A convenience bean of type +`HttpMessageConverters` is provided and is always available if you use the default MVC +configuration. It has some useful methods to access the default and user-enhanced message +converters (For example, it can be useful if you want to manually inject them into a +custom `RestTemplate`). As in normal MVC usage, any `WebMvcConfigurer` beans that you provide can also contribute converters by overriding the `configureMessageConverters` method. However, unlike @@ -1203,7 +1217,8 @@ Spring Boot default MVC configuration by providing your own `@EnableWebMvc` conf you can take control completely and do everything manually by using `getMessageConverters` from `WebMvcConfigurationSupport`. -See the {sc-spring-boot-autoconfigure}/web/servlet/WebMvcAutoConfiguration.{sc-ext}[`WebMvcAutoConfiguration`] +See the +{sc-spring-boot-autoconfigure}/web/servlet/WebMvcAutoConfiguration.{sc-ext}[`WebMvcAutoConfiguration`] source code for more details. @@ -1222,15 +1237,16 @@ The multipart support is helpful when you want to receive multipart encoded file a `@RequestParam`-annotated parameter of type `MultipartFile` in a Spring MVC controller handler method. -See the {sc-spring-boot-autoconfigure}/web/servlet/MultipartAutoConfiguration.{sc-ext}[`MultipartAutoConfiguration`] +See the +{sc-spring-boot-autoconfigure}/web/servlet/MultipartAutoConfiguration.{sc-ext}[`MultipartAutoConfiguration`] source for more details. [[howto-switch-off-the-spring-mvc-dispatcherservlet]] === Switch Off the Spring MVC DispatcherServlet -Spring Boot wants to serve all content from the root of your application (`/`) down. If you -would rather map your own servlet to that URL, you can do it. However, you may lose +Spring Boot wants to serve all content from the root of your application (`/`) down. If +you would rather map your own servlet to that URL, you can do it. However, you may lose some of the other Boot MVC features. To add your own servlet and map it to the root resource, declare a `@Bean` of type `Servlet` and give it the special bean name, `dispatcherServlet`. (You can also create a bean of a different type with that name if @@ -1262,44 +1278,44 @@ added. `WebMvcAutoConfiguration` adds the following `ViewResolvers` to your context: * An `InternalResourceViewResolver` named '`defaultViewResolver`'. This one locates - physical resources that can be rendered by using the `DefaultServlet` (including static - resources and JSP pages, if you use those). It applies a prefix and a suffix to the - view name and then looks for a physical resource with that path in the servlet context - (the defaults are both empty but are accessible for external configuration through - `spring.mvc.view.prefix` and `spring.mvc.view.suffix`). You can override it by - providing a bean of the same type. +physical resources that can be rendered by using the `DefaultServlet` (including static +resources and JSP pages, if you use those). It applies a prefix and a suffix to the +view name and then looks for a physical resource with that path in the servlet context +(the defaults are both empty but are accessible for external configuration through +`spring.mvc.view.prefix` and `spring.mvc.view.suffix`). You can override it by +providing a bean of the same type. * A `BeanNameViewResolver` named '`beanNameViewResolver`'. This is a useful member of the - view resolver chain and picks up any beans with the same name as the `View` being - resolved. It should not be necessary to override or replace it. +view resolver chain and picks up any beans with the same name as the `View` being +resolved. It should not be necessary to override or replace it. * A `ContentNegotiatingViewResolver` named '`viewResolver`' is added only if there *are* - actually beans of type `View` present. This is a '`master`' resolver, delegating to all - the others and attempting to find a match to the '`Accept`' HTTP header sent by the - client. There is a useful - https://spring.io/blog/2013/06/03/content-negotiation-using-views[blog about `ContentNegotiatingViewResolver`] - that you might like to study to learn more, and you might also look at the source code - for detail. You can switch off the auto-configured `ContentNegotiatingViewResolver` by - defining a bean named '`viewResolver`'. +actually beans of type `View` present. This is a '`master`' resolver, delegating to all +the others and attempting to find a match to the '`Accept`' HTTP header sent by the +client. There is a useful +https://spring.io/blog/2013/06/03/content-negotiation-using-views[blog about +`ContentNegotiatingViewResolver`] that you might like to study to learn more, and you +might also look at the source code for detail. You can switch off the auto-configured +`ContentNegotiatingViewResolver` by defining a bean named '`viewResolver`'. * If you use Thymeleaf, you also have a `ThymeleafViewResolver` named - '`thymeleafViewResolver`'. It looks for resources by surrounding the view name with a - prefix and suffix. The prefix is `spring.thymeleaf.prefix`, and the suffix is - `spring.thymeleaf.suffix`. The values of the prefix and suffix default to - '`classpath:/templates/`' and '`.html`', respectively. You can override - `ThymeleafViewResolver` by providing a bean of the same name. +'`thymeleafViewResolver`'. It looks for resources by surrounding the view name with a +prefix and suffix. The prefix is `spring.thymeleaf.prefix`, and the suffix is +`spring.thymeleaf.suffix`. The values of the prefix and suffix default to +'`classpath:/templates/`' and '`.html`', respectively. You can override +`ThymeleafViewResolver` by providing a bean of the same name. * If you use FreeMarker, you also have a `FreeMarkerViewResolver` named - '`freeMarkerViewResolver`'. It looks for resources in a loader path (which is - externalized to `spring.freemarker.templateLoaderPath` and has a default value of - '`classpath:/templates/`') by surrounding the view name with a prefix and suffix. The - prefix is externalized to `spring.freemarker.prefix`, and the suffix is externalized to - `spring.freemarker.suffix`. The default values of the prefix and suffix are empty and - '`.ftl`', respectively. You can override `FreeMarkerViewResolver` by providing a bean - of the same name. +'`freeMarkerViewResolver`'. It looks for resources in a loader path (which is +externalized to `spring.freemarker.templateLoaderPath` and has a default value of +'`classpath:/templates/`') by surrounding the view name with a prefix and a suffix. The +prefix is externalized to `spring.freemarker.prefix`, and the suffix is externalized to +`spring.freemarker.suffix`. The default values of the prefix and suffix are empty and +'`.ftl`', respectively. You can override `FreeMarkerViewResolver` by providing a bean +of the same name. * If you use Groovy templates (actually, if `groovy-templates` is on your classpath), you - also have a `GroovyMarkupViewResolver` named '`groovyMarkupViewResolver`'. It looks for - resources in a loader path by surrounding the view name with a prefix and suffix - (externalized to `spring.groovy.template.prefix` and `spring.groovy.template.suffix`). - The prefix and suffix have default values of '`classpath:/templates/`' and '`.tpl`', - respectively. You can override `GroovyMarkupViewResolver` by providing a bean of the - same name. +also have a `GroovyMarkupViewResolver` named '`groovyMarkupViewResolver`'. It looks for +resources in a loader path by surrounding the view name with a prefix and suffix +(externalized to `spring.groovy.template.prefix` and `spring.groovy.template.suffix`). +The prefix and suffix have default values of '`classpath:/templates/`' and '`.tpl`', +respectively. You can override `GroovyMarkupViewResolver` by providing a bean of the +same name. For more detail, see the following sections: @@ -1314,7 +1330,7 @@ For more detail, see the following sections: == HTTP Clients Spring Boot offers a number of starters that work with HTTP clients. This section answers -questions related to doing so. +questions related to using them. [[howto-http-clients-proxy-configuration]] === Configure RestTemplate to Use a Proxy @@ -1339,12 +1355,12 @@ include::{code-examples}/web/client/RestTemplateProxyCustomizationExample.java[t == Logging Spring Boot has no mandatory logging dependency, except for the Commons Logging API, of -which there are many implementations to choose from. To use http://logback.qos.ch[Logback], -you need to include it and `jcl-over-slf4j` (which implements the Commons Logging API) on -the classpath. The simplest way to do that is through the starters, which all depend on -`spring-boot-starter-logging`. For a web application, you need only -`spring-boot-starter-web`, since it depends transitively on the logging starter. If you -use Maven, the following dependency adds logging for you: +which there are many implementations to choose from. To use +http://logback.qos.ch[Logback], you need to include it and `jcl-over-slf4j` (which +implements the Commons Logging API) on the classpath. The simplest way to do that is +through the starters, which all depend on `spring-boot-starter-logging`. For a web +application, you need only `spring-boot-starter-web`, since it depends transitively on the +logging starter. If you use Maven, the following dependency adds logging for you: [source,xml,indent=0,subs="verbatim,quotes,attributes"] ---- @@ -1590,8 +1606,8 @@ However, there is a catch. Because the actual type of the connection pool is not no keys are generated in the metadata for your custom `DataSource` and no completion is available in your IDE (because the `DataSource` interface exposes no properties). Also, if you happen to have Hikari on the classpath, this basic setup does not work, because Hikari -has no `url` property (but does have a `jdbcUrl` property). In that case, you must rewrite your -configuration as follows: +has no `url` property (but does have a `jdbcUrl` property). In that case, you must rewrite +your configuration as follows: [source,properties,indent=0] ---- @@ -1613,12 +1629,12 @@ include::{code-examples}/jdbc/SimpleDataSourceExample.java[tag=configuration] ---- 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 one 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 +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,quotes,attributes"] @@ -1644,7 +1660,7 @@ has no effect. In practice, the builder is initialized with whatever value you might set there and then overridden by the call to `.type()`. See "`<>`" in the -'`Spring Boot features`' section and the +"`Spring Boot features`" section and the {sc-spring-boot-autoconfigure}/jdbc/DataSourceAutoConfiguration.{sc-ext}[`DataSourceAutoConfiguration`] class for more details. @@ -1653,9 +1669,9 @@ class for more details. [[howto-two-datasources]] === Configure Two DataSources If you need to configure multiple data sources, you can apply the same tricks that are -described in the previous section. You must, however, mark one of the `DataSource` instances as -`@Primary`, because various auto-configurations down the road expect to be able to get one by -type. +described in the previous section. You must, however, mark one of the `DataSource` +instances as `@Primary`, because various auto-configurations down the road expect to be +able to get one by type. 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 @@ -1698,21 +1714,24 @@ logic as Spring Boot would use in auto-configuration. [[howto-use-spring-data-repositories]] === Use Spring Data Repositories -Spring Data can create implementations for you of `@Repository` interfaces of various -flavors. Spring Boot handles all of that for you, as long as those `@Repositories` -are included in the same package (or a sub-package) of your `@EnableAutoConfiguration` -class. +Spring Data can create implementations of `@Repository` interfaces of various flavors. +Spring Boot handles all of that for you, as long as those `@Repositories` are included in +the same package (or a sub-package) of your `@EnableAutoConfiguration` class. For many applications, all you need is to put the right Spring Data dependencies on your classpath (there is a `spring-boot-starter-data-jpa` for JPA and a -`spring-boot-starter-data-mongodb` for Mongodb) and create some repository interfaces to handle your -`@Entity` objects. Examples are in the {github-code}/spring-boot-samples/spring-boot-sample-data-jpa[JPA sample] -and the {github-code}/spring-boot-samples/spring-boot-sample-data-mongodb[Mongodb sample]. +`spring-boot-starter-data-mongodb` for Mongodb) and create some repository interfaces to +handle your `@Entity` objects. Examples are in the +{github-code}/spring-boot-samples/spring-boot-sample-data-jpa[JPA sample] and the +{github-code}/spring-boot-samples/spring-boot-sample-data-mongodb[Mongodb sample]. Spring Boot tries to guess the location of your `@Repository` definitions, based on the `@EnableAutoConfiguration` it finds. To get more control, use the `@EnableJpaRepositories` annotation (from Spring Data JPA). +For more about Spring Data, see the {spring-data}[Spring Data project page]. + + [[howto-separate-entity-definitions-from-spring-configuration]] === Separate @Entity Definitions from Spring Configuration @@ -1736,14 +1755,14 @@ annotation, as shown in the following example: [[howto-configure-jpa-properties]] === Configure JPA Properties -Spring Data JPA already provides some vendor-independent configuration options (such as those -for SQL logging), and Spring Boot exposes those options and a few more for Hibernate as external -configuration properties. Some of them are automatically detected according to the context -so you should not have to set them. +Spring Data JPA already provides some vendor-independent configuration options (such as +those for SQL logging), and Spring Boot exposes those options and a few more for Hibernate +as external configuration properties. Some of them are automatically detected according to +the context so you should not have to set them. The `spring.jpa.hibernate.ddl-auto` is a special case, because, depending on runtime -conditions, it has different defaults. If an embedded database is used and no schema manager -(such as Liquibase or Flyway) is handling the `DataSource`, it defaults to +conditions, it has different defaults. If an embedded database is used and no schema +manager (such as Liquibase or Flyway) is handling the `DataSource`, it defaults to `create-drop`. In all other cases, it defaults to `none`. The dialect to use is also automatically detected based on the current `DataSource`, but @@ -1751,9 +1770,10 @@ you can set `spring.jpa.database` yourself if you want to be explicit and bypass check on startup. NOTE: Specifying a `database` leads to the configuration of a well-defined Hibernate -dialect. Several databases have more than one `Dialect`, and this may not suit your need. -In that case, you can either set `spring.jpa.database` to `default` to let Hibernate figure -things out or set the dialect by setting the `spring.jpa.database-platform` property. +dialect. Several databases have more than one `Dialect`, and this may not suit your needs. +In that case, you can either set `spring.jpa.database` to `default` to let Hibernate +figure things out or set the dialect by setting the `spring.jpa.database-platform` +property. The most common options to set are shown in the following example: @@ -1763,8 +1783,9 @@ The most common options to set are shown in the following example: spring.jpa.show-sql=true ---- -In addition, all properties in `+spring.jpa.properties.*+` are passed through as normal JPA -properties (with the prefix stripped) when the local `EntityManagerFactory` is created. +In addition, all properties in `+spring.jpa.properties.*+` are passed through as normal +JPA properties (with the prefix stripped) when the local `EntityManagerFactory` is +created. @@ -1793,7 +1814,7 @@ If you prefer to use Hibernate 5's default instead, set the following property: spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl ---- -Alternatively, configure the following bean: +Alternatively, you can configure the following bean: [source,java,indent=0,subs="verbatim,quotes,attributes"] ---- @@ -1852,12 +1873,12 @@ following example: ---- The configuration above almost works on its own. To complete the picture, you need to -configure `TransactionManagers` for the two `EntityManagers` as well. One of them could -be picked up by the default `JpaTransactionManager` in Spring Boot if you mark it as -`@Primary`. The other would have to be explicitly injected into a new instance. -Alternatively, you might be able to use a JTA transaction manager that spans both. +configure `TransactionManagers` for the two `EntityManagers` as well. If you mark one of +them as `@Primary`, it could be picked up by the default `JpaTransactionManager` in Spring +Boot. The other would have to be explicitly injected into a new instance. Alternatively, +you might be able to use a JTA transaction manager that spans both. -If you are using Spring Data, you need to configure `@EnableJpaRepositories` accordingly, +If you use Spring Data, you need to configure `@EnableJpaRepositories` accordingly, as shown in the following example: [source,java,indent=0,subs="verbatim,quotes,attributes"] @@ -1882,9 +1903,10 @@ as shown in the following example: [[howto-use-traditional-persistence-xml]] === Use a Traditional `persistence.xml` File Spring does not require the use of XML to configure the JPA provider, and Spring Boot -assumes you want to take advantage of that feature. If you prefer to use `persistence.xml`, -you need to define your own `@Bean` of type `LocalEntityManagerFactoryBean` (with -an ID of '`entityManagerFactory`') and set the persistence unit name there. +assumes you want to take advantage of that feature. If you prefer to use +`persistence.xml`, you need to define your own `@Bean` of type +`LocalEntityManagerFactoryBean` (with an ID of '`entityManagerFactory`') and set the +persistence unit name there. See {sc-spring-boot-autoconfigure}/orm/jpa/JpaBaseConfiguration.{sc-ext}[`JpaBaseConfiguration`] @@ -1897,10 +1919,10 @@ for the default settings. Spring Data JPA and Spring Data Mongo can both automatically create `Repository` implementations for you. If they are both present on the classpath, you might have to do -some extra configuration to tell Spring Boot which one (or both) you want to create -repositories for you. The most explicit way to do that is to use the standard Spring Data -`+@EnableJpaRepositories+` and `+@EnableMongoRepositories+` annotations and provide the -location of your `Repository` interfaces. +some extra configuration to tell Spring Boot which repositories to create. The most +explicit way to do that is to use the standard Spring Data `+@EnableJpaRepositories+` and +`+@EnableMongoRepositories+` annotations and provide the location of your `Repository` +interfaces. There are also flags (`+spring.data.*.repositories.enabled+` and `+spring.data.*.repositories.type+`) that you can use to switch the auto-configured @@ -1909,8 +1931,8 @@ case you want to switch off the Mongo repositories and still use the auto-config `MongoTemplate`. The same obstacle and the same features exist for other auto-configured Spring Data -repository types (Elasticsearch, Solr, and others). To work with them, change the names of the annotations and flags -accordingly. +repository types (Elasticsearch, Solr, and others). To work with them, change the names of +the annotations and flags accordingly. @@ -1919,8 +1941,8 @@ accordingly. Spring Data REST can expose the `Repository` implementations as REST endpoints for you, provided Spring MVC has been enabled for the application. -Spring Boot exposes a set of useful properties (from the `spring.data.rest` namespace) that -customize the +Spring Boot exposes a set of useful properties (from the `spring.data.rest` namespace) +that customize the {spring-data-rest-javadoc}/core/config/RepositoryRestConfiguration.{dc-ext}[`RepositoryRestConfiguration`]. If you need to provide additional customization, you should use a {spring-data-rest-javadoc}/webmvc/config/RepositoryRestConfigurer.{dc-ext}[`RepositoryRestConfigurer`] @@ -1956,7 +1978,7 @@ include::{code-examples}/elasticsearch/HibernateSearchElasticsearchExample.java[ [[howto-configure-jOOQ-with-multiple-datasources]] === Configure jOOQ with Two DataSources If you need to use jOOQ with multiple data sources, you should create your own -`DSLContext` for each, refer to +`DSLContext` for each one. Refer to {sc-spring-boot-autoconfigure}/jooq/JooqAutoConfiguration.{sc-ext}[JooqAutoConfiguration] for more details. @@ -1979,19 +2001,19 @@ JPA has features for DDL generation, and these can be set up to run on startup a database. This is controlled through two external properties: * `spring.jpa.generate-ddl` (boolean) switches the feature on and off and is vendor - independent. +independent. * `spring.jpa.hibernate.ddl-auto` (enum) is a Hibernate feature that controls the - behavior in a more fine-grained way. This feature is described in more detail later in - the document. +behavior in a more fine-grained way. This feature is described in more detail later in +this guide. [[howto-initialize-a-database-using-hibernate]] === Initialize a Database Using Hibernate You can set `spring.jpa.hibernate.ddl-auto` explicitly and the standard Hibernate property -values are `none`, `validate`, `update`, `create`, and `create-drop`. Spring Boot chooses a -default value for you based on whether it thinks your database is embedded. It defaults to -`create-drop` if no schema manager has been detected or `none` in all other cases. An +values are `none`, `validate`, `update`, `create`, and `create-drop`. Spring Boot chooses +a default value for you based on whether it thinks your database is embedded. It defaults +to `create-drop` if no schema manager has been detected or `none` in all other cases. An embedded database is detected by looking at the `Connection` type. `hsqldb`, `h2`, and `derby` are embedded, and others are not. Be careful when switching from in-memory to a '`real`' database that you do not make assumptions about the existence of the tables and @@ -1999,13 +2021,14 @@ data in the new platform. You either have to set `ddl-auto` explicitly or use on other mechanisms to initialize the database. NOTE: You can output the schema creation by enabling the `org.hibernate.SQL` logger. This -is done for you automatically if you enable the <>. +is done for you automatically if you enable the +<>. In addition, a file named `import.sql` in the root of the classpath is executed on startup if Hibernate creates the schema from scratch (that is, if the `ddl-auto` property is set to `create` or `create-drop`). This can be useful for demos and for testing if you -are careful but is probably not something you want to be on the classpath in production. It -is a Hibernate feature (and has nothing to do with Spring). +are careful but is probably not something you want to be on the classpath in production. +It is a Hibernate feature (and has nothing to do with Spring). [[howto-initialize-a-database-using-spring-jdbc]] @@ -2022,9 +2045,9 @@ Spring Boot automatically creates the schema of an embedded `DataSource`. This b can be customized by using the `spring.datasource.initialization-mode` property (and it can also be `always` or `never`). -By default, Spring Boot enables the fail-fast feature of the Spring JDBC initializer, so, -if the scripts cause exceptions, the application fails to start. You can tune that -behavior by setting `spring.datasource.continue-on-error`. +By default, Spring Boot enables the fail-fast feature of the Spring JDBC initializer. This +means that, if the scripts cause exceptions, the application fails to start. You can tune +that behavior by setting `spring.datasource.continue-on-error`. NOTE: In a JPA-based app, you can choose to let Hibernate create the schema or use `schema.sql`, but you cannot do both. Make sure to disable @@ -2034,11 +2057,10 @@ NOTE: In a JPA-based app, you can choose to let Hibernate create the schema or u [[howto-initialize-a-spring-batch-database]] === Initialize a Spring Batch Database -If you use Spring Batch, it comes pre-packaged with SQL initialization scripts -for most popular database platforms. Spring Boot can detect your database type and -execute those scripts on startup. If you use an embedded database, this happens -by default. You can also enable it for any database type, as shown in the following -example: +If you use Spring Batch, it comes pre-packaged with SQL initialization scripts for most +popular database platforms. Spring Boot can detect your database type and execute those +scripts on startup. If you use an embedded database, this happens by default. You can also +enable it for any database type, as shown in the following example: [indent=0,subs="verbatim,quotes,attributes"] ---- @@ -2061,19 +2083,20 @@ To automatically run Flyway database migrations on startup, add the `org.flywaydb:flyway-core` to your classpath. The migrations are scripts in the form `V__.sql` (with `` an -underscore-separated version, such as '`1`' or '`2_1`'). By default, they live in a folder called -`classpath:db/migration`, but you can modify that location by setting `spring.flyway.locations`. You can -also add a special `{vendor}` placeholder to use vendor-specific scripts. Assume the -following: +underscore-separated version, such as '`1`' or '`2_1`'). By default, they are in a folder +called `classpath:db/migration`, but you can modify that location by setting +`spring.flyway.locations`. You can also add a special `{vendor}` placeholder to use +vendor-specific scripts. Assume the following: [source,properties,indent=0] ---- spring.flyway.locations=db/migration/{vendor} ---- -Rather than using `db/migration`, the preceding configuration sets the folder to use according -to the type of the database (such as `db/migration/mysql` for MySQL). The list of supported -database are available in {sc-spring-boot}/jdbc/DatabaseDriver.{sc-ext}[`DatabaseDriver`]. +Rather than using `db/migration`, the preceding configuration sets the folder to use +according to the type of the database (such as `db/migration/mysql` for MySQL). The list +of supported databases is available in +{sc-spring-boot}/jdbc/DatabaseDriver.{sc-ext}[`DatabaseDriver`]. See the Flyway class from flyway-core for details of available settings such as schemas and others. In addition, Spring Boot provides a small set of properties (in @@ -2102,10 +2125,10 @@ that you can see how to set things up. You can also use Flyway to provide data for specific scenarios. For example, you can place test-specific migrations in `src/test/resources` and they are run only when your -application starts for testing. If you want to be more sophisticated, you can use -profile-specific configuration to customize `spring.flyway.locations` so that certain -migrations run only when a particular profile is active. For example, in -`application-dev.properties`, you might specify the following setting: +application starts for testing. Also, you can use profile-specific configuration to +customize `spring.flyway.locations` so that certain migrations run only when a particular +profile is active. For example, in `application-dev.properties`, you might specify the +following setting: [source,properties,indent=0] ---- @@ -2122,22 +2145,23 @@ active. To automatically run Liquibase database migrations on startup, add the `org.liquibase:liquibase-core` to your classpath. -By default, the master change log is read from `db/changelog/db.changelog-master.yaml`, but -you can change the location by setting `spring.liquibase.change-log`. In addition to YAML, Liquibase also -supports JSON, XML, and SQL change log formats. +By default, the master change log is read from `db/changelog/db.changelog-master.yaml`, +but you can change the location by setting `spring.liquibase.change-log`. In addition to +YAML, Liquibase also supports JSON, XML, and SQL change log formats. By default, Liquibase autowires the (`@Primary`) `DataSource` in your context and uses -that for migrations. If you like to use a different `DataSource`, you can create one and +that for migrations. If you need to use a different `DataSource`, you can create one and mark its `@Bean` as `@LiquibaseDataSource`. If you do so and you want two data sources, -remember to create another one and mark it as `@Primary`. Alternatively, you can use Liquibase's native -`DataSource` by setting `spring.liquibase.[url,user,password]` in external properties. +remember to create another one and mark it as `@Primary`. Alternatively, you can use +Liquibase's native `DataSource` by setting `spring.liquibase.[url,user,password]` in +external properties. See {sc-spring-boot-autoconfigure}/liquibase/LiquibaseProperties.{sc-ext}[`LiquibaseProperties`] for details about available settings such as contexts, the default schema, and others. -There is a {github-code}/spring-boot-samples/spring-boot-sample-liquibase[Liquibase sample] -so that you can see how to set things up. +There is a {github-code}/spring-boot-samples/spring-boot-sample-liquibase[Liquibase +sample] so that you can see how to set things up. @@ -2149,11 +2173,11 @@ questions that arise from using messaging with Spring Boot. [[howto-jms-disable-transaction]] === Disable Transacted JMS Session -If your JMS broker does not support transacted session, you have to disable the +If your JMS broker does not support transacted sessions, you have to disable the support of transactions altogether. 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 session, as follows: +can disable transacted sessions, as follows: [source,java,indent=0] ---- @@ -2178,11 +2202,16 @@ other factory that your application defines, if any. [[howto-batch-applications]] == Batch Applications +This section answers questions that arise from using Spring Batch with Spring Boot. + NOTE: By default, batch applications require a `DataSource` to store job details. If you want to deviate from that, you need to implement `BatchConfigurer`. See {spring-batch-javadoc}/core/configuration/annotation/EnableBatchProcessing.html[The Javadoc of `@EnableBatchProcessing`] for more details. +For more about Spring Batch, see the https://projects.spring.io/spring-batch/[Spring Batch +project page]. + [[howto-execute-spring-batch-jobs-on-startup]] @@ -2193,7 +2222,7 @@ Spring Batch auto-configuration is enabled by adding `@EnableBatchProcessing` By default, it executes *all* `Jobs` in the application context on startup (see {sc-spring-boot-autoconfigure}/batch/JobLauncherCommandLineRunner.{sc-ext}[JobLauncherCommandLineRunner] for details). You can narrow down to a specific job or jobs by specifying -`spring.batch.job.names` (comma-separated job name patterns). +`spring.batch.job.names` (which takes a comma-separated list of job name patterns). If the application context includes a `JobRegistry`, the jobs in `spring.batch.job.names` are looked up in the registry instead of being autowired from the @@ -2217,16 +2246,17 @@ arise from its use. [[howto-change-the-http-port-or-address-of-the-actuator-endpoints]] === Change the HTTP Port or Address of the Actuator Endpoints In a standalone application, the Actuator HTTP port defaults to the same as the main HTTP -port. To make the application listen on a different port, set the external property, -`management.server.port`. To listen on a completely different network address (such as when you have -an internal network for management and an external one for user applications), you can -also set `management.server.address` to a valid IP address to which the server is able to bind. +port. To make the application listen on a different port, set the external property: +`management.server.port`. To listen on a completely different network address (such as +when you have an internal network for management and an external one for user +applications), you can also set `management.server.address` to a valid IP address to which +the server is able to bind. For more detail, see the {sc-spring-boot-actuator-autoconfigure}/web/server/ManagementServerProperties.{sc-ext}[`ManagementServerProperties`] source code and "`<>`" -in the '`Production-ready features`' section. +in the "`Production-ready features`" section. @@ -2238,7 +2268,7 @@ see a sensible response with the right error code). NOTE: Set `server.error.whitelabel.enabled=false` to switch the default error page off. Doing so restores the default of the servlet container that you are using. Note that -Spring Boot still tries to resolve the error view, so you should probably add you own +Spring Boot still tries to resolve the error view, so you should probably add your own error page rather than disabling it completely. Overriding the error page with your own depends on the templating technology that you @@ -2259,6 +2289,12 @@ of how to register handlers in the servlet container. [[howto-security]] == Security +This section addresses questions about security when working with Spring Boot, including +questions that arise from using Spring Security with Spring Boot. + +For more about Spring Security, see the {spring-security}[Spring Security project page]. + + [[howto-switch-off-spring-boot-security-configuration]] === Switch off the Spring Boot Security Configuration @@ -2268,14 +2304,16 @@ it switches off the default webapp security settings in Spring Boot. [[howto-change-the-authenticationmanager-and-add-user-accounts]] === Change the AuthenticationManager and Add User Accounts -If you provide a `@Bean` of type `AuthenticationManager`, `AuthenticationProvider` +If you provide a `@Bean` of type `AuthenticationManager`, `AuthenticationProvider`, or `UserDetailsService`, the default `@Bean` for `InMemoryUserDetailsManager` is not -created. So you have the full feature set of Spring Security available (such as -http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#jc-authentication[various authentication options]). +created, so you have the full feature set of Spring Security available (such as +http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#jc-authentication[various +authentication options]). The easiest way to add user accounts is to provide your own `UserDetailsService` bean. + [[howto-enable-https]] === Enable HTTPS When Running behind a Proxy Server Ensuring that all your main endpoints are only available over HTTPS is an important @@ -2295,7 +2333,7 @@ by adding some entries to `application.properties`, as shown in the following ex ---- (The presence of either of those properties switches on the valve. Alternatively, you can -add the `RemoteIpValve` yourself by adding a `TomcatServletWebServerFactory` bean.) +add the `RemoteIpValve` by adding a `TomcatServletWebServerFactory` bean.) To configure Spring Security to require a secure channel for all (or some) requests, consider adding your own `WebSecurityConfigurerAdapter` that adds the following @@ -2321,22 +2359,24 @@ requests, consider adding your own `WebSecurityConfigurerAdapter` that adds the Spring Boot supports hot swapping. This section answers questions about how it works. + + [[howto-reload-static-content]] === Reload Static Content There are several options for hot reloading. The recommended approach is to use <>, as it provides additional development-time features, such as support for fast application restarts -and LiveReload as well as sensible development-time configuration (such as template caching). -Devtools works by monitoring the classpath for changes. This means that static resource -changes must be "built" for the change to take affect. By default, this happens -automatically in Eclipse when you save your changes. In IntelliJ IDEA, Make Project -triggers the necessary build. Due to the +and LiveReload as well as sensible development-time configuration (such as template +caching). Devtools works by monitoring the classpath for changes. This means that static +resource changes must be "built" for the change to take affect. By default, this happens +automatically in Eclipse when you save your changes. In IntelliJ IDEA, the Make Project +command triggers the necessary build. Due to the <>, changes to static resources do not trigger a restart of your application. They do, however, trigger a live reload. Alternatively, running in an IDE (especially with debugging on) is a good way to do -development (all modern IDEs allow reloading of static resources and usually also +development (all modern IDEs allow reloading of static resources and usually also allow hot-swapping of Java class changes). Finally, the <> can @@ -2383,18 +2423,20 @@ for other Groovy customization options. [[howto-reload-fast-restart]] === Fast Application Restarts The `spring-boot-devtools` module includes support for automatic application restarts. -While not as fast as technologies such as http://zeroturnaround.com/software/jrebel/[JRebel] -it is usually significantly faster than a "`cold start`". You should probably give it a try -before investigating some of the more complex reload options discussed later in this document. +While not as fast as technologies such as +http://zeroturnaround.com/software/jrebel/[JRebel] it is usually significantly faster than +a "`cold start`". You should probably give it a try before investigating some of the more +complex reload options discussed later in this document. For more details, see the <> section. + [[howto-reload-java-classes-without-restarting]] === Reload Java Classes without Restarting the Container -Many modern IDEs (Eclipse, IDEA, and others) support hot swapping of bytecode, so, if you make a -change that does not affect class or method signatures, it should reload cleanly with no -side effects. +Many modern IDEs (Eclipse, IDEA, and others) support hot swapping of bytecode. +Consequently, if you make a change that does not affect class or method signatures, it +should reload cleanly with no side effects. @@ -2404,6 +2446,8 @@ side effects. Spring Boot includes build plugins for Maven and Gradle. This section answers common questions about these plugins. + + [[howto-build-info]] === Generate Build Information Both the Maven plugin and the Gradle plugin allow generating build information containing @@ -2494,20 +2538,21 @@ plugin, as shown in the following example: ---- TIP: The commit time in `git.properties` is expected to match the following format: -`yyyy-MM-dd'T'HH:mm:ssZ`. This is the default format for both plugins listed above. Using this format -allows the time to be parsed into a `Date` and its format, when serialized to JSON, to be controlled by -Jackson's date serialization configuration settings. +`yyyy-MM-dd'T'HH:mm:ssZ`. This is the default format for both plugins listed above. Using +this format lets the time be parsed into a `Date` and its format, when serialized to JSON, +to be controlled by Jackson's date serialization configuration settings. [[howto-customize-dependency-versions-with-maven]] [[howto-customize-dependency-versions]] === Customize Dependency Versions -If you use a Maven build that inherits directly or indirectly from `spring-boot-dependencies` -(for instance `spring-boot-starter-parent`) but you want to override a specific -third-party dependency, you can add appropriate `` elements. Browse -the {github-code}/spring-boot-project/spring-boot-dependencies/pom.xml[`spring-boot-dependencies`] -POM for a complete list of properties. For example, to pick a different `slf4j` version +If you use a Maven build that inherits directly or indirectly from +`spring-boot-dependencies` (for instance, `spring-boot-starter-parent`) but you want to +override a specific third-party dependency, you can add appropriate `` +elements. Browse the +{github-code}/spring-boot-project/spring-boot-dependencies/pom.xml[`spring-boot-dependencies`] +POM for a complete list of properties. For example, to pick a different `slf4j` version, you would add the following property: [source,xml,indent=0,subs="verbatim,quotes,attributes"] @@ -2525,13 +2570,15 @@ the artifact yourself instead of overriding the property. WARNING: Each Spring Boot release is designed and tested against a specific set of third-party dependencies. Overriding versions may cause compatibility issues. +// TODO: Where can the reader see those dependencies? + [[howto-create-an-executable-jar-with-maven]] === Create an Executable JAR with Maven -The `spring-boot-maven-plugin` can be used to create an executable '`fat`' JAR. If you -are using the `spring-boot-starter-parent` POM, you can simply declare the plugin and -your jars are repackaged as follows: +The `spring-boot-maven-plugin` can be used to create an executable "`fat`" JAR. If you +use the `spring-boot-starter-parent` POM, you can declare the plugin and your jars are +repackaged as follows: [source,xml,indent=0,subs="verbatim,quotes,attributes"] ---- @@ -2590,7 +2637,7 @@ To produce the two artifacts, one that can be used as a dependency and one that executable, a classifier must be specified. This classifier is applied to the name of the executable archive, leaving the default archive for use as a dependency. -To configure a classifier of `exec` in Maven, the following configuration can be used: +To configure a classifier of `exec` in Maven, you can use the following configuration: [source,xml,indent=0,subs="verbatim,quotes,attributes"] ---- @@ -2617,10 +2664,10 @@ jar support, which assumes that the `jruby-complete.jar` is always directly avai file in its own right. To deal with any problematic libraries, you can flag that specific nested jars should be -automatically unpacked to the '`temp folder`' when the executable jar first runs. +automatically unpacked to the "`temp folder`" when the executable jar first runs. -For example, to indicate that JRuby should be flagged for unpacking by using the Maven Plugin, -you would add the following configuration: +For example, to indicate that JRuby should be flagged for unpacking by using the Maven +Plugin, you would add the following configuration: [source,xml,indent=0,subs="verbatim,quotes,attributes"] ---- @@ -2646,9 +2693,10 @@ you would add the following configuration: [[howto-create-a-nonexecutable-jar]] === Create a Non-executable JAR with Exclusions -Often, if you have an executable and a non-executable jar as build products, the executable -version has additional configuration files that are not needed in a library jar. -For example, the `application.yml` configuration file might by excluded from the non-executable JAR. +Often, if you have an executable and a non-executable jar as two separate build products, +the executable version has additional configuration files that are not needed in a library +jar. For example, the `application.yml` configuration file might by excluded from the +non-executable JAR. In Maven, the executable jar must be the main artifact and you can add a classified jar for the library, as follows: @@ -2687,10 +2735,11 @@ for the library, as follows: [[howto-remote-debug-maven-run]] === Remote Debug a Spring Boot Application Started with Maven -To attach a remote debugger to a Spring Boot application that was started with Maven, you can use -the `jvmArguments` property of the {spring-boot-maven-plugin-site}/[maven plugin]. +To attach a remote debugger to a Spring Boot application that was started with Maven, you +can use the `jvmArguments` property of the {spring-boot-maven-plugin-site}/[maven plugin]. -See {spring-boot-maven-plugin-site}/examples/run-debug.html[this example] for more details. +See {spring-boot-maven-plugin-site}/examples/run-debug.html[this example] for more +details. @@ -2701,18 +2750,18 @@ archive. To make it executable, you can either use the `spring-boot-antlib` module or you can follow these instructions: . If you are building a jar, package the application's classes and resources in a nested - `BOOT-INF/classes` directory. If you are building a war, package the application's - classes in a nested `WEB-INF/classes` directory as usual. +`BOOT-INF/classes` directory. If you are building a war, package the application's +classes in a nested `WEB-INF/classes` directory as usual. . Add the runtime dependencies in a nested `BOOT-INF/lib` directory for a jar or - `WEB-INF/lib` for a war. Remember *not* to compress the entries in the archive. +`WEB-INF/lib` for a war. Remember *not* to compress the entries in the archive. . Add the `provided` (embedded container) dependencies in a nested `BOOT-INF/lib` - directory for a jar or `WEB-INF/lib-provided` for a war. Remember *not* to compress the - entries in the archive. +directory for a jar or `WEB-INF/lib-provided` for a war. Remember *not* to compress the +entries in the archive. . Add the `spring-boot-loader` classes at the root of the archive (so that the `Main-Class` - is available). +is available). . Use the appropriate launcher (such as `JarLauncher` for a jar file) as a `Main-Class` - attribute in the manifest and specify the other properties it needs as manifest entries -- - principally, by setting a `Start-Class` property. +attribute in the manifest and specify the other properties it needs as manifest entries -- +principally, by setting a `Start-Class` property. The following example shows how to build an executable archive with Ant: @@ -2742,7 +2791,8 @@ The following example shows how to build an executable archive with Ant: ---- The {github-code}/spring-boot-samples/spring-boot-sample-ant[Ant Sample] has a -`build.xml` file with a `manual` task that should work if you run it with the following command: +`build.xml` file with a `manual` task that should work if you run it with the following +command: [indent=0,subs="verbatim,quotes,attributes"] ---- @@ -2764,14 +2814,16 @@ Then you can run the application with the following command: Spring Boot supports traditional deployment as well as more modern forms of deployment. This section answers common questions about traditional deployment. + + [[howto-create-a-deployable-war-file]] === Create a Deployable War File The first step in producing a deployable war file is to provide a -`SpringBootServletInitializer` subclass and override its `configure` method. 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 +`SpringBootServletInitializer` subclass and override its `configure` method. 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,quotes,attributes"] @@ -2791,10 +2843,10 @@ following example: } ---- -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: +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: [source,xml,indent=0,subs="verbatim,quotes,attributes"] ---- @@ -2841,8 +2893,8 @@ case) as being provided: } ---- -NOTE: `providedRuntime` is preferred to Gradle's `compileOnly` configuration. Among other -limitations, `compileOnly` dependencies are not on the test classpath so any web-based +TIP: `providedRuntime` is preferred to Gradle's `compileOnly` configuration. Among other +limitations, `compileOnly` dependencies are not on the test classpath, so any web-based integration tests fail. If you use the <>, @@ -2852,15 +2904,15 @@ that, in addition to being deployable to a servlet container, you can also run y application by using `java -jar` on the command line. TIP: Take a look at Spring Boot's sample applications for a -{github-code}/spring-boot-samples/spring-boot-sample-traditional/pom.xml[Maven-based example] -of the previously described configuration. +{github-code}/spring-boot-samples/spring-boot-sample-traditional/pom.xml[Maven-based +example] of the previously described configuration. [[howto-create-a-deployable-war-file-for-older-containers]] === Create a Deployable War File for Older Servlet Containers Older Servlet containers do not have support for the `ServletContextInitializer` bootstrap -process used in Servlet 3.0. You can still use Spring and Spring Boot in these containers +process used in Servlet 3.0. You can still use Spring and Spring Boot in these containers, but you are going to need to add a `web.xml` to your application and configure it to load an `ApplicationContext` via a `DispatcherServlet`. @@ -2876,9 +2928,9 @@ creating a deployable war application and then migrating it later to an executab or jar. See the http://spring.io/guides/gs/convert-jar-to-war/[Getting Started Guide on Converting a jar to a war]. -To create a deployable war by extending `SpringBootServletInitializer` (for example, in a class -called `Application`) and add the Spring Boot `@SpringBootApplication` annotation, use -code similar to that shown in the following example: +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,quotes,attributes"] ---- @@ -2908,15 +2960,15 @@ Static resources can be moved to `/public` (or `/static` or `/resources` or Vanilla usage of Spring `DispatcherServlet` and Spring Security should require no further changes. If you have other features in your application (for instance, using other servlets or filters), you may need to add some configuration to your `Application` -context, by replacing those elements from the `web.xml` as follows: +context, by replacing those elements from the `web.xml`, as follows: * A `@Bean` of type `Servlet` or `ServletRegistrationBean` installs that bean in the - container as if it were a `` and `` in `web.xml`. +container as if it were a `` and `` in `web.xml`. * A `@Bean` of type `Filter` or `FilterRegistrationBean` behaves similarly (as a - `` and ``). +`` and ``). * An `ApplicationContext` in an XML file can be added through an `@ImportResource` in - your `Application`. Alternatively, simple cases where annotation configuration is - heavily used already can be recreated in a few lines as `@Bean` definitions. +your `Application`. Alternatively, simple cases where annotation configuration is +heavily used already can be recreated in a few lines as `@Bean` definitions. 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: @@ -2932,7 +2984,7 @@ your `Application`, as shown in the following example: ==== 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 the `main` method, in a class similar to the +`SpringBootServletInitializer` callback and in the `main` method in a class similar to the following: [source,java,indent=0,subs="verbatim,quotes,attributes"] @@ -3038,7 +3090,7 @@ and so on), so you cannot use the same application in a Servlet 2.5 container. It *is*, however, possible to run a Spring Boot application on an older container with some special tools. If you include `org.springframework.boot:spring-boot-legacy` as a dependency (https://github.com/scratches/spring-boot-legacy[maintained separately] to the -core of Spring Boot and currently available at 1.0.2.RELEASE), all you should need to do +core of Spring Boot and currently available at 1.1.0.RELEASE), all you need to do is create a `web.xml` and declare a context listener to create the application context and your filters and servlets. The context listener is a special purpose one for Spring Boot, but the rest of it is normal for a Spring application in Servlet 2.5. The following Maven @@ -3088,9 +3140,10 @@ example shows how to set up a Spring Boot project to run in a Servlet 2.5 contai ---- -In the preceding example, we use a single application context (the one created by the context -listener) and attach it to the `DispatcherServlet` by using an `init` parameter. This is -normal in a Spring Boot application (you normally only have one application context). +In the preceding example, we use a single application context (the one created by the +context listener) and attach it to the `DispatcherServlet` by using an `init` parameter. +This is normal in a Spring Boot application (you normally only have one application +context). diff --git a/spring-boot-project/spring-boot-docs/src/main/asciidoc/index.adoc b/spring-boot-project/spring-boot-docs/src/main/asciidoc/index.adoc index 5f71dcb6dd3..ab51e6bcb4c 100644 --- a/spring-boot-project/spring-boot-docs/src/main/asciidoc/index.adoc +++ b/spring-boot-project/spring-boot-docs/src/main/asciidoc/index.adoc @@ -39,15 +39,24 @@ Phillip Webb; Dave Syer; Josh Long; Stéphane Nicoll; Rob Winch; Andy Wilkinson; :spring-boot-maven-plugin-site: http://docs.spring.io/spring-boot/docs/{spring-boot-docs-version}/maven-plugin/ :spring-boot-gradle-plugin: http://docs.spring.io/spring-boot/docs/{spring-boot-docs-version}/gradle-plugin/ :spring-reference: http://docs.spring.io/spring/docs/{spring-docs-version}/spring-framework-reference/ +:spring-rest-docs: http://projects.spring.io/spring-restdocs/ +:spring-integration: http://projects.spring.io/spring-integration/ +:spring-session: https://projects.spring.io/spring-session/ +:spring-framework: http://projects.spring.io/spring-framework/ +:spring-security: http://projects.spring.io/spring-security/ +:spring-data-jpa: http://projects.spring.io/spring-data-jpa/ :spring-security-reference: http://docs.spring.io/spring-security/site/docs/{spring-security-docs-version}/reference/htmlsingle :spring-security-oauth2-reference: http://projects.spring.io/spring-security-oauth/docs/oauth2.html :spring-webservices-reference: http://docs.spring.io/spring-ws/docs/{spring-webservices-docs-version}/reference/ :spring-javadoc: http://docs.spring.io/spring/docs/{spring-docs-version}/javadoc-api/org/springframework +:spring-framework-javadoc: https://docs.spring.io/spring-framework/docs/{spring-docs-version}/javadoc-api/org/springframework/ :spring-amqp-javadoc: http://docs.spring.io/spring-amqp/docs/current/api/org/springframework/amqp :spring-batch-javadoc: http://docs.spring.io/spring-batch/apidocs/org/springframework/batch :spring-data-javadoc: http://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa :spring-data-commons-javadoc: http://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data :spring-data-mongo-javadoc: http://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb +:spring-data-mongo: http://projects.spring.io/spring-data-mongodb/ +:spring-data: http://projects.spring.io/spring-data/ :spring-data-rest-javadoc: http://docs.spring.io/spring-data/rest/docs/current/api/org/springframework/data/rest :gradle-userguide: http://www.gradle.org/docs/current/userguide :propdeps-plugin: https://github.com/spring-projects/gradle-plugins/tree/master/propdeps-plugin diff --git a/spring-boot-project/spring-boot-docs/src/main/asciidoc/production-ready-features.adoc b/spring-boot-project/spring-boot-docs/src/main/asciidoc/production-ready-features.adoc index 48af0c0396b..e7ad3cb00cd 100644 --- a/spring-boot-project/spring-boot-docs/src/main/asciidoc/production-ready-features.adoc +++ b/spring-boot-project/spring-boot-docs/src/main/asciidoc/production-ready-features.adoc @@ -19,7 +19,7 @@ features is to add a dependency to the `spring-boot-starter-actuator` '`Starter` .Definition of Actuator **** -An actuator is a manufacturing term, referring to a mechanical device for moving or +An actuator is a manufacturing term that refers to a mechanical device for moving or controlling something. Actuators can generate a large amount of motion from a small change. **** @@ -71,8 +71,8 @@ The following technology-agnostic endpoints are available: |Displays a complete list of all the Spring beans in your application. |`conditions` -|Showing the conditions that were evaluated on configuration and auto-configuration - classes and the reasons why they did or did not match. +|Shows the conditions that were evaluated on configuration and auto-configuration +classes and the reasons why they did or did not match. |`configprops` |Displays a collated list of all `@ConfigurationProperties`. @@ -92,6 +92,9 @@ The following technology-agnostic endpoints are available: |`loggers` |Shows and modifies the configuration of loggers in the application. +// TODO "and modifies"? Why would the endpoint modify the configuration? Do we mean "shows +// any modifications"? + |`liquibase` |Shows any Liquibase database migrations that have been applied. @@ -106,7 +109,7 @@ The following technology-agnostic endpoints are available: |`sessions` |Allows retrieval and deletion of user sessions from a Spring Session-backed session - store. Not available when using Spring Session's support for reactive web applications. +store. Not available when using Spring Session's support for reactive web applications. |`shutdown` |Lets the application be gracefully shutdown (not enabled by default). @@ -139,21 +142,20 @@ content. |=== To learn more about the Actuator's endpoints and their request and response formats, -please refer to the separate API documentation that is available in the following formats: - -* {spring-boot-actuator-api}/html[HTML] -* {spring-boot-actuator-api}/pdf/spring-boot-actuator-web-api.pdf[PDF] +please refer to the separate API documentation ({spring-boot-actuator-api}/html[HTML] or +{spring-boot-actuator-api}/pdf/spring-boot-actuator-web-api.pdf[PDF]). [[production-ready-endpoints-exposing-endpoints]] === Exposing Endpoints Since Endpoints may contain sensitive information, careful consideration should be given -about when to expose them. Out of the box, Spring Boot will expose all enabled endpoints -over JMX, but only the `health` and `info` endpoints over HTTP. +about when to expose them. By default, Spring Boot exposes all enabled endpoints +over JMX but only the `health` and `info` endpoints over HTTP. -To change the endpoints that are exposed you can use the `expose` and `exclude` property -for the technology. For example, to only expose the `health` over JMX you would use: +To change the endpoints that are exposed, you can use the `expose` and `exclude` property +for the technology. For example, to only expose the `health` over JMX you would set the +following property: .application.properties [source,properties,indent=0] @@ -162,7 +164,7 @@ for the technology. For example, to only expose the `health` over JMX you would ---- The `*` character can be used to indicate all endpoints. For example, to expose everything -over HTTP except the `env` endpoint you would use: +over HTTP except the `env` endpoint, you would use the following properties: .application.properties [source,properties,indent=0] @@ -171,10 +173,10 @@ over HTTP except the `env` endpoint you would use: management.endpoints.web.exclude=env ---- -NOTE: If your application is exposed publicly we strongly recommend that you also +NOTE: If your application is exposed publicly, we strongly recommend that you also <>. -TIP: If you want to implement your own strategy for when endpoints are exposed you can +TIP: If you want to implement your own strategy for when endpoints are exposed, you can register an `EndpointFilter` bean. @@ -182,11 +184,11 @@ register an `EndpointFilter` bean. [[production-ready-endpoints-security]] === Securing HTTP Endpoints You should take care to secure HTTP endpoints in the same way that you would any other -sensitive URL. Spring Boot will not apply any security on your behalf, however, it does -provide some convenient ``RequestMatcher``s that can be used in combination with Spring -Security. +sensitive URL. Spring Boot does not apply any security on your behalf. However, it does +provide some convenient RequestMatcher` objects that can be used in combination with +Spring Security. -A typical Spring Security configuration could look something like this: +A typical Spring Security configuration might look something like the following example: [source,java,indent=0] ---- @@ -204,9 +206,11 @@ A typical Spring Security configuration could look something like this: } ---- -The above uses `EndpointRequest.toAnyEndpoint()` to match a request to any endpoint, then -ensure that all have the `ENDPOINT_ADMIN` role. Several other matcher methods are -also available on `EndpointRequest` (see the API documentation for details). +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`. See the API documentation +({spring-boot-actuator-api}/html[HTML] or +{spring-boot-actuator-api}/pdf/spring-boot-actuator-web-api.pdf[PDF]) for details. If you deploy applications behind a firewall, you may prefer that all your actuator endpoints can be accessed without requiring authentication. You can do so by changing the @@ -223,9 +227,9 @@ endpoints can be accessed without requiring authentication. You can do so by cha [[production-ready-customizing-endpoints]] === Customizing Endpoints Endpoints can be customized by using Spring properties. You can change whether an -endpoint is `enabled` and the amount of time it will cache responses. +endpoint is `enabled` and the amount of time for which it caches responses. -For example, the following `application.properties` changes the time-to-live of the +For example, the following `application.properties` file changes the time-to-live of the `beans` endpoint to 10 seconds and also enables `shutdown`: [source,properties,indent=0] @@ -248,9 +252,9 @@ disable _all_ endpoints except for `info`: management.endpoint.info.enabled=true ---- -NOTE: Disabled endpoints are removed entirely from the `ApplicationContext`. If you only -want to change the technologies over which an endpoint is exposed you can use the `expose` -and `exclude` properties (see <>). +NOTE: Disabled endpoints are removed entirely from the `ApplicationContext`. If you want +to change only the technologies over which an endpoint is exposed, you can use the +`expose` and `exclude` properties (see <>). @@ -269,13 +273,13 @@ disabled to prevent the possibility of a clash with other mappings. [[production-ready-endpoint-custom-mapping]] === Actuator Web Endpoint Paths -By default, endpoints are exposed over HTTP under the `/actuator` path using ID of the -endpoint. For example, the `beans` endpoint is exposed under `/actuator/beans`. If you -want to map endpoints to a different path you can use the -`management.endpoints.web.path-mapping` property. You can also use -`management.endpoints.web.base-path` if you want change the base path. +By default, endpoints are exposed over HTTP under the `/actuator` path by using the ID of +the endpoint. For example, the `beans` endpoint is exposed under `/actuator/beans`. If you +want to map endpoints to a different path, you can use the +`management.endpoints.web.path-mapping` property. Also, if you want change the base path, +you can use `management.endpoints.web.base-path`. -Here's an example that remaps `/actuator/health` to `/healthcheck`: +The following example remaps `/actuator/health` to `/healthcheck`: .application.properties [source,properties,indent=0] @@ -289,8 +293,8 @@ Here's an example that remaps `/actuator/health` to `/healthcheck`: [[production-ready-endpoint-cors]] === CORS Support http://en.wikipedia.org/wiki/Cross-origin_resource_sharing[Cross-origin resource sharing] -(CORS) is a http://www.w3.org/TR/cors/[W3C specification] that allows you to specify in a -flexible way what kind of cross domain requests are authorized. If you use Spring MVC or +(CORS) is a http://www.w3.org/TR/cors/[W3C specification] that lets you specify in a +flexible way what kind of cross-domain requests are authorized. If you use Spring MVC or Spring WebFlux, Actuator's web endpoints can be configured to support such scenarios. CORS support is disabled by default and is only enabled once the @@ -303,29 +307,32 @@ configuration permits `GET` and `POST` calls from the `example.com` domain: management.endpoints.web.cors.allowed-methods=GET,POST ---- -TIP: See {sc-spring-boot-actuator-autoconfigure}/endpoint/web/CorsEndpointProperties.{sc-ext}[CorsEndpointProperties] for a complete list of options. +TIP: See +{sc-spring-boot-actuator-autoconfigure}/endpoint/web/CorsEndpointProperties.{sc-ext}[CorsEndpointProperties] +for a complete list of options. [[production-ready-customizing-endpoints-programmatically]] === Adding Custom Endpoints If you add a `@Bean` annotated with `@Endpoint`, any methods annotated with -`@ReadOperation`, `@WriteOperation` or `@DeleteOperation` are automatically exposed over +`@ReadOperation`, `@WriteOperation`, or `@DeleteOperation` are automatically exposed over JMX and, in a web application, over HTTP as well. -You can also write technology specific endpoints by using `@JmxEndpoint` or +You can also write technology-specific endpoints by using `@JmxEndpoint` or `@WebEndpoint`. These endpoints are filtered to their respective technologies. For -example, `@WebEndpoint` will be exposed only over HTTP and not over JMX. +example, `@WebEndpoint` is exposed only over HTTP and not over JMX. -Finally, it's possible to write technology specific extensions using -`@EndpointWebExtension` and `@EndpointJmxExtension`. These annotations allow you to -provide technology specific operations to augment an existing endpoint. +Finally, you can write technology-specific extensions by using `@EndpointWebExtension` and +`@EndpointJmxExtension`. These annotations let you provide technology-specific operations +to augment an existing endpoint. TIP: If you add endpoints as a library feature, consider adding a configuration class annotated with `@ManagementContextConfiguration` to `/META-INF/spring.factories` under the -key, `org.springframework.boot.actuate.autoconfigure.ManagementContextConfiguration`. If -you do so and if your users ask for a separate management port or address, the endpoint -moves to a child context with all the other web endpoints. +following key: +`org.springframework.boot.actuate.autoconfigure.ManagementContextConfiguration`. If you do +so and if your users ask for a separate management port or address, the endpoint moves to +a child context with all the other web endpoints. @@ -335,7 +342,7 @@ You can use health information to check the status of your running application. often used by monitoring software to alert someone when a production system goes down. The information exposed by the `health` endpoint depends on the `management.endpoint.health.show-details` property. By default, the property's value is -`false` and a simple '`status`' message is returned. When the property's value is set to +`false` and a simple "`status`" message is returned. When the property's value is set to `true`, additional details from the individual health indicators are also displayed. Health information is collected from all @@ -393,7 +400,7 @@ The following `HealthIndicators` are auto-configured by Spring Boot when appropr |Checks that a Solr server is up. |=== -TIP: It is possible to disable them all using the `management.health.defaults.enabled` +TIP: You can disable them all by setting the `management.health.defaults.enabled` property. @@ -440,7 +447,7 @@ the `management.health.status.order` configuration property. For example, assume a new `Status` with code `FATAL` is being used in one of your `HealthIndicator` implementations. To configure the severity order, add the following -to your application properties: +property to your application properties: [source,properties,indent=0] ---- @@ -482,17 +489,17 @@ The following table shows the default status mappings for the built-in statuses: [[reactive-health-indicators]] ==== Reactive Health Indicators -For reactive applications, such as those using Spring WebFlux, ReactiveHealthIndicators -provide a non-blocking contract for getting application health. Similar to a traditional +For reactive applications, such as those using Spring WebFlux, `ReactiveHealthIndicator` +provides a non-blocking contract for getting application health. Similar to a traditional `HealthIndicator`, health information is collected from all {sc-spring-boot-actuator}/health/ReactiveHealthIndicator.{sc-ext}[`ReactiveHealthIndicator`] -beans defined in your `ApplicationContext`. Regular HealthIndicators that do not check -against a reactive API are included and executed on the elastic scheduler. +beans defined in your `ApplicationContext`. Regular `HealthIndicator` beans that do not +check against a reactive API are included and executed on the elastic scheduler. To provide custom health information from a reactive API, you can register Spring beans that implement the -{sc-spring-boot-actuator}/health/ReactiveHealthIndicator.{sc-ext}[`ReactiveHealthIndicator`] interface. -The following code shows a sample `ReactiveHealthIndicator` implementation: +{sc-spring-boot-actuator}/health/ReactiveHealthIndicator.{sc-ext}[`ReactiveHealthIndicator`] +interface. The following code shows a sample `ReactiveHealthIndicator` implementation: [source,java,indent=0] ---- @@ -525,7 +532,7 @@ appropriate: |Checks that a Redis server is up. |=== -TIP: Those reactive indicators replace the regular ones if necessary. Also, any +TIP: If necessary, reactive indicators replace the regular ones. Also, any `HealthIndicator` that is not handled explicitly is wrapped automatically. @@ -535,34 +542,35 @@ TIP: Those reactive indicators replace the regular ones if necessary. Also, any Application information exposes various information collected from all {sc-spring-boot-actuator}/info/InfoContributor.{sc-ext}[`InfoContributor`] beans defined in your `ApplicationContext`. Spring Boot includes a number of auto-configured -`InfoContributors`, and you can write your own. +`InfoContributor` beans, and you can write your own. [[production-ready-application-info-autoconfigure]] ==== Auto-configured InfoContributors -The following `InfoContributors` are auto-configured by Spring Boot, when appropriate: +The following `InfoContributor ` beans are auto-configured by Spring Boot, when +appropriate: [cols="1,4"] |=== |Name |Description |{sc-spring-boot-actuator}/info/EnvironmentInfoContributor.{sc-ext}[`EnvironmentInfoContributor`] -|Expose any key from the `Environment` under the `info` key. +|Exposes any key from the `Environment` under the `info` key. |{sc-spring-boot-actuator}/info/GitInfoContributor.{sc-ext}[`GitInfoContributor`] -|Expose git information if a `git.properties` file is available. +|Exposes git information if a `git.properties` file is available. |{sc-spring-boot-actuator}/info/BuildInfoContributor.{sc-ext}[`BuildInfoContributor`] -|Expose build information if a `META-INF/build-info.properties` file is available. +|Exposes build information if a `META-INF/build-info.properties` file is available. |=== -TIP: It is possible to disable them all using the `management.info.defaults.enabled` +TIP: It is possible to disable them all by setting the `management.info.defaults.enabled` property. [[production-ready-application-info-env]] ==== Custom Application Information You can customize the data exposed by the `info` endpoint by setting `+info.*+` Spring -properties. All `Environment` properties under the info key are automatically exposed. +properties. All `Environment` properties under the `info` key are automatically exposed. For example, you could add the following settings to your `application.properties` file: [source,properties,indent=0] @@ -593,7 +601,7 @@ Assuming you use Maven, you could rewrite the preceding example as follows: ==== Git Commit Information Another useful feature of the `info` endpoint is its ability to publish information about the state of your `git` source code repository when the project was built. If a -`GitProperties` bean is available, the `git.branch`, `git.commit.id` and +`GitProperties` bean is available, the `git.branch`, `git.commit.id`, and `git.commit.time` properties are exposed. TIP: A `GitProperties` bean is auto-configured if a `git.properties` file is available at @@ -668,7 +676,7 @@ enabled endpoints to be exposed over HTTP. The default convention is to use the the endpoint with a prefix of `/actuator` as the URL path. For example, `health` is exposed as `/actuator/health`. -TIP: Actuator is supported natively with Spring MVC, Spring WebFlux and Jersey. +TIP: Actuator is supported natively with Spring MVC, Spring WebFlux, and Jersey. @@ -685,11 +693,11 @@ management endpoint, as shown in the following example: ---- The preceding `application.properties` example changes the endpoint from -`/actuator/{id}` to `/manage/{id}` (e.g. `/manage/info`). +`/actuator/{id}` to `/manage/{id}` (for example, `/manage/info`). NOTE: Unless the management port has been configured to -<>, `management.endpoints.web.base-path` is relative to +<>, `management.endpoints.web.base-path` is relative to `server.servlet.context-path`. If `management.server.port` is configured, `management.endpoints.web.base-path` is relative to `management.server.servlet.context-path`. @@ -699,7 +707,7 @@ HTTP port>>, `management.endpoints.web.base-path` is relative to [[production-ready-customizing-management-server-port]] === Customizing the Management Server Port Exposing management endpoints by using the default HTTP port is a sensible choice for -cloud based deployments. If, however, your application runs inside your own data center, +cloud-based deployments. If, however, your application runs inside your own data center, you may prefer to expose endpoints by using a different HTTP port. You can set the `management.server.port` property to change the HTTP port, as shown in @@ -713,15 +721,16 @@ the following example: Since your management port is often protected by a firewall and not exposed to the public, you might not need security on the management endpoints, even if your main application is secure. In that case, you should have Spring Security on the classpath, -and you can disable management security as follows: +and you can disable management security, as follows: [source,properties,indent=0] ---- management.security.enabled=false ---- -(If you do not have Spring Security on the classpath, there is no need to explicitly -disable the management security in this way. Doing so might even break the application.) +CAUTION: If you do not have Spring Security on the classpath, there is no need to +explicitly disable the management security in this way. Doing so might even break the +application. @@ -729,7 +738,7 @@ disable the management security in this way. Doing so might even break the appli === Configuring Management-specific SSL When configured to use a custom port, the management server can also be configured with its own SSL by using the various `management.server.ssl.*` properties. For example, doing -so lets a management server be available via HTTP while the main application uses HTTPS, +so lets a management server be available over HTTP while the main application uses HTTPS, as shown in the following property settings: [source,properties,indent=0] @@ -766,7 +775,7 @@ the `management.server.address` property. Doing so can be useful if you want to only on an internal or ops-facing network or to listen only for connections from `localhost`. -NOTE: You can only listen on a different address if the port is different from the main +NOTE: You can listen on a different address only when the port differs from the main server port. The following example `application.properties` does not allow remote management @@ -802,7 +811,7 @@ the `org.springframework.boot` domain. [[production-ready-custom-mbean-names]] === Customizing MBean Names -The name of the MBean is usually generated from the `id` of the endpoint. For example the +The name of the MBean is usually generated from the `id` of the endpoint. For example, the `health` endpoint is exposed as `org.springframework.boot:type=Endpoint,name=Health`. If your application contains more than one Spring `ApplicationContext`, you may find that @@ -854,9 +863,9 @@ server. [[production-ready-customizing-jolokia]] ==== Customizing Jolokia -Jolokia has a number of settings that you would traditionally configure using servlet -parameters. With Spring Boot, you can use your `application.properties`. Prefix the -parameter with `management.jolokia.config.`, as shown in the following example: +Jolokia has a number of settings that you would traditionally configure by setting servlet +parameters. With Spring Boot, you can use your `application.properties` file. To do so, +prefix the parameter with `management.jolokia.config.`, as shown in the following example: [source,properties,indent=0] ---- @@ -900,8 +909,8 @@ one of: [[production-ready-logger-configuration]] === Configure a Logger -In order to configure a given logger, you `POST` a partial entity to the resource's URI, -as shown in the following example: +To configure a given logger, `POST` a partial entity to the resource's URI, as shown in +the following example: [source,json,indent=0] ---- @@ -910,7 +919,7 @@ as shown in the following example: } ---- -TIP: To "reset" the specific level of the logger (and use the default configuration +TIP: To "`reset`" the specific level of the logger (and use the default configuration instead), you can pass a value of `null` as the `configuredLevel`. @@ -919,7 +928,7 @@ instead), you can pass a value of `null` as the `configuredLevel`. == Metrics Spring Boot Actuator provides dependency management and auto-configuration for https://micrometer.io[Micrometer], an application metrics facade that supports numerous -monitoring systems: +monitoring systems, including: - https://github.com/Netflix/atlas[Atlas] - https://www.datadoghq.com[Datadog] @@ -928,6 +937,10 @@ monitoring systems: - https://www.influxdata.com[Influx] - https://prometheus.io[Prometheus] +NOTE: At the time of this writing, the number of monitoring systems supported by +Micrometer is growing rapidly. See the https://micrometer.io[Micrometer project] for more +information. + Micrometer provides a separate module for each supported monitoring system. Depending on one (or more) of these modules is sufficient to get started with Micrometer in your Spring Boot application. To learn more about Micrometer's capabilities, please refer to @@ -951,10 +964,10 @@ customized by setting the `management.metrics.web.server.requests-metrics-name` ==== Spring MVC Metric Tags By default, Spring MVC-related metrics are tagged with the following information: -- The request's method. -- The request's URI (templated if possible). -- The simple class name of any exception that was thrown while handling the request. -- The response's status. +* The request's method. +* The request's URI (templated if possible). +* The simple class name of any exception that was thrown while handling the request. +* The response's status. To customize the tags, provide a `@Bean` that implements `WebMvcTagsProvider`. @@ -971,23 +984,23 @@ the name by setting the `management.metrics.web.server.requests-metrics-name` pr [[production-ready-metrics-web-flux-tags]] -==== WebFlux Metric Tags +==== WebFlux Metrics Tags By default, WebFlux-related metrics for the annotation-based programming model are tagged with the following information: -- The request's method. -- The request's URI (templated if possible). -- The simple class name of any exception that was thrown while handling the request. -- The response's status. +* The request's method. +* The request's URI (templated if possible). +* The simple class name of any exception that was thrown while handling the request. +* The response's status. To customize the tags, provide a `@Bean` that implements `WebFluxTagsProvider`. By default, metrics for the functional programming model are tagged with the following information: -- The request's method -- The request's URI (templated if possible). -- The response's status. +* The request's method +* The request's URI (templated if possible). +* The response's status. To customize the tags, use the `defaultTags` method on your `RouterFunctionMetrics` instance. @@ -1010,10 +1023,10 @@ customized by setting the `management.metrics.web.client.requests-metrics-name` By default, metrics generated by an instrumented `RestTemplate` are tagged with the following information: -- The request's method. -- The request's URI (templated if possible). -- The response's status. -- The request URI's host. +* The request's method. +* The request's URI (templated if possible). +* The response's status. +* The request URI's host. @@ -1042,15 +1055,15 @@ is required. A `CacheMetricsRegistrar` bean is made available to make that proce [[production-ready-metrics-jdbc]] -=== DataSource metrics -Auto-configuration will enable the instrumentation of all available ``DataSource``s with a -metric named `data.source`. Data source instrumentation results in gauges representing -the currently active, maximum allowed, and minimum allowed connections in the pool. Each -of these gauges has a name which is prefixed by `data.source` by default. The prefix can -be customized by using the `management.metrics.jdbc.datasource-metric-name` property. - -Metrics will also be tagged by the name of the `DataSource` computed based on the bean -name. +=== DataSource Metrics +Auto-configuration enables the instrumentation of all available ``DataSource`` objects +with a metric named `data.source`. Data source instrumentation results in gauges +representing the currently active, maximum allowed, and minimum allowed connections in the +pool. Each of these gauges has a name that is prefixed by `data.source` by default. The +prefix can be customized by setting the `management.metrics.jdbc.datasource-metric-name` +property. + +Metrics are also tagged by the name of the `DataSource` computed based on the bean name. @@ -1115,13 +1128,15 @@ Auto-configuration enables binding of a number of Spring Integration-related met [[production-ready-auditing]] == Auditing -Once Spring Security is in play Spring Boot Actuator has a flexible audit framework that -publishes events (by default, '`authentication success`', '`failure`' and -'`access denied`' exceptions). This feature can be very useful for reporting and for +Once Spring Security is in play, Spring Boot Actuator has a flexible audit framework that +publishes events (by default, "`authentication success`", "`failure`" and +"`access denied`" exceptions). This feature can be very useful for reporting and for implementing a lock-out policy based on authentication failures. To customize published security events, you can provide your own implementations of `AbstractAuthenticationAuditListener` and `AbstractAuthorizationAuditListener`. +// TODO A sample showing how to customize published security events would be good. + You can also use the audit services for your own business events. To do so, either inject the existing `AuditEventRepository` into your own components and use that directly or publish an `AuditApplicationEvent` with the Spring `ApplicationEventPublisher` (by @@ -1211,18 +1226,20 @@ In the `spring-boot` module, you can find two classes to create files that are o useful for process monitoring: * `ApplicationPidFileWriter` creates a file containing the application PID (by default, -in the application directory with the file name, `application.pid`). +in the application directory with a file name of `application.pid`). * `EmbeddedServerPortFileWriter` creates a file (or files) containing the ports of the -embedded server (by default, in the application directory with the file name +embedded server (by default, in the application directory with a file name of `application.port`). -By default, these writers are not activated, but you can enable them in one of the ways -described in the next section. +By default, these writers are not activated, but you can enable: + +* <> +* <> [[production-ready-process-monitoring-configuration]] -=== Extend Configuration +=== Extending Configuration In the `META-INF/spring.factories` file, you can activate the listener(s) that writes a PID file, as shown in the following example: diff --git a/spring-boot-project/spring-boot-docs/src/main/asciidoc/spring-boot-cli.adoc b/spring-boot-project/spring-boot-docs/src/main/asciidoc/spring-boot-cli.adoc index 170883019df..606a798d513 100644 --- a/spring-boot-project/spring-boot-docs/src/main/asciidoc/spring-boot-cli.adoc +++ b/spring-boot-project/spring-boot-docs/src/main/asciidoc/spring-boot-cli.adoc @@ -79,7 +79,7 @@ using, as follows: [[cli-run]] === Running Applications with the CLI You can compile and run Groovy source code by using the `run` command. The Spring Boot CLI -is completely self-contained, so you don't need any external Groovy installation. +is completely self-contained, so you do not need any external Groovy installation. The following example shows a "`hello world`" web application written in Groovy: @@ -97,14 +97,14 @@ The following example shows a "`hello world`" web application written in Groovy: } ---- -To compile and run the application type the following command: +To compile and run the application, type the following command: [indent=0,subs="verbatim,quotes,attributes"] ---- $ spring run hello.groovy ---- -To pass command-line arguments to the application, use a `--` to separate the commands +To pass command-line arguments to the application, use `--` to separate the commands from the "`spring`" command arguments, as shown in the following example: [indent=0,subs="verbatim,quotes,attributes"] @@ -186,10 +186,11 @@ in the Spring Boot CLI source code to understand exactly how customizations are ==== Deduced "`grab`" Coordinates Spring Boot extends Groovy's standard `@Grab` support by letting you specify a dependency without a group or version (for example, `@Grab('freemarker')`). Doing so consults Spring -Boot's default dependency metadata to deduce the artifact's group and version. Note that -the default metadata is tied to the version of the CLI that you use – it changes only when -you move to a new version of the CLI, putting you in control of when the versions of your -dependencies may change. A table showing the dependencies and their versions that are +Boot's default dependency metadata to deduce the artifact's group and version. + +NOTE: The default metadata is tied to the version of the CLI that you use. it changes only +when you move to a new version of the CLI, putting you in control of when the versions of +your dependencies may change. A table showing the dependencies and their versions that are included in the default metadata can be found in the <>. @@ -242,8 +243,8 @@ as shown in the following example: "com.example.another-bom:1.0.0"]) ---- -The preceding example indicates that dependency management in `another-bom` overrides the -dependency management in `custom-bom`. +The preceding example indicates that the dependency management in `another-bom` overrides +the dependency management in `custom-bom`. You can use `@DependencyManagementBom` anywhere that you can use `@Grab`. However, to ensure consistent ordering of the dependency management, you can use @@ -282,10 +283,10 @@ jar file, as shown in the following example: The resulting jar contains the classes produced by compiling the application and all of the application's dependencies so that it can then be run by using `java -jar`. The jar -file also contains entries from the application's classpath. You can add explicit paths to -the jar by using `--include` and `--exclude`. Both are comma-separated, and both accept -prefixes, in the form of "`+`" and "`-`", to signify that they should be removed from the -defaults. The default includes are as follows: +file also contains entries from the application's classpath. You can add and remove +explicit paths to the jar by using `--include` and `--exclude`. Both are comma-separated, +and both accept prefixes, in the form of "`+`" and "`-`", to signify that they should be +removed from the defaults. The default includes are as follows: [indent=0] ---- @@ -399,8 +400,8 @@ In addition to installing the artifacts identified by the coordinates you supply the artifacts' dependencies are also installed. To uninstall a dependency, use the `uninstall` command. As with the `install` command, it -takes one or more sets of artifact coordinates in the format `group:artifact:version`, as -shown in the following example: +takes one or more sets of artifact coordinates in the format of `group:artifact:version`, +as shown in the following example: [indent=0,subs="verbatim,quotes,attributes"] ---- @@ -462,14 +463,14 @@ The Spring Boot CLI uses Aether, Maven's dependency resolution engine, to resolv dependencies. The CLI makes use of the Maven configuration found in `~/.m2/settings.xml` to configure Aether. The following configuration settings are honored by the CLI: - * Offline - * Mirrors - * Servers - * Proxies - * Profiles - ** Activation - ** Repositories - * Active profiles +* Offline +* Mirrors +* Servers +* Proxies +* Profiles +** Activation +** Repositories +* Active profiles See https://maven.apache.org/settings.html[Maven's settings documentation] for further information. diff --git a/spring-boot-project/spring-boot-docs/src/main/asciidoc/spring-boot-features.adoc b/spring-boot-project/spring-boot-docs/src/main/asciidoc/spring-boot-features.adoc index 4ef993e5295..bdee083f4bb 100644 --- a/spring-boot-project/spring-boot-docs/src/main/asciidoc/spring-boot-features.adoc +++ b/spring-boot-project/spring-boot-docs/src/main/asciidoc/spring-boot-features.adoc @@ -6,7 +6,7 @@ This section dives into the details of Spring Boot. Here you can learn about the key features that you may want to use and customize. If you have not already done so, you might want to read the "<>" and -"<>" sections so that you have a good grounding of the +"<>" sections, so that you have a good grounding of the basics. -- @@ -44,7 +44,8 @@ When your application starts, you should see something similar to the following ---- By default, `INFO` logging messages are shown, including some relevant startup details, -such as the user that launched the application. +such as the user that launched the application. If you need a log level other than `INFO`, +you can set it, as described in <>, @@ -142,7 +143,7 @@ The printed banner is registered as a singleton bean under the following name: [NOTE] ==== YAML maps `off` to `false`, so be sure to add quotes if you want to disable the banner in -your application. +your application, as shown in the following example: [source,yaml,indent=0] ---- @@ -167,7 +168,7 @@ instance and customize it. For example, to turn off the banner, you could write: ---- NOTE: The constructor arguments passed to `SpringApplication` are configuration sources -for spring beans. In most cases, these are references to `@Configuration` classes, but +for Spring beans. In most cases, these are references to `@Configuration` classes, but they could also be references to XML configuration or to packages that should be scanned. It is also possible to configure the `SpringApplication` by using an @@ -181,7 +182,7 @@ For a complete list of the configuration options, see the [[boot-features-fluent-builder-api]] === Fluent Builder API If you need to build an `ApplicationContext` hierarchy (multiple contexts with a -parent/child relationship) or if you just prefer using a '`fluent`' builder API, you can +parent/child relationship) or if you prefer using a "`fluent`" builder API, you can use the `SpringApplicationBuilder`. The `SpringApplicationBuilder` lets you chain together multiple method calls and includes @@ -211,8 +212,8 @@ a `SpringApplication` sends some additional application events. ==== Some events are actually triggered before the `ApplicationContext` is created, so you cannot register a listener on those as a `@Bean`. You can register them with the -`SpringApplication.addListeners(...)` or `SpringApplicationBuilder.listeners(...)` -methods. +`SpringApplication.addListeners(...)` method or the +`SpringApplicationBuilder.listeners(...)` method. If you want those listeners to be registered automatically, regardless of the way the application is created, you can add a `META-INF/spring.factories` file to your project @@ -228,8 +229,8 @@ and reference your listener(s) by using the Application events are sent in the following order, as your application runs: -. An `ApplicationStartingEvent` is sent at the start of a run but before any processing -except the registration of listeners and initializers. +. An `ApplicationStartingEvent` is sent at the start of a run but before any processing, +except for the registration of listeners and initializers. . An `ApplicationEnvironmentPreparedEvent` is sent when the `Environment` to be used in the context is known but before the context is created. . An `ApplicationPreparedEvent` is sent just before the refresh is started but after bean @@ -243,7 +244,7 @@ exist. Internally, Spring Boot uses events to handle a variety of tasks. Application events are sent by using Spring Framework's event publishing mechanism. Part of this mechanism ensures that an event published to the listeners in a child context is -also published to the listeners in any ancestors contexts. As a result of this, if your +also published to the listeners in any ancestor contexts. As a result of this, if your application uses a hierarchy of `SpringApplication` instances, a listener may receive multiple instances of the same type of application event. @@ -262,9 +263,9 @@ behalf. By default, an `AnnotationConfigApplicationContext` or `AnnotationConfigServletWebServerApplicationContext` is used, depending on whether you are developing a web application or not. -The algorithm used to determine a '`web environment`' is fairly simplistic (it is based -on the presence of a few classes). You can use -`setWebEnvironment(boolean webEnvironment)` if you need to override the default. +The algorithm used to determine a "`web environment`" is fairly simplistic (it is based +on the presence of a few classes). If you need to override the default, you can use +`setWebEnvironment(boolean webEnvironment)`. It is also possible to take complete control of the `ApplicationContext` type that is used by calling `setApplicationContextClass(...)`. @@ -302,7 +303,7 @@ and `non-option` arguments, as shown in the following example: ---- TIP: Spring Boot also registers a `CommandLinePropertySource` with the Spring -`Environment`. This allows you to also inject single application arguments by using the +`Environment`. This lets you also inject single application arguments by using the `@Value` annotation. @@ -316,7 +317,7 @@ in the same way and offer a single `run` method, which is called just before The `CommandLineRunner` interfaces provides access to application arguments as a simple string array, whereas the `ApplicationRunner` uses the `ApplicationArguments` interface -discussed earlier. +discussed earlier. The following example shows a `CommandLineRunner` with a `run` method: [source,java,indent=0] ---- @@ -333,9 +334,10 @@ discussed earlier. } ---- -You can additionally implement the `org.springframework.core.Ordered` interface or use -the `org.springframework.core.annotation.Order` annotation if several `CommandLineRunner` -or `ApplicationRunner` beans are defined that must be called in a specific order. +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. @@ -384,7 +386,7 @@ Spring Boot lets you externalize your configuration so that you can work with th application code in different environments. You can use properties files, YAML files, environment variables, and command-line arguments to externalize configuration. Property values can be injected directly into your beans by using the `@Value` annotation, -accessed through Spring's `Environment` abstraction or +accessed through Spring's `Environment` abstraction, or be <> through `@ConfigurationProperties`. @@ -405,7 +407,7 @@ variable or system property). . JNDI attributes from `java:comp/env`. . Java System properties (`System.getProperties()`). . OS environment variables. -. A `RandomValuePropertySource` that only has properties in `+random.*+`. +. A `RandomValuePropertySource` that has properties only in `+random.*+`. . <> outside of your packaged jar (`application-{profile}.properties` and YAML variants). @@ -418,7 +420,7 @@ variants). variants). . {spring-javadoc}/context/annotation/PropertySource.{dc-ext}[`@PropertySource`] annotations on your `@Configuration` classes. -. Default properties (specified using `SpringApplication.setDefaultProperties`). +. Default properties (specified by setting `SpringApplication.setDefaultProperties`). To provide a concrete example, suppose you develop a `@Component` that uses a `name` property, as shown in the following example: @@ -479,7 +481,7 @@ You can also supply the JSON as a JNDI variable, as follows: [[boot-features-external-config-random-values]] === Configuring Random Values The `RandomValuePropertySource` is useful for injecting random values (for example, into -secrets or test cases). It can produce integers, longs, uuids or strings, as shown in the +secrets or test cases). It can produce integers, longs, uuids, or strings, as shown in the following example: [source,properties,indent=0] @@ -501,9 +503,9 @@ value and `max` is the maximum value (exclusive). [[boot-features-external-config-command-line-args]] === Accessing Command Line Properties By default, `SpringApplication` converts any command line option arguments (that is, -arguments starting with '`--`', such as `--server.port=9000`) to a `property` and add it -to the Spring `Environment`. As mentioned previously, command line properties always take -precedence over other property sources. +arguments starting with `--`, such as `--server.port=9000`) to a `property` and adds +them to the Spring `Environment`. As mentioned previously, command line properties always +take precedence over other property sources. If you do not want command line properties to be added to the `Environment`, you can disable them by using `SpringApplication.setAddCommandLineProperties(false)`. @@ -515,7 +517,7 @@ disable them by using `SpringApplication.setAddCommandLineProperties(false)`. `SpringApplication` loads properties from `application.properties` files in the following locations and adds them to the Spring `Environment`: -. A `/config` subdirectory of the current directory. +. A `/config` subdirectory of the current directory . The current directory . A classpath `/config` package . The classpath root @@ -529,8 +531,8 @@ alternative to '.properties'. If you do not like `application.properties` as the configuration file name, you can switch to another file name by specifying a `spring.config.name` environment property. You can also refer to an explicit location by using the `spring.config.location` -environment property (a comma-separated list of directory locations or file paths). The -following example shows how to specify a different file name: +environment property (which is a comma-separated list of directory locations or file +paths). The following example shows how to specify a different file name: [indent=0] ---- @@ -546,7 +548,7 @@ The following example shows how to specify two locations: WARNING: `spring.config.name` and `spring.config.location` are used very early to determine which files have to be loaded, so they must be defined as an environment -property (typically an OS environment variable, a system property, or a command line +property (typically an OS environment variable, a system property, or a command-line argument). If `spring.config.location` contains directories (as opposed to files), they should end @@ -564,9 +566,9 @@ the following: . `classpath:/config/` . `classpath:/` -When custom config locations are configured using `spring.config.location`, they replace -the default locations. For example, if `spring.config.location` is configured with the -value `classpath:/custom-config/,file:./custom-config/`, the search order becomes the +When custom config locations are configured by using `spring.config.location`, they +replace the default locations. For example, if `spring.config.location` is configured with +the value `classpath:/custom-config/,file:./custom-config/`, the search order becomes the following: . `file:./custom-config/` @@ -589,7 +591,7 @@ This search ordering lets you specify default values in one configuration file a selectively override those values in another. You can provide default values for your application in `application.properties` (or whatever other basename you choose with `spring.config.name`) in one of the default locations. These default values can then be -overriden at runtime with a different file located in one of the custom locations. +overridden at runtime with a different file located in one of the custom locations. NOTE: If you use environment variables rather than system properties, most operating systems disallow period-separated key names, but you can use underscores instead (for @@ -604,14 +606,14 @@ environment variables or system properties. [[boot-features-external-config-profile-specific-properties]] === Profile-specific Properties In addition to `application.properties` files, profile-specific properties can also be -defined by using the naming convention `application-{profile}.properties`. The -`Environment` has a set of default profiles (by default `[default]`) that are used if no +defined by using the following naming convention: `application-{profile}.properties`. The +`Environment` has a set of default profiles (by default, `[default]`) that are used if no active profiles are set. In other words, if no profiles are explicitly activated, then properties from `application-default.properties` are loaded. Profile-specific properties are loaded from the same locations as standard `application.properties`, with profile-specific files always overriding the non-specific -ones, irrespective of whether the profile-specific files are inside or outside your +ones, whether or not the profile-specific files are inside or outside your packaged jar. If several profiles are specified, a last-wins strategy applies. For example, profiles @@ -636,7 +638,7 @@ System properties). app.description=${app.name} is a Spring Boot application ---- -TIP: You can also use this technique to create '`short`' variants of existing Spring Boot +TIP: You can also use this technique to create "`short`" variants of existing Spring Boot properties. See the _<>_ how-to for details. @@ -644,12 +646,12 @@ details. [[boot-features-external-config-yaml]] === Using YAML Instead of Properties -http://yaml.org[YAML] is a superset of JSON and, as such, is a very convenient format for +http://yaml.org[YAML] is a superset of JSON and, as such, is a convenient format for specifying hierarchical configuration data. The `SpringApplication` class automatically supports YAML as an alternative to properties whenever you have the http://www.snakeyaml.org/[SnakeYAML] library on your classpath. -NOTE: If you use '`Starters`', SnakeYAML is automatically provided by +NOTE: If you use "`Starters`", SnakeYAML is automatically provided by `spring-boot-starter`. @@ -723,10 +725,11 @@ previously: [NOTE] ==== -When lists are configured in more than one place, overriding works by replacing the entire list. -In the preceding example, when `my.servers` is redefined in several places, the entire list from -the `PropertySource` with higher precedence will override any other configuration for that list. -Both comma-separated lists and yaml lists can be used for completely overriding the contents of the list. +When lists are configured in more than one place, overriding works by replacing the entire +list. In the preceding example, when `my.servers` is defined in several places, the +entire list from the `PropertySource` with higher precedence overrides any other +configuration for that list. Both comma-separated lists and YAML lists can be used for +completely overriding the contents of the list. ==== @@ -768,7 +771,7 @@ profiles are *not* enabled, then the value for the property is `192.168.1.100`. If none are explicitly active when the application context starts, the default profiles are activated. So, in the following YAML, we set a value for `spring.security.user.password` -that is *only* available in the "default" profile: +that is available *only* in the "default" profile: [source,yaml,indent=0] ---- @@ -796,7 +799,7 @@ necessary: password: weak ---- -Spring profiles designated by using the "spring.profiles" element may optionally be +Spring profiles designated by using the `spring.profiles` element may optionally be negated by using the `!` character. If both negated and non-negated profiles are specified for a single document, at least one non-negated profile must match, and no negated profiles may match. @@ -812,12 +815,13 @@ that you need to load values that way, you need to use a properties file. [[boot-features-external-config-complex-type-merge]] ==== Merging YAML Lists -As <>, any YAML content is +As <>, any YAML content is ultimately transformed to properties. That process may be counter-intuitive when overriding "`list`" properties through a profile. For example, assume a `MyPojo` object with `name` and `description` attributes that are -`null` by default. The following example exposes a list of `MyPojo` from `AcmeProperties`: +`null` by default. The following example exposes a list of `MyPojo` objects from +`AcmeProperties`: [source,java,indent=0] ---- @@ -849,14 +853,14 @@ Consider the following configuration: - name: my another name ---- -If the `dev` profile is not active, `AcmeProperties.list` contains one `MyPojo` entry -as defined above. If the `dev` profile is enabled however, the `list` _still_ -contains only one entry (with a name of "`my another name`" and a description of `null`). +If the `dev` profile is not active, `AcmeProperties.list` contains one `MyPojo` entry, +as previously defined. If the `dev` profile is enabled, however, the `list` _still_ +contains only one entry (with a name of `my another name` and a description of `null`). This configuration _does not_ add a second `MyPojo` instance to the list, and it does not merge the items. When a collection is specified in multiple profiles, the one with the highest priority -(and only that one) is used: +(and only that one) is used. Consider the following example: [source,yaml,indent=0] ---- @@ -875,7 +879,7 @@ When a collection is specified in multiple profiles, the one with the highest pr ---- In the preceding example, if the `dev` profile is active, `AcmeProperties.list` contains -_one_ `MyPojo` entry (with a name of "`my another name`" and a description of `null`). +_one_ `MyPojo` entry (with a name of `my another name` and a description of `null`). @@ -943,7 +947,7 @@ your application, as shown in the following example: The preceding POJO defines the following properties: -* `acme.enabled`, `false` by default. +* `acme.enabled`, with a value of `false` by default. * `acme.remote-address`, with a type that can be coerced from `String`. * `acme.security.username`, with a nested "security" object whose name is determined by the name of the property. In particular, the return type is not used at all there and @@ -968,7 +972,7 @@ example), a setter is not required. If you want the binder to create the instanc fly by using its default constructor, you need a setter. Some people use Project Lombok to add getters and setters automatically. Make sure that -Lombok does not generate any particular constructor for such type, as it is used +Lombok does not generate any particular constructor for such a type, as it is used automatically by the container to instantiate the object. ==== @@ -976,7 +980,7 @@ TIP: See also the <>. You also need to list the properties classes to register in the -`@EnableConfigurationProperties` annotation: +`@EnableConfigurationProperties` annotation, as shown in the following example: [source,java,indent=0] ---- @@ -990,7 +994,7 @@ You also need to list the properties classes to register in the ==== When the `@ConfigurationProperties` bean is registered that way, the bean has a conventional name: `-`, where `` is the environment key prefix -specified in the `@ConfigurationProperties` annotation and `` the fully qualified +specified in the `@ConfigurationProperties` annotation and `` is the fully qualified name of the bean. If the annotation does not provide any prefix, only the fully qualified name of the bean is used. @@ -1034,7 +1038,7 @@ YAML configuration, as shown in the following example: # additional configuration as required ---- -To work with `@ConfigurationProperties` beans, you can just inject them in the same way +To work with `@ConfigurationProperties` beans, you can inject them in the same way as any other bean, as shown in the following example: [source,java,indent=0] @@ -1085,7 +1089,7 @@ its bean registration, as shown in the following example: ---- Any property defined with the `another` prefix is mapped onto that `AnotherComponent` bean -in a similar manner as the preceding `AcmeProperties` example. +in manner similar to the preceding `AcmeProperties` example. @@ -1136,11 +1140,11 @@ In the preceding example, the following properties names can all be used: files. |`ACME_MYPROJECT_PERSON_FIRSTNAME` -|Upper case format, which is recommended when using a system environment variables. +|Upper case format, which is recommended when using system environment variables. |=== NOTE: The `prefix` value for the annotation _must_ be in kebab case (lowercase and -separated by `-`, i.e. `acme.my-project.person`). +separated by `-`, such as `acme.my-project.person`). .relaxed binding rules per property source [cols="2,4,4"] @@ -1173,7 +1177,7 @@ such as `my.property-name=acme`. ==== Properties Conversion Spring attempts to coerce the external application properties to the right type when it binds to the `@ConfigurationProperties` beans. If you need custom type conversion, you -can provide a `ConversionService` bean (with bean named `conversionService`) or custom +can provide a `ConversionService` bean (with a bean named `conversionService`) or custom property editors (through a `CustomEditorConfigurer` bean) or custom `Converters` (with bean definitions annotated as `@ConfigurationPropertiesBinding`). @@ -1277,13 +1281,13 @@ features that are supported by `@ConfigurationProperties` and `@Value`: | Yes |=== -If you define a set of configuration keys for your own components, we recommend you to +If you define a set of configuration keys for your own components, we recommend you group them in a POJO annotated with `@ConfigurationProperties`. You should also be aware that, since `@Value` does not support relaxed binding, it is not a good candidate if you need to provide the value by using environment variables. Finally, while you can write a `SpEL` expression in `@Value`, such expressions are not -processed from <>. @@ -1306,9 +1310,10 @@ example: } ---- -In the normal Spring way, you can use a `spring.profiles.active` `Environment` property -to specify which profiles are active. You can specify the property in any of the usual -ways. For example, you could include it in your `application.properties`: +You can use a `spring.profiles.active` `Environment` property to specify which profiles +are active. You can specify the property in any of the ways described earlier in this +chapter. For example, you could include it in your `application.properties`, as shown in +the following example: [source,properties,indent=0] ---- @@ -1331,7 +1336,8 @@ Sometimes, it is useful to have profile-specific properties that *add* to the ac profiles rather than replace them. The `spring.profiles.include` property can be used to unconditionally add active profiles. The `SpringApplication` entry point also has a Java API for setting additional profiles (that is, on top of those activated by the -`spring.profiles.active` property). See the `setAdditionalProfiles()` method. +`spring.profiles.active` property). See the `setAdditionalProfiles()` method in +{dc-spring-boot}/SpringApplication.html[SpringApplication]. For example, when an application with the following properties is run by using the switch, `--spring.profiles.active=prod`, the `proddb` and `prodmq` profiles are also @@ -1365,8 +1371,8 @@ possible to activate profiles by using Spring's `ConfigurableEnvironment` interf [[boot-features-profile-specific-configuration]] === Profile-specific Configuration Files Profile-specific variants of both `application.properties` (or `application.yml`) and -files referenced through `@ConfigurationProperties` are considered as files are loaded. -See _<>_ for details. +files referenced through `@ConfigurationProperties` are considered as files and loaded. +See "<>" for details. @@ -1380,7 +1386,7 @@ Logging], http://logging.apache.org/log4j/2.x/[Log4J2], and http://logback.qos.ch/[Logback]. In each case, loggers are pre-configured to use console output with optional file output also available. -By default, if you use the '`Starters`', Logback is used for logging. Appropriate Logback +By default, if you use the "`Starters`", Logback is used for logging. Appropriate Logback routing is also included to ensure that dependent libraries that use Java Util Logging, Commons Logging, Log4J, or SLF4J all work correctly. @@ -1405,12 +1411,12 @@ The default log output from Spring Boot resembles the following example: The following items are output: -* Date and Time -- Millisecond precision and easily sortable. -* Log Level -- `ERROR`, `WARN`, `INFO`, `DEBUG`, or `TRACE`. +* Date and Time: Millisecond precision and easily sortable. +* Log Level: `ERROR`, `WARN`, `INFO`, `DEBUG`, or `TRACE`. * Process ID. * A `---` separator to distinguish the start of actual log messages. -* Thread name -- Enclosed in square brackets (may be truncated for console output). -* Logger name -- This is usually the source class name (often abbreviated). +* Thread name: Enclosed in square brackets (may be truncated for console output). +* Logger name: This is usually the source class name (often abbreviated). * The log message. NOTE: Logback does not have a `FATAL` level. It is mapped to `ERROR`. @@ -1445,7 +1451,7 @@ If your terminal supports ANSI, color output is used to aid readability. You can {dc-spring-boot}/ansi/AnsiOutput.Enabled.{dc-ext}[supported value] to override the auto detection. -Color coding is configured by using the `%clr` conversion word. In its simplest form the +Color coding is configured by using the `%clr` conversion word. In its simplest form, the converter colors the output according to the log level, as shown in the following example: @@ -1454,7 +1460,7 @@ example: %clr(%5p) ---- -The mapping of log level to a color is as follows: +The following table describes the mapping of log levels to colors: |=== |Level | Color @@ -1489,13 +1495,13 @@ setting: The following colors and styles are supported: - - `blue` - - `cyan` - - `faint` - - `green` - - `magenta` - - `red` - - `yellow` +* `blue` +* `cyan` +* `faint` +* `green` +* `magenta` +* `red` +* `yellow` [[boot-features-logging-file-output]] === File Output @@ -1547,7 +1553,7 @@ not managed by spring Boot. === Log Levels All the supported logging systems can have the logger levels set in the Spring `Environment` (for example, in `application.properties`) by using -'`+logging.level.*=LEVEL+`' where '`LEVEL`' is one of TRACE, DEBUG, INFO, WARN, ERROR, +`+logging.level.*=LEVEL+` where `LEVEL` is one of TRACE, DEBUG, INFO, WARN, ERROR, FATAL, or OFF. The `root` logger can be configured by using `logging.level.root`. The following example shows potential logging settings in `application.properties`: @@ -1564,8 +1570,8 @@ following example shows potential logging settings in `application.properties`: === Custom Log Configuration The various logging systems can be activated by including the appropriate libraries on the classpath and can be further customized by providing a suitable configuration file in -the root of the classpath or in a location specified by the Spring `Environment` property -`logging.config`. +the root of the classpath or in a location specified by the following Spring `Environment` +property: `logging.config`. You can force Spring Boot to use a particular logging system by using the `org.springframework.boot.logging.LoggingSystem` system property. The value should be the @@ -1617,12 +1623,12 @@ To help with the customization, some other properties are transferred from the S |`logging.file.max-size` |`LOG_FILE_MAX_SIZE` |Maximum log file size (if LOG_FILE enabled). (Only supported with the default Logback - setup.) +setup.) |`logging.file.max-history` |`LOG_FILE_MAX_HISTORY` |Maximum number of archive log files to keep (if LOG_FILE enabled). (Only supported with - the default Logback setup.) +the default Logback setup.) |`logging.path` |`LOG_PATH` @@ -1690,7 +1696,7 @@ Spring Boot includes a number of extensions to Logback that can help with advanc configuration. You can use these extensions in your `logback-spring.xml` configuration file. -NOTE: Because the standard `logback.xml` configuration file is loaded too early, you +NOTE: Because the standard `logback.xml` configuration file is loaded too early, you cannot use extensions in it. You need to either use `logback-spring.xml` or define a `logging.config` property. @@ -1710,7 +1716,7 @@ ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action f The `` tag lets you optionally include or exclude sections of configuration based on the active Spring profiles. Profile sections are supported anywhere within the `` element. Use the `name` attribute to specify which -profile accepts the configuration. Multiple profiles can be specified using a +profile accepts the configuration. Multiple profiles can be specified with a comma-separated list. The following listing shows three sample profiles: [source,xml,indent=0] @@ -1738,7 +1744,8 @@ way to Logback's standard `` tag. However, rather than specifying a di `value`, you specify the `source` of the property (from the `Environment`). If you need to store the property somewhere other than in `local` scope, you can use the `scope` attribute. If you need a fallback value (in case the property is not set in the -`Environment`), you can use the `defaultValue` attribute. +`Environment`), you can use the `defaultValue` attribute. The following example shows how +to expose properties for use within Logback: [source,xml,indent=0] ---- @@ -1750,7 +1757,7 @@ attribute. If you need a fallback value (in case the property is not set in the ---- -NOTE: The `source` must be specified using kebab case (such as `my.property-name`). +NOTE: The `source` must be specified in kebab case (such as `my.property-name`). However, properties can be added to the `Environment` by using the relaxed rules. @@ -1770,13 +1777,13 @@ _<>_ se [[boot-features-spring-mvc]] -=== The '`Spring Web MVC Framework`' -The Spring Web MVC framework (often referred to as simply '`Spring MVC`') is a rich -'`model view controller`' web framework. Spring MVC lets you create special `@Controller` -or `@RestController` beans to handle incoming HTTP requests. Methods in your controller -are mapped to HTTP by using `@RequestMapping` annotations. +=== The "`Spring Web MVC Framework`" +The {spring-reference}web.html#mvc[Spring Web MVC framework] (often referred to as simply +"`Spring MVC`") is a rich "`model view controller`" web framework. Spring MVC lets you +create special `@Controller`or `@RestController` beans to handle incoming HTTP requests. +Methods in your controller are mapped to HTTP by using `@RequestMapping` annotations. -The following code shows a typical example `@RestController` to serve JSON data: +The following code shows a typical `@RestController` that serves JSON data: [source,java,indent=0] ---- @@ -1816,15 +1823,18 @@ applications. The auto-configuration adds the following features on top of Spring's defaults: * Inclusion of `ContentNegotiatingViewResolver` and `BeanNameViewResolver` beans. -* Support for serving static resources, including support for WebJars (covered later in -this document). +* Support for serving static resources, including support for WebJars (covered +<>)). * Automatic registration of `Converter`, `GenericConverter`, and `Formatter` beans. -* Support for `HttpMessageConverters` (see below). -* Automatic registration of `MessageCodesResolver` (covered later in this document). +* Support for `HttpMessageConverters` (covered +<>). +* Automatic registration of `MessageCodesResolver` (covered +<>). * Static `index.html` support. -* Custom `Favicon` support (covered later in this document). -* Automatic use of a `ConfigurableWebBindingInitializer` bean (covered later in this - document). +* Custom `Favicon` support (covered <>). +* Automatic use of a `ConfigurableWebBindingInitializer` bean (covered +<>). If you want to keep Spring Boot MVC features and you want to add additional {spring-reference}web.html#mvc[MVC configuration] (interceptors, formatters, view @@ -1847,7 +1857,7 @@ Jackson XML extension, if available, or by using JAXB if the Jackson XML extensi available). By default, strings are encoded in `UTF-8`. If you need to add or customize converters, you can use Spring Boot's -`HttpMessageConverters` class: +`HttpMessageConverters` class, as shown in the following listing: [source,java,indent=0] ---- @@ -1882,8 +1892,8 @@ a module], but Spring Boot provides an alternative `@JsonComponent` annotation t it easier to directly register Spring Beans. You can use the `@JsonComponent` annotation directly on `JsonSerializer` or -`JsonDeserializer` implementations. You can also use it on classes that contains -serializers/deserializers as inner-classes, as shown in the following example: +`JsonDeserializer` 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] ---- @@ -1941,8 +1951,8 @@ you can modify that behavior by adding your own `WebMvcConfigurer` and overridin In a stand-alone web application, the default servlet from the container is also enabled and acts as a fallback, serving content from the root of the `ServletContext` if Spring -decides not to handle it. Most of the time, this will not happen (unless you modify the -default MVC configuration) because Spring can always handle requests through the +decides not to handle it. Most of the time, this does not happen (unless you modify the +default MVC configuration), because Spring can always handle requests through the `DispatcherServlet`. By default, resources are mapped on `+/**+`, but you can tune that with the @@ -1956,10 +1966,10 @@ By default, resources are mapped on `+/**+`, but you can tune that with the You can also customize the static resource locations by using the `spring.resources.static-locations` property (replacing the default values with a list of -directory locations). The root Servlet context path `"/"` is automatically added as a +directory locations). The root Servlet context path, `"/"`, is automatically added as a location as well. -In addition to the '`standard`' static resource locations mentioned earlier, a special +In addition to the "`standard`" static resource locations mentioned earlier, a special case is made for http://www.webjars.org/[Webjars content]. Any resources with a path in `+/webjars/**+` are served from jar files if they are packaged in the Webjars format. @@ -1976,7 +1986,7 @@ Then declare your Webjar. Using jQuery as an example, adding `"/webjars/jquery/dist/jquery.min.js"` results in `"/webjars/jquery/x.y.z/dist/jquery.min.js"`. where `x.y.z` is the Webjar version. -NOTE: If you are using JBoss, you need to declare the `webjars-locator-jboss-vfs` +NOTE: If you use JBoss, you need to declare the `webjars-locator-jboss-vfs` dependency instead of the `webjars-locator`. Otherwise, all Webjars resolve as a `404`. To use cache busting, the following configuration configures a cache busting solution for @@ -2015,7 +2025,7 @@ versioning strategy (`"/v12/js/lib/mymodule.js"`), while other resources still u content one (``). See {sc-spring-boot-autoconfigure}/web/ResourceProperties.{sc-ext}[`ResourceProperties`] -for more of the supported options. +for more supported options. [TIP] ==== @@ -2029,7 +2039,7 @@ post] and in Spring Framework's ==== Welcome Page Spring Boot supports both static and templated welcome pages. It first looks for an `index.html` file in the configured static content locations. If one is not found, it -then looks for an `index` template. If either is found it is automatically used as the +then looks for an `index` template. If either is found, it is automatically used as the welcome page of the application. @@ -2077,7 +2087,7 @@ different ordering than when you run your application by using Maven or Gradle o its packaged jar. This can cause Spring Boot to fail to find the templates on the classpath. If you have this problem, you can reorder the classpath in the IDE to place the module's classes and resources first. Alternatively, you can configure the template -prefix to search every templates directory on the classpath, as follows: +prefix to search every `templates` directory on the classpath, as follows: `classpath*:/templates/`. @@ -2085,11 +2095,11 @@ prefix to search every templates directory on the classpath, as follows: [[boot-features-error-handling]] ==== Error Handling By default, Spring Boot provides an `/error` mapping that handles all errors in a -sensible way, and it is registered as a '`global`' error page in the servlet container. +sensible way, and it is registered as a "`global`" error page in the servlet container. For machine clients, it produces a JSON response with details of the error, the HTTP -status, and the exception message. For browser clients, there is a '`whitelabel`' error +status, and the exception message. For browser clients, there is a "`whitelabel`" error view that renders the same data in HTML format (to customize it, add a `View` that -resolves to '`error`'). To replace the default behavior completely, you can implement +resolves to `error`). To replace the default behavior completely, you can implement `ErrorController` and register a bean definition of that type or add a bean of type `ErrorAttributes` to use the existing mechanism but replace the contents. @@ -2136,7 +2146,7 @@ used instead of the `ErrorAttributes` representation. ===== Custom Error Pages If you want to display a custom HTML error page for a given status code, you can add a file to an `/error` folder. Error pages can either be static HTML (that is, added under -any of the static resource folders) or built by using templates. The name of the file +any of the static resource folders) or be built by using templates. The name of the file should be the exact status code or a series mask. For example, to map `404` to a static HTML file, your folder structure would be as @@ -2246,10 +2256,9 @@ type. [[boot-features-error-handling-websphere]] -===== Error Handling on WebSphere Application Server -When deployed to a servlet container, Spring Boot uses its error page filter to forward a -request with an error status to the appropriate error page. The request can only be -forwarded to the correct error page if the response has not already been committed. By +CAUTION:When deployed to a servlet container, Spring Boot uses its error page filter to +forward a request with an error status to the appropriate error page. The request can only +be forwarded to the correct error page if the response has not already been committed. By default, WebSphere Application Server 8.0 and later commits the response upon successful completion of a servlet's service method. You should disable this behavior by setting `com.ibm.ws.webcontainer.invokeFlushAfterService` to `false`. @@ -2268,7 +2277,7 @@ setting the various `spring.jackson.*` properties or, if one exists, by a `Jackson2ObjectMapperBuilder` bean. You can take control of Spring HATEOAS's configuration by using -`@EnableHypermediaSupport`. Note that this disables the `ObjectMapper` customization +`@EnableHypermediaSupport`. Note that doing so disables the `ObjectMapper` customization described earlier. @@ -2278,7 +2287,7 @@ described earlier. http://en.wikipedia.org/wiki/Cross-origin_resource_sharing[Cross-origin resource sharing] (CORS) is a http://www.w3.org/TR/cors/[W3C specification] implemented by -http://caniuse.com/#feat=cors[most browsers] that allows you to specify in a flexible +http://caniuse.com/#feat=cors[most browsers] that lets you specify in a flexible way what kind of cross-domain requests are authorized, instead of using some less secure and less powerful approaches such as IFRAME or JSONP. @@ -2311,7 +2320,7 @@ defined by registering a `WebMvcConfigurer` bean with a customized [[boot-features-webflux]] -=== The '`Spring WebFlux Framework`' +=== The "`Spring WebFlux Framework`" Spring WebFlux is the new reactive web framework introduced in Spring Framework 5.0. Unlike Spring MVC, it does not require the Servlet API, is fully asynchronous and @@ -2319,7 +2328,7 @@ non-blocking, and implements the http://www.reactive-streams.org/[Reactive Strea specification through http://projectreactor.io/[the Reactor project]. Spring WebFlux comes in two flavors: functional and annotation-based. The -annotation-based one is quite close to the Spring MVC model we know, as shown in the +annotation-based one is quite close to the Spring MVC model, as shown in the following example: [source,java,indent=0] @@ -2346,7 +2355,7 @@ following example: } ---- -'`WebFlux.fn`', the functional variant, separates the routing configuration from the +"`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] @@ -2388,7 +2397,7 @@ To get started, add the `spring-boot-starter-webflux` module to your application NOTE: Adding both `spring-boot-starter-web` and `spring-boot-starter-webflux` modules in your application results in Spring Boot auto-configuring Spring MVC, not WebFlux. This behavior has been chosen because many Spring developers add `spring-boot-starter-webflux` -to their Spring MVC application to use the reactive `WebCLient`. You can still enforce +to their Spring MVC application to use the reactive `WebClient`. You can still enforce your choice by setting the chosen application type to `SpringApplication.setWebApplicationType(WebApplicationType.REACTIVE)`. @@ -2402,9 +2411,9 @@ applications. The auto-configuration adds the following features on top of Spring's defaults: * Configuring codecs for `HttpMessageReader` and `HttpMessageWriter` instances (described -later in this document). -* Support for serving static resources, including support for WebJars (described later in -this document). +<>). +* Support for serving static resources, including support for WebJars (described +<>). If you want to keep Spring Boot WebFlux features and you want to add additional {spring-reference}web.html#web-reactive[WebFlux configuration], you can add your own @@ -2471,7 +2480,7 @@ directory locations. If you do so, the default welcome page detection switches t custom locations. So, if there is an `index.html` in any of your locations on startup, it is the home page of the application. -In addition to the '`standard`' static resource locations listed earlier, a special case +In addition to the "`standard`" static resource locations listed earlier, a special case is made for http://www.webjars.org/[Webjars content]. Any resources with a path in `+/webjars/**+` are served from jar files if they are packaged in the Webjars format. @@ -2502,15 +2511,15 @@ templates are picked up automatically from `src/main/resources/templates`. Spring Boot provides a `WebExceptionHandler` that handles all errors in a sensible way. Its position in the processing order is immediately before the handlers provided by -WebFlux, which are considered last. For machine clients it will produce a JSON response -with details of the error, the HTTP status and the exception message. For browser clients -there is a '`whitelabel`' error handler that renders the same data in HTML format. You -can also provide your own HTML templates to display errors (see the +WebFlux, which are considered last. For machine clients, it produces a JSON response +with details of the error, the HTTP status, and the exception message. For browser +clients, there is a "`whitelabel`" error handler that renders the same data in HTML +format. You can also provide your own HTML templates to display errors (see the <>). -The first step to customizing this feature is often about using the existing mechanism -but replacing or augmenting the error contents. For that, you can simply add a bean of -type `ErrorAttributes`. +The first step to customizing this feature often involves using the existing mechanism +but replacing or augmenting the error contents. For that, you can add a bean of type +`ErrorAttributes`. To change the error handling behavior, you can implement `ErrorWebExceptionHandler` and register a bean definition of that type. Because a `WebExceptionHandler` is quite @@ -2584,10 +2593,11 @@ follows: [[boot-features-jersey]] === JAX-RS and Jersey If you prefer the JAX-RS programming model for REST endpoints, you can use one of the -available implementations instead of Spring MVC. Jersey 1.x and Apache CXF work quite -well out of the box if you register their `Servlet` or `Filter` as a `@Bean` in your -application context. Jersey 2.x has some native Spring support, so we also provide -auto-configuration support for it in Spring Boot, together with a starter. +available implementations instead of Spring MVC. https://jersey.github.io/[Jersey] 1.x and +http://cxf.apache.org/[Apache CXF] work quite well out of the box if you register their +`Servlet` or `Filter` as a `@Bean` in your application context. Jersey 2.x has some native +Spring support, so we also provide auto-configuration support for it in Spring Boot, +together with a starter. To get started with Jersey 2.x, include the `spring-boot-starter-jersey` as a dependency and then you need one `@Bean` of type `ResourceConfig` in which you register all the @@ -2611,11 +2621,11 @@ running an executable war file. To avoid this limitation, the `packages` method not be used, and endpoints should be registered individually by using the `register` method, as shown in the preceding example. -You can also register an arbitrary number of beans implementing -`ResourceConfigCustomizer` for more advanced customizations. +For more advanced customizations, you can also register an arbitrary number of beans that +implement `ResourceConfigCustomizer`. All the registered endpoints should be `@Components` with HTTP resource annotations -(`@GET` etc.), as shown in the following example: +(`@GET` and others), as shown in the following example: [source,java,indent=0,subs="verbatim,quotes,attributes"] ---- @@ -2659,16 +2669,17 @@ JAX-RS resources are packaged as nested jars, you may need to do the same. [[boot-features-embedded-container]] === Embedded Servlet Container Support -Spring Boot includes support for embedded Tomcat, Jetty, and Undertow servers. Most -developers use the appropriate '`Starter`' to obtain a fully configured instance. By +Spring Boot includes support for embedded http://tomcat.apache.org/[Tomcat], +https://www.eclipse.org/jetty/[Jetty], and http://undertow.io/[Undertow] servers. Most +developers use the appropriate "`Starter`" to obtain a fully configured instance. By default, the embedded server listens for HTTP requests on port `8080`. -WARNING: If you choose to use Tomcat on CentOS, be aware that, by default, a temporary -directory is used to store compiled JSPs, file uploads, and so on. This directory may be -deleted by `tmpwatch` while your application is running, leading to failures. To avoid -this behavior, you may want to customize your `tmpwatch` configuration, so that -`tomcat.*` directories are not deleted or configure `server.tomcat.basedir`, so that -embedded Tomcat uses a different location. +WARNING: If you choose to use Tomcat on https://www.centos.org/[CentOS], be aware that, by +default, a temporary directory is used to store compiled JSPs, file uploads, and so on. +This directory may be deleted by `tmpwatch` while your application is running, leading to +failures. To avoid this behavior, you may want to customize your `tmpwatch` configuration +such that `tomcat.*` directories are not deleted or configure `server.tomcat.basedir` such +that embedded Tomcat uses a different location. @@ -2713,8 +2724,9 @@ easily be used as an adapter to an existing `WebApplicationInitializer`. [[boot-features-embedded-container-servlets-filters-listeners-scanning]] ===== Scanning for Servlets, Filters, and listeners -When using an embedded container, automatic registration of `@WebServlet`, `@WebFilter`, -and `@WebListener` annotated classes can be enabled by using `@ServletComponentScan`. +When using an embedded container, automatic registration of classes annotated with +`@WebServlet`, `@WebFilter`, and `@WebListener` can be enabled by using +`@ServletComponentScan`. TIP: `@ServletComponentScan` has no effect in a standalone container, where the container's built-in discovery mechanisms are used instead. @@ -2723,8 +2735,8 @@ container's built-in discovery mechanisms are used instead. [[boot-features-embedded-container-application-context]] ==== The ServletWebServerApplicationContext -Under the hood, Spring Boot uses a new type of `ApplicationContext` for embedded servlet -container support. The `ServletWebServerApplicationContext` is a special type of +Under the hood, Spring Boot uses a different type of `ApplicationContext` for embedded +servlet container support. The `ServletWebServerApplicationContext` is a special type of `WebApplicationContext` that bootstraps itself by searching for a single `ServletWebServerFactory` bean. Usually a `TomcatServletWebServerFactory`, `JettyServletWebServerFactory`, or `UndertowServletWebServerFactory` @@ -2750,7 +2762,7 @@ address to bind to `server.address`, and so on. session timeout (`server.session.timeout`), location of session data (`server.session.store-dir`), and session-cookie configuration (`server.session.cookie.*`). -* Error management: Location of the error page (`server.error.path`), and so on. +* Error management: Location of the error page (`server.error.path`) and so on. * <> * <> @@ -2844,15 +2856,15 @@ that you can see how to set things up. [[boot-features-security]] == Security -If Spring Security is on the classpath, then web applications are secure by default. -Spring Boot relies on Spring Security’s content-negotiation strategy to determine whether -to use `httpBasic` -or `formLogin`. To add method-level security to a web application, you can also add -`@EnableGlobalMethodSecurity` with your desired settings. Additional information can be -found in the {spring-security-reference}#jc-method[Spring Security Reference]. - -The default `AuthenticationManager` has a single user (the user name is '`user`', and the -password is random and is printed at INFO level when the application starts), as shown in +If {spring-security}[Spring Security] is on the classpath, then web applications are +secure by default. Spring Boot relies on Spring Security’s content-negotiation strategy to +determine whether to use `httpBasic` or `formLogin`. To add method-level security to a web +application, you can also add `@EnableGlobalMethodSecurity` with your desired settings. +Additional information can be found in the {spring-security-reference}#jc-method[Spring +Security Reference Guide]. + +The default `AuthenticationManager` has a single user. The user name is `user`, and the +password is random and is printed at INFO level when the application starts, as shown in the following example: [indent=0] @@ -2871,32 +2883,37 @@ The default security configuration is implemented in `SecurityAutoConfiguration` the classes imported from there (`SpringBootWebSecurityConfiguration` for web security and `AuthenticationManagerConfiguration` for authentication configuration, which is also relevant in non-web applications). To switch off the default web application security -configuration completely, you can add a bean of type `WebSecurityConfigurerAdapter` (this -does not disable the authentication manager configuration or Actuator's security). +configuration completely, you can add a bean of type `WebSecurityConfigurerAdapter` (doing +so does not disable the authentication manager configuration or Actuator's security). To also switch off the authentication manager configuration, you can add a bean of type -`UserDetailsService`, `AuthenticationProvider` or `AuthenticationManager`. +`UserDetailsService`, `AuthenticationProvider`, or `AuthenticationManager`. There are several secure applications in the {github-code}/spring-boot-samples/[Spring Boot samples] to get you started with common use cases. The basic features you get by default in a web application are: * A `UserDetailsService` bean with in-memory store and a single user with a generated - password (see `SecurityProperties.User` for the properties of the user). +password (see +{dc-spring-boot}/autoconfigure/security/SecurityProperties.User.html[`SecurityProperties.User`] +for the properties of the user). * Form-based login or HTTP Basic security (depending on Content-Type) for the entire - application (including actuator endpoints if actuator is on the classpath). +application (including actuator endpoints if actuator is on the classpath). -Access rules can be overriden by adding a custom `WebSecurityConfigurerAdapter`. Spring +Access rules can be overridden by adding a custom `WebSecurityConfigurerAdapter`. Spring Boot provides convenience methods that can be used to override access rules for actuator endpoints and static resources. `EndpointRequest` can be used to create a `RequestMatcher` that is based on the `management.endpoints.web.base-path` property. `StaticResourceRequest` can be used to create a `RequestMatcher` for static resources in commonly used locations. + + [[boot-features-security-oauth2]] === OAuth2 -OAuth2 is a widely used authorization framework that is supported by Spring. +https://oauth.net/2/[OAuth2] is a widely used authorization framework that is supported by +Spring. ==== Client If you have `spring-security-oauth2-client` on your classpath, you can take advantage of @@ -2933,10 +2950,11 @@ You can register multiple OAuth2 clients and providers under the spring.security.oauth2.client.provider.my-oauth-provider.user-name-attribute=name ---- -By default, Spring Security's `OAuth2LoginAuthenticationFilter` will only process URLs matching -`/login/oauth2/code/*`. If you want to customize the `redirect-uri-template` to use a different pattern, -you will need to provide configuration to process that custom pattern. For example, you can add your own -`WebSecurityConfigurerAdapter` that looks like this: +By default, Spring Security's `OAuth2LoginAuthenticationFilter` only processes URLs +matching `/login/oauth2/code/*`. If you want to customize the `redirect-uri-template` to +use a different pattern, you need to provide configuration to process that custom pattern. +For example, you can add your own `WebSecurityConfigurerAdapter` that resembles the +following: [source,java,indent=0] ---- @@ -2955,12 +2973,12 @@ public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter { } ---- -For common OAuth2 and OpenID providers such as Google, Github, Facebook, and Okta, -we provide a set of provider defaults (`google`, `github`, `facebook`, and `okta` +For common OAuth2 and OpenID providers, including Google, Github, Facebook, and Okta, +we provide a set of provider defaults (`google`, `github`, `facebook`, and `okta`, respectively). If you do not need to customize these providers, you can set the `provider` attribute to -the one for which you need to infer defaults. Also if the ID of your client matches the +the one for which you need to infer defaults. Also, if the ID of your client matches the default supported provider, Spring Boot infers that as well. In other words, the two configurations in the following example use the Google provider: @@ -2979,7 +2997,7 @@ In other words, the two configurations in the following example use the Google p [[boot-features-security-actuator]] === Actuator Security -If the Actuator is also in use, you can see that: +If the Actuator is also in use: * The management endpoints are secure even if the application endpoints are insecure. * Security events are transformed into `AuditEvent` instances and published to the @@ -2997,21 +3015,21 @@ the application access rules and the actuator access rules. [[boot-features-sql]] == Working with SQL Databases -The Spring Framework provides extensive support for working with SQL databases, from -direct JDBC access using `JdbcTemplate` to complete '`object relational mapping`' -technologies such as Hibernate. Spring Data provides an additional level of -functionality: creating `Repository` implementations directly from interfaces and using -conventions to generate queries from your method names. +The {spring-framework}[Spring Framework] provides extensive support for working with SQL +databases, from direct JDBC access using `JdbcTemplate` to complete "`object relational +mapping`" technologies such as Hibernate. {spring-data}[Spring Data] provides an +additional level of functionality: creating `Repository` implementations directly from +interfaces and using conventions to generate queries from your method names. [[boot-features-configure-datasource]] === Configure a DataSource Java's `javax.sql.DataSource` interface provides a standard method of working with -database connections. Traditionally, a DataSource uses a `URL` along with some +database connections. Traditionally, a 'DataSource' uses a `URL` along with some credentials to establish a database connection. -TIP: See <> for more +TIP: See <> for more advanced examples, typically to take full control over the configuration of the DataSource. @@ -3019,12 +3037,12 @@ DataSource. [[boot-features-embedded-database-support]] ==== Embedded Database Support -It is often convenient to develop applications using an in-memory embedded database. +It is often convenient to develop applications by using an in-memory embedded database. Obviously, in-memory databases do not provide persistent storage. You need to populate your database when your application starts and be prepared to throw away data when your application ends. -TIP: The '`How-to`' section includes a <>. Spring Boot can auto-configure embedded http://www.h2database.com[H2], @@ -3040,7 +3058,7 @@ use. If you want to make sure that each context has a separate embedded database should set `spring.datasource.generate-unique-name` to `true`. ==== -For example, typical POM dependencies would be as follows: +For example, the typical POM dependencies would be as follows: [source,xml,indent=0] ---- @@ -3056,7 +3074,7 @@ For example, typical POM dependencies would be as follows: ---- NOTE: You need a dependency on `spring-jdbc` for an embedded database to be -auto-configured. In this example, it is pulled in transitively via +auto-configured. In this example, it is pulled in transitively through `spring-boot-starter-data-jpa`. TIP: If, for whatever reason, you do configure the connection URL for an embedded @@ -3074,18 +3092,18 @@ Production database connections can also be auto-configured by using a pooling `DataSource`. Spring Boot uses the following algorithm for choosing a specific implementation: -. We prefer HikariCP for its performance and concurrency. If HikariCP is available, we - always choose it. +. We prefer https://github.com/brettwooldridge/HikariCP[HikariCP] for its performance and +concurrency. If HikariCP is available, we always choose it. . Otherwise, if the Tomcat pooling `DataSource` is available, we use it. -. If neither HikariCP nor the Tomcat pooling datasource are available and if Commons - DBCP2 is available, we use it. +. If neither HikariCP nor the Tomcat pooling datasource are available and if +https://commons.apache.org/proper/commons-dbcp/[Commons DBCP2] is available, we use it. -If you use the `spring-boot-starter-jdbc` or `spring-boot-starter-data-jpa` '`starters`', +If you use the `spring-boot-starter-jdbc` or `spring-boot-starter-data-jpa` "`starters`", you automatically get a dependency to `HikariCP`. NOTE: You can bypass that algorithm completely and specify the connection pool to use by -setting the `spring.datasource.type` property. This is especially important if you are -running your application in a Tomcat container, as `tomcat-jdbc` is provided by default. +setting the `spring.datasource.type` property. This is especially important if you run +your application in a Tomcat container, as `tomcat-jdbc` is provided by default. TIP: Additional connection pools can always be configured manually. If you define your own `DataSource` bean, auto-configuration does not occur. @@ -3110,20 +3128,21 @@ deduce it for most databases from the `url`. NOTE: For a pooling `DataSource` to be created, we need to be able to verify that a valid `Driver` class is available, so we check for that before doing anything. In other words, -if you set `spring.datasource.driver-class-name=com.mysql.jdbc.Driver` then that class +if you set `spring.datasource.driver-class-name=com.mysql.jdbc.Driver`, then that class has to be loadable. See {sc-spring-boot-autoconfigure}/jdbc/DataSourceProperties.{sc-ext}[`DataSourceProperties`] for more of the supported options. These are the standard options that work regardless of the actual implementation. It is also possible to fine-tune implementation-specific -settings using their respective prefix (`+spring.datasource.hikari.*+`, +settings by using their respective prefix (`+spring.datasource.hikari.*+`, `+spring.datasource.tomcat.*+`, and `+spring.datasource.dbcp2.*+`). Refer to the documentation of the connection pool implementation you are using for more details. For instance, if you use the http://tomcat.apache.org/tomcat-8.0-doc/jdbc-pool.html#Common_Attributes[Tomcat -connection pool], you could customize many additional settings: +connection pool], you could customize many additional settings, as shown in the following +example: [source,properties,indent=0] @@ -3143,7 +3162,7 @@ connection pool], you could customize many additional settings: [[boot-features-connecting-to-a-jndi-datasource]] ==== Connection to a JNDI DataSource If you deploy your Spring Boot application to an Application Server, you might want to -configure and manage your DataSource using your Application Server's built-in features +configure and manage your DataSource by using your Application Server's built-in features and access it by using JNDI. The `spring.datasource.jndi-name` property can be used as an alternative to the @@ -3186,7 +3205,7 @@ you can `@Autowire` them directly into your own beans, as shown in the following ---- You can customize some properties of the template by using the `spring.jdbc.template.*` -properties as shown in the following example: +properties, as shown in the following example: [source,properties,indent=0] ---- @@ -3200,30 +3219,30 @@ scenes. If more than one `JdbcTemplate` is defined and no primary candidate exis [[boot-features-jpa-and-spring-data]] -=== JPA and '`Spring Data`' -The Java Persistence API is a standard technology that lets you '`map`' objects to +=== JPA and "`Spring Data`" +The Java Persistence API is a standard technology that lets you "`map`" objects to relational databases. The `spring-boot-starter-data-jpa` POM provides a quick way to get started. It provides the following key dependencies: -* Hibernate -- One of the most popular JPA implementations. -* Spring Data JPA -- Makes it easy to implement JPA-based repositories. -* Spring ORMs -- Core ORM support from the Spring Framework. +* Hibernate: One of the most popular JPA implementations. +* Spring Data JPA: Makes it easy to implement JPA-based repositories. +* Spring ORMs: Core ORM support from the Spring Framework. -TIP: We do not go into too many details of JPA or Spring Data here. You can follow the -http://spring.io/guides/gs/accessing-data-jpa/['`Accessing Data with JPA`'] guide from -http://spring.io and read the http://projects.spring.io/spring-data-jpa/[Spring Data JPA] -and http://hibernate.org/orm/documentation/[Hibernate] reference documentation. +TIP: We do not go into too many details of JPA or {spring-data}[Spring Data] here. You can +follow the http://spring.io/guides/gs/accessing-data-jpa/["`Accessing Data with JPA`"] +guide from http://spring.io and read the {spring-data-jpa}[Spring Data JPA] and +http://hibernate.org/orm/documentation/[Hibernate] reference documentation. [[boot-features-entity-classes]] ==== Entity Classes -Traditionally, JPA '`Entity`' classes are specified in a `persistence.xml` file. With -Spring Boot, this file is not necessary and '`Entity Scanning`' is used instead. By +Traditionally, JPA "`Entity`" classes are specified in a `persistence.xml` file. With +Spring Boot, this file is not necessary and "`Entity Scanning`" is used instead. By default, all packages below your main configuration class (the one annotated with `@EnableAutoConfiguration` or `@SpringBootApplication`) are searched. -Any classes annotated with `@Entity`, `@Embeddable` or `@MappedSuperclass` are +Any classes annotated with `@Entity`, `@Embeddable`, or `@MappedSuperclass` are considered. A typical entity class resembles the following example: [source,java,indent=0] @@ -3279,10 +3298,10 @@ how-to. [[boot-features-spring-data-jpa-repositories]] ==== Spring Data JPA Repositories -Spring Data JPA repositories are interfaces that you can define to access data. JPA -queries are created automatically from your method names. For example, a `CityRepository` -interface might declare a `findAllByState(String state)` method to find all the cities in -a given state. +{http://projects.spring.io/spring-data-jpa/}[Spring Data JPA] repositories are interfaces +that you can define to access data. JPA queries are created automatically from your method +names. For example, a `CityRepository` interface might declare a `findAllByState(String +state)` method to find all the cities in a given state. For more complex queries, you can annotate your method with Spring Data's {spring-data-javadoc}/repository/Query.html[`Query`] annotation. @@ -3313,7 +3332,8 @@ The following example shows a typical Spring Data repository interface definitio ---- TIP: We have barely scratched the surface of Spring Data JPA. For complete details, see -the http://projects.spring.io/spring-data-jpa/[Spring Data JPA reference documentation]. +the https://docs.spring.io/spring-data/jpa/docs/current/reference/html/[Spring Data JPA +reference documentation]. @@ -3354,7 +3374,7 @@ fine-grained. ==== Open EntityManager in View If you are running a web application, Spring Boot by default registers {spring-javadoc}/orm/jpa/support/OpenEntityManagerInViewInterceptor.{dc-ext}[`OpenEntityManagerInViewInterceptor`] -to apply the "Open EntityManager in View" pattern, to allow for lazy loading in web +to apply the "`Open EntityManager in View`" pattern, to allow for lazy loading in web views. If you do not want this behavior, you should set `spring.jpa.open-in-view` to `false` in your `application.properties`. @@ -3370,11 +3390,13 @@ conditions are met: * You are developing a web application. * `com.h2database:h2` is on the classpath. * You are using <>. +tools>>. TIP: If you are not using Spring Boot's developer tools but would still like to make use of H2's console, you can configure the `spring.h2.console.enabled` property with a value -of `true`. The H2 console is only intended for use during development, so you should take +of `true`. + +NOTE: The H2 console is only intended for use during development, so you should take care to ensure that `spring.h2.console.enabled` is not set to `true` in production. @@ -3482,7 +3504,7 @@ of jOOQ. ==== Customizing jOOQ More advanced customizations can be achieved by defining your own `@Bean` definitions, -which will be used when the jOOQ `Configuration` is created. You can define beans for the +which is used when the jOOQ `Configuration` is created. You can define beans for the following jOOQ Types: * `ConnectionProvider` @@ -3526,12 +3548,12 @@ https://github.com/xetorthio/jedis/[Jedis] client libraries and the abstractions of them provided by https://github.com/spring-projects/spring-data-redis[Spring Data Redis]. -There is a `spring-boot-starter-data-redis` '`Starter`' for collecting the dependencies +There is a `spring-boot-starter-data-redis` "`Starter`" for collecting the dependencies in a convenient way. By default, it uses https://github.com/lettuce-io/lettuce-core/[Lettuce]. That starter handles both traditional and reactive applications. -TIP: we also provide a `spring-boot-starter-data-redis-reactive` '`Starter`' for +TIP: we also provide a `spring-boot-starter-data-redis-reactive` "`Starter`" for consistency with the other stores with reactive support. @@ -3565,8 +3587,8 @@ TIP: You can also register an arbitrary number of beans that implement use Jedis, `JedisClientConfigurationBuilderCustomizer` is also available. If you add your own `@Bean` of any of the auto-configured types, it replaces the default -(except in the case of `RedisTemplate`, when the exclusion is based on the bean name -'`redisTemplate`', not its type). By default, if `commons-pool2` is on the classpath, you +(except in the case of `RedisTemplate`, when the exclusion is based on the bean name, +`redisTemplate`, not its type). By default, if `commons-pool2` is on the classpath, you get a pooled connection factory. @@ -3577,7 +3599,7 @@ http://www.mongodb.com/[MongoDB] is an open-source NoSQL document database that JSON-like schema instead of traditional table-based relational data. Spring Boot offers several conveniences for working with MongoDB, including the `spring-boot-starter-data-mongodb` and `spring-boot-starter-data-mongodb-reactive` -'`Starters`'. +"`Starters`". @@ -3638,14 +3660,14 @@ TIP: If `spring.data.mongodb.port` is not specified, the default of `27017` is u could delete this line from the example shown earlier. TIP: If you do not use Spring Data Mongo, you can inject `com.mongodb.Mongo` beans -instead of using `MongoDbFactory`. You can also declare your own `MongoDbFactory` or -`Mongo` bean if you want to take complete control of establishing the MongoDB connection. +instead of using `MongoDbFactory`. If you want to take complete control of establishing +the MongoDB connection, you can also declare your own `MongoDbFactory` or `Mongo` bean. [[boot-features-mongo-template]] ==== MongoTemplate -Spring Data Mongo provides a +{spring-data-mongo}[Spring Data MongoDB] provides a {spring-data-mongo-javadoc}/core/MongoTemplate.html[`MongoTemplate`] class that is very similar in its design to Spring's `JdbcTemplate`. As with `JdbcTemplate`, Spring Boot auto-configures a bean for you to inject the template, as follows: @@ -3680,7 +3702,7 @@ Javadoc] for complete details. [[boot-features-spring-data-mongo-repositories]] ==== Spring Data MongoDB Repositories Spring Data includes repository support for MongoDB. As with the JPA repositories -discussed earlier, the basic principle is that queries are constructed automatically +discussed earlier, the basic principle is that queries are constructed automatically, based on method names. In fact, both Spring Data JPA and Spring Data MongoDB share the same common @@ -3704,10 +3726,10 @@ in the following example: } ---- -TIP: You can customize document scanning locations using the `@EntityScan` annotation. +TIP: You can customize document scanning locations by using the `@EntityScan` annotation. TIP: For complete details of Spring Data MongoDB, including its rich object mapping -technologies, refer to the http://projects.spring.io/spring-data-mongodb/[reference +technologies, refer to its http://projects.spring.io/spring-data-mongodb/[reference documentation]. @@ -3740,7 +3762,7 @@ the Mongo instance's configuration and logging routing. http://neo4j.com/[Neo4j] is an open-source NoSQL graph database that uses a rich data model of nodes related by first class relationships, which is better suited for connected big data than traditional rdbms approaches. Spring Boot offers several conveniences for -working with Neo4j, including the `spring-boot-starter-data-neo4j` '`Starter`'. +working with Neo4j, including the `spring-boot-starter-data-neo4j` "`Starter`". @@ -3843,7 +3865,7 @@ following two annotations to your Spring configuration: ==== Repository Example -The following examples shows an interface definition for a Neo4j repository: +The following example shows an interface definition for a Neo4j repository: [source,java,indent=0] ---- @@ -3872,7 +3894,7 @@ documentation]. https://github.com/spring-projects/spring-data-gemfire[Spring Data Gemfire] provides convenient Spring-friendly tools for accessing the http://pivotal.io/big-data/pivotal-gemfire#details[Pivotal Gemfire] data management -platform. There is a `spring-boot-starter-data-gemfire` '`Starter`' for collecting the +platform. There is a `spring-boot-starter-data-gemfire` "`Starter`" for collecting the dependencies in a convenient way. There is currently no auto-configuration support for Gemfire, but you can enable Spring Data Repositories with a https://github.com/spring-projects/spring-data-gemfire/blob/master/src/main/java/org/springframework/data/gemfire/repository/config/EnableGemfireRepositories.java[single annotation: `@EnableGemfireRepositories`]. @@ -3884,7 +3906,7 @@ https://github.com/spring-projects/spring-data-gemfire/blob/master/src/main/java http://lucene.apache.org/solr/[Apache Solr] is a search engine. Spring Boot offers basic auto-configuration for the Solr 5 client library and the abstractions on top of it provided by https://github.com/spring-projects/spring-data-solr[Spring Data Solr]. There -is a `spring-boot-starter-data-solr` '`Starter`' for collecting the dependencies in a +is a `spring-boot-starter-data-solr` "`Starter`" for collecting the dependencies in a convenient way. @@ -3918,11 +3940,11 @@ If you add your own `@Bean` of type `SolrClient`, it replaces the default. [[boot-features-spring-data-solr-repositories]] ==== Spring Data Solr Repositories Spring Data includes repository support for Apache Solr. As with the JPA repositories -discussed earlier, the basic principle is that queries are constructed for you -automatically based on method names. +discussed earlier, the basic principle is that queries are automatically constructed for \ +you based on method names. In fact, both Spring Data JPA and Spring Data Solr share the same common infrastructure. -So you could take the JPA example from earlier and, assuming that `City` is now a +You could take the JPA example from earlier and, assuming that `City` is now a `@SolrDocument` class rather than a JPA `@Entity`, it works in the same way. TIP: For complete details of Spring Data Solr, refer to the @@ -3936,7 +3958,7 @@ http://www.elasticsearch.org/[Elasticsearch] is an open source, distributed, rea search and analytics engine. Spring Boot offers basic auto-configuration for Elasticsearch and the abstractions on top of it provided by https://github.com/spring-projects/spring-data-elasticsearch[Spring Data Elasticsearch]. -There is a `spring-boot-starter-data-elasticsearch` '`Starter`' for collecting the +There is a `spring-boot-starter-data-elasticsearch` "`Starter`" for collecting the dependencies in a convenient way. Spring Boot also supports https://github.com/searchbox-io/Jest[Jest]. @@ -3944,8 +3966,8 @@ https://github.com/searchbox-io/Jest[Jest]. [[boot-features-connecting-to-elasticsearch-jest]] ==== Connecting to Elasticsearch by Using Jest -If you have `Jest` on the classpath, you can inject an auto-configured `JestClient` -targeting `http://localhost:9200` by default. You can further tune how the client is +If you have `Jest` on the classpath, you can inject an auto-configured `JestClient` that +by default targets `http://localhost:9200`. You can further tune how the client is configured, as shown in the following example: [source,properties,indent=0] @@ -3973,7 +3995,7 @@ To take full control over the registration, define a `JestClient` bean. ==== Connecting to Elasticsearch by Using Spring Data To connect to Elasticsearch, you must provide the address of one or more cluster nodes. The address can be specified by setting the `spring.data.elasticsearch.cluster-nodes` -property to a comma-separated '`host:port`' list. With this configuration in place, an +property to a comma-separated `host:port` list. With this configuration in place, an `ElasticsearchTemplate` or `TransportClient` can be injected like any other Spring bean, as shown in the following example: @@ -4025,7 +4047,7 @@ http://cassandra.apache.org/[Cassandra] is an open source, distributed database management system designed to handle large amounts of data across many commodity servers. Spring Boot offers auto-configuration for Cassandra and the abstractions on top of it provided by https://github.com/spring-projects/spring-data-cassandra[Spring Data -Cassandra]. There is a `spring-boot-starter-data-cassandra` '`Starter`' for collecting +Cassandra]. There is a `spring-boot-starter-data-cassandra` "`Starter`" for collecting the dependencies in a convenient way. @@ -4079,12 +4101,12 @@ http://docs.spring.io/spring-data/cassandra/docs/[reference documentation]. [[boot-features-couchbase]] === Couchbase -http://www.couchbase.com/[Couchbase] is an open-source, distributed multi-model NoSQL +http://www.couchbase.com/[Couchbase] is an open-source, distributed, multi-model NoSQL document-oriented database that is optimized for interactive applications. Spring Boot offers auto-configuration for Couchbase and the abstractions on top of it provided by https://github.com/spring-projects/spring-data-couchbase[Spring Data Couchbase]. There are -a `spring-boot-starter-data-couchbase` and `spring-boot-starter-data-couchbase-reactive` -'`Starters`' for collecting the dependencies in a convenient way. +`spring-boot-starter-data-couchbase` and `spring-boot-starter-data-couchbase-reactive` +"`Starters`" for collecting the dependencies in a convenient way. @@ -4105,7 +4127,7 @@ example: [TIP] ==== You need to provide _at least_ the bootstrap host(s), in which case the bucket name is -`default` and the password is the empty String. Alternatively, you can define your own +`default` and the password is an empty String. Alternatively, you can define your own `org.springframework.data.couchbase.config.CouchbaseConfigurer` `@Bean` to take control over the whole configuration. ==== @@ -4163,7 +4185,7 @@ provided by the auto-configuration: * A `CustomConversions` `@Bean` with a name of `couchbaseCustomConversions`. To avoid hard-coding those names in your own config, you can reuse `BeanNames` provided -by Spring Data Couchbase. For instance, you can customize the converters to use as +by Spring Data Couchbase. For instance, you can customize the converters to use, as follows: [source,java,indent=0] @@ -4198,7 +4220,7 @@ https://www.ldap.com/unboundid-ldap-sdk-for-java[UnboundID]. LDAP abstractions are provided by https://github.com/spring-projects/spring-data-ldap[Spring Data LDAP]. -There is a `spring-boot-starter-data-ldap` '`Starter`' for collecting the dependencies in +There is a `spring-boot-starter-data-ldap` "`Starter`" for collecting the dependencies in a convenient way. @@ -4206,7 +4228,7 @@ a convenient way. [[boot-features-ldap-connecting]] ==== Connecting to an LDAP Server To connect to an LDAP server, make sure you declare a dependency on the -`spring-boot-starter-data-ldap` '`Starter`' or `spring-ldap-core` and then declare the +`spring-boot-starter-data-ldap` "`Starter`" or `spring-ldap-core` and then declare the URLs of your server in your application.properties, as shown in the following example: [source,properties,indent=0] @@ -4253,9 +4275,10 @@ other Spring Bean, as shown in the following example: [[boot-features-ldap-embedded]] ==== Embedded In-memory LDAP Server -For testing purposes Spring Boot supports auto-configuration of an in-memory LDAP server -from https://www.ldap.com/unboundid-ldap-sdk-for-java[UnboundID]. To configure the server -add a dependency to `com.unboundid:unboundid-ldapsdk` and declare a `base-dn` property: +For testing purposes, Spring Boot supports auto-configuration of an in-memory LDAP server +from https://www.ldap.com/unboundid-ldap-sdk-for-java[UnboundID]. To configure the server, +add a dependency to `com.unboundid:unboundid-ldapsdk` and declare a `base-dn` property, as +follows: [source,properties,indent=0] ---- @@ -4269,9 +4292,9 @@ If there is a `schema.ldif` file on your classpath, it is used to initialize the If you want to load the initialization script from a different resource, you can also use the `spring.ldap.embedded.ldif` property. -By default, a standard schema is used to validate `LDIF` files, you can turn off -validation altogether using the `spring.ldap.embedded.validation.enabled` property. If -you have custom attributes, you can use `spring.ldap.embedded.validation.schema` to +By default, a standard schema is used to validate `LDIF` files. You can turn off +validation altogether by setting the `spring.ldap.embedded.validation.enabled` property. +If you have custom attributes, you can use `spring.ldap.embedded.validation.schema` to define your custom attribute types or object classes. @@ -4360,6 +4383,8 @@ TIP: It is also possible to transparently {spring-reference}integration.html#cache-annotations-put[update] or {spring-reference}integration.html#cache-annotations-evict[evict] data from the cache. +// TODO Updating and evicting should be a section (or two) with samples. + NOTE: If you use the cache infrastructure with beans that are not interface-based, make sure to enable the `proxyTargetClass` attribute of `@EnableCaching`. @@ -4370,8 +4395,9 @@ materialized by the `org.springframework.cache.Cache` and `org.springframework.cache.CacheManager` interfaces. If you have not defined a bean of type `CacheManager` or a `CacheResolver` named -`cacheResolver` (see `CachingConfigurer`), Spring Boot tries to detect the following -providers (in the indicated order): +`cacheResolver` (see +{spring-framework-javadoc}cache/annotation/CachingConfigurer.html[`CachingConfigurer`]), +Spring Boot tries to detect the following providers (in the indicated order): . <> . <> (EhCache 3, Hazelcast, @@ -4389,7 +4415,7 @@ TIP: It is also possible to _force_ a particular cache provider by setting the <> in certain environment (such as tests). -TIP: Use the `spring-boot-starter-cache` '`Starter`' to quickly add basic caching +TIP: Use the `spring-boot-starter-cache` "`Starter`" to quickly add basic caching dependencies. The starter brings in `spring-context-support`. If you add dependencies manually, you must include `spring-context-support` in order to use the JCache, EhCache 2.x, or Guava support. @@ -4414,10 +4440,10 @@ values should be passed down to the underlying map: [NOTE] ==== -In the example above, an auto-configured `ConcurrentMapCacheManager` is expected. If that -is not the case (either you provided your own config or a different cache provider was -auto-configured), the customizer is not invoked at all. You can have as many customizers -as you want, and you can also order them as usual by using `@Order` or `Ordered`. +In the preceding example, an auto-configured `ConcurrentMapCacheManager` is expected. If +that is not the case (either you provided your own config or a different cache provider +was auto-configured), the customizer is not invoked at all. You can have as many +customizers as you want, and you can also order them by using `@Order` or `Ordered`. ==== @@ -4432,11 +4458,12 @@ is created. [[boot-features-caching-provider-jcache]] ==== JCache (JSR-107) -JCache is bootstrapped via the presence of a `javax.cache.spi.CachingProvider` on the -classpath (that is, a JSR-107 compliant caching library exists on the classpath) and the -`JCacheCacheManager` provided by the `spring-boot-starter-cache` '`Starter`'. Various -compliant libraries are available, and Spring Boot provides dependency management for -Ehcache 3, Hazelcast, and Infinispan. Any other compliant library can be added as well. +https://jcp.org/en/jsr/detail?id=107[JCache] is bootstrapped through the presence of a +`javax.cache.spi.CachingProvider` on the classpath (that is, a JSR-107 compliant caching +library exists on the classpath), and the `JCacheCacheManager` is provided by the +`spring-boot-starter-cache` "`Starter`". Various compliant libraries are available, and +Spring Boot provides dependency management for Ehcache 3, Hazelcast, and Infinispan. Any +other compliant library can be added as well. It might happen that more than one provider is present, in which case the provider must be explicitly specified. Even if the JSR-107 standard does not enforce a standardized way @@ -4462,10 +4489,10 @@ single `HazelcastInstance` is available, it is automatically reused for the There are two ways to customize the underlying `javax.cache.cacheManager`: * Caches can be created on startup by setting the `spring.cache.cache-names` property. If - a custom `javax.cache.configuration.Configuration` bean is defined, it is used to - customize them. +a custom `javax.cache.configuration.Configuration` bean is defined, it is used to +customize them. * `org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer` beans are - invoked with the reference of the `CacheManager` for full customization. +invoked with the reference of the `CacheManager` for full customization. TIP: If a standard `javax.cache.CacheManager` bean is defined, it is wrapped automatically in an `org.springframework.cache.CacheManager` implementation that the @@ -4475,9 +4502,9 @@ abstraction expects. No further customization is applied to it. [[boot-features-caching-provider-ehcache2]] ==== EhCache 2.x -EhCache 2.x is used if a file named `ehcache.xml` can be found at the root of the -classpath. If EhCache 2.x is found, the `EhCacheCacheManager` provided by the -`spring-boot-starter-cache` '`Starter`' is used to bootstrap the cache manager. An +http://www.ehcache.org/[EhCache] 2.x is used if a file named `ehcache.xml` can be found at +the root of the classpath. If EhCache 2.x is found, the `EhCacheCacheManager` provided by +the `spring-boot-starter-cache` "`Starter`" is used to bootstrap the cache manager. An alternate configuration file can be provided as well, as shown in the following example: [source,properties,indent=0] @@ -4498,8 +4525,8 @@ Spring Boot has <>. If a [[boot-features-caching-provider-infinispan]] ==== Infinispan -Infinispan has no default configuration file location, so it must be specified -explicitly. Otherwise, the default bootstrap is used. +http://infinispan.org/[Infinispan] has no default configuration file location, so it must +be specified explicitly. Otherwise, the default bootstrap is used. [source,properties,indent=0] ---- @@ -4521,14 +4548,14 @@ details. [[boot-features-caching-provider-couchbase]] ==== Couchbase -If the Couchbase Java client and the `couchbase-spring-cache` implementation are -available and Couchbase is <>, a +If the https://www.couchbase.com/[Couchbase] Java client and the `couchbase-spring-cache` +implementation are available and Couchbase is <>, a `CouchbaseCacheManager` is auto-configured. It is also possible to create additional caches on startup by setting the `spring.cache.cache-names` property. These caches operate on the `Bucket` that was auto-configured. You can _also_ create additional caches on another `Bucket` by using the customizer. Assume you need two caches (`cache1` and -`cache2`) on the "main" `Bucket` and one `cache3` cache with a custom time to live of 2 -seconds on the "another" `Bucket`. You can create the first two caches through +`cache2`) on the "main" `Bucket` and one (`cache3`) cache with a custom time to live of 2 +seconds on the "`another`" `Bucket`. You can create the first two caches through configuration, as follows: [source,properties,indent=0] @@ -4567,15 +4594,16 @@ Then you can define a `@Configuration` class to configure the extra `Bucket` and } ---- -This sample configuration reuses the `Cluster` that was created via auto-configuration. +This sample configuration reuses the `Cluster` that was created through +auto-configuration. [[boot-features-caching-provider-redis]] ==== Redis -If Redis is available and configured, a `RedisCacheManager` is auto-configured. It is -possible to create additional caches on startup by setting the -`spring.cache.cache-names` property and cache defaults can be configured using +If http://redis.io/[Redis] is available and configured, a `RedisCacheManager` is +auto-configured. It is possible to create additional caches on startup by setting the +`spring.cache.cache-names` property and cache defaults can be configured by using `spring.cache.redis.*` properties. For instance, the following configuration creates `cache1` and `cache2` caches with a _time to live_ of 10 minutes: @@ -4596,10 +4624,10 @@ recommend keeping this setting enabled if you create your own `RedisCacheManager [[boot-features-caching-provider-caffeine]] ==== Caffeine -Caffeine is a Java 8 rewrite of Guava's cache that supersedes support for Guava. If -Caffeine is present, a `CaffeineCacheManager` (provided by the -`spring-boot-starter-cache` '`Starter`') is auto-configured. Caches can be created on -startup by setting the `spring.cache.cache-names` property and can be customized by one +https://github.com/ben-manes/caffeine[Caffeine] is a Java 8 rewrite of Guava's cache that +supersedes support for Guava. If Caffeine is present, a `CaffeineCacheManager` (provided +by the `spring-boot-starter-cache` "`Starter`") is auto-configured. Caches can be created +on startup by setting the `spring.cache.cache-names` property and can be customized by one of the following (in the indicated order): . A cache spec defined by `spring.cache.caffeine.spec` @@ -4660,7 +4688,7 @@ example: The Spring Framework provides extensive support for integrating with messaging systems, from simplified use of the JMS API using `JmsTemplate` to a complete infrastructure to receive messages asynchronously. Spring AMQP provides a similar feature set for the -'`Advanced Message Queuing Protocol`'. Spring Boot also provides auto-configuration +Advanced Message Queuing Protocol. Spring Boot also provides auto-configuration options for `RabbitTemplate` and RabbitMQ. Spring WebSocket natively includes support for STOMP messaging, and Spring Boot has support for that through starters and a small amount of auto-configuration. Spring Boot also has support for Apache Kafka. @@ -4681,9 +4709,10 @@ infrastructure to send and receive messages. [[boot-features-activemq]] ==== ActiveMQ Support -When ActiveMQ is available on the classpath, Spring Boot can also configure a -`ConnectionFactory`. If the broker is present, an embedded broker is automatically started -and configured (provided no broker URL is specified through configuration). +When http://activemq.apache.org/[ActiveMQ] is available on the classpath, Spring Boot can +also configure a `ConnectionFactory`. If the broker is present, an embedded broker is +automatically started and configured (provided no broker URL is specified through +configuration). NOTE: If you use `spring-boot-starter-activemq`, the necessary dependencies to connect or embed an ActiveMQ instance are provided, as is the Spring infrastructure to integrate with @@ -4722,16 +4751,17 @@ are resolved against their provided names. [[boot-features-artemis]] ==== Artemis Support -Spring Boot can auto-configure a `ConnectionFactory` when it detects that Artemis is -available on the classpath. If the broker is present, an embedded broker is automatically -started and configured (unless the mode property has been explicitly set). The supported -modes are `embedded` (to make explicit that an embedded broker is required and that an -error should occur if the broker is not available on the classpath) and `native` (to -connect to a broker using the `netty` transport protocol). When the latter is configured, -Spring Boot configures a `ConnectionFactory` that connects to a broker running on the -local machine with the default settings. - -NOTE: If you are using `spring-boot-starter-artemis`, the necessary dependencies to +Spring Boot can auto-configure a `ConnectionFactory` when it detects that +http://activemq.apache.org/artemis/[Artemis] is available on the classpath. If the broker +is present, an embedded broker is automatically started and configured (unless the mode +property has been explicitly set). The supported modes are `embedded` (to make explicit +that an embedded broker is required and that an error should occur if the broker is not +available on the classpath) and `native` (to connect to a broker using the `netty` +transport protocol). When the latter is configured, Spring Boot configures a +`ConnectionFactory` that connects to a broker running on the local machine with the +default settings. + +NOTE: If you use `spring-boot-starter-artemis`, the necessary dependencies to connect to an existing Artemis instance are provided, as well as the Spring infrastructure to integrate with JMS. Adding `org.apache.activemq:artemis-jms-server` to your application lets you use embedded mode. @@ -4761,7 +4791,7 @@ See for more supported options. No JNDI lookup is involved, and destinations are resolved against their names, using -either the '`name`' attribute in the Artemis configuration or the names provided through +either the `name` attribute in the Artemis configuration or the names provided through configuration. @@ -4814,7 +4844,6 @@ is defined, it is associated automatically to the auto-configured `JmsTemplate`. [[boot-features-using-jms-receiving]] ==== Receiving a Message - When the JMS infrastructure is present, any bean can be annotated with `@JmsListener` to create a listener endpoint. If no `JmsListenerContainerFactory` has been defined, a default one is configured automatically. If a `DestinationResolver` or a @@ -4897,14 +4926,15 @@ The Advanced Message Queuing Protocol (AMQP) is a platform-neutral, wire-level p for message-oriented middleware. The Spring AMQP project applies core Spring concepts to the development of AMQP-based messaging solutions. Spring Boot offers several conveniences for working with AMQP through RabbitMQ, including the `spring-boot-starter-amqp` -'`Starter`'. +"`Starter`". [[boot-features-rabbitmq]] ==== RabbitMQ support -RabbitMQ is a lightweight, reliable, scalable, and portable message broker based on the -AMQP protocol. Spring uses `RabbitMQ` to communicate through the AMQP protocol. +https://www.rabbitmq.com/[RabbitMQ] is a lightweight, reliable, scalable, and portable +message broker based on the AMQP protocol. Spring uses `RabbitMQ` to communicate through +the AMQP protocol. RabbitMQ configuration is controlled by external configuration properties in `+spring.rabbitmq.*+`. For example, you might declare the following section in @@ -5026,7 +5056,7 @@ specific `MessageConverter`: } ---- -Then you can use the factory in any `@RabbitListener`-annotated method as follows: +Then you can use the factory in any `@RabbitListener`-annotated method, as follows: [source,java,indent=0] [subs="verbatim,quotes"] @@ -5052,8 +5082,8 @@ IMPORTANT: By default, if retries are disabled and the listener throws an except delivery is retried indefinitely. You can modify this behavior in two ways: Set the `defaultRequeueRejected` property to `false` so that zero re-deliveries are attempted or throw an `AmqpRejectAndDontRequeueException` to signal the message should be rejected. -The latter is the mechanism used when retries are enabled and the maximum delivery -attempts are reached. +The latter is the mechanism used when retries are enabled and the maximum number of +delivery attempts is reached. @@ -5163,14 +5193,14 @@ IMPORTANT: Properties set in this way override any configuration item that Sprin explicitly supports. [[boot-features-resttemplate]] -== Calling REST Services with '`RestTemplate`' +== Calling REST Services with `RestTemplate` If you need to call remote REST services from your application, you can use the Spring -Framework's `RestTemplate` class. Since `RestTemplate` instances often need to be -customized before being used, Spring Boot does not provide any single auto-configured -`RestTemplate` bean. It does, however, auto-configure a `RestTemplateBuilder`, which can -be used to create `RestTemplate` instances when needed. The auto-configured -`RestTemplateBuilder` ensures that sensible `HttpMessageConverters` are applied to -`RestTemplate` instances. +Framework's {spring-javadoc}/web/client/RestTemplate.html[`RestTemplate`] class. Since +`RestTemplate` instances often need to be customized before being used, Spring Boot does +not provide any single auto-configured `RestTemplate` bean. It does, however, +auto-configure a `RestTemplateBuilder`, which can be used to create `RestTemplate` +instances when needed. The auto-configured `RestTemplateBuilder` ensures that sensible +`HttpMessageConverters` are applied to `RestTemplate` instances. The following code shows a typical example: @@ -5193,7 +5223,7 @@ The following code shows a typical example: ---- 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 +quickly configure a `RestTemplate`. For example, to add BASIC auth support, you can use `builder.basicAuthorization("user", "password").build()`. @@ -5227,9 +5257,9 @@ Finally, the most extreme (and rarely used) option is to create your own [[boot-features-webclient]] -== Calling REST Services with '`WebClient`' +== Calling REST Services with `WebClient` If you have Spring WebFlux on your classpath, you can also choose to use `WebClient` to -call remote REST services, Compared to `RestTemplate`, this client has a more functional +call remote REST services. Compared to `RestTemplate`, this client has a more functional feel and is fully reactive. You can create your own client instance with the builder, `WebClient.create()`. See the {spring-reference}web.html#web-reactive-client[relevant section on WebClient]. @@ -5321,7 +5351,7 @@ detailed explanation of how you can use `JavaMailSender`. If `spring.mail.host` and the relevant libraries (as defined by `spring-boot-starter-mail`) are available, a default `JavaMailSender` is created if none exists. The sender can be further customized by configuration items from the -`spring.mail` namespace, see +`spring.mail` namespace. See {sc-spring-boot-autoconfigure}/mail/MailProperties.{sc-ext}[`MailProperties`] for more details. @@ -5356,17 +5386,17 @@ the JTA auto-configuration. [[boot-features-jta-atomikos]] === Using an Atomikos Transaction Manager -Atomikos is a popular open source transaction manager which can be embedded into your -Spring Boot application. You can use the `spring-boot-starter-jta-atomikos` Starter to -pull in the appropriate Atomikos libraries. Spring Boot auto-configures Atomikos and -ensures that appropriate `depends-on` settings are applied to your Spring beans for -correct startup and shutdown ordering. - -By default Atomikos transaction logs are written to a `transaction-logs` directory in -your application home directory (the directory in which your application jar file -resides). You can customize this directory by setting a `spring.jta.log-dir` property in -your `application.properties` file. Properties starting with -`spring.jta.atomikos.properties` can also be used to customize the Atomikos +https://www.atomikos.com/[Atomikos] is a popular open source transaction manager which can +be embedded into your Spring Boot application. You can use the +`spring-boot-starter-jta-atomikos` Starter to pull in the appropriate Atomikos libraries. +Spring Boot auto-configures Atomikos and ensures that appropriate `depends-on` settings +are applied to your Spring beans for correct startup and shutdown ordering. + +By default, Atomikos transaction logs are written to a `transaction-logs` directory in +your application's home directory (the directory in which your application jar file +resides). You can customize the location of this directory by setting a +`spring.jta.log-dir` property in your `application.properties` file. Properties starting +with `spring.jta.atomikos.properties` can also be used to customize the Atomikos `UserTransactionServiceImp`. See the {dc-spring-boot}/jta/atomikos/AtomikosProperties.{dc-ext}[`AtomikosProperties` Javadoc] for complete details. @@ -5381,16 +5411,17 @@ property with a different value for each instance of your application. [[boot-features-jta-bitronix]] === Using a Bitronix Transaction Manager -Bitronix is popular open source JTA transaction manager implementation. You can use the -`spring-boot-starter-jta-bitronix` starter to add the appropriate Bitronix dependencies -to your project. As with Atomikos, Spring Boot automatically configures Bitronix and -post-processes your beans to ensure that startup and shutdown ordering is correct. +https://github.com/bitronix/btm[Bitronix] is a spopular open-source JTA transaction +manager implementation. You can use the `spring-boot-starter-jta-bitronix` starter to add +the appropriate Bitronix dependencies to your project. As with Atomikos, Spring Boot +automatically configures Bitronix and post-processes your beans to ensure that startup and +shutdown ordering is correct. By default, Bitronix transaction log files (`part1.btm` and `part2.btm`) are written to -a `transaction-logs` directory in your application home directory. You can customize this -directory by setting the `spring.jta.log-dir` property. Properties starting with -`spring.jta.bitronix.properties` are also bound to the `bitronix.tm.Configuration` bean, -allowing for complete customization. See the +a `transaction-logs` directory in your application home directory. You can customize the +location of this directory by setting the `spring.jta.log-dir` property. Properties +starting with `spring.jta.bitronix.properties` are also bound to the +`bitronix.tm.Configuration` bean, allowing for complete customization. See the https://github.com/bitronix/btm/wiki/Transaction-manager-configuration[Bitronix documentation] for details. @@ -5404,17 +5435,17 @@ property with a different value for each instance of your application. [[boot-features-jta-narayana]] === Using a Narayana Transaction Manager -Narayana is popular open source JTA transaction manager implementation supported by -JBoss. You can use the `spring-boot-starter-jta-narayana` starter to add the appropriate -Narayana dependencies to your project. As with Atomikos and Bitronix, Spring Boot -automatically configures Narayana and post-processes your beans to ensure that startup -and shutdown ordering is correct. +http://narayana.io/[Narayana] is a popular open source JTA transaction manager +implementation supported by JBoss. You can use the `spring-boot-starter-jta-narayana` +starter to add the appropriate Narayana dependencies to your project. As with Atomikos and +Bitronix, Spring Boot automatically configures Narayana and post-processes your beans to +ensure that startup and shutdown ordering is correct. By default, Narayana transaction logs are written to a `transaction-logs` directory in your application home directory (the directory in which your application jar file -resides). You can customize this directory by setting a `spring.jta.log-dir` property in -your `application.properties` file. Properties starting with -`spring.jta.narayana.properties` can also be used to customize the Narayana +resides). You can customize the location of this directory by setting a +`spring.jta.log-dir` property in your `application.properties` file. Properties starting +with `spring.jta.narayana.properties` can also be used to customize the Narayana configuration. See the {dc-spring-boot}/jta/narayana/NarayanaProperties.{dc-ext}[`NarayanaProperties` Javadoc] for complete details. @@ -5444,14 +5475,14 @@ to configure your `DataSource`. [[boot-features-jta-mixed-jms]] === Mixing XA and Non-XA JMS Connections -When using JTA, the primary JMS `ConnectionFactory` bean is XA aware and participates +When using JTA, the primary JMS `ConnectionFactory` bean is XA-aware and participates in distributed transactions. In some situations, you might want to process certain JMS -messages using a non-XA `ConnectionFactory`. For example, your JMS processing logic might -take longer than the XA timeout. +messages by using a non-XA `ConnectionFactory`. For example, your JMS processing logic +might take longer than the XA timeout. If you want to use a non-XA `ConnectionFactory`, you can inject the `nonXaJmsConnectionFactory` bean rather than the `@Primary` `jmsConnectionFactory` bean. -For consistency the `jmsConnectionFactory` bean is also provided by using the bean alias +For consistency, the `jmsConnectionFactory` bean is also provided by using the bean alias `xaJmsConnectionFactory`. The following example shows how to inject `ConnectionFactory` instances: @@ -5495,15 +5526,16 @@ provide good examples of how to write XA wrappers. [[boot-features-hazelcast]] == Hazelcast -If Hazelcast is on the classpath and a suitable configuration is found, Spring Boot -auto-configures a `HazelcastInstance` that you can inject in your application. +If https://hazelcast.com/[Hazelcast] is on the classpath and a suitable configuration is +found, Spring Boot auto-configures a `HazelcastInstance` that you can inject in your +application. If you define a `com.hazelcast.config.Config` bean, Spring Boot uses that. If your configuration defines an instance name, Spring Boot tries to locate an existing instance rather than creating a new one. -You could also specify the `hazelcast.xml` configuration file to use via configuration, as -shown in the following example: +You could also specify the `hazelcast.xml` configuration file to use through +configuration, as shown in the following example: [source,properties,indent=0] ---- @@ -5533,15 +5565,16 @@ implementation. [[boot-features-quartz]] == Quartz Scheduler -Spring Boot offers several conveniences for working with the Quartz scheduler, including -the `spring-boot-starter-quartz` '`Starter`'. If Quartz is available, a `Scheduler` is -auto-configured (via the `SchedulerFactoryBean` abstraction). +Spring Boot offers several conveniences for working with the +http://www.quartz-scheduler.org/[Quartz scheduler], including the +`spring-boot-starter-quartz` "`Starter`". If Quartz is available, a `Scheduler` is +auto-configured (through the `SchedulerFactoryBean` abstraction). Beans of the following types are automatically picked up and associated with the `Scheduler`: * `JobDetail`: defines a particular Job. `JobDetail` instances can be built with the - `JobBuilder` API. +`JobBuilder` API. * `Calendar`. * `Trigger`: defines when a particular job is triggered. @@ -5555,7 +5588,7 @@ following example: spring.quartz.job-store-type=jdbc ---- -When the jdbc store is used, the schema can be initialized on startup, as shown in the +When the JDBC store is used, the schema can be initialized on startup, as shown in the following example: [source,properties,indent=0] @@ -5600,15 +5633,15 @@ in a similar manner, as shown in the following example: [[boot-features-integration]] == Spring Integration -Spring Boot offers several conveniences for working with Spring Integration, including -the `spring-boot-starter-integration` '`Starter`'. Spring Integration provides -abstractions over messaging and also other transports such as HTTP, TCP, and others. If -Spring Integration is available on your classpath, it is initialized through the -`@EnableIntegration` annotation. +Spring Boot offers several conveniences for working with {spring-integration}[Spring +Integration], including the `spring-boot-starter-integration` "`Starter`". Spring +Integration provides abstractions over messaging and also other transports such as HTTP, +TCP, and others. If Spring Integration is available on your classpath, it is initialized +through the `@EnableIntegration` annotation. Spring Boot also configures some features that are triggered by the presence of additional -Spring Integration modules. If `'spring-integration-jmx'` is also on the classpath, -message processing statistics are published over JMX . If `'spring-integration-jdbc'` is +Spring Integration modules. If `spring-integration-jmx` is also on the classpath, +message processing statistics are published over JMX . If `spring-integration-jdbc` is available, the default database schema can be created on startup, as shown in the following line: @@ -5626,8 +5659,9 @@ classes for more details. [[boot-features-session]] == Spring Session -Spring Boot provides Spring Session auto-configuration for a wide range of data stores. -When building a Servlet web application, the following stores can be auto-configured: +Spring Boot provides {spring-session}[Spring Session] auto-configuration for a wide range +of data stores. When building a Servlet web application, the following stores can be +auto-configured: * JDBC * Redis @@ -5664,9 +5698,9 @@ the name of the table for the JDBC store, as shown in the following example: [[boot-features-jmx]] == Monitoring and Management over JMX Java Management Extensions (JMX) provide a standard mechanism to monitor and manage -applications. By default, Spring Boot creates an `MBeanServer` a bean with an ID of -'`mbeanServer`' and exposes any of your beans that are annotated with Spring JMX -annotations (`@ManagedResource`, `@ManagedAttribute`, and `@ManagedOperation`). +applications. By default, Spring Boot creates an `MBeanServer` bean with an ID of +`mbeanServer` and exposes any of your beans that are annotated with Spring JMX +annotations (`@ManagedResource`, `@ManagedAttribute`, or `@ManagedOperation`). See the {sc-spring-boot-autoconfigure}/jmx/JmxAutoConfiguration.{sc-ext}[`JmxAutoConfiguration`] @@ -5677,10 +5711,10 @@ class for more details. [[boot-features-testing]] == Testing Spring Boot provides a number of utilities and annotations to help when testing your -application. Test support is provided by two modules; `spring-boot-test` contains core +application. Test support is provided by two modules: `spring-boot-test` contains core items, and `spring-boot-test-autoconfigure` supports auto-configuration for tests. -Most developers use the `spring-boot-starter-test` '`Starter`', which imports both Spring +Most developers use the `spring-boot-starter-test` "`Starter`", which imports both Spring Boot test modules as well as JUnit, AssertJ, Hamcrest, and a number of other useful libraries. @@ -5688,7 +5722,7 @@ libraries. [[boot-features-test-scope-dependencies]] === Test Scope Dependencies -The `spring-boot-starter-test` '`Starter`' (in the `test` `scope`)contains +The `spring-boot-starter-test` "`Starter`" (in the `test` `scope`)contains the following provided libraries: * http://junit.org[JUnit]: The de-facto standard for unit testing Java applications. @@ -5704,22 +5738,25 @@ as constraints or predicates). We generally find these common libraries to be useful when writing tests. If these libraries do not suit your needs, you can add additional test dependencies of your own. +// TODO Describe how to add additional test dependencies. That content should be a new +// heading, with a link here. + [[boot-features-testing-spring-applications]] === Testing Spring Applications One of the major advantages of dependency injection is that it should make your code -easier to unit test. You can instantiate objects using the `new` operator without +easier to unit test. You can instantiate objects by using the `new` operator without even involving Spring. You can also use _mock objects_ instead of real dependencies. -Often, you need to move beyond '`unit testing`' and start '`integration testing`' (with +Often, you need to move beyond unit testing and start integration testing (with a Spring `ApplicationContext`). It is useful to be able to perform integration testing without requiring deployment of your application or needing to connect to other infrastructure. The Spring Framework includes a dedicated test module for such integration testing. You can declare a dependency directly to `org.springframework:spring-test` or use the -`spring-boot-starter-test` '`Starter`' to pull it in transitively. +`spring-boot-starter-test` "`Starter`" to pull it in transitively. If you have not used the `spring-test` module before, you should start by reading the {spring-reference}testing.html#testing[relevant section] of the Spring Framework @@ -5731,9 +5768,10 @@ reference documentation. === Testing Spring Boot Applications A Spring Boot application is a Spring `ApplicationContext`, so nothing very special has to be done to test it beyond what you would normally do with a vanilla Spring context. -One thing to watch out for, though, is that the external properties, logging, and other -features of Spring Boot are installed in the context by default only if you use -`SpringApplication` to create it. + + +NOTE: External properties, logging, and other features of Spring Boot are installed in the +context by default only if you use `SpringApplication` to create it. Spring Boot provides a `@SpringBootTest` annotation, which can be used as an alternative to the standard `spring-test` `@ContextConfiguration` annotation when you need Spring @@ -5764,8 +5802,8 @@ run in separate threads and, thus, in separate transactions. Any transaction ini the server does not roll back in this case. NOTE: In addition to `@SpringBootTest`, a number of other annotations are also provided -for testing more specific slices of an application. You can find more detail later in -this document. +for testing more specific slices of an application. You can find more detail throughout +this chapter. TIP: Do not forget to add `@RunWith(SpringRunner.class)` to your test. Otherwise, the annotations are ignored. @@ -5801,16 +5839,16 @@ instead of your application's primary configuration, a nested `@TestConfiguratio is used in addition to your application's primary configuration. NOTE: Spring's test framework caches application contexts between tests. Therefore, as -long as your tests share the same configuration (no matter how it's discovered), the +long as your tests share the same configuration (no matter how it is discovered), the potentially time-consuming process of loading the context happens only once. [[boot-features-testing-spring-boot-applications-excluding-config]] ==== Excluding Test Configuration -If your application uses component scanning, for example if you use -`@SpringBootApplication` or `@ComponentScan`, you may find top-level configuration -classes created only for specific tests accidentally get picked up everywhere. +If your application uses component scanning (for example, if you use +`@SpringBootApplication` or `@ComponentScan`), you may find top-level configuration +classes that you created only for specific tests accidentally get picked up everywhere. As we <>, `@TestConfiguration` can be used on an inner class of a test to customize the @@ -5877,7 +5915,7 @@ 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, a listener need to be explicitly added, as shown in the following example: +arrangement, a listener must be explicitly added, as shown in the following example: [source,java,indent=0] ---- @@ -5930,13 +5968,13 @@ the {dc-spring-boot-test}/mock/mockito/SpyBean.{dc-ext}[Javadoc] for full detail ==== Auto-configured Tests Spring Boot's auto-configuration system works well for applications but can sometimes be a little too much for tests. It often helps to load only the parts of the configuration -that are required to test a '`slice`' of your application. For example, you might want to -test that Spring MVC controllers are mapping URLs correctly, and you don't want to -involve database calls in those tests, or you _might want_ to test JPA entities, and you +that are required to test a "`slice`" of your application. For example, you might want to +test that Spring MVC controllers are mapping URLs correctly, and you do not want to +involve database calls in those tests, or you might want to test JPA entities, and you are not interested in the web layer when those tests run. The `spring-boot-test-autoconfigure` module includes a number of annotations that can be -used to automatically configure such '`slices`'. Each of them works in a similar way, +used to automatically configure such "`slices`". Each of them works in a similar way, providing a `@...Test` annotation that loads the `ApplicationContext` and one or more `@AutoConfigure...` annotations that can be used to customize auto-configuration settings. @@ -5947,13 +5985,13 @@ attribute. Alternatively, you can use `@ImportAutoConfiguration#exclude`. TIP: It is also possible to use the `@AutoConfigure...` annotations with the standard `@SpringBootTest` annotation. You can use this combination if you are not interested in -'`slicing`' your application but you want some of the auto-configured test beans. +"`slicing`" your application but you want some of the auto-configured test beans. [[boot-features-testing-spring-boot-applications-testing-autoconfigured-json-tests]] ==== Auto-configured JSON Tests -To test that object JSON serialization and deserialization is working as expected you can +To test that object JSON serialization and deserialization is working as expected, you can use the `@JsonTest` annotation. `@JsonTest` auto-configures the available supported JSON mapper, which can be one of the following libraries: @@ -5965,7 +6003,7 @@ If you need to configure elements of the auto-configuration, you can use the `@AutoConfigureJsonTesters` annotation. Spring Boot includes AssertJ-based helpers that work with the JSONassert and JsonPath -libraries to check that JSON is as expected. The `JacksonTester`, `GsonTester`, +libraries to check that JSON appears as expected. The `JacksonTester`, `GsonTester`, `JsonbTester`, and `BasicJsonTester` classes can be used for Jackson, Gson, Jsonb, and Strings respectively. Any helper fields on the test class can be `@Autowired` when using `@JsonTest`. The following example shows a test class for Jackson: @@ -6011,8 +6049,7 @@ Strings respectively. Any helper fields on the test class can be `@Autowired` wh } ---- - -NOTE: JSON helper classes can also be used directly in standard unit tests. Simply +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`. @@ -6023,14 +6060,14 @@ A list of the auto-configuration that is enabled by `@JsonTest` can be [[boot-features-testing-spring-boot-applications-testing-autoconfigured-mvc-tests]] ==== Auto-configured Spring MVC Tests -To test Spring MVC controllers are working as expected, you can use the `@WebMvcTest` +To test whether Spring MVC controllers are working as expected, use the `@WebMvcTest` annotation. `@WebMvcTest` auto-configures the Spring MVC infrastructure and limits scanned beans to `@Controller`, `@ControllerAdvice`, `@JsonComponent`, `Converter`, `GenericConverter`, `Filter`, `WebMvcConfigurer`, and `HandlerMethodArgumentResolver`. Regular `@Component` beans are not scanned when using this annotation. -TIP: If you need to register extra components such as Jackson `Module`, you can import -additional configuration classes using `@Import` on your test. +TIP: If you need to register extra components, such as the Jackson `Module`, you can +import additional configuration classes by using `@Import` on your test. Often, `@WebMvcTest` is limited to a single controller and is used in combination with `@MockBean` to provide mock implementations for required collaborators. @@ -6118,7 +6155,7 @@ bean and/or a `WebDriver` bean. The following example uses HtmlUnit: ---- NOTE: By default, Spring Boot puts `WebDriver` beans in a special "`scope`" to ensure -that the driver is quit after each test and that a new instance is injected. If you do +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. @@ -6129,13 +6166,14 @@ A list of the auto-configuration settings that are enabled by `@WebMvcTest` can [[boot-features-testing-spring-boot-applications-testing-autoconfigured-webflux-tests]] ==== Auto-configured Spring WebFlux Tests -To test that Spring WebFlux controllers are working as expected, you can use the -`@WebFluxTest` annotation. `@WebFluxTest` auto-configures the Spring WebFlux -infrastructure and limits scanned beans to `@Controller`, `@ControllerAdvice`, -`@JsonComponent`, `Converter`, `GenericConverter`, and `WebFluxConfigurer`. Regular -`@Component` beans are not scanned when the `@WebFluxTest` annotation is used. - -TIP: If you need to register extra components such as Jackson `Module`, you can import +To test that {spring-reference}html/web-reactive.html[Spring WebFlux] controllers are +working as expected, you can use the `@WebFluxTest` annotation. `@WebFluxTest` +auto-configures the Spring WebFlux infrastructure and limits scanned beans to +`@Controller`, `@ControllerAdvice`, `@JsonComponent`, `Converter`, `GenericConverter`, and +`WebFluxConfigurer`. Regular `@Component` beans are not scanned when the `@WebFluxTest` +annotation is used. + +TIP: If you need to register extra components, such as Jackson `Module`, you can import additional configuration classes using `@Import` on your test. Often, `@WebFluxTest` is limited to a single controller and used in combination with the @@ -6278,14 +6316,15 @@ A list of the auto-configuration settings that are enabled by `@DataJpaTest` can [[boot-features-testing-spring-boot-applications-testing-autoconfigured-jdbc-test]] ==== Auto-configured JDBC Tests -`@JdbcTest` is similar to `@DataJpaTest` but for pure JDBC-related tests. By default, it -also configures an in-memory embedded database and a `JdbcTemplate`. Regular `@Component` -beans are not loaded into the `ApplicationContext`. +`@JdbcTest` is similar to `@DataJpaTest` but is for pure JDBC-related tests. By default, +it also configures an in-memory embedded database and a `JdbcTemplate`. Regular +`@Component` beans are not loaded into the `ApplicationContext`. By default, JDBC tests are transactional and roll back at the end of each test. See the {spring-reference}testing.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. If that is not what you -want, you can disable transaction management for a test or for the whole class as follows: +want, you can disable transaction management for a test or for the whole class, as +follows: [source,java,indent=0] ---- @@ -6306,7 +6345,7 @@ want, you can disable transaction management for a test or for the whole class a 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 -<>.) +"<>".) A list of the auto-configuration that is enabled by `@JdbcTest` can be <>. @@ -6318,7 +6357,8 @@ A list of the auto-configuration that is enabled by `@JdbcTest` can be You can use `@JooqTest` in a similar fashion as `@JdbcTest` but for jOOQ-related tests. As jOOQ relies heavily on a Java-based schema that corresponds with the database schema, the existing `DataSource` is used. If you want to replace it with an in-memory database, -you can use `@AutoconfigureTestDatabase` to override those settings. +you can use `@AutoconfigureTestDatabase` to override those settings. (For more about using +jOOQ with Spring Boot, see "<>", earlier in this chapter.) `@JooqTest` configures a `DSLContext`. Regular `@Component` beans are not loaded into the `ApplicationContext`. The following example shows the `@JooqTest` annotation in use: @@ -6356,8 +6396,10 @@ A list of the auto-configuration that is enabled by `@JooqTest` can be You can use `@DataMongoTest` to test MongoDB applications. By default, it configures an in-memory embedded MongoDB (if available), configures a `MongoTemplate`, scans for `@Document` classes, and configures Spring Data MongoDB repositories. Regular -`@Component` beans are not loaded into the `ApplicationContext`. The following class -shows the `@DataMongoTest` annotation in use: +`@Component` beans are not loaded into the `ApplicationContext`. (For more about using +MongoDB with Spring Boot, see "<>", earlier in this chapter.) + +The following class shows the `@DataMongoTest` annotation in use: [source,java,indent=0] ---- @@ -6407,7 +6449,10 @@ A list of the auto-configuration settings that are enabled by `@DataMongoTest` c You can use `@DataNeo4jTest` to test Neo4j applications. By default, it uses an in-memory embedded Neo4j (if the embedded driver is available), scans for `@NodeEntity` classes, and configures Spring Data Neo4j repositories. Regular `@Component` beans are not loaded into -the `ApplicationContext`: +the `ApplicationContext`. (For more about using Neo4J with Spring Boot, see +"<>", earlier in this chapter.) + +The followig example shows a typical setup for using Neo4J tests in Spring Boot: [source,java,indent=0] ---- @@ -6430,7 +6475,7 @@ the `ApplicationContext`: By default, Data Neo4j tests are transactional and roll back at the end of each test. See the {spring-reference}testing.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. If that is not -what you want, you can disable transaction management for a test or for the whole class +what you want, you can disable transaction management for a test or for the whole class, as follows: [source,java,indent=0] @@ -6460,8 +6505,10 @@ A list of the auto-configuration settings that are enabled by `@DataNeo4jTest` c ==== Auto-configured Data Redis Tests You can use `@DataRedisTest` to test Redis applications. By default, it scans for `@RedisHash` classes and configures Spring Data Redis repositories. Regular `@Component` -beans are not loaded into the `ApplicationContext`. The following example shows the -`@DataRedisTest` annotation in use: +beans are not loaded into the `ApplicationContext`. (For more about using Redis with +Spring Boot, see "<>", earlier in this chapter.) + +The following example shows the `@DataRedisTest` annotation in use: [source,java,indent=0] ---- @@ -6491,8 +6538,10 @@ A list of the auto-configuration settings that are enabled by `@DataRedisTest` c You can use `@DataLdapTest` to test LDAP applications. By default, it configures an in-memory embedded LDAP (if available), configures an `LdapTemplate`, scans for `@Entry` classes, and configures Spring Data LDAP repositories. Regular `@Component` beans are not -loaded into the `ApplicationContext`. The following example shows the `@DataLdapTest` -annotation in use: +loaded into the `ApplicationContext`. (For more about using LDAP with +Spring Boot, see "<>", earlier in this chapter.) + +The following example shows the `@DataLdapTest` annotation in use: [source,java,indent=0] ---- @@ -6577,8 +6626,9 @@ A list of the auto-configuration settings that are enabled by `@RestClientTest` [[boot-features-testing-spring-boot-applications-testing-autoconfigured-rest-docs]] ==== Auto-configured Spring REST Docs Tests -You can use the `@AutoConfigureRestDocs` annotation to use Spring REST Docs in your tests -with Mock MVC or REST Assured. It removes the need for the JUnit rule in Spring REST Docs. +You can use the `@AutoConfigureRestDocs` annotation to use {spring-rest-docs}[Spring REST +Docs] in your tests with Mock MVC or REST Assured. It removes the need for the JUnit rule +in Spring REST Docs. `@AutoConfigureRestDocs` can be used to override the default output directory (`target/generated-snippets` if you are using Maven or `build/generated-snippets` if you @@ -6626,8 +6676,8 @@ Mock MVC and Spring REST Docs, as shown in the following example: ---- If you require more control over Spring REST Docs configuration than offered by the -attributes of `@AutoConfigureRestDocs`, a `RestDocsMockMvcConfigurationCustomizer` bean -can be used, as shown in the following example: +attributes of `@AutoConfigureRestDocs`, you can use a +`RestDocsMockMvcConfigurationCustomizer` bean, as shown in the following example: [source,java,indent=0] ---- @@ -6721,9 +6771,9 @@ at the same level as your application, as shown in the following example: ---- 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 when -it makes sense. The latter approach lets you enable it in one of your tests, if necessary, -with the `@Import` annotation. +`@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. 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 @@ -6736,8 +6786,8 @@ resemble the following code: public class SampleApplication { ... } ---- -This 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 +Doing so effectively overrides the default component scan directive with the side effect +of scanning those two packages regardless of the slice that you chose. For instance, a `@DataJpaTest` seems to suddenly scan components and user configurations of your application. Again, moving the custom directive to a separate class is a good way to fix this issue. @@ -6746,6 +6796,9 @@ TIP: If this is not an option for you, you can create a `@SpringBootConfiguratio somewhere in the hierarchy of your test so that it is used instead. Alternatively, you can specify a source for your test, which disables the behavior of finding a default one. +// TODO We should describe how to specify a test in a new section and link to it from this +// tip. + [[boot-features-testing-spring-boot-applications-with-spock]] @@ -6770,7 +6823,8 @@ packaged as part of `spring-boot`. ==== ConfigFileApplicationContextInitializer `ConfigFileApplicationContextInitializer` is an `ApplicationContextInitializer` that you can apply to your tests to load Spring Boot `application.properties` files. You can use -it when you do not need the full set of features provided by `@SpringBootTest`. +it when you do not need the full set of features provided by `@SpringBootTest`, as shown +in the following example: [source,java,indent=0] ---- @@ -6782,7 +6836,7 @@ NOTE: Using `ConfigFileApplicationContextInitializer` alone does not provide sup `@Value("${...}")` injection. Its only job is to ensure that `application.properties` files are loaded into Spring's `Environment`. For `@Value` support, you need to either additionally configure a `PropertySourcesPlaceholderConfigurer` or use `@SpringBootTest`, -where one will be auto-configured for you. +which auto-configures one for you. @@ -6861,7 +6915,7 @@ the following example: ---- Alternatively, if you use the `@SpringBootTest` annotation with -`WebEnvironment.RANDOM_PORT` or `WebEnvironment.DEFINED_PORT`, you can just inject a +`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 @@ -6937,7 +6991,7 @@ or commercial library, you might want to develop your own auto-configuration. Auto-configuration classes can be bundled in external jars and still be picked-up by Spring Boot. -Auto-configuration can be associated to a "starter" that provides the auto-configuration +Auto-configuration can be associated to a "`starter`" that provides the auto-configuration code as well as the typical libraries that you would use with it. We first cover what you need to know to build your own auto-configuration and then we move on to the <>. @@ -6957,7 +7011,7 @@ only when relevant classes are found and when you have not declared your own `@Configuration`. You can browse the source code of {sc-spring-boot-autoconfigure}[`spring-boot-autoconfigure`] -to see the `@Configuration` classes that we provide (see the +to see the `@Configuration` classes that Spring provides (see the {github-code}/spring-boot-project/spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories[`META-INF/spring.factories`] file). @@ -7001,7 +7055,7 @@ scanning. === Condition Annotations You almost always want to include one or more `@Conditional` annotations on your auto-configuration class. The `@ConditionalOnMissingBean` annotation is one common -example that is used to allow developers to '`override`' auto-configuration if they are +example that is used to allow developers to override auto-configuration if they are not happy with your defaults. Spring Boot includes a number of `@Conditional` annotations that you can reuse in your @@ -7060,10 +7114,10 @@ method, as shown in the following example: In the preceding example, the `myService` bean is going to be created if no bean of type `MyService` is already contained in the `ApplicationContext`. -TIP: You need to be very careful about the order that bean definitions are added as these -conditions are evaluated based on what has been processed so far. For this reason, we -recommend only using `@ConditionalOnBean` and `@ConditionalOnMissingBean` annotations on -auto-configuration classes (since these are guaranteed to load after any user-defined +TIP: You need to be very careful about the order in which bean definitions are added, as +these conditions are evaluated based on what has been processed so far. For this reason, +we recommend using only `@ConditionalOnBean` and `@ConditionalOnMissingBean` annotations +on auto-configuration classes (since these are guaranteed to load after any user-defined bean definitions have been added). NOTE: `@ConditionalOnBean` and `@ConditionalOnMissingBean` do not prevent `@Configuration` @@ -7093,8 +7147,8 @@ conventions, as shown in the following example: `file:/home/user/test.dat`. [[boot-features-web-application-conditions]] ==== Web Application Conditions The `@ConditionalOnWebApplication` and `@ConditionalOnNotWebApplication` annotations let -configuration be included depending on whether the application is a 'web application'. -A web application is any application that is using a Spring `WebApplicationContext`, +configuration be included depending on whether the application is a "`web application`". +A web application is any application that uses a Spring `WebApplicationContext`, defines a `session` scope, or has a `StandardServletEnvironment`. @@ -7107,16 +7161,16 @@ result of a {spring-reference}core.html#expressions[SpEL expression]. [[boot-features-test-autoconfig]] -=== Testing your auto-configuration +=== Testing your Auto-configuration An auto-configuration can be affected by many factors: user configuration (`@Bean` definition and `Environment` customization), condition evaluation (presence of a -particular library), etc. Concretely, each test should create a well-defined -`ApplicationContext` that represents a combination of those customizations and +particular library), and others. Concretely, each test should create a well defined +`ApplicationContext` that represents a combination of those customizations. `ApplicationContextRunner` provides a great way to achieve that. `ApplicationContextRunner` is usually defined as a field of the test class to gather the -base, common configuration. The following makes sure that `UserServiceAutoConfiguration` -is always invoked: +base, common configuration. The following example makes sure that +`UserServiceAutoConfiguration` is always invoked: [source,java,indent=0] ---- @@ -7124,20 +7178,21 @@ include::{test-examples}/autoconfigure/UserServiceAutoConfigurationTests.java[ta ---- TIP: If multiple auto-configurations have to be defined, there is no need to order their -declarations as they will be invoked in the exact same order as when running the +declarations as they are invoked in the exact same order as when running the application. -Each test can use the runner to represents a particular use case. For instance, the sample +Each test can use the runner to represent a particular use case. For instance, the sample below invokes a user configuration (`UserConfiguration`) and checks that the auto-configuration backs off properly. Invoking `run` provides a callback context that can -be used with AssertJ: +be used with `Assert4J`. [source,java,indent=0] ---- include::{test-examples}/autoconfigure/UserServiceAutoConfigurationTests.java[tag=test-user-config] ---- -It is also possible to easily customize the `Environment`: +It is also possible to easily customize the `Environment`, as shown in the following +example: [source,java,indent=0] ---- @@ -7146,18 +7201,18 @@ include::{test-examples}/autoconfigure/UserServiceAutoConfigurationTests.java[ta -==== Simulating a web context +==== Simulating a Web Context If you need to test an auto-configuration that only operates in a Servlet or Reactive web application context, use the `WebApplicationContextRunner` or `ReactiveWebApplicationContextRunner` respectively. -==== Overriding the classpath +==== Overriding the Classpath It is also possible to test what happens when a particular class and/or package is not present at runtime. Spring Boot ships with a `FilteredClassLoader` that can easily be used -by the runner. In the example below, we assert that if `UserService` is not present, the -auto-configuration will be properly disabled: +by the runner. In the following example, we assert that if `UserService` is not present, the +auto-configuration is properly disabled: [source,java,indent=0] ---- @@ -7183,7 +7238,7 @@ single module if you do not need to separate those two concerns. [[boot-features-custom-starter-naming]] ==== Naming You should make sure to provide a proper namespace for your starter. Do not start your -module names with `spring-boot`, even if you are using a different Maven `groupId`. We may +module names with `spring-boot`, even if you use a different Maven `groupId`. We may offer official support for the thing you auto-configure in the future. As a rule of thumb, you should name a combined module after the starter. For example, @@ -7191,10 +7246,10 @@ assume that you are creating a starter for "acme" and that you name the auto-con module `acme-spring-boot-autoconfigure` and the starter `acme-spring-boot-starter`. If you only have one module that combines the two, name it `acme-spring-boot-starter`. -Also, if your starter provides configuration keys, use a proper (that is, unique) -namespace for them. In particular, do not include your keys in the namespaces that Spring -Boot uses (such as `server`, `management`, `spring`, and so on). If you use the same -namespace, we may modify these namespaces in the future in ways that break your modules. +Also, if your starter provides configuration keys, use a unique namespace for them. In +particular, do not include your keys in the namespaces that Spring Boot uses (such as +`server`, `management`, `spring`, and so on). If you use the same namespace, we may modify +these namespaces in the future in ways that break your modules. Make sure to <>_ "`How-to`" . [[using-boot-starter]] === Starters Starters are a set of convenient dependency descriptors that you can include in your -application. You get a one-stop shop for all the Spring and related technology that you +application. You get a one-stop shop for all the Spring and related technologies that you need without having to hunt through sample code and copy-paste loads of dependency descriptors. For example, if you want to get started using Spring and JPA for database access, include the `spring-boot-starter-data-jpa` dependency in your project. @@ -285,9 +285,9 @@ running quickly and with a consistent, supported set of managed transitive depen **** All **official** starters follow a similar naming pattern; `+spring-boot-starter-*+`, where `+*+` is a particular type of application. This naming structure is intended to -help when you need to find a starter. The Maven integration in many IDEs allow you to +help when you need to find a starter. The Maven integration in many IDEs lets you search dependencies by name. For example, with the appropriate Eclipse or STS plugin -installed, you can simply hit `ctrl-space` in the POM editor and type +installed, you can press `ctrl-space` in the POM editor and type "`spring-boot-starter`" for a complete list. As explained in the "`<> section below and the +See the <> section later in this chapter and the <> for details. @@ -716,10 +717,10 @@ listings for Maven and Gradle: ---- NOTE: Developer tools are automatically disabled when running a fully packaged -application. If your application is launched using `java -jar` or if it is started from a +application. If your application is launched from `java -jar` or if it is started from a special classloader, then it is considered a "`production application`". Flagging the dependency as optional is a best practice that prevents devtools from being transitively -applied to other modules using your project. Gradle does not support `optional` +applied to other modules that use your project. Gradle does not support `optional` dependencies out-of-the-box, so you may want to have a look at the {propdeps-plugin}[`propdeps-plugin`]. @@ -852,7 +853,7 @@ You may want your application to be restarted or reloaded when you make changes that are not on the classpath. To do so, use the `spring.devtools.restart.additional-paths` property to configure additional paths to watch for changes. You can use the `spring.devtools.restart.exclude` property -<> to control whether changes +<> to control whether changes beneath the additional paths trigger a full restart or a <>. @@ -865,7 +866,7 @@ If you do not want to use the restart feature, you can disable it by using the your `application.properties` (doing so still initializes the restart classloader, but it does not watch for file changes). -If you need to _completely_ disable restart support (for example, because it doesn't work +If you need to _completely_ disable restart support (for example, because it does not work with a specific library), you need to set the `spring.devtools.restart.enabled` `System` property to `false` before calling `SpringApplication.run(...)`, as shown in the following example: @@ -885,7 +886,7 @@ following example: If you work with an IDE that continuously compiles changed files, you might prefer to trigger restarts only at specific times. To do so, you can use a "`trigger file`", which is a special file that must be modified when you want to actually trigger a restart -check. Changing the file only triggers the check and the restart will only occur if +check. Changing the file only triggers the check and the restart only occurs if Devtools has detected it has to do something. The trigger file can be updated manually or with an IDE plugin. @@ -900,9 +901,9 @@ in the same way. [[using-boot-devtools-customizing-classload]] ==== Customizing the Restart Classloader -As described in the <> section above, restart +As described earlier in the <> section, restart functionality is implemented by using two classloaders. For most applications, this -approach works well. However, sometimes it can cause classloading issues. +approach works well. However, it can sometimes cause classloading issues. By default, any open project in your IDE is loaded with the "`restart`" classloader, and any regular `.jar` file is loaded with the "`base`" classloader. If you work on a @@ -924,7 +925,7 @@ pattern that is applied to the classpath, as shown in the following example: NOTE: All property keys must be unique. As long as a property starts with `restart.include.` or `restart.exclude.` it is considered. -TIP: All `META-INF/spring-devtools.properties` from the classpath will be loaded. You can +TIP: All `META-INF/spring-devtools.properties` from the classpath are loaded. You can package files inside your project, or in the libraries that the project consumes. @@ -977,7 +978,7 @@ property: [[using-boot-devtools-remote]] === Remote Applications -The Spring Boot developer tools are not just limited to local development. You can also +The Spring Boot developer tools are not limited to local development. You can also use several features when running applications remotely. Remote support is opt-in. To enable it, you need to make sure that `devtools` is included in the repackaged archive, as shown in the following listing: