@@ -131,7 +131,7 @@ The following example enables the `shutdown` endpoint:
If you prefer endpoint enablement to be opt-in rather than opt-out, set the configprop:management.endpoints.enabled-by-default[] property to `false` and use individual endpoint `enabled` properties to opt back in.
The following example enables the `info` endpoint and disables all other endpoints:
@@ -343,7 +343,7 @@ You can do so by changing the configprop:management.endpoints.web.exposure.inclu
Additionally, if Spring Security is present, you would need to add custom security configuration that allows unauthenticated access to the endpoints as shown in the following example:
@@ -818,7 +818,7 @@ If you need to register a regular `HealthContributor`, you should wrap it using
To provide custom health information from a reactive API, you can register Spring beans that implement the {spring-boot-actuator-module-code}/health/ReactiveHealthIndicator.java[`ReactiveHealthIndicator`] interface.
The following code shows a sample `ReactiveHealthIndicator` implementation:
@@ -872,7 +872,7 @@ It's sometimes useful to organize health indicators into groups that can be used
To create a health indicator group you can use the `management.endpoint.health.group.<name>` property and specify a list of health indicator IDs to `include` or `exclude`.
For example, to create a group that includes only database indicators you can define the following:
@@ -899,7 +899,7 @@ Similarly, to create a group that excludes the database indicators from the grou
By default groups will inherit the same `StatusAggregator` and `HttpCodeStatusMapper` settings as the system health, however, these can also be defined on a per-group basis.
It's also possible to override the `show-details` and `roles` properties if required:
@@ -940,7 +940,7 @@ They will also be exposed as separate HTTP Probes using <<actuator#actuator.endp
You can then configure your Kubernetes infrastructure with the following endpoint information:
[source,yml,indent=0]
[source,yml,indent=0,subs="verbatim"]
----
livenessProbe:
httpGet:
...
...
@@ -976,7 +976,7 @@ In this case, a probe check could be successful even if the main application doe
Actuator configures the "liveness" and "readiness" probes as Health Groups; this means that all the <<actuator#actuator.endpoints.health.groups, Health Groups features>> are available for them.
You can, for example, configure additional Health Indicators:
@@ -1149,7 +1149,7 @@ By default, the endpoint exposes `git.branch`, `git.commit.id`, and `git.commit.
If you don't want any of these properties in the endpoint response, they need to be excluded from the `git.properties` file.
If you want to display the full git information (that is, the full content of `git.properties`), use the configprop:management.info.git.mode[] property, as follows:
@@ -1159,7 +1159,7 @@ If you want to display the full git information (that is, the full content of `g
To disable the git commit information from the `info` endpoint completely, set the configprop:management.info.git.enabled[] property to `false`, as follows:
@@ -35,7 +35,7 @@ The following settings show an example of doing so in `application.properties`:
=== Disabling JMX Endpoints
If you do not want to expose endpoints over JMX, you can set the configprop:management.endpoints.jmx.exposure.exclude[] property to `*`, as shown in the following example:
@@ -90,7 +90,7 @@ To do so, prefix the parameter with `management.endpoint.jolokia.config.`, as sh
==== Disabling Jolokia
If you use Jolokia but do not want Spring Boot to configure it, set the configprop:management.endpoint.jolokia.enabled[] property to `false`, as follows:
@@ -56,7 +56,7 @@ You can also disable all registries unless stated otherwise by the registry-spec
Spring Boot will also add any auto-configured registries to the global static composite registry on the `Metrics` class unless you explicitly tell it not to:
@@ -65,14 +65,14 @@ Spring Boot will also add any auto-configured registries to the global static co
You can register any number of `MeterRegistryCustomizer` beans to further configure the registry, such as applying common tags, before any meters are registered with the registry:
@@ -373,7 +373,7 @@ TIP: The endpoint is not available by default and must be exposed, see <<actuato
Here is an example `scrape_config` to add to `prometheus.yml`:
[source,yaml,indent=0]
[source,yaml,indent=0,subs="verbatim"]
----
scrape_configs:
- job_name: 'spring'
...
...
@@ -385,7 +385,7 @@ Here is an example `scrape_config` to add to `prometheus.yml`:
For ephemeral or batch jobs which may not exist long enough to be scraped, https://github.com/prometheus/pushgateway[Prometheus Pushgateway] support can be used to expose their metrics to Prometheus.
To enable Prometheus Pushgateway support, add the following dependency to your project:
[source,xml,indent=0]
[source,xml,indent=0,subs="verbatim"]
----
<dependency>
<groupId>io.prometheus</groupId>
...
...
@@ -406,7 +406,7 @@ For advanced configuration, you can also provide your own `PrometheusPushGateway
SignalFx registry pushes metrics to {micrometer-registry-docs}/signalFx[SignalFx] periodically.
To export metrics to https://www.signalfx.com[SignalFx], your access token must be provided:
@@ -17,7 +17,7 @@ Sometimes, it is useful to customize the prefix for the management endpoints.
For example, your application might already use `/actuator` for another purpose.
You can use the configprop:management.endpoints.web.base-path[] property to change the prefix for your management endpoint, as shown in the following example:
@@ -70,7 +70,7 @@ If you want to use a custom management port on Cloud Foundry, you will need to e
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 over HTTP while the main application uses HTTPS, as shown in the following property settings:
Spring Framework 4.0 has native support for a `beans{}` "`DSL`" (borrowed from https://grails.org/[Grails]), and you can embed bean definitions in your Groovy application scripts by using the same format.
This is sometimes a good way to include external features like middleware declarations, as shown in the following example:
To compile and run the application, type the following command:
[indent=0,subs="verbatim,quotes,attributes"]
[indent=0,subs="verbatim"]
----
$ spring run hello.groovy
----
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"]
[indent=0,subs="verbatim"]
----
$ spring run hello.groovy -- --server.port=9000
----
To set JVM command line arguments, you can use the `JAVA_OPTS` environment variable, as shown in the following example:
[indent=0,subs="verbatim,quotes,attributes"]
[indent=0,subs="verbatim"]
----
$ JAVA_OPTS=-Xmx1024m spring run hello.groovy
----
...
...
@@ -175,7 +175,7 @@ The annotation's value should specify the coordinates (`groupId:artifactId:versi
@@ -305,7 +305,7 @@ If you do not use either of these shells (perhaps you are a Windows user), you c
From inside the embedded shell, you can run other commands directly:
[indent=0,subs="verbatim,quotes,attributes"]
[indent=0,subs="verbatim,attributes"]
----
$ version
Spring CLI v{spring-boot-version}
...
...
@@ -322,7 +322,7 @@ To exit the embedded shell, press `ctrl-c`.
You can add extensions to the CLI by using the `install` command.
The command takes one or more sets of artifact coordinates in the format `group:artifact:version`, as shown in the following example:
[indent=0,subs="verbatim,quotes,attributes"]
[indent=0,subs="verbatim"]
----
$ spring install com.example:spring-boot-cli-extension:1.0.0.RELEASE
----
...
...
@@ -332,7 +332,7 @@ In addition to installing the artifacts identified by the coordinates you supply
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 of `group:artifact:version`, as shown in the following example:
[indent=0,subs="verbatim,quotes,attributes"]
[indent=0,subs="verbatim"]
----
$ spring uninstall com.example:spring-boot-cli-extension:1.0.0.RELEASE
----
...
...
@@ -341,7 +341,7 @@ It uninstalls the artifacts identified by the coordinates you supply and their d
To uninstall all additional dependencies, you can use the `--all` option, as shown in the following example:
@@ -31,7 +31,7 @@ With Gradle, the dependency should be declared in the `annotationProcessor` conf
If you are using an `additional-spring-configuration-metadata.json` file, the `compileJava` task should be configured to depend on the `processResources` task, as shown in the following example:
@@ -45,7 +45,7 @@ There are several ways to do this.
With Maven, you can configure the `maven-apt-plugin` explicitly and add the dependency to the annotation processor only there.
You could also let the AspectJ plugin run all the processing and disable annotation processing in the `maven-compiler-plugin` configuration, as follows:
@@ -86,14 +86,14 @@ Also, the annotation processor cannot auto-detect default values for ``Enum``s a
For cases where the default value could not be detected, <<configuration-metadata#configuration-metadata.annotation-processor.adding-additional-metadata,manual metadata>> should be provided.
In order to document default values for properties in the class above, you could add the following content to <<configuration-metadata#configuration-metadata.annotation-processor.adding-additional-metadata,the manual metadata of the module>>:
[source,json,indent=0]
[source,json,indent=0,subs="verbatim"]
----
{"properties": [
{
...
...
@@ -117,7 +117,7 @@ The annotation processor automatically considers inner classes as nested propert
Rather than documenting the `ip` and `port` at the root of the namespace, we could create a sub-namespace for it.
Configuration metadata files are located inside jars under `META-INF/spring-configuration-metadata.json`.
They use a JSON format with items categorized under either "`groups`" or "`properties`" and additional values hints categorized under "hints", as shown in the following example:
[source,json,indent=0]
[source,json,indent=0,subs="verbatim"]
----
{"groups": [
{
...
...
@@ -68,7 +68,7 @@ They use a JSON format with items categorized under either "`groups`" or "`prope
Each "`property`" is a configuration item that the user specifies with a given value.
For example, `server.port` and `server.address` might be specified in `application.properties`, as follows:
The magic values are (in this example) are `sample1` and `sample2`.
In order to offer additional content assistance for the keys, you could add the following JSON to <<configuration-metadata#configuration-metadata.annotation-processor.adding-additional-metadata,the manual metadata of the module>>:
[source,json,indent=0]
[source,json,indent=0,subs="verbatim"]
----
{"hints": [
{
...
...
@@ -101,7 +101,7 @@ This provider is typically used if you have a list of values and any extra value
The following example offers `on` and `off` as auto-completion values for `system.state`:
[source,json,indent=0]
[source,json,indent=0,subs="verbatim"]
----
{"hints": [
{
...
...
@@ -152,7 +152,7 @@ This provider supports the following parameters:
The following metadata snippet corresponds to the standard `server.servlet.jsp.class-name` property that defines the `JspServlet` class name to use:
[source,json,indent=0]
[source,json,indent=0,subs="verbatim"]
----
{"hints": [
{
...
...
@@ -202,7 +202,7 @@ TIP: If multiple values can be provided, use a `Collection` or _Array_ type to t
The following metadata snippet corresponds to the standard `spring.liquibase.change-log` property that defines the path to the changelog to use.
It is actually used internally as a `org.springframework.core.io.Resource` but cannot be exposed as such, because we need to keep the original String value to pass it to the Liquibase API.
[source,json,indent=0]
[source,json,indent=0,subs="verbatim"]
----
{"hints": [
{
...
...
@@ -246,7 +246,7 @@ The following metadata snippet corresponds to the standard `logging.level` prope
Keys are _logger names_, and values correspond to the standard log levels or any custom level.
As Spring Boot defines a few logger groups out-of-the-box, dedicated value hints have been added for those.
[source,json,indent=0]
[source,json,indent=0,subs="verbatim"]
----
{"hints": [
{
...
...
@@ -326,7 +326,7 @@ This provider supports the following parameters:
The following metadata snippet corresponds to the standard `spring.jmx.server` property that defines the name of the `MBeanServer` bean to use:
[source,json,indent=0]
[source,json,indent=0,subs="verbatim"]
----
{"hints": [
{
...
...
@@ -354,7 +354,7 @@ The **spring-profile-name** provider auto-completes the Spring profiles that are
The following metadata snippet corresponds to the standard `spring.profiles.active` property that defines the name of the Spring profile(s) to enable:
@@ -27,7 +27,7 @@ Once you have built your application (by using, for example, `mvn clean package`
Be sure to have https://docs.cloudfoundry.org/cf-cli/getting-started.html#login[logged in with your `cf` command line client] before pushing an application.
The following line shows using the `cf push` command to deploy an application:
@@ -39,7 +39,7 @@ If there is a Cloud Foundry https://docs.cloudfoundry.org/devguide/deploy-apps/m
At this point, `cf` starts uploading your application, producing output similar to the following example:
[indent=0,subs="verbatim,quotes,attributes"]
[indent=0,subs="verbatim,quotes"]
----
Uploading acloudyspringtime... *OK*
Preparing to start acloudyspringtime... *OK*
...
...
@@ -68,7 +68,7 @@ Congratulations! The application is now live!
Once your application is live, you can verify the status of the deployed application by using the `cf apps` command, as shown in the following example:
[indent=0,subs="verbatim,quotes,attributes"]
[indent=0,subs="verbatim"]
----
$ cf apps
Getting applications in ...
...
...
@@ -93,7 +93,7 @@ Process-scoped environment variables are language agnostic.
Environment variables do not always make for the easiest API, so Spring Boot automatically extracts them and flattens the data into properties that can be accessed through Spring's `Environment` abstraction, as shown in the following example:
@@ -321,7 +321,7 @@ If your executable jar or war contains an https://boxfuse.com/docs/payloads/spri
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 example:
[indent=0,subs="verbatim,quotes,attributes"]
[indent=0,subs="verbatim"]
----
Fusing Image for myapp-1.0.jar ...
Image fused in 00:06.838s (53937 K) -> axelfontaine/myapp:1.0
@@ -66,7 +66,7 @@ The script supports the following features:
Assuming that you have a Spring Boot application installed in `/var/myapp`, to install a Spring Boot application as an `init.d` service, create a symlink, as follows:
@@ -74,7 +74,7 @@ Assuming that you have a Spring Boot application installed in `/var/myapp`, to i
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:
[indent=0,subs="verbatim,quotes,attributes"]
[indent=0,subs="verbatim"]
----
$ service myapp start
----
...
...
@@ -84,7 +84,7 @@ TIP: If your application fails to start, check the log file written to `/var/log
You can also flag the application to start automatically by using your standard operating system tools.
For example, on Debian, you could use the following command:
[indent=0,subs="verbatim,quotes,attributes"]
[indent=0,subs="verbatim"]
----
$ update-rc.d myapp defaults <priority>
----
...
...
@@ -101,7 +101,7 @@ When the environment variable is not set, the user who owns the jar file is used
You should never run a Spring Boot application as `root`, so `RUN_AS_USER` should never be root and your application's jar file should never be owned by root.
Instead, create a specific user to run your application and set the `RUN_AS_USER` environment variable or use `chown` to make it the owner of the jar file, as shown in the following example:
[indent=0,subs="verbatim,quotes,attributes"]
[indent=0,subs="verbatim"]
----
$ chown bootapp:bootapp your-app.jar
----
...
...
@@ -114,7 +114,7 @@ For example, you can set the account's shell to `/usr/sbin/nologin`.
You should also take steps to prevent the modification of your application's jar file.
Firstly, configure its permissions so that it cannot be written and can only be read or executed by its owner, as shown in the following example:
[indent=0,subs="verbatim,quotes,attributes"]
[indent=0,subs="verbatim"]
----
$ chmod 500 your-app.jar
----
...
...
@@ -123,7 +123,7 @@ Second, you should also take steps to limit the damage if your application or th
If an attacker does gain access, they could make the jar file writable and change its contents.
One way to protect against this is to make it immutable by using `chattr`, as shown in the following example:
[indent=0,subs="verbatim,quotes,attributes"]
[indent=0,subs="verbatim"]
----
$ sudo chattr +i your-app.jar
----
...
...
@@ -134,7 +134,7 @@ If root is used to control the application's service and you <<deployment#deploy
It should be secured accordingly.
Use `chmod` so that the file can only be read by the owner and use `chown` to make root the owner, as shown in the following example:
[indent=0,subs="verbatim,quotes,attributes"]
[indent=0,subs="verbatim"]
----
$ chmod 400 your-app.conf
$ sudo chown root:root your-app.conf
...
...
@@ -174,7 +174,7 @@ Consult the https://www.freedesktop.org/software/systemd/man/systemd.service.htm
To flag the application to start automatically on system boot, use the following command:
[indent=0,subs="verbatim,quotes,attributes"]
[indent=0,subs="verbatim"]
----
$ systemctl enable myapp.service
----
...
...
@@ -370,7 +370,7 @@ The file is expected to be next to the jar file and have the same name but suffi
For example, a jar named `/var/myapp/myapp.jar` uses the configuration file named `/var/myapp/myapp.conf`, as shown in the following example:
@@ -59,7 +59,7 @@ If you add dependencies manually, you must include `spring-context-support` in o
If the `CacheManager` is auto-configured by Spring Boot, you can further tune its configuration before it is fully initialized by exposing a bean that implements the `CacheManagerCustomizer` interface.
The following example sets a flag to say that `null` values should be passed down to the underlying map:
@@ -86,7 +86,7 @@ Any other compliant library can be added as well.
It might happen that more than one provider is present, in which case the provider must be explicitly specified.
Even if the JSR-107 standard does not enforce a standardized way to define the location of the configuration file, Spring Boot does its best to accommodate setting a cache with implementation details, as shown in the following example:
@@ -163,7 +163,7 @@ If Spring Data Couchbase is available and Couchbase is <<features#features.nosql
It is possible to create additional caches on startup by setting the configprop:spring.cache.cache-names[] property and cache defaults can be configured by using `spring.cache.couchbase.*` properties.
For instance, the following configuration creates `cache1` and `cache2` caches with an entry _expiration_ of 10 minutes:
@@ -188,7 +188,7 @@ If https://redis.io/[Redis] is available and configured, a `RedisCacheManager` i
It is possible to create additional caches on startup by setting the configprop: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:
@@ -264,7 +264,7 @@ This is similar to the way the "real" cache providers behave if you use an undec
When `@EnableCaching` is present in your configuration, a suitable cache configuration is expected as well.
If you need to disable caching altogether in certain environments, force the cache type to `none` to use a no-op implementation, as shown in the following example:
@@ -293,7 +293,7 @@ It is recommended to add the following dependency in a module that contains auto
If you have defined auto-configurations directly in your application, make sure to configure the `spring-boot-maven-plugin` to prevent the `repackage` goal from adding the dependency into the fat jar:
@@ -150,7 +150,7 @@ Otherwise, all Webjars resolve as a `404`.
To use cache busting, the following configuration configures a cache busting solution for all static resources, effectively adding a content hash, such as `<link href="/css/spring-2a2d595e6ed9a0b24f027f2b63b134d6.css"/>`, in URLs:
@@ -218,7 +218,7 @@ Nowadays, Content Negotiation is much more reliable.
There are other ways to deal with HTTP clients that don't consistently send proper "Accept" request headers.
Instead of using suffix matching, we can use a query parameter to ensure that requests like `"GET /projects/spring-boot?format=json"` will be mapped to `@GetMapping("/projects/spring-boot")`:
@@ -347,7 +347,7 @@ To do so, extend `BasicErrorController`, add a public method with a `@RequestMap
You can also define a class annotated with `@ControllerAdvice` to customize the JSON document to return for a particular controller and/or exception type, as shown in the following example:
@@ -357,7 +357,7 @@ In the preceding example, if `YourException` is thrown by a controller defined i
In some cases, errors handled at the controller level are not recorded by the <<actuator#actuator.metrics.supported.spring-mvc, metrics infrastructure>>.
Applications can ensure that such exceptions are recorded with the request metrics by setting the handled exception as a request attribute:
NOTE: If you register an `ErrorPage` with a path that ends up being handled by a `Filter` (as is common with some non-Spring web frameworks, like Jersey and Wicket), then the `Filter` has to be explicitly registered as an `ERROR` dispatcher, as shown in the following example:
@@ -467,7 +467,7 @@ As of version 4.2, Spring MVC {spring-framework-docs}/web.html#mvc-cors[supports
Using {spring-framework-docs}/web.html#mvc-cors-controller[controller method CORS configuration] with {spring-framework-api}/web/bind/annotation/CrossOrigin.html[`@CrossOrigin`] annotations in your Spring Boot application does not require any specific configuration.
{spring-framework-docs}/web.html#mvc-cors-global[Global CORS configuration] can be defined by registering a `WebMvcConfigurer` bean with a customized `addCorsMappings(CorsRegistry)` method, as shown in the following example:
"`WebFlux.fn`", the functional variant, separates the routing configuration from the actual handling of the requests, as shown in the following example:
@@ -612,7 +612,7 @@ For that, you can add a bean of type `ErrorAttributes`.
To change the error handling behavior, you can implement `ErrorWebExceptionHandler` and register a bean definition of that type.
Because a `ErrorWebExceptionHandler` is quite low-level, Spring Boot also provides a convenient `AbstractErrorWebExceptionHandler` to let you handle errors in a WebFlux functional way, as shown in the following example:
@@ -622,7 +622,7 @@ For a more complete picture, you can also subclass `DefaultErrorWebExceptionHand
In some cases, errors handled at the controller or handler function level are not recorded by the <<actuator#actuator.metrics.supported.spring-webflux, metrics infrastructure>>.
Applications can ensure that such exceptions are recorded with the request metrics by setting the handled exception as a request attribute:
@@ -700,7 +700,7 @@ Jersey has some native Spring support, so we also provide auto-configuration sup
To get started with Jersey, include the `spring-boot-starter-jersey` as a dependency and then you need one `@Bean` of type `ResourceConfig` in which you register all the endpoints, as shown in the following example:
`TomcatServletWebServerFactory`, `JettyServletWebServerFactory` and `UndertowServletWebServerFactory` are dedicated variants of `ConfigurableServletWebServerFactory` that have additional customization setter methods for Tomcat, Jetty and Undertow respectively.
The following example shows how to customize `TomcatServletWebServerFactory` that provides access to Tomcat-specific configuration options:
@@ -10,7 +10,7 @@ See {spring-boot-autoconfigure-module-code}/mail/MailProperties.java[`MailProper
In particular, certain default timeout values are infinite, and you may want to change that to avoid having a thread blocked by an unresponsive mail server, as shown in the following example:
@@ -382,7 +382,7 @@ Configuration trees can also be used for Docker secrets.
When a Docker swarm service is granted access to a secret, the secret gets mounted into the container.
For example, if a secret named `db.password` is mounted at location `/run/secrets/`, you can make `db.password` available to the Spring environment using the following:
@@ -421,7 +421,7 @@ Three consecutive hyphens represent the end of one document, and the start of th
For example, the following file has two logical documents:
[source,yaml,indent=0]
[source,yaml,indent=0,subs="verbatim"]
----
spring.application.name: MyApp
---
...
...
@@ -431,7 +431,7 @@ For example, the following file has two logical documents:
For `application.properties` files a special `#---` comment is used to mark the document splits:
[source,properties,indent=0]
[source,properties,indent=0,subs="verbatim"]
----
spring.application.name=MyApp
#---
...
...
@@ -472,7 +472,7 @@ The following activation properties are available:
For example, the following specifies that the second document is only active when running on Kubernetes, and only when either the "`prod`" or "`staging`" profiles are active:
@@ -669,7 +669,7 @@ Default values can be specified using `@DefaultValue` and the same conversion se
By default, if no properties are bound to `Security`, the `MyProperties` instance will contain a `null` value for `security`.
If you wish you return a non-null instance of `Security` even when no properties are bound to it, you can use an empty `@DefaultValue` annotation to do so:
@@ -1107,7 +1107,7 @@ Spring Boot attempts to validate `@ConfigurationProperties` classes whenever the
You can use JSR-303 `javax.validation` constraint annotations directly on your configuration class.
To do so, ensure that a compliant JSR-303 implementation is on your classpath and then add constraint annotations to your fields, as shown in the following example:
@@ -1117,7 +1117,7 @@ TIP: You can also trigger validation by annotating the `@Bean` method that creat
To ensure that validation is always triggered for nested properties, even when no properties are found, the associated field must be annotated with `@Valid`.
The following example builds on the preceding `MyProperties` example:
@@ -9,7 +9,7 @@ If no properties file is found that matches any of the configured base names, th
The basename of the resource bundle as well as several other attributes can be configured using the `spring.messages` namespace, as shown in the following example:
@@ -73,7 +73,7 @@ Spring Boot provides an idiomatic way to run an application with `runApplication
This is a drop-in replacement for `SpringApplication.run(MyApplication::class.java, *args)`.
It also allows customization of the application as shown in the following example:
[source,kotlin,indent=0]
[source,kotlin,indent=0,subs="verbatim"]
----
runApplication<MyApplication>(*args) {
setBannerMode(OFF)
...
...
@@ -110,7 +110,7 @@ TIP: `org.jetbrains.kotlinx:kotlinx-coroutines-reactor` dependency is provided b
=== @ConfigurationProperties
`@ConfigurationProperties` when used in combination with <<features#features.external-config.typesafe-configuration-properties.constructor-binding,`@ConstructorBinding`>> supports classes with immutable `val` properties as shown in the following example:
@@ -38,7 +38,7 @@ For example, you might declare the following section in `application.properties`
By default, a `CachingConnectionFactory` wraps the native `ConnectionFactory` with sensible settings that you can control by external configuration properties in `+spring.jms.*+`:
@@ -48,7 +48,7 @@ By default, a `CachingConnectionFactory` wraps the native `ConnectionFactory` wi
If you'd rather use native pooling, you can do so by adding a dependency to `org.messaginghub:pooled-jms` and configuring the `JmsPoolConnectionFactory` accordingly, as shown in the following example:
@@ -92,7 +92,7 @@ These can be specified as a comma-separated list to create them with the default
By default, a `CachingConnectionFactory` wraps the native `ConnectionFactory` with sensible settings that you can control by external configuration properties in `+spring.jms.*+`:
@@ -102,7 +102,7 @@ By default, a `CachingConnectionFactory` wraps the native `ConnectionFactory` wi
If you'd rather use native pooling, you can do so by adding a dependency to `org.messaginghub:pooled-jms` and configuring the `JmsPoolConnectionFactory` accordingly, as shown in the following example:
@@ -237,7 +237,7 @@ TIP: See https://spring.io/blog/2010/06/14/understanding-amqp-the-protocol-used-
==== Sending a Message
Spring's `AmqpTemplate` and `AmqpAdmin` are auto-configured, and you can autowire them directly into your own beans, as shown in the following example:
@@ -77,7 +77,7 @@ Each will be called in order with the `MongoClientSettings.Builder` that is used
You can set the configprop:spring.data.mongodb.uri[] property to change the URL and configure additional settings such as the _replica set_, as shown in the following example:
@@ -113,7 +113,7 @@ The auto-configuration configures this factory automatically if Netty is availab
{spring-data-mongodb}[Spring Data MongoDB] provides a {spring-data-mongodb-api}/core/MongoTemplate.html[`MongoTemplate`] class that is very similar in its design to Spring's `JdbcTemplate`.
As with `JdbcTemplate`, Spring Boot auto-configures a bean for you to inject the template, as follows:
@@ -130,7 +130,7 @@ As with the JPA repositories discussed earlier, the basic principle is that quer
In fact, both Spring Data JPA and Spring Data MongoDB share the same common infrastructure.
You could take the JPA example from earlier and, assuming that `City` is now a MongoDB data class rather than a JPA `@Entity`, it works in the same way, as shown in the following example:
@@ -204,7 +204,7 @@ For complete details of Spring Data Neo4j, refer to the {spring-data-neo4j-docs}
Spring Data Neo4j shares the common infrastructure with Spring Data JPA as many other Spring Data modules do.
You could take the JPA example from earlier and define `City` as Spring Data Neo4j `@Node` rather than JPA `@Entity` and the repository abstraction works in the same way, as shown in the following example:
@@ -272,7 +272,7 @@ Spring Boot provides support for the "High Level" client, which ships with `org.
If you have this dependency on the classpath, Spring Boot will auto-configure and register a `RestHighLevelClient` bean that by default targets `http://localhost:9200`.
You can further tune how `RestHighLevelClient` is configured, as shown in the following example:
@@ -291,7 +291,7 @@ TIP: If your application needs access to a "Low Level" `RestClient`, you can get
Additionally, if `elasticsearch-rest-client-sniffer` is on the classpath, a `Sniffer` is auto-configured to automatically discover nodes from a running Elasticsearch cluster and set them to the `RestHighLevelClient` bean.
You can further tune how `Sniffer` is configured, as shown in the following example:
@@ -464,7 +464,7 @@ You can get a `Cluster` by adding the Couchbase SDK and some configuration.
The `spring.couchbase.*` properties can be used to customize the connection.
Generally, you provide the https://github.com/couchbaselabs/sdk-rfcs/blob/master/rfc/0011-connection-string.md[connection string], username, and password, as shown in the following example:
@@ -501,7 +501,7 @@ For complete details of Spring Data Couchbase, refer to the {spring-data-couchba
You can inject an auto-configured `CouchbaseTemplate` instance as you would with any other Spring Bean, provided a `CouchbaseClientFactory` bean is available.
This happens when a `Cluster` is available, as described above, and a bucket name has been specified:
@@ -546,7 +546,7 @@ There is a `spring-boot-starter-data-ldap` "`Starter`" for collecting the depend
==== Connecting to an LDAP Server
To connect to an LDAP server, make sure you declare a dependency on the `spring-boot-starter-data-ldap` "`Starter`" or `spring-ldap-core` and then declare the URLs of your server in your application.properties, as shown in the following example:
For testing purposes, Spring Boot supports auto-configuration of an in-memory LDAP server from https://ldap.com/unboundid-ldap-sdk-for-java/[UnboundID].
To configure the server, add a dependency to `com.unboundid:unboundid-ldapsdk` and declare a configprop:spring.ldap.embedded.base-dn[] property, as follows:
@@ -628,7 +628,7 @@ https://www.influxdata.com/[InfluxDB] is an open-source time series database opt
==== Connecting to InfluxDB
Spring Boot auto-configures an `InfluxDB` instance, provided the `influxdb-java` client is on the classpath and the URL of the database is set, as shown in the following example:
@@ -13,7 +13,7 @@ Beans of the following types are automatically picked up and associated with the
By default, an in-memory `JobStore` is used.
However, it is possible to configure a JDBC-based store if a `DataSource` bean is available in your application and if the configprop:spring.quartz.job-store-type[] property is configured accordingly, as shown in the following example:
@@ -38,7 +38,7 @@ Finally, you can also create your own `RestTemplateBuilder` bean.
To prevent switching off the auto-configuration of a `RestTemplateBuilder` and prevent any `RestTemplateCustomizer` beans from being used, make sure to configure your custom instance with a `RestTemplateBuilderConfigurer`.
The following example exposes a `RestTemplateBuilder` with what Spring Boot would auto-configure, except that custom connect and read timeouts are also specified:
@@ -35,7 +35,7 @@ This depends on the type of application and its configuration.
For WebFlux application (i.e. of type `WebApplicationType.REACTIVE`), the RSocket server will be plugged into the Web Server only if the following properties match:
When your application starts, you should see something similar to the following output:
[indent=0,subs="attributes"]
[indent=0,subs="verbatim,attributes"]
----
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
...
...
@@ -71,7 +71,7 @@ To do so, you need to <<features#features.external-config,enable the `debug` pro
For instance, if you are running your application by using `java -jar`, you can enable the `debug` property as follows:
[indent=0,subs="attributes"]
[indent=0,subs="verbatim"]
----
$ java -jar myproject-0.0.1-SNAPSHOT.jar --debug
----
...
...
@@ -93,7 +93,7 @@ For these reasons, lazy initialization is not enabled by default and it is recom
Lazy initialization can be enabled programmatically using the `lazyInitialization` method on `SpringApplicationBuilder` or the `setLazyInitialization` method on `SpringApplication`.
Alternatively, it can be enabled using the configprop:spring.main.lazy-initialization[] property as shown in the following example:
@@ -186,7 +186,7 @@ If you need to build an `ApplicationContext` hierarchy (multiple contexts with a
The `SpringApplicationBuilder` lets you chain together multiple method calls and includes `parent` and `child` methods that let you create a hierarchy, as shown in the following example:
@@ -332,7 +332,7 @@ TIP: It is often desirable to call `setWebApplicationType(WebApplicationType.NON
If you need to access the application arguments that were passed to `SpringApplication.run(...)`, you can inject a `org.springframework.boot.ApplicationArguments` bean.
The `ApplicationArguments` interface provides access to both the raw `String[]` arguments as well as parsed `option` and `non-option` arguments, as shown in the following example:
@@ -353,7 +353,7 @@ NOTE: This contract is well suited for tasks that should run after application s
The `CommandLineRunner` interfaces provides access to application arguments as a string array, whereas the `ApplicationRunner` uses the `ApplicationArguments` interface discussed earlier.
The following example shows a `CommandLineRunner` with a `run` method:
@@ -370,7 +370,7 @@ All the standard Spring lifecycle callbacks (such as the `DisposableBean` interf
In addition, beans may implement the `org.springframework.boot.ExitCodeGenerator` interface if they wish to return a specific exit code when `SpringApplication.exit()` is called.
This exit code can then be passed to `System.exit()` to return it as a status code, as shown in the following example:
@@ -410,7 +410,7 @@ The first available implementation, `FlightRecorderApplicationStartup` is provid
It adds Spring-specific startup events to a Java Flight Recorder session and is meant for profiling applications and correlating their Spring context lifecycle with JVM events (such as allocations, GCs, class loading...).
Once configured, you can record data by running the application with the Flight Recorder enabled:
@@ -21,7 +21,7 @@ If a single Spring Session module is present on the classpath, Spring Boot uses
If you have more than one implementation, you must choose the {spring-boot-autoconfigure-module-code}/session/StoreType.java[`StoreType`] that you wish to use to store the sessions.
For instance, to use JDBC as the back-end store, you can configure your application as follows:
@@ -95,7 +95,7 @@ Refer to the documentation of the connection pool implementation you are using f
For instance, if you use the {tomcat-docs}/jdbc-pool.html#Common_Attributes[Tomcat connection pool], you could customize many additional settings, as shown in the following example:
@@ -145,7 +145,7 @@ If you deploy your Spring Boot application to an Application Server, you might w
The configprop:spring.datasource.jndi-name[] property can be used as an alternative to the configprop:spring.datasource.url[], configprop:spring.datasource.username[], and configprop:spring.datasource.password[] properties to access the `DataSource` from a specific JNDI location.
For example, the following section in `application.properties` shows how you can access a JBoss AS defined `DataSource`:
@@ -158,14 +158,14 @@ For example, the following section in `application.properties` shows how you can
=== Using JdbcTemplate
Spring's `JdbcTemplate` and `NamedParameterJdbcTemplate` classes are auto-configured, and you can `@Autowire` them directly into your own beans, as shown in the following example:
@@ -428,14 +428,14 @@ TIP: The "`How-to`" section includes a <<howto#howto.data-initialization.using-b
To customize the connections created by a `ConnectionFactory`, i.e., set specific parameters that you do not want (or cannot) configure in your central database configuration, you can use a `ConnectionFactoryOptionsBuilderCustomizer` `@Bean`.
The following example shows how to manually override the database port while the rest of the options is taken from the application configuration:
@@ -30,7 +30,7 @@ Shrinking of the pool is more aggressive as threads are reclaimed when they are
A `ThreadPoolTaskScheduler` can also be auto-configured if need to be associated to scheduled task execution (e.g. `@EnableScheduling`).
The thread pool uses one thread by default and its settings can be fine-tuned using the `spring.task.scheduling` namespace, as shown in the following example:
By default, `@SpringBootTest` does not start the server.
If you have web endpoints that you want to test against this mock environment, you can additionally configure {spring-framework-docs}/testing.html#spring-mvc-test-framework[`MockMvc`] as shown in the following example:
@@ -209,7 +209,7 @@ If you use `@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)`, an avai
The `@LocalServerPort` annotation can be used to <<howto#howto.webserver.discover-port,inject the actual port used>> into your test.
For convenience, tests that need to make REST calls to the started server can additionally `@Autowire` a {spring-framework-docs}/testing.html#webtestclient-tests[`WebTestClient`], which resolves relative links to the running server and comes with a dedicated API for verifying responses, as shown in the following example:
@@ -428,7 +428,7 @@ Often, `@WebFluxTest` is limited to a single controller and used in combination
TIP: You can also auto-configure `WebTestClient` in a non-`@WebFluxTest` (such as `@SpringBootTest`) by annotating it with `@AutoConfigureWebTestClient`.
The following example shows a class that uses both `@WebFluxTest` and a `WebTestClient`:
@@ -481,7 +481,7 @@ By default, data JPA tests are transactional and roll back at the end of each te
See the {spring-framework-docs}/testing.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details.
If that is not what you want, you can disable transaction management for a test or for the whole class as follows:
In-memory embedded databases generally work well for tests, since they are fast and do not require any installation.
If, however, you prefer to run tests against a real database you can use the `@AutoConfigureTestDatabase` annotation, as shown in the following example:
@@ -519,7 +519,7 @@ By default, JDBC tests are transactional and roll back at the end of each test.
See the {spring-framework-docs}/testing.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details.
If that is not what you want, you can disable transaction management for a test or for the whole class, as follows:
In-memory embedded MongoDB generally works well for tests, since it is fast and does not require any developer installation.
If, however, you prefer to run tests against a real MongoDB server, you should exclude the embedded MongoDB auto-configuration, as shown in the following example:
@@ -619,7 +619,7 @@ By default, Data Neo4j tests are transactional and roll back at the end of each
See the {spring-framework-docs}/testing.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details.
If that is not what you want, you can disable transaction management for a test or for the whole class, as follows:
In-memory embedded LDAP generally works well for tests, since it is fast and does not require any developer installation.
If, however, you prefer to run tests against a real LDAP server, you should exclude the embedded LDAP auto-configuration, as shown in the following example:
@@ -686,7 +686,7 @@ TIP: A list of the auto-configuration settings that are enabled by `@RestClientT
The specific beans that you want to test should be specified by using the `value` or `components` attribute of `@RestClientTest`, as shown in the following example:
@@ -708,14 +708,14 @@ It can also be used to configure the host, scheme, and port that appears in any
`@AutoConfigureRestDocs` customizes the `MockMvc` bean to use Spring REST Docs when testing Servlet-based web applications.
You can inject it by using `@Autowired` and use it in your tests as you normally would when using Mock MVC and Spring REST Docs, as shown in the following example:
If you require more control over Spring REST Docs configuration than offered by the attributes of `@AutoConfigureRestDocs`, you can use a `RestDocsMockMvcConfigurationCustomizer` bean, as shown in the following example:
`@AutoConfigureRestDocs` can also be used with `WebTestClient` when testing reactive web applications.
You can inject it by using `@Autowired` and use it in your tests as you normally would when using `@WebFluxTest` and Spring REST Docs, as shown in the following example:
If you require more control over Spring REST Docs configuration than offered by the attributes of `@AutoConfigureRestDocs`, you can use a `RestDocsWebTestClientConfigurationCustomizer` bean, as shown in the following example:
`@AutoConfigureRestDocs` makes a `RequestSpecification` bean, preconfigured to use Spring REST Docs, available to your tests.
You can inject it by using `@Autowired` and use it in your tests as you normally would when using REST Assured and Spring REST Docs, as shown in the following example:
If you require more control over Spring REST Docs configuration than offered by the attributes of `@AutoConfigureRestDocs`, a `RestDocsRestAssuredConfigurationCustomizer` bean can be used, as shown in the following example:
Each slice provides one or more `@AutoConfigure...` annotations that namely defines the auto-configurations that should be included as part of a slice.
Additional auto-configurations can be added on a test-by-test basis by creating a custom `@AutoConfigure...` annotation or by adding `@ImportAutoConfiguration` to the test as shown in the following example:
Because this class is the source configuration for the test, any slice test actually tries to start Spring Batch, which is definitely not what you want to do.
A recommended approach is to move that area-specific configuration to a separate `@Configuration` class at the same level as your application, as shown in the following example:
@@ -838,14 +838,14 @@ The latter approach lets you enable it in one of your tests, if necessary, with
Test slices exclude `@Configuration` classes from scanning.
For example, for a `@WebMvcTest`, the following configuration will not include the given `WebMvcConfigurer` bean in the application context loaded by the test slice:
@@ -890,7 +890,7 @@ A few test utility classes that are generally useful when testing your applicati
`ConfigDataApplicationContextInitializer` is an `ApplicationContextInitializer` that you can apply to your tests to load Spring Boot `application.properties` files.
You can use it when you do not need the full set of features provided by `@SpringBootTest`, as shown in the following example:
`OutputCapture` is a JUnit `Extension` that you can use to capture `System.out` and `System.err` output.
To use add `@ExtendWith(OutputCaptureExtension.class)` and inject `CapturedOutput` as an argument to your test class constructor or test method as follows:
By default, `WebServiceTemplateBuilder` detects a suitable HTTP-based `WebServiceMessageSender` using the available HTTP client libraries on the classpath.
You can also customize read and connection timeouts as follows:
@@ -7,7 +7,7 @@ Spring Framework provides {spring-framework-docs}/web.html#websocket[rich WebSoc
WebSocket support is also available for {spring-framework-docs}/web-reactive.html#webflux-websocket[reactive web applications] and requires to include the WebSocket API alongside `spring-boot-starter-webflux`:
@@ -149,7 +149,7 @@ If you run `mvn dependency:tree` again, you see that there are now a number of a
To finish our application, we need to create a single Java file.
By default, Maven compiles sources from `src/main/java`, so you need to create that directory structure and then add a file named `src/main/java/MyApplication.java` to contain the following code:
@@ -93,7 +93,7 @@ Alternatively, you can use `java -jar` with the `.jar` file (the script helps yo
SDKMAN! (The Software Development Kit Manager) can be used for managing multiple versions of various binary SDKs, including Groovy and the Spring Boot CLI.
Get SDKMAN! from https://sdkman.io and install Spring Boot by using the following commands:
[indent=0,subs="verbatim,quotes,attributes"]
[indent=0,subs="verbatim,attributes"]
----
$ sdk install springboot
$ spring --version
...
...
@@ -102,7 +102,7 @@ Get SDKMAN! from https://sdkman.io and install Spring Boot by using the followin
If you develop features for the CLI and want access to the version you built, use the following commands:
[indent=0,subs="verbatim,quotes,attributes"]
[indent=0,subs="verbatim,attributes"]
----
$ sdk install springboot dev /path/to/spring-boot/spring-boot-cli/target/spring-boot-cli-{spring-boot-version}-bin/spring-{spring-boot-version}/
$ sdk default springboot dev
...
...
@@ -115,7 +115,7 @@ It points at your target build location, so every time you rebuild Spring Boot,
You can see it by running the following command:
[indent=0,subs="verbatim,quotes,attributes"]
[indent=0,subs="verbatim,attributes"]
----
$ sdk ls springboot
...
...
@@ -202,7 +202,7 @@ In that case, run `scoop update` and try again.
You can use the following web application to test your installation.
To start, create a file called `app.groovy`, as follows:
@@ -244,7 +244,7 @@ When upgrading to a new feature release, some properties may have been renamed o
Spring Boot provides a way to analyze your application's environment and print diagnostics at startup, but also temporarily migrate properties at runtime for you.
To enable that feature, add the following dependency to your project:
@@ -55,7 +55,7 @@ Both Maven and Gradle allow generating a `git.properties` file containing inform
For Maven users, the `spring-boot-starter-parent` POM includes a pre-configured plugin to generate a `git.properties` file.
To use it, add the following declaration to your POM:
[source,xml,indent=0]
[source,xml,indent=0,subs="verbatim"]
----
<build>
<plugins>
...
...
@@ -69,7 +69,7 @@ To use it, add the following declaration to your POM:
Gradle users can achieve the same result by using the https://plugins.gradle.org/plugin/com.gorylenko.gradle-git-properties[`gradle-git-properties`] plugin, as shown in the following example:
[source,gradle,indent=0]
[source,gradle,indent=0,subs="verbatim"]
----
plugins {
id "com.gorylenko.gradle-git-properties" version "2.2.4"
...
...
@@ -103,7 +103,7 @@ To override dependency versions in Gradle, see {spring-boot-gradle-plugin-docs}#
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:
@@ -63,7 +63,7 @@ Because the actual type of the connection pool is not exposed, no keys are gener
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:
@@ -88,7 +88,7 @@ You can easily initialize a `DataSourceBuilder` from the state of any `DataSourc
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:
This setup puts you _in sync_ with what Spring Boot does for you by default, except that a dedicated connection pool is chosen (in code) and its settings are exposed in the `app.datasource.configuration` sub namespace.
Because `DataSourceProperties` is taking care of the `url`/`jdbcUrl` translation for you, you can configure it as follows:
@@ -242,21 +242,21 @@ Alternatively, if `ImplicitNamingStrategy` or `PhysicalNamingStrategy` beans are
By default, Spring Boot configures the physical naming strategy with `SpringPhysicalNamingStrategy`.
This implementation provides the same table structure as Hibernate 4: all dots are replaced by underscores and camel casing is replaced by underscores as well. Additionally, by default, all table names are generated in lower case. For example, a `TelephoneNumber` entity is mapped to the `telephone_number` table. If your schema requires mixed-case identifiers, define a custom `SpringPhysicalNamingStrategy` bean, as shown in the following example:
@@ -390,7 +390,7 @@ For example, when Flyway is auto-configured, Hibernate is configured to depend u
If you are configuring a component yourself, you can use an `EntityManagerFactoryDependsOnPostProcessor` subclass as a convenient way of setting up the necessary dependencies.
For example, if you use Hibernate Search with Elasticsearch as its index manager, any `EntityManagerFactory` beans must be configured to depend on the `elasticsearchClient` bean, as shown in the following example:
@@ -141,7 +141,7 @@ For example, you can place test-specific migrations in `src/test/resources` and
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:
@@ -11,7 +11,7 @@ This prevents Jersey from committing the response before Spring Security has had
The `jersey.config.server.response.setStatusOverSendError` property must be set to `true` on the application's `ResourceConfig` bean, as shown in the following example:
@@ -24,7 +24,7 @@ To use Jersey alongside another web framework, such as Spring MVC, it should be
First, configure Jersey to use a Filter rather than a Servlet by configuring the configprop:spring.jersey.type[] application property with a value of `filter`.
Second, configure your `ResourceConfig` to forward requests that would have resulted in a 404, as shown in the following example.
@@ -19,7 +19,7 @@ If Logback is available, it is the first choice.
If the only change you need to make to logging is to set the levels of various loggers, you can do so in `application.properties` by using the "logging.level" prefix, as shown in the following example:
@@ -91,7 +91,7 @@ Any `logback-spring.groovy` files will not be detected.
==== Configure Logback for File-only Output
If you want to disable console logging and write output only to a file, you need a custom `logback-spring.xml` that imports `file-appender.xml` but not `console-appender.xml`, as shown in the following example:
@@ -16,7 +16,7 @@ This is possible in both Maven and Gradle.
You can automatically expand properties from the Maven project by using resource filtering.
If you use the `spring-boot-starter-parent`, you can then refer to your Maven '`project properties`' with `@..@` placeholders, as shown in the following example:
@@ -33,7 +33,7 @@ See the {spring-boot-maven-plugin-docs}#getting-started[plugin usage page] for m
If you do not use the starter parent, you need to include the following element inside the `<build/>` element of your `pom.xml`:
[source,xml,indent=0]
[source,xml,indent=0,subs="verbatim"]
----
<resources>
<resource>
...
...
@@ -45,7 +45,7 @@ If you do not use the starter parent, you need to include the following element
You also need to include the following element inside `<plugins/>`:
[source,xml,indent=0]
[source,xml,indent=0,subs="verbatim"]
----
<plugin>
<groupId>org.apache.maven.plugins</groupId>
...
...
@@ -69,7 +69,7 @@ If that property is not set to `false`, these may be expanded by the build.
==== Automatic Property Expansion Using Gradle
You can automatically expand properties from the Gradle project by configuring the Java plugin's `processResources` task to do so, as shown in the following example:
[source,gradle,indent=0]
[source,gradle,indent=0,subs="verbatim"]
----
processResources {
expand(project.properties)
...
...
@@ -78,7 +78,7 @@ You can automatically expand properties from the Gradle project by configuring t
You can then refer to your Gradle project's properties by using placeholders, as shown in the following example:
@@ -110,21 +110,21 @@ Then the Spring Boot banner is not printed on startup, and the application is no
Properties defined in external configuration override and replace the values specified with the Java API, with the notable exception of the primary sources.
Primary sources are those provided to the `SpringApplication` constructor:
@@ -183,7 +183,7 @@ In those two platforms, the `PORT` environment variable is set automatically and
=== Use YAML for External Properties
YAML is a superset of JSON and, as such, is a convenient syntax for storing external properties in a hierarchical format, as shown in the following example:
@@ -218,14 +218,14 @@ See "`<<features#features.external-config.yaml>>`" in the '`Spring Boot features
The Spring `Environment` has an API for this, but you would normally set a System property (configprop:spring.profiles.active[]) or an OS environment variable (configprop:spring.profiles.active[format=envvar]).
Also, you can launch your application with a `-D` argument (remember to put it before the main class or jar archive), as follows:
@@ -246,7 +246,7 @@ Spring Boot supports multi-document YAML and Properties files (see <<features#fe
If a document contains a `spring.config.activate.on-profile` key, then the profiles value (a comma-separated list of profiles or a profile expression) is fed into the Spring `Environment.acceptsProfiles()` method.
If the profile expression matches then that document is included in the final merge (otherwise, it is not), as shown in the following example:
@@ -28,7 +28,7 @@ If you use Tomcat as a servlet container, then Spring Boot adds Tomcat's own `Re
The standard behavior is determined by the presence or absence of certain request headers (`x-forwarded-for` and `x-forwarded-proto`), whose names are conventional, so it should work with most front-end proxies.
You can switch on the valve by adding some entries to `application.properties`, as shown in the following example:
@@ -42,7 +42,7 @@ Alternatively, you can add the `RemoteIpValve` by customizing the `TomcatServlet
To configure Spring Security to require a secure channel for all (or some) requests, consider adding your own `SecurityFilterChain` bean that adds the following `HttpSecurity` configuration:
@@ -10,7 +10,7 @@ This section answers common questions about Spring MVC and Spring Boot.
=== Write a JSON REST Service
Any Spring `@RestController` in a Spring Boot application should render JSON response by default as long as Jackson2 is on the classpath, as shown in the following example:
@@ -36,7 +36,7 @@ To use the Jackson XML renderer, add the following dependency to your project:
If Jackson's XML extension is not available and JAXB is available, XML can be rendered with the additional requirement of having `MyThing` annotated as `@XmlRootElement`, as shown in the following example:
The next step is to update your build configuration such that your project produces a war file rather than a jar file.
If you use Maven and `spring-boot-starter-parent` (which configures Maven's war plugin for you), all you need to do is to modify `pom.xml` to change the packaging to war, as follows:
@@ -79,7 +79,7 @@ See the https://spring.io/guides/gs/convert-jar-to-war/[Getting Started Guide on
To create a deployable war by extending `SpringBootServletInitializer` (for example, in a class called `Application`) and adding the Spring Boot `@SpringBootApplication` annotation, use code similar to that shown in the following example:
If you intend to start your application as a war or as an executable application, you need to share the customizations of the builder in a method that is both available to the `SpringBootServletInitializer` callback and in the `main` method in a class similar to the following:
@@ -104,7 +104,7 @@ The best way to get that and be sure it has been initialized is to add a `@Bean`
Tests that use `@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)` can also inject the actual port into a field by using the `@LocalServerPort` annotation, as shown in the following example:
@@ -194,7 +194,7 @@ More on this in the https://tomcat.apache.org/tomcat-9.0-doc/apr.html[official T
Starting Tomcat 9.0.x on JDK 8 with HTTP/2 and SSL enabled but without that native support logs the following error:
[indent=0,subs="attributes"]
[indent=0,subs="verbatim"]
----
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.
----
...
...
@@ -246,7 +246,7 @@ You can declare such a component and get access to the server factory relevant t
The example below is for Tomcat with the `spring-boot-starter-web` (Servlet stack):
@@ -319,7 +319,7 @@ Like any other Spring bean, you can define the order of Servlet filter beans; pl
As <<howto#howto.webserver.add-servlet-filter-listener.spring-bean,described earlier>>, 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:
@@ -441,7 +441,7 @@ You can take complete control of the configuration of Tomcat's `RemoteIpValve` b
=== Enable Multiple Connectors with Tomcat
You can add an `org.apache.catalina.connector.Connector` to the `TomcatServletWebServerFactory`, which can allow multiple connectors, including HTTP and HTTPS connectors, as shown in the following example:
@@ -461,7 +461,7 @@ If at all possible, you should consider updating your code to only store values
If, however, you cannot change the way that cookies are written, you can instead configure Tomcat to use a `LegacyCookieProcessor`.
To switch to the `LegacyCookieProcessor`, use an `WebServerFactoryCustomizer` bean that adds a `TomcatContextCustomizer`, as shown in the following example:
@@ -474,7 +474,7 @@ Embedded Tomcat's MBean registry is disabled by default.
This minimizes Tomcat's memory footprint.
If you want to use Tomcat's MBeans, for example so that they can be used to expose metrics via Micrometer, you must use the configprop:server.tomcat.mbeanregistry.enabled[] property to do so, as shown in the following example:
=== Create WebSocket Endpoints Using @ServerEndpoint
If you want to use `@ServerEndpoint` in a Spring Boot application that used an embedded container, you must declare a single `ServerEndpointExporter` `@Bean`, as shown in the following example:
@@ -25,7 +25,7 @@ Doing so enables debug logs for a selection of core loggers and logs a condition
=== Disabling Specific Auto-configuration Classes
If you find that specific auto-configuration classes that you do not want are being applied, you can use the exclude attribute of `@SpringBootApplication` to disable them, as shown in the following example:
@@ -162,7 +162,7 @@ In most cases, you can set this property in your `application.properties` (doing
If you need to _completely_ disable restart support (for example, because it does not work with a specific library), you need to set the configprop:spring.devtools.restart.enabled[] `System` property to `false` before calling `SpringApplication.run(...)`, as shown in the following example:
@@ -224,7 +224,7 @@ The `spring-devtools.properties` file can contain properties prefixed with `rest
The `include` elements are items that should be pulled up into the "`restart`" classloader, and the `exclude` elements are items that should be pushed down into the "`base`" classloader.
The value of the property is a regex pattern that is applied to the classpath, as shown in the following example:
@@ -277,7 +277,7 @@ You can configure global devtools settings by adding any of the following files
Any properties added to these file apply to _all_ Spring Boot applications on your machine that use devtools.
For example, to configure restart to always use a <<using#using.devtools.restart.triggerfile, trigger file>>, you would add the following property to your `spring-boot-devtools` file:
@@ -304,7 +304,7 @@ Profile specific filenames (of the form `spring-boot-devtools-<profile>.properti
Since Spring Boot relies entirely on the IDE to compile and copy files into the location from where Spring Boot can read them, you might find that there are times when certain changes are not reflected when devtools restarts the application.
If you observe such problems constantly, try increasing the `spring.devtools.restart.poll-interval` and `spring.devtools.restart.quiet-period` parameters to the values that fit your development environment:
@@ -30,7 +30,7 @@ STS users can use the `Relaunch` button rather than the `Run` button to ensure t
=== Running as a Packaged Application
If you use the Spring Boot Maven or Gradle plugins to create an executable jar, you can run your application using `java -jar`, as shown in the following example:
@@ -7,7 +7,7 @@ A single `@SpringBootApplication` annotation can be used to enable those three f
* `@ComponentScan`: enable `@Component` scan on the package where the application is located (see <<using#using.structuring-your-code,the best practices>>)
* `@Configuration`: allow to register extra beans in the context or import additional configuration classes