diff --git a/.gitignore b/.gitignore index b0e1ce60a6dab273a23ea4021d8cafee8b6e500a..f9e8bf7a5a99153ec186413cf7f7314b4ec4aca4 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ node_modules docs/.vuepress/dist .vscode package-lock.json +.idea/ # macos .DS_Store diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js index d2192be85b7fc814bc91e28e6297e5615abc5970..3bcfb845f99a4d975b3816f197e770cfbdfead36 100644 --- a/docs/.vuepress/config.js +++ b/docs/.vuepress/config.js @@ -154,20 +154,11 @@ module.exports = { sidebarDepth: 2, collapsable: false, children: [ - "/en/spring-boot/legal.md", - "/en/spring-boot/getting-help.md", - "/en/spring-boot/documentation-overview.md", - "/en/spring-boot/getting-started.md", - "/en/spring-boot/upgrading-spring-boot-applications.md", - "/en/spring-boot/documentation-overview.md", - "/en/spring-boot/documentation-overview.md", - "/en/spring-boot/documentation-overview.md", - "/en/spring-boot/documentation-overview.md", - "/en/spring-boot/documentation-overview.md", - "/en/spring-boot/documentation-overview.md", - "/en/spring-boot/documentation-overview.md", - "/en/spring-boot/documentation-overview.md", - "/en/spring-boot/documentation-overview.md", + "/en/spring-boot/build-tool-plugins.md", + "/en/spring-boot/container-images.md", + "/en/spring-boot/core-features.md", + "/en/spring-boot/data.md", + "/en/spring-boot/deploying-spring-boot-applications.md" ], initialOpenGroupIndex: 0 // 可选的, 默认值是 0 } @@ -291,11 +282,11 @@ module.exports = { sidebarDepth: 2, collapsable: false, children: [ - "/spring-boot/getting-help.md", "/spring-boot/build-tool-plugins.md", - "/spring-boot/getting-started.md", - "/spring-boot/upgrading.md", - "/spring-boot/documentation.md" + "/spring-boot/container-images.md", + "/spring-boot/core-features.md", + "/spring-boot/data.md", + "/spring-boot/deploying-spring-boot-applications.md" ], initialOpenGroupIndex: 0 // 可选的, 默认值是 0 } diff --git a/docs/en/spring-boot/actuator.md b/docs/en/spring-boot/actuator.md index e54638d02f6c9e49ed488adad22cfc067dabf996..6f7ba832d48de7150337e88831bbbcf1333b9a86 100644 --- a/docs/en/spring-boot/actuator.md +++ b/docs/en/spring-boot/actuator.md @@ -1,156 +1,10 @@ -Production-ready Features -========== - -Table of Contents - -[Back to index](index.html) - -* [1. Enabling Production-ready Features](#actuator.enabling) -* [2. Endpoints](#actuator.endpoints) - * [2.1. Enabling Endpoints](#actuator.endpoints.enabling) - * [2.2. Exposing Endpoints](#actuator.endpoints.exposing) - * [2.3. Security](#actuator.endpoints.security) - * [2.3.1. Cross Site Request Forgery Protection](#actuator.endpoints.security.csrf) - - * [2.4. Configuring Endpoints](#actuator.endpoints.caching) - * [2.5. Hypermedia for Actuator Web Endpoints](#actuator.endpoints.hypermedia) - * [2.6. CORS Support](#actuator.endpoints.cors) - * [2.7. Implementing Custom Endpoints](#actuator.endpoints.implementing-custom) - * [2.7.1. Receiving Input](#actuator.endpoints.implementing-custom.input) - * [Input Type Conversion](#actuator.endpoints.implementing-custom.input.conversion) - - * [2.7.2. Custom Web Endpoints](#actuator.endpoints.implementing-custom.web) - * [Web Endpoint Request Predicates](#actuator.endpoints.implementing-custom.web.request-predicates) - * [Path](#actuator.endpoints.implementing-custom.web.path-predicates) - * [HTTP method](#actuator.endpoints.implementing-custom.web.method-predicates) - * [Consumes](#actuator.endpoints.implementing-custom.web.consumes-predicates) - * [Produces](#actuator.endpoints.implementing-custom.web.produces-predicates) - * [Web Endpoint Response Status](#actuator.endpoints.implementing-custom.web.response-status) - * [Web Endpoint Range Requests](#actuator.endpoints.implementing-custom.web.range-requests) - * [Web Endpoint Security](#actuator.endpoints.implementing-custom.web.security) - - * [2.7.3. Servlet Endpoints](#actuator.endpoints.implementing-custom.servlet) - * [2.7.4. Controller Endpoints](#actuator.endpoints.implementing-custom.controller) - - * [2.8. Health Information](#actuator.endpoints.health) - * [2.8.1. Auto-configured HealthIndicators](#actuator.endpoints.health.auto-configured-health-indicators) - * [2.8.2. Writing Custom HealthIndicators](#actuator.endpoints.health.writing-custom-health-indicators) - * [2.8.3. Reactive Health Indicators](#actuator.endpoints.health.reactive-health-indicators) - * [2.8.4. Auto-configured ReactiveHealthIndicators](#actuator.endpoints.health.auto-configured-reactive-health-indicators) - * [2.8.5. Health Groups](#actuator.endpoints.health.groups) - * [2.8.6. DataSource Health](#actuator.endpoints.health.datasource) - - * [2.9. Kubernetes Probes](#actuator.endpoints.kubernetes-probes) - * [2.9.1. Checking External State with Kubernetes Probes](#actuator.endpoints.kubernetes-probes.external-state) - * [2.9.2. Application Lifecycle and Probe States](#actuator.endpoints.kubernetes-probes.lifecycle) - - * [2.10. Application Information](#actuator.endpoints.info) - * [2.10.1. Auto-configured InfoContributors](#actuator.endpoints.info.auto-configured-info-contributors) - * [2.10.2. Custom Application Information](#actuator.endpoints.info.custom-application-information) - * [2.10.3. Git Commit Information](#actuator.endpoints.info.git-commit-information) - * [2.10.4. Build Information](#actuator.endpoints.info.build-information) - * [2.10.5. Java Information](#actuator.endpoints.info.java-information) - * [2.10.6. Writing Custom InfoContributors](#actuator.endpoints.info.writing-custom-info-contributors) - -* [3. Monitoring and Management over HTTP](#actuator.monitoring) - * [3.1. Customizing the Management Endpoint Paths](#actuator.monitoring.customizing-management-server-context-path) - * [3.2. Customizing the Management Server Port](#actuator.monitoring.customizing-management-server-port) - * [3.3. Configuring Management-specific SSL](#actuator.monitoring.management-specific-ssl) - * [3.4. Customizing the Management Server Address](#actuator.monitoring.customizing-management-server-address) - * [3.5. Disabling HTTP Endpoints](#actuator.monitoring.disabling-http-endpoints) - -* [4. Monitoring and Management over JMX](#actuator.jmx) - * [4.1. Customizing MBean Names](#actuator.jmx.custom-mbean-names) - * [4.2. Disabling JMX Endpoints](#actuator.jmx.disable-jmx-endpoints) - * [4.3. Using Jolokia for JMX over HTTP](#actuator.jmx.jolokia) - * [4.3.1. Customizing Jolokia](#actuator.jmx.jolokia.customizing) - * [4.3.2. Disabling Jolokia](#actuator.jmx.jolokia.disabling) - -* [5. Loggers](#actuator.loggers) - * [5.1. Configure a Logger](#actuator.loggers.configure) - -* [6. Metrics](#actuator.metrics) - * [6.1. Getting started](#actuator.metrics.getting-started) - * [6.2. Supported Monitoring Systems](#actuator.metrics.export) - * [6.2.1. AppOptics](#actuator.metrics.export.appoptics) - * [6.2.2. Atlas](#actuator.metrics.export.atlas) - * [6.2.3. Datadog](#actuator.metrics.export.datadog) - * [6.2.4. Dynatrace](#actuator.metrics.export.dynatrace) - * [v2 API](#actuator.metrics.export.dynatrace.v2-api) - * [v1 API (Legacy)](#actuator.metrics.export.dynatrace.v1-api) - * [Version-independent Settings](#actuator.metrics.export.dynatrace.version-independent-settings) - - * [6.2.5. Elastic](#actuator.metrics.export.elastic) - * [6.2.6. Ganglia](#actuator.metrics.export.ganglia) - * [6.2.7. Graphite](#actuator.metrics.export.graphite) - * [6.2.8. Humio](#actuator.metrics.export.humio) - * [6.2.9. Influx](#actuator.metrics.export.influx) - * [6.2.10. JMX](#actuator.metrics.export.jmx) - * [6.2.11. KairosDB](#actuator.metrics.export.kairos) - * [6.2.12. New Relic](#actuator.metrics.export.newrelic) - * [6.2.13. Prometheus](#actuator.metrics.export.prometheus) - * [6.2.14. SignalFx](#actuator.metrics.export.signalfx) - * [6.2.15. Simple](#actuator.metrics.export.simple) - * [6.2.16. Stackdriver](#actuator.metrics.export.stackdriver) - * [6.2.17. StatsD](#actuator.metrics.export.statsd) - * [6.2.18. Wavefront](#actuator.metrics.export.wavefront) - - * [6.3. Supported Metrics and Meters](#actuator.metrics.supported) - * [6.3.1. JVM Metrics](#actuator.metrics.supported.jvm) - * [6.3.2. System Metrics](#actuator.metrics.supported.system) - * [6.3.3. Application Startup Metrics](#actuator.metrics.supported.application-startup) - * [6.3.4. Logger Metrics](#actuator.metrics.supported.logger) - * [6.3.5. Task Execution and Scheduling Metrics](#actuator.metrics.supported.tasks) - * [6.3.6. Spring MVC Metrics](#actuator.metrics.supported.spring-mvc) - * [6.3.7. Spring WebFlux Metrics](#actuator.metrics.supported.spring-webflux) - * [6.3.8. Jersey Server Metrics](#actuator.metrics.supported.jersey) - * [6.3.9. HTTP Client Metrics](#actuator.metrics.supported.http-clients) - * [6.3.10. Tomcat Metrics](#actuator.metrics.supported.tomcat) - * [6.3.11. Cache Metrics](#actuator.metrics.supported.cache) - * [6.3.12. DataSource Metrics](#actuator.metrics.supported.jdbc) - * [6.3.13. Hibernate Metrics](#actuator.metrics.supported.hibernate) - * [6.3.14. Spring Data Repository Metrics](#actuator.metrics.supported.spring-data-repository) - * [6.3.15. RabbitMQ Metrics](#actuator.metrics.supported.rabbitmq) - * [6.3.16. Spring Integration Metrics](#actuator.metrics.supported.spring-integration) - * [6.3.17. Kafka Metrics](#actuator.metrics.supported.kafka) - * [6.3.18. MongoDB Metrics](#actuator.metrics.supported.mongodb) - * [MongoDB Command Metrics](#actuator.metrics.supported.mongodb.command) - * [MongoDB Connection Pool Metrics](#actuator.metrics.supported.mongodb.connection-pool) - - * [6.3.19. Jetty Metrics](#actuator.metrics.supported.jetty) - * [6.3.20. @Timed Annotation Support](#actuator.metrics.supported.timed-annotation) - * [6.3.21. Redis Metrics](#actuator.metrics.supported.redis) - - * [6.4. Registering Custom Metrics](#actuator.metrics.registering-custom) - * [6.5. Customizing Individual Metrics](#actuator.metrics.customizing) - * [6.5.1. Common Tags](#actuator.metrics.customizing.common-tags) - * [6.5.2. Per-meter Properties](#actuator.metrics.customizing.per-meter-properties) - - * [6.6. Metrics Endpoint](#actuator.metrics.endpoint) - -* [7. Auditing](#actuator.auditing) - * [7.1. Custom Auditing](#actuator.auditing.custom) - -* [8. HTTP Tracing](#actuator.tracing) - * [8.1. Custom HTTP tracing](#actuator.tracing.custom) - -* [9. Process Monitoring](#actuator.process-monitoring) - * [9.1. Extending Configuration](#actuator.process-monitoring.configuration) - * [9.2. Programmatically Enabling Process Monitoring](#actuator.process-monitoring.programmatically) - -* [10. Cloud Foundry Support](#actuator.cloud-foundry) - * [10.1. Disabling Extended Cloud Foundry Actuator Support](#actuator.cloud-foundry.disable) - * [10.2. Cloud Foundry Self-signed Certificates](#actuator.cloud-foundry.ssl) - * [10.3. Custom Context Path](#actuator.cloud-foundry.custom-context-path) - -* [11. What to Read Next](#actuator.whats-next) +# Production-ready Features Spring Boot includes a number of additional features to help you monitor and manage your application when you push it to production. You can choose to manage and monitor your application by using HTTP endpoints or with JMX. Auditing, health, and metrics gathering can also be automatically applied to your application. -[](#actuator.enabling)1. Enabling Production-ready Features ----------- +## 1. Enabling Production-ready Features The [`spring-boot-actuator`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-actuator) module provides all of Spring Boot’s production-ready features. The recommended way to enable the features is to add a dependency on the `spring-boot-starter-actuator` “Starter”. @@ -179,8 +33,7 @@ dependencies { } ``` -[](#actuator.endpoints)2. Endpoints ----------- +## 2. Endpoints Actuator endpoints let you monitor and interact with your application. Spring Boot includes a number of built-in endpoints and lets you add your own. @@ -230,7 +83,7 @@ If your application is a web application (Spring MVC, Spring WebFlux, or Jersey) | `logfile` |Returns the contents of the logfile (if the `logging.file.name` or the `logging.file.path` property has been set).
Supports the use of the HTTP `Range` header to retrieve part of the log file’s content.| |`prometheus`| Exposes metrics in a format that can be scraped by a Prometheus server.
Requires a dependency on `micrometer-registry-prometheus`. | -### [](#actuator.endpoints.enabling)2.1. Enabling Endpoints ### +### 2.1. Enabling Endpoints By default, all endpoints except for `shutdown` are enabled. To configure the enablement of an endpoint, use its `management.endpoint..enabled` property. @@ -275,7 +128,7 @@ management: | |Disabled endpoints are removed entirely from the application context.
If you want to change only the technologies over which an endpoint is exposed, use the [`include` and `exclude` properties](#actuator.endpoints.exposing) instead.| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#actuator.endpoints.exposing)2.2. Exposing Endpoints ### +### 2.2. Exposing Endpoints Since Endpoints may contain sensitive information, you should carefully consider when to expose them. The following table shows the default exposure for the built-in endpoints: @@ -370,7 +223,7 @@ management: | |If you want to implement your own strategy for when endpoints are exposed, you can register an `EndpointFilter` bean.| |---|---------------------------------------------------------------------------------------------------------------------| -### [](#actuator.endpoints.security)2.3. Security ### +### 2.3. Security For security purposes, all actuators other than `/health` are disabled by default. You can use the `management.endpoints.web.exposure.include` property to enable the actuators. @@ -456,7 +309,7 @@ public class MySecurityConfiguration { | |In both of the preceding examples, the configuration applies only to the actuator endpoints.
Since Spring Boot’s security configuration backs off completely in the presence of any `SecurityFilterChain` bean, you need to configure an additional `SecurityFilterChain` bean with rules that apply to the rest of the application.| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#actuator.endpoints.security.csrf)2.3.1. Cross Site Request Forgery Protection #### +#### 2.3.1. Cross Site Request Forgery Protection Since Spring Boot relies on Spring Security’s defaults, CSRF protection is turned on by default. This means that the actuator endpoints that require a `POST` (shutdown and loggers endpoints), a `PUT`, or a `DELETE` get a 403 (forbidden) error when the default security configuration is in use. @@ -466,7 +319,7 @@ This means that the actuator endpoints that require a `POST` (shutdown and logge You can find additional information about CSRF protection in the [Spring Security Reference Guide](https://docs.spring.io/spring-security/reference/5.6.2/features/exploits/csrf.html). -### [](#actuator.endpoints.caching)2.4. Configuring Endpoints ### +### 2.4. Configuring Endpoints Endpoints automatically cache responses to read operations that do not take any parameters. To configure the amount of time for which an endpoint caches a response, use its `cache.time-to-live` property. @@ -491,7 +344,7 @@ management: | |The `management.endpoint.` prefix uniquely identifies the endpoint that is being configured.| |---|--------------------------------------------------------------------------------------------------| -### [](#actuator.endpoints.hypermedia)2.5. Hypermedia for Actuator Web Endpoints ### +### 2.5. Hypermedia for Actuator Web Endpoints A “discovery page” is added with links to all the endpoints. The “discovery page” is available on `/actuator` by default. @@ -518,7 +371,7 @@ When a custom management context path is configured, the “discovery page” au For example, if the management context path is `/management`, the discovery page is available from `/management`. When the management context path is set to `/`, the discovery page is disabled to prevent the possibility of a clash with other mappings. -### [](#actuator.endpoints.cors)2.6. CORS Support ### +### 2.6. CORS Support [Cross-origin resource sharing](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) (CORS) is a [W3C specification](https://www.w3.org/TR/cors/) that lets you specify in a flexible way what kind of cross-domain requests are authorized. If you use Spring MVC or Spring WebFlux, you can configure Actuator’s web endpoints to support such scenarios. @@ -547,7 +400,7 @@ management: | |See [`CorsEndpointProperties`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/CorsEndpointProperties.java) for a complete list of options.| |---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#actuator.endpoints.implementing-custom)2.7. Implementing Custom Endpoints ### +### 2.7. Implementing Custom Endpoints If you add a `@Bean` annotated with `@Endpoint`, any methods annotated with `@ReadOperation`, `@WriteOperation`, or `@DeleteOperation` are automatically exposed over JMX and, in a web application, over HTTP as well. Endpoints can be exposed over HTTP by using Jersey, Spring MVC, or Spring WebFlux. @@ -572,7 +425,7 @@ These annotations let you provide technology-specific operations to augment an e Finally, if you need access to web-framework-specific functionality, you can implement servlet or Spring `@Controller` and `@RestController` endpoints at the cost of them not being available over JMX or when using a different web framework. -#### [](#actuator.endpoints.implementing-custom.input)2.7.1. Receiving Input #### +#### 2.7.1. Receiving Input Operations on an endpoint receive input through their parameters. When exposed over the web, the values for these parameters are taken from the URL’s query parameters and from the JSON request body. @@ -606,21 +459,21 @@ public void updateData(String name, int counter) { | |To let the input be mapped to the operation method’s parameters, Java code that implements an endpoint should be compiled with `-parameters`, and Kotlin code that implements an endpoint should be compiled with `-java-parameters`.
This will happen automatically if you use Spring Boot’s Gradle plugin or if you use Maven and `spring-boot-starter-parent`.| |---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -##### [](#actuator.endpoints.implementing-custom.input.conversion)Input Type Conversion ##### +##### Input Type Conversion The parameters passed to endpoint operation methods are, if necessary, automatically converted to the required type. Before calling an operation method, the input received over JMX or HTTP is converted to the required types by using an instance of `ApplicationConversionService` as well as any `Converter` or `GenericConverter` beans qualified with `@EndpointConverter`. -#### [](#actuator.endpoints.implementing-custom.web)2.7.2. Custom Web Endpoints #### +#### 2.7.2. Custom Web Endpoints Operations on an `@Endpoint`, `@WebEndpoint`, or `@EndpointWebExtension` are automatically exposed over HTTP using Jersey, Spring MVC, or Spring WebFlux. If both Jersey and Spring MVC are available, Spring MVC is used. -##### [](#actuator.endpoints.implementing-custom.web.request-predicates)Web Endpoint Request Predicates ##### +##### Web Endpoint Request Predicates A request predicate is automatically generated for each operation on a web-exposed endpoint. -##### [](#actuator.endpoints.implementing-custom.web.path-predicates)Path ##### +##### Path The path of the predicate is determined by the ID of the endpoint and the base path of the web-exposed endpoints. The default base path is `/actuator`. @@ -631,7 +484,7 @@ Such a parameter is added to the path predicate as a path variable. The variable’s value is passed into the operation method when the endpoint operation is invoked. If you want to capture all remaining path elements, you can add `@Selector(Match=ALL_REMAINING)` to the last parameter and make it a type that is conversion-compatible with a `String[]`. -##### [](#actuator.endpoints.implementing-custom.web.method-predicates)HTTP method ##### +##### HTTP method The HTTP method of the predicate is determined by the operation type, as shown in the following table: @@ -641,12 +494,12 @@ The HTTP method of the predicate is determined by the operation type, as shown i |`@WriteOperation` | `POST` | |`@DeleteOperation`| `DELETE` | -##### [](#actuator.endpoints.implementing-custom.web.consumes-predicates)Consumes ##### +##### Consumes For a `@WriteOperation` (HTTP `POST`) that uses the request body, the `consumes` clause of the predicate is `application/vnd.spring-boot.actuator.v2+json, application/json`. For all other operations, the `consumes` clause is empty. -##### [](#actuator.endpoints.implementing-custom.web.produces-predicates)Produces ##### +##### Produces The `produces` clause of the predicate can be determined by the `produces` attribute of the `@DeleteOperation`, `@ReadOperation`, and `@WriteOperation` annotations. The attribute is optional. @@ -656,7 +509,7 @@ If the operation method returns `void` or `Void`, the `produces` clause is empty If the operation method returns a `org.springframework.core.io.Resource`, the `produces` clause is `application/octet-stream`. For all other operations, the `produces` clause is `application/vnd.spring-boot.actuator.v2+json, application/json`. -##### [](#actuator.endpoints.implementing-custom.web.response-status)Web Endpoint Response Status ##### +##### Web Endpoint Response Status The default response status for an endpoint operation depends on the operation type (read, write, or delete) and what, if anything, the operation returns. @@ -668,7 +521,7 @@ If it does not return a value, the response status will be 204 (No Content). If an operation is invoked without a required parameter or with a parameter that cannot be converted to the required type, the operation method is not called, and the response status will be 400 (Bad Request). -##### [](#actuator.endpoints.implementing-custom.web.range-requests)Web Endpoint Range Requests ##### +##### Web Endpoint Range Requests You can use an HTTP range request to request part of an HTTP resource. When using Spring MVC or Spring Web Flux, operations that return a `org.springframework.core.io.Resource` automatically support range requests. @@ -676,27 +529,27 @@ When using Spring MVC or Spring Web Flux, operations that return a `org.springfr | |Range requests are not supported when using Jersey.| |---|---------------------------------------------------| -##### [](#actuator.endpoints.implementing-custom.web.security)Web Endpoint Security ##### +##### Web Endpoint Security An operation on a web endpoint or a web-specific endpoint extension can receive the current `java.security.Principal` or `org.springframework.boot.actuate.endpoint.SecurityContext` as a method parameter. The former is typically used in conjunction with `@Nullable` to provide different behavior for authenticated and unauthenticated users. The latter is typically used to perform authorization checks by using its `isUserInRole(String)` method. -#### [](#actuator.endpoints.implementing-custom.servlet)2.7.3. Servlet Endpoints #### +#### 2.7.3. Servlet Endpoints A servlet can be exposed as an endpoint by implementing a class annotated with `@ServletEndpoint` that also implements `Supplier`. Servlet endpoints provide deeper integration with the servlet container but at the expense of portability. They are intended to be used to expose an existing servlet as an endpoint. For new endpoints, the `@Endpoint` and `@WebEndpoint` annotations should be preferred whenever possible. -#### [](#actuator.endpoints.implementing-custom.controller)2.7.4. Controller Endpoints #### +#### 2.7.4. Controller Endpoints You can use `@ControllerEndpoint` and `@RestControllerEndpoint` to implement an endpoint that is exposed only by Spring MVC or Spring WebFlux. Methods are mapped by using the standard annotations for Spring MVC and Spring WebFlux, such as `@RequestMapping` and `@GetMapping`, with the endpoint’s ID being used as a prefix for the path. Controller endpoints provide deeper integration with Spring’s web frameworks but at the expense of portability. The `@Endpoint` and `@WebEndpoint` annotations should be preferred whenever possible. -### [](#actuator.endpoints.health)2.8. Health Information ### +### 2.8. Health Information You can use health information to check the status of your running application. It is often used by monitoring software to alert someone when a production system goes down. @@ -731,7 +584,7 @@ If no `HealthIndicator` returns a status that is known to the `StatusAggregator` | |You can use the `HealthContributorRegistry` to register and unregister health indicators at runtime.| |---|----------------------------------------------------------------------------------------------------| -#### [](#actuator.endpoints.health.auto-configured-health-indicators)2.8.1. Auto-configured HealthIndicators #### +#### 2.8.1. Auto-configured HealthIndicators When appropriate, Spring Boot auto-configures the `HealthIndicators` listed in the following table. You can also enable or disable selected indicators by configuring `management.health.key.enabled`, @@ -766,7 +619,7 @@ Additional `HealthIndicators` are available but are not enabled by default: |`livenessstate` | [`LivenessStateHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/availability/LivenessStateHealthIndicator.java) |Exposes the “Liveness” application availability state. | |`readinessstate`|[`ReadinessStateHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/availability/ReadinessStateHealthIndicator.java)|Exposes the “Readiness” application availability state.| -#### [](#actuator.endpoints.health.writing-custom-health-indicators)2.8.2. Writing Custom HealthIndicators #### +#### 2.8.2. Writing Custom HealthIndicators To provide custom health information, you can register Spring beans that implement the [`HealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthIndicator.java) interface. You need to provide an implementation of the `health()` method and return a `Health` response. @@ -865,7 +718,7 @@ The following table shows the default status mappings for the built-in statuses: | `UP` |No mapping by default, so HTTP status is `200`| | `UNKNOWN` |No mapping by default, so HTTP status is `200`| -#### [](#actuator.endpoints.health.reactive-health-indicators)2.8.3. Reactive Health Indicators #### +#### 2.8.3. Reactive Health Indicators For reactive applications, such as those that use Spring WebFlux, `ReactiveHealthContributor` provides a non-blocking contract for getting application health. Similar to a traditional `HealthContributor`, health information is collected from the content of a [`ReactiveHealthContributorRegistry`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ReactiveHealthContributorRegistry.java) (by default, all [`HealthContributor`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthContributor.java) and [`ReactiveHealthContributor`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ReactiveHealthContributor.java) instances defined in your `ApplicationContext`). @@ -905,7 +758,7 @@ public class MyReactiveHealthIndicator implements ReactiveHealthIndicator { | |To handle the error automatically, consider extending from `AbstractReactiveHealthIndicator`.| |---|---------------------------------------------------------------------------------------------| -#### [](#actuator.endpoints.health.auto-configured-reactive-health-indicators)2.8.4. Auto-configured ReactiveHealthIndicators #### +#### 2.8.4. Auto-configured ReactiveHealthIndicators #### When appropriate, Spring Boot auto-configures the following `ReactiveHealthIndicators`: @@ -921,7 +774,7 @@ When appropriate, Spring Boot auto-configures the following `ReactiveHealthIndic | |If necessary, reactive indicators replace the regular ones.
Also, any `HealthIndicator` that is not handled explicitly is wrapped automatically.| |---|----------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#actuator.endpoints.health.groups)2.8.5. Health Groups #### +#### 2.8.5. Health Groups It is sometimes useful to organize health indicators into groups that you can use for different purposes. @@ -1025,14 +878,14 @@ This would make the `live` health group available on the main server port at `/h The prefix is mandatory and must be either `server:` (represents the main server port) or `management:` (represents the management port, if configured.) The path must be a single path segment. -#### [](#actuator.endpoints.health.datasource)2.8.6. DataSource Health #### +#### 2.8.6. DataSource Health The `DataSource` health indicator shows the health of both standard data sources and routing data source beans. The health of a routing data source includes the health of each of its target data sources. In the health endpoint’s response, each of a routing data source’s targets is named by using its routing key. If you prefer not to include routing data sources in the indicator’s output, set `management.health.db.ignore-routing-data-sources` to `true`. -### [](#actuator.endpoints.kubernetes-probes)2.9. Kubernetes Probes ### +### 2.9. Kubernetes Probes Applications deployed on Kubernetes can provide information about their internal state with [Container Probes](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#container-probes). Depending on [your Kubernetes configuration](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/), the kubelet calls those probes and reacts to the result. @@ -1080,7 +933,7 @@ management.endpoint.health.probes.add-additional-paths=true This would make `liveness` available at `/livez` and `readiness` at `readyz` on the main server port. -#### [](#actuator.endpoints.kubernetes-probes.external-state)2.9.1. Checking External State with Kubernetes Probes #### +#### 2.9.1. Checking External State with Kubernetes Probes #### Actuator configures the “liveness” and “readiness” probes as Health Groups. This means that all the [health groups features](#actuator.endpoints.health.groups) are available for them. @@ -1121,7 +974,7 @@ Unfortunately, an external system that is shared by all application instances is Also, if an application uses Kubernetes [autoscaling](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/), it may react differently to applications being taken out of the load-balancer, depending on its autoscaler configuration. -#### [](#actuator.endpoints.kubernetes-probes.lifecycle)2.9.2. Application Lifecycle and Probe States #### +#### 2.9.2. Application Lifecycle and Probe States An important aspect of the Kubernetes Probes support is its consistency with the application lifecycle. There is a significant difference between the `AvailabilityState` (which is the in-memory, internal state of the application) @@ -1152,12 +1005,12 @@ When a Spring Boot application shuts down: | |See [Kubernetes container lifecycle section](deployment.html#deployment.cloud.kubernetes.container-lifecycle) for more information about Kubernetes deployment.| |---|---------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#actuator.endpoints.info)2.10. Application Information ### +### 2.10. Application Information Application information exposes various information collected from all [`InfoContributor`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoContributor.java) beans defined in your `ApplicationContext`. Spring Boot includes a number of auto-configured `InfoContributor` beans, and you can write your own. -#### [](#actuator.endpoints.info.auto-configured-info-contributors)2.10.1. Auto-configured InfoContributors #### +#### 2.10.1. Auto-configured InfoContributors When appropriate, Spring auto-configures the following `InfoContributor` beans: @@ -1178,7 +1031,7 @@ The `build` and `git` info contributors are enabled by default. Each can be disabled by setting its `management.info..enabled` property to `false`. Alternatively, to disable every contributor that is usually enabled by default, set the `management.info.defaults.enabled` property to `false`. -#### [](#actuator.endpoints.info.custom-application-information)2.10.2. Custom Application Information #### +#### 2.10.2. Custom Application Information When the `env` contributor is enabled, 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. @@ -1206,7 +1059,7 @@ info: | |Rather than hardcoding those values, you could also [expand info properties at build time](howto.html#howto.properties-and-configuration.expand-properties).

Assuming you use Maven, you could rewrite the preceding example as follows:

Properties

```
[email protected]@
[email protected]@
[email protected]@
```

Yaml

```
info:
app:
encoding: "@[email protected]"
java:
source: "@[email protected]"
target: "@[email protected]"
```| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#actuator.endpoints.info.git-commit-information)2.10.3. Git Commit Information #### +#### 2.10.3. 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, you can use the `info` endpoint to expose these properties. @@ -1250,7 +1103,7 @@ management: enabled: false ``` -#### [](#actuator.endpoints.info.build-information)2.10.4. Build Information #### +#### 2.10.4. Build Information If a `BuildProperties` bean is available, the `info` endpoint can also publish information about your build. This happens if a `META-INF/build-info.properties` file is available in the classpath. @@ -1258,11 +1111,11 @@ This happens if a `META-INF/build-info.properties` file is available in the clas | |The Maven and Gradle plugins can both generate that file.
See "[how to generate build information](howto.html#howto.build.generate-info)" for more details.| |---|---------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#actuator.endpoints.info.java-information)2.10.5. Java Information #### +#### 2.10.5. Java Information The `info` endpoint publishes information about your Java runtime environment, see [`JavaInfo`](https://docs.spring.io/spring-boot/docs/2.6.4/api/org/springframework/boot/info/JavaInfo.html) for more details. -#### [](#actuator.endpoints.info.writing-custom-info-contributors)2.10.6. Writing Custom InfoContributors #### +#### 2.10.6. Writing Custom InfoContributors To provide custom application information, you can register Spring beans that implement the [`InfoContributor`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoContributor.java) interface. @@ -1297,8 +1150,7 @@ If you reach the `info` endpoint, you should see a response that contains the fo } ``` -[](#actuator.monitoring)3. Monitoring and Management over HTTP ----------- +## 3. Monitoring and Management over HTTP If you are developing a web application, Spring Boot Actuator auto-configures all enabled endpoints to be exposed over HTTP. The default convention is to use the `id` of the endpoint with a prefix of `/actuator` as the URL path. @@ -1310,7 +1162,7 @@ For example, `health` is exposed as `/actuator/health`. | |Jackson is a required dependency in order to get the correct JSON responses as documented in the API documentation ([HTML](https://docs.spring.io/spring-boot/docs/2.6.4/actuator-api/htmlsingle) or [PDF](https://docs.spring.io/spring-boot/docs/2.6.4/actuator-api/pdf/spring-boot-actuator-web-api.pdf)).| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#actuator.monitoring.customizing-management-server-context-path)3.1. Customizing the Management Endpoint Paths ### +### 3.1. Customizing the Management Endpoint Paths ### Sometimes, it is useful to customize the prefix for the management endpoints. For example, your application might already use `/actuator` for another purpose. @@ -1358,7 +1210,7 @@ management: health: "healthcheck" ``` -### [](#actuator.monitoring.customizing-management-server-port)3.2. Customizing the Management Server Port ### +### 3.2. 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, you may prefer to expose endpoints by using a different HTTP port. @@ -1382,7 +1234,7 @@ management: | |On Cloud Foundry, by default, applications receive requests only on port 8080 for both HTTP and TCP routing.
If you want to use a custom management port on Cloud Foundry, you need to explicitly set up the application’s routes to forward traffic to the custom port.| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#actuator.monitoring.management-specific-ssl)3.3. Configuring Management-specific SSL ### +### 3.3. Configuring Management-specific SSL When configured to use a custom port, you can also configure the management server 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 the following property settings show: @@ -1447,7 +1299,7 @@ management: key-password: "secret" ``` -### [](#actuator.monitoring.customizing-management-server-address)3.4. Customizing the Management Server Address ### +### 3.4. Customizing the Management Server Address You can customize the address on which the management endpoints are available by setting the `management.server.address` property. Doing so can be useful if you want to listen only on an internal or ops-facing network or to listen only for connections from `localhost`. @@ -1473,7 +1325,7 @@ management: address: "127.0.0.1" ``` -### [](#actuator.monitoring.disabling-http-endpoints)3.5. Disabling HTTP Endpoints ### +### 3.5. Disabling HTTP Endpoints If you do not want to expose endpoints over HTTP, you can set the management port to `-1`, as the following example shows: @@ -1509,8 +1361,7 @@ management: exclude: "*" ``` -[](#actuator.jmx)4. Monitoring and Management over JMX ----------- +## 4. Monitoring and Management over JMX Java Management Extensions (JMX) provide a standard mechanism to monitor and manage applications. By default, this feature is not enabled. @@ -1526,7 +1377,7 @@ See the [`JmxAutoConfiguration`](https://github.com/spring-projects/spring-boot/ By default, Spring Boot also exposes management endpoints as JMX MBeans under the `org.springframework.boot` domain. To take full control over endpoint registration in the JMX domain, consider registering your own `EndpointObjectNameFactory` implementation. -### [](#actuator.jmx.custom-mbean-names)4.1. Customizing MBean Names ### +### 4.1. Customizing MBean Names 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`. @@ -1556,7 +1407,7 @@ management: domain: "com.example.myapp" ``` -### [](#actuator.jmx.disable-jmx-endpoints)4.2. Disabling JMX Endpoints ### +### 4.2. Disabling JMX Endpoints If you do not want to expose endpoints over JMX, you can set the `management.endpoints.jmx.exposure.exclude` property to `*`, as the following example shows: @@ -1576,7 +1427,7 @@ management: exclude: "*" ``` -### [](#actuator.jmx.jolokia)4.3. Using Jolokia for JMX over HTTP ### +### 4.3. Using Jolokia for JMX over HTTP Jolokia is a JMX-HTTP bridge that provides an alternative method of accessing JMX beans. To use Jolokia, include a dependency to `org.jolokia:jolokia-core`. @@ -1595,7 +1446,7 @@ You can then access it by using `/actuator/jolokia` on your management HTTP serv | |The Jolokia endpoint exposes Jolokia’s servlet as an actuator endpoint.
As a result, it is specific to servlet environments, such as Spring MVC and Jersey.
The endpoint is not available in a WebFlux application.| |---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#actuator.jmx.jolokia.customizing)4.3.1. Customizing Jolokia #### +#### 4.3.1. Customizing Jolokia 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. @@ -1617,7 +1468,7 @@ management: debug: true ``` -#### [](#actuator.jmx.jolokia.disabling)4.3.2. Disabling Jolokia #### +#### 4.3.2. Disabling Jolokia If you use Jolokia but do not want Spring Boot to configure it, set the `management.endpoint.jolokia.enabled` property to `false`, as follows: @@ -1636,8 +1487,7 @@ management: enabled: false ``` -[](#actuator.loggers)5. Loggers ----------- +## 5. Loggers Spring Boot Actuator includes the ability to view and configure the log levels of your application at runtime. You can view either the entire list or an individual logger’s configuration, which is made up of both the explicitly configured logging level as well as the effective logging level given to it by the logging framework. @@ -1661,7 +1511,7 @@ These levels can be one of: `null` indicates that there is no explicit configuration. -### [](#actuator.loggers.configure)5.1. Configure a Logger ### +### 5.1. Configure a Logger To configure a given logger, `POST` a partial entity to the resource’s URI, as the following example shows: @@ -1674,8 +1524,7 @@ To configure a given logger, `POST` a partial entity to the resource’s URI, as | |To “reset” the specific level of the logger (and use the default configuration instead), you can pass a value of `null` as the `configuredLevel`.| |---|-------------------------------------------------------------------------------------------------------------------------------------------------| -[](#actuator.metrics)6. Metrics ----------- +## 6. Metrics Spring Boot Actuator provides dependency management and auto-configuration for [Micrometer](https://micrometer.io), an application metrics facade that supports [numerous monitoring systems](https://micrometer.io/docs), including: @@ -1718,7 +1567,7 @@ Spring Boot Actuator provides dependency management and auto-configuration for [ | |To learn more about Micrometer’s capabilities, see its [reference documentation](https://micrometer.io/docs), in particular the [concepts section](https://micrometer.io/docs/concepts).| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#actuator.metrics.getting-started)6.1. Getting started ### +### 6.1. Getting started Spring Boot auto-configures a composite `MeterRegistry` and adds a registry to the composite for each of the supported implementations that it finds on the classpath. Having a dependency on `micrometer-registry-{system}` in your runtime classpath is enough for Spring Boot to configure the registry. @@ -1827,11 +1676,11 @@ public class MyMeterRegistryConfiguration { Spring Boot also [configures built-in instrumentation](#actuator.metrics.supported) that you can control through configuration or dedicated annotation markers. -### [](#actuator.metrics.export)6.2. Supported Monitoring Systems ### +### 6.2. Supported Monitoring Systems This section briefly describes each of the supported monitoring systems. -#### [](#actuator.metrics.export.appoptics)6.2.1. AppOptics #### +#### 6.2.1. AppOptics By default, the AppOptics registry periodically pushes metrics to `[api.appoptics.com/v1/measurements](https://api.appoptics.com/v1/measurements)`. To export metrics to SaaS [AppOptics](https://micrometer.io/docs/registry/appOptics), your API token must be provided: @@ -1852,7 +1701,7 @@ management: api-token: "YOUR_TOKEN" ``` -#### [](#actuator.metrics.export.atlas)6.2.2. Atlas #### +#### 6.2.2. Atlas By default, metrics are exported to [Atlas](https://micrometer.io/docs/registry/atlas) running on your local machine. You can provide the location of the [Atlas server](https://github.com/Netflix/atlas): @@ -1873,7 +1722,7 @@ management: uri: "https://atlas.example.com:7101/api/v1/publish" ``` -#### [](#actuator.metrics.export.datadog)6.2.3. Datadog #### +#### 6.2.3. Datadog A Datadog registry periodically pushes metrics to [datadoghq](https://www.datadoghq.com). To export metrics to [Datadog](https://micrometer.io/docs/registry/datadog), you must provide your API key: @@ -1912,7 +1761,7 @@ management: step: "30s" ``` -#### [](#actuator.metrics.export.dynatrace)6.2.4. Dynatrace #### +#### 6.2.4. Dynatrace Dynatrace offers two metrics ingest APIs, both of which are implemented for [Micrometer](https://micrometer.io/docs/registry/dynatrace). Configuration properties in the `v1` namespace apply only when exporting to the [Timeseries v1 API](https://www.dynatrace.com/support/help/dynatrace-api/environment-api/metric-v1/). @@ -1921,7 +1770,7 @@ Note that this integration can export only to either the `v1` or `v2` version of If the `device-id` (required for v1 but not used in v2) is set in the `v1` namespace, metrics are exported to the `v1` endpoint. Otherwise, `v2` is assumed. -##### [](#actuator.metrics.export.dynatrace.v2-api)v2 API ##### +##### v2 API You can use the v2 API in two ways. @@ -1997,7 +1846,7 @@ management: key2: "value2" ``` -##### [](#actuator.metrics.export.dynatrace.v1-api)v1 API (Legacy) ##### +##### v1 API (Legacy) The Dynatrace v1 API metrics registry pushes metrics to the configured URI periodically by using the [Timeseries v1 API](https://www.dynatrace.com/support/help/dynatrace-api/environment-api/metric-v1/). For backwards-compatibility with existing setups, when `device-id` is set (required for v1, but not used in v2), metrics are exported to the Timeseries v1 endpoint. @@ -2026,7 +1875,7 @@ management: For the v1 API, you must specify the base environment URI without a path, as the v1 endpoint path is added automatically. -##### [](#actuator.metrics.export.dynatrace.version-independent-settings)Version-independent Settings ##### +##### Version-independent Settings In addition to the API endpoint and token, you can also change the interval at which metrics are sent to Dynatrace. The default export interval is `60s`. @@ -2050,7 +1899,7 @@ management: You can find more information on how to set up the Dynatrace exporter for Micrometer in [the Micrometer documentation](https://micrometer.io/docs/registry/dynatrace). -#### [](#actuator.metrics.export.elastic)6.2.5. Elastic #### +#### 6.2.5. Elastic By default, metrics are exported to [Elastic](https://micrometer.io/docs/registry/elastic) running on your local machine. You can provide the location of the Elastic server to use by using the following property: @@ -2071,7 +1920,7 @@ management: host: "https://elastic.example.com:8086" ``` -#### [](#actuator.metrics.export.ganglia)6.2.6. Ganglia #### +#### 6.2.6. Ganglia By default, metrics are exported to [Ganglia](https://micrometer.io/docs/registry/ganglia) running on your local machine. You can provide the [Ganglia server](http://ganglia.sourceforge.net) host and port, as the following example shows: @@ -2094,7 +1943,7 @@ management: port: 9649 ``` -#### [](#actuator.metrics.export.graphite)6.2.7. Graphite #### +#### 6.2.7. Graphite By default, metrics are exported to [Graphite](https://micrometer.io/docs/registry/graphite) running on your local machine. You can provide the [Graphite server](https://graphiteapp.org) host and port, as the following example shows: @@ -2122,7 +1971,7 @@ Micrometer provides a default `HierarchicalNameMapper` that governs how a dimens | |To take control over this behavior, define your `GraphiteMeterRegistry` and supply your own `HierarchicalNameMapper`.
An auto-configured `GraphiteConfig` and `Clock` beans are provided unless you define your own:

```
import io.micrometer.core.instrument.Clock;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.config.NamingConvention;
import io.micrometer.core.instrument.util.HierarchicalNameMapper;
import io.micrometer.graphite.GraphiteConfig;
import io.micrometer.graphite.GraphiteMeterRegistry;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration(proxyBeanMethods = false)
public class MyGraphiteConfiguration {

@Bean
public GraphiteMeterRegistry graphiteMeterRegistry(GraphiteConfig config, Clock clock) {
return new GraphiteMeterRegistry(config, clock, this::toHierarchicalName);
}

private String toHierarchicalName(Meter.Id id, NamingConvention convention) {
return ...
}

}

```| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#actuator.metrics.export.humio)6.2.8. Humio #### +#### 6.2.8. Humio By default, the Humio registry periodically pushes metrics to [cloud.humio.com](https://cloud.humio.com). To export metrics to SaaS [Humio](https://micrometer.io/docs/registry/humio), you must provide your API token: @@ -2164,7 +2013,7 @@ management: bravo: "b" ``` -#### [](#actuator.metrics.export.influx)6.2.9. Influx #### +#### 6.2.9. Influx By default, metrics are exported to an [Influx](https://micrometer.io/docs/registry/influx) v1 instance running on your local machine with the default configuration. To export metrics to InfluxDB v2, configure the `org`, `bucket`, and authentication `token` for writing metrics. @@ -2186,7 +2035,7 @@ management: uri: "https://influx.example.com:8086" ``` -#### [](#actuator.metrics.export.jmx)6.2.10. JMX #### +#### 6.2.10. JMX Micrometer provides a hierarchical mapping to [JMX](https://micrometer.io/docs/registry/jmx), primarily as a cheap and portable way to view metrics locally. By default, metrics are exported to the `metrics` JMX domain. @@ -2213,7 +2062,7 @@ Micrometer provides a default `HierarchicalNameMapper` that governs how a dimens | |To take control over this behavior, define your `JmxMeterRegistry` and supply your own `HierarchicalNameMapper`.
An auto-configured `JmxConfig` and `Clock` beans are provided unless you define your own:

```
import io.micrometer.core.instrument.Clock;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.config.NamingConvention;
import io.micrometer.core.instrument.util.HierarchicalNameMapper;
import io.micrometer.jmx.JmxConfig;
import io.micrometer.jmx.JmxMeterRegistry;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration(proxyBeanMethods = false)
public class MyJmxConfiguration {

@Bean
public JmxMeterRegistry jmxMeterRegistry(JmxConfig config, Clock clock) {
return new JmxMeterRegistry(config, clock, this::toHierarchicalName);
}

private String toHierarchicalName(Meter.Id id, NamingConvention convention) {
return ...
}

}

```| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#actuator.metrics.export.kairos)6.2.11. KairosDB #### +#### 6.2.11. KairosDB By default, metrics are exported to [KairosDB](https://micrometer.io/docs/registry/kairos) running on your local machine. You can provide the location of the [KairosDB server](https://kairosdb.github.io/) to use by using: @@ -2234,7 +2083,7 @@ management: uri: "https://kairosdb.example.com:8080/api/v1/datapoints" ``` -#### [](#actuator.metrics.export.newrelic)6.2.12. New Relic #### +#### 6.2.12. New Relic A New Relic registry periodically pushes metrics to [New Relic](https://micrometer.io/docs/registry/new-relic). To export metrics to [New Relic](https://newrelic.com), you must provide your API key and account ID: @@ -2295,7 +2144,7 @@ management: Finally, you can take full control by defining your own `NewRelicClientProvider` bean. -#### [](#actuator.metrics.export.prometheus)6.2.13. Prometheus #### +#### 6.2.13. Prometheus [Prometheus](https://micrometer.io/docs/registry/prometheus) expects to scrape or poll individual application instances for metrics. Spring Boot provides an actuator endpoint at `/actuator/prometheus` to present a [Prometheus scrape](https://prometheus.io) with the appropriate format. @@ -2329,7 +2178,7 @@ This manages the pushing of metrics to a Prometheus Pushgateway. You can tune the `PrometheusPushGatewayManager` by using properties under `management.metrics.export.prometheus.pushgateway`. For advanced configuration, you can also provide your own `PrometheusPushGatewayManager` bean. -#### [](#actuator.metrics.export.signalfx)6.2.14. SignalFx #### +#### 6.2.14. SignalFx SignalFx registry periodically pushes metrics to [SignalFx](https://micrometer.io/docs/registry/signalFx). To export metrics to [SignalFx](https://www.signalfx.com), you must provide your access token: @@ -2368,7 +2217,7 @@ management: step: "30s" ``` -#### [](#actuator.metrics.export.simple)6.2.15. Simple #### +#### 6.2.15. Simple Micrometer ships with a simple, in-memory backend that is automatically used as a fallback if no other registry is configured. This lets you see what metrics are collected in the [metrics endpoint](#actuator.metrics.endpoint). @@ -2392,7 +2241,7 @@ management: enabled: false ``` -#### [](#actuator.metrics.export.stackdriver)6.2.16. Stackdriver #### +#### 6.2.16. Stackdriver The Stackdriver registry periodically pushes metrics to [Stackdriver](https://cloud.google.com/stackdriver/). To export metrics to SaaS [Stackdriver](https://micrometer.io/docs/registry/stackdriver), you must provide your Google Cloud project ID: @@ -2431,7 +2280,7 @@ management: step: "30s" ``` -#### [](#actuator.metrics.export.statsd)6.2.17. StatsD #### +#### 6.2.17. StatsD The StatsD registry eagerly pushes metrics over UDP to a StatsD agent. By default, metrics are exported to a [StatsD](https://micrometer.io/docs/registry/statsD) agent running on your local machine. @@ -2475,7 +2324,7 @@ management: flavor: "etsy" ``` -#### [](#actuator.metrics.export.wavefront)6.2.18. Wavefront #### +#### 6.2.18. Wavefront The Wavefront registry periodically pushes metrics to [Wavefront](https://micrometer.io/docs/registry/wavefront). If you are exporting metrics to [Wavefront](https://www.wavefront.com/) directly, you must provide your API token: @@ -2535,12 +2384,12 @@ management: step: "30s" ``` -### [](#actuator.metrics.supported)6.3. Supported Metrics and Meters ### +### 6.3. Supported Metrics and Meters Spring Boot provides automatic meter registration for a wide variety of technologies. In most situations, the defaults provide sensible metrics that can be published to any of the supported monitoring systems. -#### [](#actuator.metrics.supported.jvm)6.3.1. JVM Metrics #### +#### 6.3.1. JVM Metrics Auto-configuration enables JVM Metrics by using core Micrometer classes. JVM metrics are published under the `jvm.` meter name. @@ -2555,7 +2404,7 @@ The following JVM metrics are provided: * The number of classes loaded and unloaded -#### [](#actuator.metrics.supported.system)6.3.2. System Metrics #### +#### 6.3.2. System Metrics Auto-configuration enables system metrics by using core Micrometer classes. System metrics are published under the `system.`, `process.`, and `disk.` meter names. @@ -2570,7 +2419,7 @@ The following system metrics are provided: * Disk space available -#### [](#actuator.metrics.supported.application-startup)6.3.3. Application Startup Metrics #### +#### 6.3.3. Application Startup Metrics Auto-configuration exposes application startup time metrics: @@ -2580,17 +2429,17 @@ Auto-configuration exposes application startup time metrics: Metrics are tagged by the fully qualified name of the application class. -#### [](#actuator.metrics.supported.logger)6.3.4. Logger Metrics #### +#### 6.3.4. Logger Metrics Auto-configuration enables the event metrics for both Logback and Log4J2. The details are published under the `log4j2.events.` or `logback.events.` meter names. -#### [](#actuator.metrics.supported.tasks)6.3.5. Task Execution and Scheduling Metrics #### +#### 6.3.5. Task Execution and Scheduling Metrics Auto-configuration enables the instrumentation of all available `ThreadPoolTaskExecutor` and `ThreadPoolTaskScheduler` beans, as long as the underling `ThreadPoolExecutor` is available. Metrics are tagged by the name of the executor, which is derived from the bean name. -#### [](#actuator.metrics.supported.spring-mvc)6.3.6. Spring MVC Metrics #### +#### 6.3.6. Spring MVC Metrics Auto-configuration enables the instrumentation of all requests handled by Spring MVC controllers and functional handlers. By default, metrics are generated with the name, `http.server.requests`. @@ -2615,7 +2464,7 @@ To replace the default tags, provide a `@Bean` that implements `WebMvcTagsProvid | |In some cases, exceptions handled in web controllers are not recorded as request metrics tags.
Applications can opt in and record exceptions by [setting handled exceptions as request attributes](web.html#web.servlet.spring-mvc.error-handling).| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#actuator.metrics.supported.spring-webflux)6.3.7. Spring WebFlux Metrics #### +#### 6.3.7. Spring WebFlux Metrics Auto-configuration enables the instrumentation of all requests handled by Spring WebFlux controllers and functional handlers. By default, metrics are generated with the name, `http.server.requests`. @@ -2640,7 +2489,7 @@ To replace the default tags, provide a bean that implements `WebFluxTagsProvider | |In some cases, exceptions handled in controllers and handler functions are not recorded as request metrics tags.
Applications can opt in and record exceptions by [setting handled exceptions as request attributes](web.html#web.reactive.webflux.error-handling).| |---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#actuator.metrics.supported.jersey)6.3.8. Jersey Server Metrics #### +#### 6.3.8. Jersey Server Metrics Auto-configuration enables the instrumentation of all requests handled by the Jersey JAX-RS implementation. By default, metrics are generated with the name, `http.server.requests`. @@ -2661,7 +2510,7 @@ By default, Jersey server metrics are tagged with the following information: To customize the tags, provide a `@Bean` that implements `JerseyTagsProvider`. -#### [](#actuator.metrics.supported.http-clients)6.3.9. HTTP Client Metrics #### +#### 6.3.9. HTTP Client Metrics Spring Boot Actuator manages the instrumentation of both `RestTemplate` and `WebClient`. For that, you have to inject the auto-configured builder and use it to create instances: @@ -2688,14 +2537,14 @@ By default, metrics generated by an instrumented client are tagged with the foll To customize the tags, and depending on your choice of client, you can provide a `@Bean` that implements `RestTemplateExchangeTagsProvider` or `WebClientExchangeTagsProvider`. There are convenience static functions in `RestTemplateExchangeTags` and `WebClientExchangeTags`. -#### [](#actuator.metrics.supported.tomcat)6.3.10. Tomcat Metrics #### +#### 6.3.10. Tomcat Metrics Auto-configuration enables the instrumentation of Tomcat only when an `MBeanRegistry` is enabled. By default, the `MBeanRegistry` is disabled, but you can enable it by setting `server.tomcat.mbeanregistry.enabled` to `true`. Tomcat metrics are published under the `tomcat.` meter name. -#### [](#actuator.metrics.supported.cache)6.3.11. Cache Metrics #### +#### 6.3.11. Cache Metrics Auto-configuration enables the instrumentation of all available `Cache` instances on startup, with metrics prefixed with `cache`. Cache instrumentation is standardized for a basic set of metrics. @@ -2718,7 +2567,7 @@ Metrics are tagged by the name of the cache and by the name of the `CacheManager | |Only caches that are configured on startup are bound to the registry.
For caches not defined in the cache’s configuration, such as caches created on the fly or programmatically after the startup phase, an explicit registration is required.
A `CacheMetricsRegistrar` bean is made available to make that process easier.| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#actuator.metrics.supported.jdbc)6.3.12. DataSource Metrics #### +#### 6.3.12. DataSource Metrics Auto-configuration enables the instrumentation of all available `DataSource` objects with metrics prefixed with `jdbc.connections`. Data source instrumentation results in gauges that represent the currently active, idle, maximum allowed, and minimum allowed connections in the pool. @@ -2731,7 +2580,7 @@ Metrics are also tagged by the name of the `DataSource` computed based on the be Also, Hikari-specific metrics are exposed with a `hikaricp` prefix. Each metric is tagged by the name of the pool (you can control it with `spring.datasource.name`). -#### [](#actuator.metrics.supported.hibernate)6.3.13. Hibernate Metrics #### +#### 6.3.13. Hibernate Metrics If `org.hibernate:hibernate-micrometer` is on the classpath, all available Hibernate `EntityManagerFactory` instances that have statistics enabled are instrumented with a metric named `hibernate`. @@ -2755,7 +2604,7 @@ spring: "[hibernate.generate_statistics]": true ``` -#### [](#actuator.metrics.supported.spring-data-repository)6.3.14. Spring Data Repository Metrics #### +#### 6.3.14. Spring Data Repository Metrics Auto-configuration enables the instrumentation of all Spring Data `Repository` method invocations. By default, metrics are generated with the name, `spring.data.repository.invocations`. @@ -2775,26 +2624,26 @@ By default, repository invocation related metrics are tagged with the following To replace the default tags, provide a `@Bean` that implements `RepositoryTagsProvider`. -#### [](#actuator.metrics.supported.rabbitmq)6.3.15. RabbitMQ Metrics #### +#### 6.3.15. RabbitMQ Metrics Auto-configuration enables the instrumentation of all available RabbitMQ connection factories with a metric named `rabbitmq`. -#### [](#actuator.metrics.supported.spring-integration)6.3.16. Spring Integration Metrics #### +#### 6.3.16. Spring Integration Metrics Spring Integration automatically provides [Micrometer support](https://docs.spring.io/spring-integration/docs/5.5.9/reference/html/system-management.html#micrometer-integration) whenever a `MeterRegistry` bean is available. Metrics are published under the `spring.integration.` meter name. -#### [](#actuator.metrics.supported.kafka)6.3.17. Kafka Metrics #### +#### 6.3.17. Kafka Metrics Auto-configuration registers a `MicrometerConsumerListener` and `MicrometerProducerListener` for the auto-configured consumer factory and producer factory, respectively. It also registers a `KafkaStreamsMicrometerListener` for `StreamsBuilderFactoryBean`. For more detail, see the [Micrometer Native Metrics](https://docs.spring.io/spring-kafka/docs/2.8.3/reference/html/#micrometer-native) section of the Spring Kafka documentation. -#### [](#actuator.metrics.supported.mongodb)6.3.18. MongoDB Metrics #### +#### 6.3.18. MongoDB Metrics This section briefly describes the available metrics for MongoDB. -##### [](#actuator.metrics.supported.mongodb.command)MongoDB Command Metrics ##### +##### MongoDB Command Metrics Auto-configuration registers a `MongoMetricsCommandListener` with the auto-configured `MongoClient`. @@ -2846,7 +2695,7 @@ management: enabled: false ``` -##### [](#actuator.metrics.supported.mongodb.connection-pool)MongoDB Connection Pool Metrics ##### +##### MongoDB Connection Pool Metrics Auto-configuration registers a `MongoMetricsConnectionPoolListener` with the auto-configured `MongoClient`. @@ -2903,12 +2752,12 @@ management: enabled: false ``` -#### [](#actuator.metrics.supported.jetty)6.3.19. Jetty Metrics #### +#### 6.3.19. Jetty Metrics Auto-configuration binds metrics for Jetty’s `ThreadPool` by using Micrometer’s `JettyServerThreadPoolMetrics`. Metrics for Jetty’s `Connector` instances are bound by using Micrometer’s `JettyConnectionMetrics` and, when `server.ssl.enabled` is set to `true`, Micrometer’s `JettySslHandshakeMetrics`. -#### [](#actuator.metrics.supported.timed-annotation)6.3.20. @Timed Annotation Support #### +#### 6.3.20. @Timed Annotation Support You can use the `@Timed` annotation from the `io.micrometer.core.annotation` package with several of the supported technologies described earlier. If supported, you can use the annotation at either the class level or the method level. @@ -3002,12 +2851,12 @@ public class MyController { | |A `@Timed` annotation with `longTask = true` enables a long task timer for the method.
Long task timers require a separate metric name and can be stacked with a short task timer.| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#actuator.metrics.supported.redis)6.3.21. Redis Metrics #### +#### 6.3.21. Redis Metrics Auto-configuration registers a `MicrometerCommandLatencyRecorder` for the auto-configured `LettuceConnectionFactory`. For more detail, see the [Micrometer Metrics section](https://lettuce.io/core/6.1.6.RELEASE/reference/index.html#command.latency.metrics.micrometer) of the Lettuce documentation. -### [](#actuator.metrics.registering-custom)6.4. Registering Custom Metrics ### +### 6.4. Registering Custom Metrics To register custom metrics, inject `MeterRegistry` into your component: @@ -3056,7 +2905,7 @@ A `MeterBinder` implementation can also be useful if you find that you repeatedl | |By default, metrics from all `MeterBinder` beans are automatically bound to the Spring-managed `MeterRegistry`.| |---|---------------------------------------------------------------------------------------------------------------| -### [](#actuator.metrics.customizing)6.5. Customizing Individual Metrics ### +### 6.5. Customizing Individual Metrics If you need to apply customizations to specific `Meter` instances, you can use the `io.micrometer.core.instrument.config.MeterFilter` interface. @@ -3083,7 +2932,7 @@ public class MyMetricsFilterConfiguration { | |By default, all `MeterFilter` beans are automatically bound to the Spring-managed `MeterRegistry`.
Make sure to register your metrics by using the Spring-managed `MeterRegistry` and not any of the static methods on `Metrics`.
These use the global registry that is not Spring-managed.| |---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#actuator.metrics.customizing.common-tags)6.5.1. Common Tags #### +#### 6.5.1. Common Tags Common tags are generally used for dimensional drill-down on the operating environment, such as host, instance, region, stack, and others. Commons tags are applied to all meters and can be configured, as the following example shows: @@ -3110,7 +2959,7 @@ The preceding example adds `region` and `stack` tags to all meters with a value | |The order of common tags is important if you use Graphite.
As the order of common tags cannot be guaranteed by using this approach, Graphite users are advised to define a custom `MeterFilter` instead.| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#actuator.metrics.customizing.per-meter-properties)6.5.2. Per-meter Properties #### +#### 6.5.2. Per-meter Properties In addition to `MeterFilter` beans, you can apply a limited set of customization on a per-meter basis by using properties. Per-meter customizations apply to any meter IDs that start with the given name. @@ -3145,7 +2994,7 @@ The following properties allow per-meter customization: For more details on the concepts behind `percentiles-histogram`, `percentiles`, and `slo`, see the [“Histograms and percentiles” section](https://micrometer.io/docs/concepts#_histograms_and_percentiles) of the Micrometer documentation. -### [](#actuator.metrics.endpoint)6.6. Metrics Endpoint ### +### 6.6. Metrics Endpoint Spring Boot provides a `metrics` endpoint that you can use diagnostically to examine the metrics collected by an application. The endpoint is not available by default and must be exposed. See [exposing endpoints](#actuator.endpoints.exposing) for more details. @@ -3161,8 +3010,7 @@ You can also add any number of `tag=KEY:VALUE` query parameters to the end of th | |The reported measurements are the *sum* of the statistics of all meters that match the meter name and any tags that have been applied.
In the preceding example, the returned `Value` statistic is the sum of the maximum memory footprints of the “Code Cache”, “Compressed Class Space”, and “Metaspace” areas of the heap.
If you wanted to see only the maximum size for the “Metaspace”, you could add an additional `tag=id:Metaspace` — that is, `/actuator/metrics/jvm.memory.max?tag=area:nonheap&tag=id:Metaspace`.| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -[](#actuator.auditing)7. Auditing ----------- +## 7. 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 implementing a lock-out policy based on authentication failures. @@ -3171,15 +3019,14 @@ You can enable auditing by providing a bean of type `AuditEventRepository` in yo For convenience, Spring Boot offers an `InMemoryAuditEventRepository`.`InMemoryAuditEventRepository` has limited capabilities, and we recommend using it only for development environments. For production environments, consider creating your own alternative `AuditEventRepository` implementation. -### [](#actuator.auditing.custom)7.1. Custom Auditing ### +### 7.1. Custom Auditing To customize published security events, you can provide your own implementations of `AbstractAuthenticationAuditListener` and `AbstractAuthorizationAuditListener`. You can also use the audit services for your own business events. To do so, either inject the `AuditEventRepository` bean into your own components and use that directly or publish an `AuditApplicationEvent` with the Spring `ApplicationEventPublisher` (by implementing `ApplicationEventPublisherAware`). -[](#actuator.tracing)8. HTTP Tracing ----------- +## 8. HTTP Tracing You can enable HTTP Tracing by providing a bean of type `HttpTraceRepository` in your application’s configuration. For convenience, Spring Boot offers `InMemoryHttpTraceRepository`, which stores traces for the last 100 (the default) request-response exchanges.`InMemoryHttpTraceRepository` is limited compared to other tracing solutions, and we recommend using it only for development environments. @@ -3188,13 +3035,12 @@ Alternatively, you can create your own `HttpTraceRepository`. You can use the `httptrace` endpoint to obtain information about the request-response exchanges that are stored in the `HttpTraceRepository`. -### [](#actuator.tracing.custom)8.1. Custom HTTP tracing ### +### 8.1. Custom HTTP tracing To customize the items that are included in each trace, use the `management.trace.http.include` configuration property. For advanced customization, consider registering your own `HttpExchangeTracer` implementation. -[](#actuator.process-monitoring)9. Process Monitoring ----------- +## 9. Process Monitoring In the `spring-boot` module, you can find two classes to create files that are often useful for process monitoring: @@ -3208,7 +3054,7 @@ By default, these writers are not activated, but you can enable them: * [Programmatically Enabling Process Monitoring](#actuator.process-monitoring.programmatically) -### [](#actuator.process-monitoring.configuration)9.1. Extending Configuration ### +### 9.1. Extending Configuration In the `META-INF/spring.factories` file, you can activate the listener (or listeners) that writes a PID file: @@ -3218,13 +3064,12 @@ org.springframework.boot.context.ApplicationPidFileWriter,\ org.springframework.boot.web.context.WebServerPortFileWriter ``` -### [](#actuator.process-monitoring.programmatically)9.2. Programmatically Enabling Process Monitoring ### +### 9.2. Programmatically Enabling Process Monitoring You can also activate a listener by invoking the `SpringApplication.addListeners(…​)` method and passing the appropriate `Writer` object. This method also lets you customize the file name and path in the `Writer` constructor. -[](#actuator.cloud-foundry)10. Cloud Foundry Support ----------- +## 10. Cloud Foundry Support Spring Boot’s actuator module includes additional support that is activated when you deploy to a compatible Cloud Foundry instance. The `/cloudfoundryapplication` path provides an alternative secured route to all `@Endpoint` beans. @@ -3235,7 +3080,7 @@ For example, an application status page can include full health information inst | |The `/cloudfoundryapplication` path is not directly accessible to regular users.
To use the endpoint, you must pass a valid UAA token with the request.| |---|-----------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#actuator.cloud-foundry.disable)10.1. Disabling Extended Cloud Foundry Actuator Support ### +### 10.1. Disabling Extended Cloud Foundry Actuator Support If you want to fully disable the `/cloudfoundryapplication` endpoints, you can add the following setting to your `application.properties` file: @@ -3253,7 +3098,7 @@ management: enabled: false ``` -### [](#actuator.cloud-foundry.ssl)10.2. Cloud Foundry Self-signed Certificates ### +### 10.2. Cloud Foundry Self-signed Certificates By default, the security verification for `/cloudfoundryapplication` endpoints makes SSL calls to various Cloud Foundry services. If your Cloud Foundry UAA or Cloud Controller services use self-signed certificates, you need to set the following property: @@ -3272,7 +3117,7 @@ management: skip-ssl-validation: true ``` -### [](#actuator.cloud-foundry.custom-context-path)10.3. Custom Context Path ### +### 10.3. Custom Context Path If the server’s context-path has been configured to anything other than `/`, the Cloud Foundry endpoints are not available at the root of the application. For example, if `server.servlet.context-path=/app`, Cloud Foundry endpoints are available at `/app/cloudfoundryapplication/*`. @@ -3343,10 +3188,8 @@ public class MyCloudFoundryConfiguration { ``` -[](#actuator.whats-next)11. What to Read Next ----------- +## 11. What to Read Next You might want to read about graphing tools such as [Graphite](https://graphiteapp.org). Otherwise, you can continue on to read about [“deployment options”](deployment.html#deployment) or jump ahead for some in-depth information about Spring Boot’s [build tool plugins](build-tool-plugins.html#build-tool-plugins). - diff --git a/docs/en/spring-boot/build-tool-plugins.md b/docs/en/spring-boot/build-tool-plugins.md index 9e8730d8a361ba95dea5a02a0e18abb78122eb90..f9c149e17afb9986c3a75dae1d757f46e608c726 100644 --- a/docs/en/spring-boot/build-tool-plugins.md +++ b/docs/en/spring-boot/build-tool-plugins.md @@ -1,35 +1,11 @@ -Build Tool Plugins -========== - -Table of Contents - -[Back to index](index.html) - -* [1. Spring Boot Maven Plugin](#build-tool-plugins.maven) -* [2. Spring Boot Gradle Plugin](#build-tool-plugins.gradle) -* [3. Spring Boot AntLib Module](#build-tool-plugins.antlib) - * [3.1. Spring Boot Ant Tasks](#build-tool-plugins.antlib.tasks) - * [3.1.1. Using the “exejar” Task](#build-tool-plugins.antlib.tasks.exejar) - * [3.1.2. Examples](#build-tool-plugins.antlib.tasks.examples) - - * [3.2. Using the “findmainclass” Task](#build-tool-plugins.antlib.findmainclass) - * [3.2.1. Examples](#build-tool-plugins.antlib.findmainclass.examples) - -* [4. Supporting Other Build Systems](#build-tool-plugins.other-build-systems) - * [4.1. Repackaging Archives](#build-tool-plugins.other-build-systems.repackaging-archives) - * [4.2. Nested Libraries](#build-tool-plugins.other-build-systems.nested-libraries) - * [4.3. Finding a Main Class](#build-tool-plugins.other-build-systems.finding-main-class) - * [4.4. Example Repackage Implementation](#build-tool-plugins.other-build-systems.example-repackage-implementation) - -* [5. What to Read Next](#build-tool-plugins.whats-next) +# 1. Build Tool Plugins Spring Boot provides build tool plugins for Maven and Gradle. The plugins offer a variety of features, including the packaging of executable jars. This section provides more details on both plugins as well as some help should you need to extend an unsupported build system. If you are just getting started, you might want to read “[using.html](using.html#using.build-systems)” from the “[using.html](using.html#using)” section first. -[](#build-tool-plugins.maven)1. Spring Boot Maven Plugin ----------- +## 1.1 Spring Boot Maven Plugin The Spring Boot Maven Plugin provides Spring Boot support in Maven, letting you package executable jar or war archives and run an application “in-place”. To use it, you must use Maven 3.2 (or later). @@ -40,8 +16,7 @@ See the plugin’s documentation to learn more: * [API](https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/api/) -[](#build-tool-plugins.gradle)2. Spring Boot Gradle Plugin ----------- +## 1.2. Spring Boot Gradle Plugin The Spring Boot Gradle Plugin provides Spring Boot support in Gradle, letting you package executable jar or war archives, run Spring Boot applications, and use the dependency management provided by `spring-boot-dependencies`. It requires Gradle 6.8, 6.9, or 7.x. @@ -51,8 +26,7 @@ See the plugin’s documentation to learn more: * [API](https://docs.spring.io/spring-boot/docs/2.6.4/gradle-plugin/api/) -[](#build-tool-plugins.antlib)3. Spring Boot AntLib Module ----------- +## 3. Spring Boot AntLib Module The Spring Boot AntLib module provides basic Spring Boot support for Apache Ant. You can use the module to create executable jars. @@ -72,10 +46,9 @@ You need to remember to start Ant using the `-lib` option, as shown in the follo $ ant -lib ``` -| |The “Using Spring Boot” section includes a more complete example of [using Apache Ant with `spring-boot-antlib`](using.html#using.build-systems.ant).| -|---|-----------------------------------------------------------------------------------------------------------------------------------------------------| +> The “Using Spring Boot” section includes a more complete example of [using Apache Ant with `spring-boot-antlib`](using.html#using.build-systems.ant). -### [](#build-tool-plugins.antlib.tasks)3.1. Spring Boot Ant Tasks ### +### 3.1. Spring Boot Ant Tasks Once the `spring-boot-antlib` namespace has been declared, the following additional tasks are available: @@ -83,7 +56,7 @@ Once the `spring-boot-antlib` namespace has been declared, the following additio * [Using the “findmainclass” Task](#build-tool-plugins.antlib.findmainclass) -#### [](#build-tool-plugins.antlib.tasks.exejar)3.1.1. Using the “exejar” Task #### +#### 3.1.1. Using the “exejar” Task You can use the `exejar` task to create a Spring Boot executable jar. The following attributes are supported by the task: @@ -101,7 +74,7 @@ The following nested elements can be used with the task: |`resources`|One or more [Resource Collections](https://ant.apache.org/manual/Types/resources.html#collection) describing a set of [Resources](https://ant.apache.org/manual/Types/resources.html) that should be added to the content of the created jar file.| | `lib` | One or more [Resource Collections](https://ant.apache.org/manual/Types/resources.html#collection) that should be added to the set of jar libraries that make up the runtime dependency classpath of the application. | -#### [](#build-tool-plugins.antlib.tasks.examples)3.1.2. Examples #### +#### 3.1.2. Examples This section shows two examples of Ant tasks. @@ -129,7 +102,7 @@ Detect start-class ``` -### [](#build-tool-plugins.antlib.findmainclass)3.2. Using the “findmainclass” Task ### +### 3.2. Using the “findmainclass” Task The `findmainclass` task is used internally by `exejar` to locate a class declaring a `main`. If necessary, you can also use this task directly in your build. @@ -141,7 +114,7 @@ The following attributes are supported: | `mainclass` |Can be used to short-circuit the `main` class search| No | | `property` |The Ant property that should be set with the result |No *(result will be logged if unspecified)*| -#### [](#build-tool-plugins.antlib.findmainclass.examples)3.2.1. Examples #### +#### 3.2.1. Examples This section contains three examples of using `findmainclass`. @@ -163,8 +136,7 @@ Override and set ``` -[](#build-tool-plugins.other-build-systems)4. Supporting Other Build Systems ----------- +## 4. Supporting Other Build Systems If you want to use a build tool other than Maven, Gradle, or Ant, you likely need to develop your own plugin. Executable jars need to follow a specific format and certain entries need to be written in an uncompressed form (see the “[executable jar format](executable-jar.html#appendix.executable-jar)” section in the appendix for details). @@ -172,26 +144,26 @@ Executable jars need to follow a specific format and certain entries need to be The Spring Boot Maven and Gradle plugins both make use of `spring-boot-loader-tools` to actually generate jars. If you need to, you may use this library directly. -### [](#build-tool-plugins.other-build-systems.repackaging-archives)4.1. Repackaging Archives ### +### 4.1. Repackaging Archives To repackage an existing archive so that it becomes a self-contained executable archive, use `org.springframework.boot.loader.tools.Repackager`. The `Repackager` class takes a single constructor argument that refers to an existing jar or war archive. Use one of the two available `repackage()` methods to either replace the original file or write to a new destination. Various settings can also be configured on the repackager before it is run. -### [](#build-tool-plugins.other-build-systems.nested-libraries)4.2. Nested Libraries ### +### 4.2. Nested Libraries When repackaging an archive, you can include references to dependency files by using the `org.springframework.boot.loader.tools.Libraries` interface. We do not provide any concrete implementations of `Libraries` here as they are usually build-system-specific. If your archive already includes libraries, you can use `Libraries.NONE`. -### [](#build-tool-plugins.other-build-systems.finding-main-class)4.3. Finding a Main Class ### +### 4.3. Finding a Main Class If you do not use `Repackager.setMainClass()` to specify a main class, the repackager uses [ASM](https://asm.ow2.io/) to read class files and tries to find a suitable class with a `public static void main(String[] args)` method. An exception is thrown if more than one candidate is found. -### [](#build-tool-plugins.other-build-systems.example-repackage-implementation)4.4. Example Repackage Implementation ### +### 4.4. Example Repackage Implementation The following example shows a typical repackage implementation: @@ -230,8 +202,7 @@ public class MyBuildTool { ``` -[](#build-tool-plugins.whats-next)5. What to Read Next ----------- +## 5. What to Read Next If you are interested in how the build tool plugins work, you can look at the [`spring-boot-tools`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-tools) module on GitHub. More technical details of the executable jar format are covered in [the appendix](executable-jar.html#appendix.executable-jar). diff --git a/docs/en/spring-boot/cli.md b/docs/en/spring-boot/cli.md index 73e2c0f29f0bd70d7776606f6e64b926762a07bd..793151dc468fdb5107765fcf82d0de4181ea1694 100644 --- a/docs/en/spring-boot/cli.md +++ b/docs/en/spring-boot/cli.md @@ -1,41 +1,15 @@ -Spring Boot CLI -========== - -Table of Contents - -[Back to index](index.html) - -* [1. Installing the CLI](#cli.installation) -* [2. Using the CLI](#cli.using-the-cli) - * [2.1. Running Applications with the CLI](#cli.using-the-cli.run) - * [2.1.1. Deduced “grab” Dependencies](#cli.using-the-cli.run.deduced-grab-annotations) - * [2.1.2. Deduced “grab” Coordinates](#cli.using-the-cli.run.deduced-grab-coordinates) - * [2.1.3. Default Import Statements](#cli.using-the-cli.run.default-import-statements) - * [2.1.4. Automatic Main Method](#cli.using-the-cli.run.automatic-main-method) - * [2.1.5. Custom Dependency Management](#cli.using-the-cli.run.custom-dependency-management) - - * [2.2. Applications with Multiple Source Files](#cli.using-the-cli.multiple-source-files) - * [2.3. Packaging Your Application](#cli.using-the-cli.packaging) - * [2.4. Initialize a New Project](#cli.using-the-cli.initialize-new-project) - * [2.5. Using the Embedded Shell](#cli.using-the-cli.embedded-shell) - * [2.6. Adding Extensions to the CLI](#cli.using-the-cli.extensions) - -* [3. Developing Applications with the Groovy Beans DSL](#cli.groovy-beans-dsl) -* [4. Configuring the CLI with settings.xml](#cli.maven-setting) -* [5. What to Read Next](#cli.whats-next) +# Spring Boot CLI The Spring Boot CLI is a command line tool that you can use if you want to quickly develop a Spring application. It lets you run Groovy scripts, which means that you have a familiar Java-like syntax without so much boilerplate code. You can also bootstrap a new project or write your own command for it. -[](#cli.installation)1. Installing the CLI ----------- +## 1. Installing the CLI The Spring Boot CLI (Command-Line Interface) can be installed manually by using SDKMAN! (the SDK Manager) or by using Homebrew or MacPorts if you are an OSX user. See *[getting-started.html](getting-started.html#getting-started.installing.cli)* in the “Getting started” section for comprehensive installation instructions. -[](#cli.using-the-cli)2. Using the CLI ----------- +## 2. Using the CLI Once you have installed the CLI, you can run it by typing `spring` and pressing Enter at the command line. If you run `spring` without any arguments, a help screen is displayed, as follows: @@ -81,7 +55,7 @@ $ spring version Spring CLI v2.6.4 ``` -### [](#cli.using-the-cli.run)2.1. Running Applications with the CLI ### +### 2.1. 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 do not need any external Groovy installation. @@ -124,7 +98,7 @@ $ JAVA_OPTS=-Xmx1024m spring run hello.groovy | |When setting `JAVA_OPTS` on Microsoft Windows, make sure to quote the entire instruction, such as `set "JAVA_OPTS=-Xms256m -Xmx2048m"`.
Doing so ensures the values are properly passed to the process.| |---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#cli.using-the-cli.run.deduced-grab-annotations)2.1.1. Deduced “grab” Dependencies #### +#### 2.1.1. Deduced “grab” Dependencies Standard Groovy includes a `@Grab` annotation, which lets you declare dependencies on third-party libraries. This useful technique lets Groovy download jars in the same way as Maven or Gradle would but without requiring you to use a build tool. @@ -151,7 +125,7 @@ The following items are used as “grab hints”: | |See subclasses of [`CompilerAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/CompilerAutoConfiguration.java) in the Spring Boot CLI source code to understand exactly how customizations are applied.| |---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#cli.using-the-cli.run.deduced-grab-coordinates)2.1.2. Deduced “grab” Coordinates #### +#### 2.1.2. 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. @@ -159,7 +133,7 @@ Doing so consults Spring Boot’s default dependency metadata to deduce the arti | |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 [appendix](dependency-versions.html#appendix.dependency-versions).| |---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#cli.using-the-cli.run.default-import-statements)2.1.3. Default Import Statements #### +#### 2.1.3. Default Import Statements To help reduce the size of your Groovy code, several `import` statements are automatically included. Notice how the preceding example refers to `@Component`, `@RestController`, and `@RequestMapping` without needing to use fully-qualified names or `import` statements. @@ -167,12 +141,12 @@ Notice how the preceding example refers to `@Component`, `@RestController`, and | |Many Spring annotations work without using `import` statements.
Try running your application to see what fails before adding imports.| |---|-----------------------------------------------------------------------------------------------------------------------------------------| -#### [](#cli.using-the-cli.run.automatic-main-method)2.1.4. Automatic Main Method #### +#### 2.1.4. Automatic Main Method Unlike the equivalent Java application, you do not need to include a `public static void main(String[] args)` method with your `Groovy` scripts. A `SpringApplication` is automatically created, with your compiled code acting as the `source`. -#### [](#cli.using-the-cli.run.custom-dependency-management)2.1.5. Custom Dependency Management #### +#### 2.1.5. Custom Dependency Management By default, the CLI uses the dependency management declared in `spring-boot-dependencies` when resolving `@Grab` dependencies. Additional dependency management, which overrides the default dependency management, can be configured by using the `@DependencyManagementBom` annotation. @@ -201,7 +175,7 @@ The preceding example indicates that the dependency management in `another-bom` You can use `@DependencyManagementBom` anywhere that you can use `@Grab`. However, to ensure consistent ordering of the dependency management, you can use `@DependencyManagementBom` at most once in your application. -### [](#cli.using-the-cli.multiple-source-files)2.2. Applications with Multiple Source Files ### +### 2.2. Applications with Multiple Source Files You can use “shell globbing” with all commands that accept file input. Doing so lets you use multiple files from a single directory, as shown in the following example: @@ -210,7 +184,7 @@ Doing so lets you use multiple files from a single directory, as shown in the fo $ spring run *.groovy ``` -### [](#cli.using-the-cli.packaging)2.3. Packaging Your Application ### +### 2.3. Packaging Your Application You can use the `jar` command to package your application into a self-contained executable jar file, as shown in the following example: @@ -236,7 +210,7 @@ The default excludes are as follows: Type `spring help jar` on the command line for more information. -### [](#cli.using-the-cli.initialize-new-project)2.4. Initialize a New Project ### +### 2.4. Initialize a New Project The `init` command lets you create a new project by using [start.spring.io](https://start.spring.io) without leaving the shell, as shown in the following example: @@ -283,7 +257,7 @@ Using service at https://start.spring.io Content saved to 'sample-app.zip' ``` -### [](#cli.using-the-cli.embedded-shell)2.5. Using the Embedded Shell ### +### 2.5. Using the Embedded Shell Spring Boot includes command-line completion scripts for the BASH and zsh shells. If you do not use either of these shells (perhaps you are a Windows user), you can use the `shell` command to launch an integrated shell, as shown in the following example: @@ -305,7 +279,7 @@ The embedded shell supports ANSI color output as well as `tab` completion. If you need to run a native command, you can use the `!` prefix. To exit the embedded shell, press `ctrl-c`. -### [](#cli.using-the-cli.extensions)2.6. Adding Extensions to the CLI ### +### 2.6. Adding Extensions to the CLI 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: @@ -331,8 +305,7 @@ To uninstall all additional dependencies, you can use the `--all` option, as sho $ spring uninstall --all ``` -[](#cli.groovy-beans-dsl)3. Developing Applications with the Groovy Beans DSL ----------- +## 3. Developing Applications with the Groovy Beans DSL Spring Framework 4.0 has native support for a `beans{}` “DSL” (borrowed from [Grails](https://grails.org/)), 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: @@ -363,8 +336,7 @@ beans { You can mix class declarations with `beans{}` in the same file as long as they stay at the top level, or, if you prefer, you can put the beans DSL in a separate file. -[](#cli.maven-setting)4. Configuring the CLI with settings.xml ----------- +## 4. Configuring the CLI with settings.xml The Spring Boot CLI uses Maven Resolver, Maven’s dependency resolution engine, to resolve dependencies. The CLI makes use of the Maven configuration found in `~/.m2/settings.xml` to configure Maven Resolver. @@ -388,8 +360,7 @@ The following configuration settings are honored by the CLI: See [Maven’s settings documentation](https://maven.apache.org/settings.html) for further information. -[](#cli.whats-next)5. What to Read Next ----------- +## 5. What to Read Next There are some [sample groovy scripts](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-cli/samples) available from the GitHub repository that you can use to try out the Spring Boot CLI. There is also extensive Javadoc throughout the [source code](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli). diff --git a/docs/en/spring-boot/container-images.md b/docs/en/spring-boot/container-images.md index 642d27aec491810007ab3deceab42baef554577a..031a04bb6fa9cba450a65467e1d5553dce5d1742 100644 --- a/docs/en/spring-boot/container-images.md +++ b/docs/en/spring-boot/container-images.md @@ -1,22 +1,9 @@ -Container Images -========== - -Table of Contents - -[Back to index](index.html) - -* [1. Efficient container images](#container-images.efficient-images) - * [1.1. Unpacking the fat jar](#container-images.efficient-images.unpacking) - * [1.2. Layering Docker Images](#container-images.efficient-images.layering) - -* [2. Dockerfiles](#container-images.dockerfiles) -* [3. Cloud Native Buildpacks](#container-images.buildpacks) -* [4. What to Read Next](#container-images.whats-next) +# Container Images Spring Boot applications can be containerized [using Dockerfiles](#container-images.dockerfiles), or by [using Cloud Native Buildpacks to create optimized docker compatible container images that you can run anywhere](#container-images.buildpacks). -[](#container-images.efficient-images)1. Efficient container images ----------- +## 1. Efficient container images + It is easily possible to package a Spring Boot fat jar as a docker image. However, there are various downsides to copying and running the fat jar as is in the docker image. @@ -25,7 +12,7 @@ The other issue is that putting your application’s code and all its dependenci Since you probably recompile your code more often than you upgrade the version of Spring Boot you use, it’s often better to separate things a bit more. If you put jar files in the layer before your application classes, Docker often only needs to change the very bottom layer and can pick others up from its cache. -### [](#container-images.efficient-images.unpacking)1.1. Unpacking the fat jar ### +### 1.1. Unpacking the fat jar If you are running your application from a container, you can use an executable jar, but it is also often an advantage to explode it and run it in a different way. Certain PaaS implementations may also choose to unpack archives before they run. @@ -50,7 +37,7 @@ $ java -cp BOOT-INF/classes:BOOT-INF/lib/* com.example.MyApplication | |Using the `JarLauncher` over the application’s main method has the added benefit of a predictable classpath order.
The jar contains a `classpath.idx` file which is used by the `JarLauncher` when constructing the classpath.| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#container-images.efficient-images.layering)1.2. Layering Docker Images ### +### 1.2. Layering Docker Images To make it easier to create optimized Docker images, Spring Boot supports adding a layer index file to the jar. It provides a list of layers and the parts of the jar that should be contained within them. @@ -90,8 +77,7 @@ Spring Boot also supports layering for war files with the help of a `layers.idx` For Maven, see the [packaging layered jar or war section](https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/reference/htmlsingle/#repackage-layers) for more details on adding a layer index to the archive. For Gradle, see the [packaging layered jar or war section](https://docs.spring.io/spring-boot/docs/2.6.4/gradle-plugin/reference/htmlsingle/#packaging-layered-archives) of the Gradle plugin documentation. -[](#container-images.dockerfiles)2. Dockerfiles ----------- +## 2. Dockerfiles While it is possible to convert a Spring Boot fat jar into a docker image with just a few lines in the Dockerfile, we will use the [layering feature](#container-images.efficient-images.layering) to create an optimized docker image. When you create a jar containing the layers index file, the `spring-boot-jarmode-layertools` jar will be added as a dependency to your jar. @@ -150,8 +136,7 @@ Each of the `COPY` commands relates to the layers extracted by the jarmode. Of course, a Dockerfile can be written without using the jarmode. You can use some combination of `unzip` and `mv` to move things to the right layer but jarmode simplifies that. -[](#container-images.buildpacks)3. Cloud Native Buildpacks ----------- +## 3. Cloud Native Buildpacks Dockerfiles are just one way to build docker images. Another way to build docker images is directly from your Maven or Gradle plugin, using buildpacks. @@ -171,8 +156,7 @@ See the individual plugin documentation on how to use buildpacks with [Maven](ht | |In order to achieve reproducible builds and container image caching, Buildpacks can manipulate the application resources metadata (such as the file "last modified" information).
You should ensure that your application does not rely on that metadata at runtime.
Spring Boot can use that information when serving static resources, but this can be disabled with `spring.web.resources.cache.use-last-modified`| |---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -[](#container-images.whats-next)4. What to Read Next ----------- +## 4. What to Read Next Once you’ve learned how to build efficient container images, you can read about [deploying applications to a cloud platform](deployment.html#deployment.cloud.kubernetes), such as Kubernetes. diff --git a/docs/en/spring-boot/data.md b/docs/en/spring-boot/data.md index 19923d60f2b7dad24ee3a87c646a9bb31051fcdf..0b1d803f8ab10b181a4511450d15bd93fd56fa03 100644 --- a/docs/en/spring-boot/data.md +++ b/docs/en/spring-boot/data.md @@ -1,92 +1,13 @@ -Data -========== - -Table of Contents - -[Back to index](index.html) - -* [1. SQL Databases](#data.sql) - * [1.1. Configure a DataSource](#data.sql.datasource) - * [1.1.1. Embedded Database Support](#data.sql.datasource.embedded) - * [1.1.2. Connection to a Production Database](#data.sql.datasource.production) - * [1.1.3. DataSource Configuration](#data.sql.datasource.configuration) - * [1.1.4. Supported Connection Pools](#data.sql.datasource.connection-pool) - * [1.1.5. Connection to a JNDI DataSource](#data.sql.datasource.jndi) - - * [1.2. Using JdbcTemplate](#data.sql.jdbc-template) - * [1.3. JPA and Spring Data JPA](#data.sql.jpa-and-spring-data) - * [1.3.1. Entity Classes](#data.sql.jpa-and-spring-data.entity-classes) - * [1.3.2. Spring Data JPA Repositories](#data.sql.jpa-and-spring-data.repositories) - * [1.3.3. Spring Data Envers Repositories](#data.sql.jpa-and-spring-data.envers-repositories) - * [1.3.4. Creating and Dropping JPA Databases](#data.sql.jpa-and-spring-data.creating-and-dropping) - * [1.3.5. Open EntityManager in View](#data.sql.jpa-and-spring-data.open-entity-manager-in-view) - - * [1.4. Spring Data JDBC](#data.sql.jdbc) - * [1.5. Using H2’s Web Console](#data.sql.h2-web-console) - * [1.5.1. Changing the H2 Console’s Path](#data.sql.h2-web-console.custom-path) - - * [1.6. Using jOOQ](#data.sql.jooq) - * [1.6.1. Code Generation](#data.sql.jooq.codegen) - * [1.6.2. Using DSLContext](#data.sql.jooq.dslcontext) - * [1.6.3. jOOQ SQL Dialect](#data.sql.jooq.sqldialect) - * [1.6.4. Customizing jOOQ](#data.sql.jooq.customizing) - - * [1.7. Using R2DBC](#data.sql.r2dbc) - * [1.7.1. Embedded Database Support](#data.sql.r2dbc.embedded) - * [1.7.2. Using DatabaseClient](#data.sql.r2dbc.using-database-client) - * [1.7.3. Spring Data R2DBC Repositories](#data.sql.r2dbc.repositories) - -* [2. Working with NoSQL Technologies](#data.nosql) - * [2.1. Redis](#data.nosql.redis) - * [2.1.1. Connecting to Redis](#data.nosql.redis.connecting) - - * [2.2. MongoDB](#data.nosql.mongodb) - * [2.2.1. Connecting to a MongoDB Database](#data.nosql.mongodb.connecting) - * [2.2.2. MongoTemplate](#data.nosql.mongodb.template) - * [2.2.3. Spring Data MongoDB Repositories](#data.nosql.mongodb.repositories) - * [2.2.4. Embedded Mongo](#data.nosql.mongodb.embedded) - - * [2.3. Neo4j](#data.nosql.neo4j) - * [2.3.1. Connecting to a Neo4j Database](#data.nosql.neo4j.connecting) - * [2.3.2. Spring Data Neo4j Repositories](#data.nosql.neo4j.repositories) - - * [2.4. Solr](#data.nosql.solr) - * [2.4.1. Connecting to Solr](#data.nosql.solr.connecting) - - * [2.5. Elasticsearch](#data.nosql.elasticsearch) - * [2.5.1. Connecting to Elasticsearch using REST clients](#data.nosql.elasticsearch.connecting-using-rest) - * [Connecting to Elasticsearch using RestHighLevelClient](#data.nosql.elasticsearch.connecting-using-rest.restclient) - * [Connecting to Elasticsearch using ReactiveElasticsearchClient](#data.nosql.elasticsearch.connecting-using-rest.webclient) - - * [2.5.2. Connecting to Elasticsearch by Using Spring Data](#data.nosql.elasticsearch.connecting-using-spring-data) - * [2.5.3. Spring Data Elasticsearch Repositories](#data.nosql.elasticsearch.repositories) - - * [2.6. Cassandra](#data.nosql.cassandra) - * [2.6.1. Connecting to Cassandra](#data.nosql.cassandra.connecting) - * [2.6.2. Spring Data Cassandra Repositories](#data.nosql.cassandra.repositories) - - * [2.7. Couchbase](#data.nosql.couchbase) - * [2.7.1. Connecting to Couchbase](#data.nosql.couchbase.connecting) - * [2.7.2. Spring Data Couchbase Repositories](#data.nosql.couchbase.repositories) - - * [2.8. LDAP](#data.nosql.ldap) - * [2.8.1. Connecting to an LDAP Server](#data.nosql.ldap.connecting) - * [2.8.2. Spring Data LDAP Repositories](#data.nosql.ldap.repositories) - * [2.8.3. Embedded In-memory LDAP Server](#data.nosql.ldap.embedded) - - * [2.9. InfluxDB](#data.nosql.influxdb) - * [2.9.1. Connecting to InfluxDB](#data.nosql.influxdb.connecting) - -* [3. What to Read Next](#data.whats-next) +# Data Spring Boot integrates with a number of data technologies, both SQL and NoSQL. -[](#data.sql)1. SQL Databases +# 1. SQL Databases ---------- The [Spring Framework](https://spring.io/projects/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](https://spring.io/projects/spring-data) provides an additional level of functionality: creating `Repository` implementations directly from interfaces and using conventions to generate queries from your method names. -### [](#data.sql.datasource)1.1. Configure a DataSource ### +### 1.1. Configure a DataSource Java’s `javax.sql.DataSource` interface provides a standard method of working with database connections. Traditionally, a 'DataSource' uses a `URL` along with some credentials to establish a database connection. @@ -94,7 +15,7 @@ Traditionally, a 'DataSource' uses a `URL` along with some credentials to establ | |See [the “How-to” section](howto.html#howto.data-access.configure-custom-datasource) for more advanced examples, typically to take full control over the configuration of the DataSource.| |---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#data.sql.datasource.embedded)1.1.1. Embedded Database Support #### +#### 1.1.1. Embedded Database Support It is often convenient to develop applications by using an in-memory embedded database. Obviously, in-memory databases do not provide persistent storage. @@ -132,11 +53,11 @@ For example, the typical POM dependencies would be as follows: | |If, for whatever reason, you do configure the connection URL for an embedded database, take care to ensure that the database’s automatic shutdown is disabled.
If you use H2, you should use `DB_CLOSE_ON_EXIT=FALSE` to do so.
If you use HSQLDB, you should ensure that `shutdown=true` is not used.
Disabling the database’s automatic shutdown lets Spring Boot control when the database is closed, thereby ensuring that it happens once access to the database is no longer needed.| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#data.sql.datasource.production)1.1.2. Connection to a Production Database #### +#### 1.1.2. Connection to a Production Database Production database connections can also be auto-configured by using a pooling `DataSource`. -#### [](#data.sql.datasource.configuration)1.1.3. DataSource Configuration #### +#### 1.1.3. DataSource Configuration DataSource configuration is controlled by external configuration properties in `spring.datasource.*`. For example, you might declare the following section in `application.properties`: @@ -196,7 +117,7 @@ spring: This will set the pool to wait 10000ms before throwing an exception if no connection is available, limit the maximum number of connections to 50 and validate the connection before borrowing it from the pool. -#### [](#data.sql.datasource.connection-pool)1.1.4. Supported Connection Pools #### +#### 1.1.4. Supported Connection Pools Spring Boot uses the following algorithm for choosing a specific implementation: @@ -233,7 +154,7 @@ The following connection pools are supported by `DataSourceBuilder`: * PostgreSQL `PGSimpleDataSource` -#### [](#data.sql.datasource.jndi)1.1.5. Connection to a JNDI DataSource #### +#### 1.1.5. Connection to a JNDI DataSource If you deploy your Spring Boot application to an Application Server, you might want to configure and manage your DataSource by using your Application Server’s built-in features and access it by using JNDI. @@ -254,7 +175,7 @@ spring: jndi-name: "java:jboss/datasources/customers" ``` -### [](#data.sql.jdbc-template)1.2. Using JdbcTemplate ### +### 1.2. 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: @@ -299,7 +220,7 @@ spring: | |The `NamedParameterJdbcTemplate` reuses the same `JdbcTemplate` instance behind the scenes.
If more than one `JdbcTemplate` is defined and no primary candidate exists, the `NamedParameterJdbcTemplate` is not auto-configured.| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#data.sql.jpa-and-spring-data)1.3. JPA and Spring Data JPA ### +### 1.3. JPA and Spring Data JPA The Java Persistence API is a standard technology that lets you “map” objects to relational databases. The `spring-boot-starter-data-jpa` POM provides a quick way to get started. @@ -314,7 +235,7 @@ It provides the following key dependencies: | |We do not go into too many details of JPA or [Spring Data](https://spring.io/projects/spring-data) here.
You can follow the [“Accessing Data with JPA”](https://spring.io/guides/gs/accessing-data-jpa/) guide from [spring.io](https://spring.io) and read the [Spring Data JPA](https://spring.io/projects/spring-data-jpa) and [Hibernate](https://hibernate.org/orm/documentation/) reference documentation.| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#data.sql.jpa-and-spring-data.entity-classes)1.3.1. Entity Classes #### +#### 1.3.1. 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. @@ -373,7 +294,7 @@ public class City implements Serializable { | |You can customize entity scanning locations by using the `@EntityScan` annotation.
See the “[howto.html](howto.html#howto.data-access.separate-entity-definitions-from-spring-configuration)” how-to.| |---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#data.sql.jpa-and-spring-data.repositories)1.3.2. Spring Data JPA Repositories #### +#### 1.3.2. Spring Data JPA Repositories [Spring Data JPA](https://spring.io/projects/spring-data-jpa) repositories are interfaces that you can define to access data. JPA queries are created automatically from your method names. @@ -413,7 +334,7 @@ If more than one exists, the one named `applicationTaskExecutor` will be used. | |We have barely scratched the surface of Spring Data JPA.
For complete details, see the [Spring Data JPA reference documentation](https://docs.spring.io/spring-data/jpa/docs/2.6.2/reference/html).| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#data.sql.jpa-and-spring-data.envers-repositories)1.3.3. Spring Data Envers Repositories #### +#### 1.3.3. Spring Data Envers Repositories If [Spring Data Envers](https://spring.io/projects/spring-data-envers) is available, JPA repositories are auto-configured to support typical Envers queries. @@ -437,7 +358,7 @@ public interface CountryRepository extends RevisionRepository ``` -#### [](#data.sql.jooq.dslcontext)1.6.2. Using DSLContext #### +#### 1.6.2. Using DSLContext The fluent API offered by jOOQ is initiated through the `org.jooq.DSLContext` interface. Spring Boot auto-configures a `DSLContext` as a Spring Bean and connects it to your application `DataSource`. @@ -601,7 +522,7 @@ public List authorsBornAfter1980() { ``` -#### [](#data.sql.jooq.sqldialect)1.6.3. jOOQ SQL Dialect #### +#### 1.6.3. jOOQ SQL Dialect Unless the `spring.jooq.sql-dialect` property has been configured, Spring Boot determines the SQL dialect to use for your datasource. If Spring Boot could not detect the dialect, it uses `DEFAULT`. @@ -609,14 +530,14 @@ If Spring Boot could not detect the dialect, it uses `DEFAULT`. | |Spring Boot can only auto-configure dialects supported by the open source version of jOOQ.| |---|------------------------------------------------------------------------------------------| -#### [](#data.sql.jooq.customizing)1.6.4. Customizing jOOQ #### +#### 1.6.4. Customizing jOOQ More advanced customizations can be achieved by defining your own `DefaultConfigurationCustomizer` bean that will be invoked prior to creating the `org.jooq.Configuration` `@Bean`. This takes precedence to anything that is applied by the auto-configuration. You can also create your own `org.jooq.Configuration` `@Bean` if you want to take complete control of the jOOQ configuration. -### [](#data.sql.r2dbc)1.7. Using R2DBC ### +### 1.7. Using R2DBC The Reactive Relational Database Connectivity ([R2DBC](https://r2dbc.io)) project brings reactive programming APIs to relational databases. R2DBC’s `io.r2dbc.spi.Connection` provides a standard method of working with non-blocking database connections. @@ -704,7 +625,7 @@ public class MyPostgresR2dbcConfiguration { When a `ConnectionFactory` bean is available, the regular JDBC `DataSource` auto-configuration backs off. If you want to retain the JDBC `DataSource` auto-configuration, and are comfortable with the risk of using the blocking JDBC API in a reactive application, add `@Import(DataSourceAutoConfiguration.class)` on a `@Configuration` class in your application to re-enable it. -#### [](#data.sql.r2dbc.embedded)1.7.1. Embedded Database Support #### +#### 1.7.1. Embedded Database Support Similarly to [the JDBC support](features.html#data.sql.datasource.embedded), Spring Boot can automatically configure an embedded database for reactive usage. You need not provide any connection URLs. @@ -721,7 +642,7 @@ You need only include a build dependency to the embedded database that you want | |If you are using this feature in your tests, you may notice that the same database is reused by your whole test suite regardless of the number of application contexts that you use.
If you want to make sure that each context has a separate embedded database, you should set `spring.r2dbc.generate-unique-name` to `true`.| |---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#data.sql.r2dbc.using-database-client)1.7.2. Using DatabaseClient #### +#### 1.7.2. Using DatabaseClient A `DatabaseClient` bean is auto-configured, and you can `@Autowire` it directly into your own beans, as shown in the following example: @@ -752,7 +673,7 @@ public class MyBean { ``` -#### [](#data.sql.r2dbc.repositories)1.7.3. Spring Data R2DBC Repositories #### +#### 1.7.3. Spring Data R2DBC Repositories [Spring Data R2DBC](https://spring.io/projects/spring-data-r2dbc) repositories are interfaces that you can define to access data. Queries are created automatically from your method names. @@ -781,7 +702,7 @@ public interface CityRepository extends Repository { | |We have barely scratched the surface of Spring Data R2DBC. For complete details, see the [Spring Data R2DBC reference documentation](https://docs.spring.io/spring-data/r2dbc/docs/1.4.2/reference/html/).| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -[](#data.nosql)2. Working with NoSQL Technologies +## 2. Working with NoSQL Technologies ---------- Spring Data provides additional projects that help you access a variety of NoSQL technologies, including: @@ -806,7 +727,7 @@ Spring Boot provides auto-configuration for Redis, MongoDB, Neo4j, Solr, Elastic You can make use of the other projects, but you must configure them yourself. See the appropriate reference documentation at [spring.io/projects/spring-data](https://spring.io/projects/spring-data). -### [](#data.nosql.redis)2.1. Redis ### +### 2.1. Redis [Redis](https://redis.io/) is a cache, message broker, and richly-featured key-value store. Spring Boot offers basic auto-configuration for the [Lettuce](https://github.com/lettuce-io/lettuce-core/) and [Jedis](https://github.com/xetorthio/jedis/) client libraries and the abstractions on top of them provided by [Spring Data Redis](https://github.com/spring-projects/spring-data-redis). @@ -818,7 +739,7 @@ That starter handles both traditional and reactive applications. | |We also provide a `spring-boot-starter-data-redis-reactive` “Starter” for consistency with the other stores with reactive support.| |---|----------------------------------------------------------------------------------------------------------------------------------| -#### [](#data.nosql.redis.connecting)2.1.1. Connecting to Redis #### +#### 2.1.1. Connecting to Redis You can inject an auto-configured `RedisConnectionFactory`, `StringRedisTemplate`, or vanilla `RedisTemplate` instance as you would any other Spring Bean. By default, the instance tries to connect to a Redis server at `localhost:6379`. @@ -854,12 +775,12 @@ If you add your own `@Bean` of any of the auto-configured types, it replaces the By default, a pooled connection factory is auto-configured if `commons-pool2` is on the classpath. -### [](#data.nosql.mongodb)2.2. MongoDB ### +### 2.2. MongoDB [MongoDB](https://www.mongodb.com/) is an open-source NoSQL document database that uses a JSON-like schema instead of traditional table-based relational data. Spring Boot offers several conveniences for working with MongoDB, including the `spring-boot-starter-data-mongodb` and `spring-boot-starter-data-mongodb-reactive` “Starters”. -#### [](#data.nosql.mongodb.connecting)2.2.1. Connecting to a MongoDB Database #### +#### 2.2.1. Connecting to a MongoDB Database To access MongoDB databases, you can inject an auto-configured `org.springframework.data.mongodb.MongoDatabaseFactory`. By default, the instance tries to connect to a MongoDB server at `mongodb://localhost/test`. @@ -953,7 +874,7 @@ spring: | |If you are using the reactive driver, Netty is required for SSL.
The auto-configuration configures this factory automatically if Netty is available and the factory to use has not been customized already.| |---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#data.nosql.mongodb.template)2.2.2. MongoTemplate #### +#### 2.2.2. MongoTemplate [Spring Data MongoDB](https://spring.io/projects/spring-data-mongodb) provides a [`MongoTemplate`](https://docs.spring.io/spring-data/mongodb/docs/3.3.2/api/org/springframework/data/mongodb/core/MongoTemplate.html) 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: @@ -986,7 +907,7 @@ public class MyBean { See the [`MongoOperations` Javadoc](https://docs.spring.io/spring-data/mongodb/docs/3.3.2/api/org/springframework/data/mongodb/core/MongoOperations.html) for complete details. -#### [](#data.nosql.mongodb.repositories)2.2.3. Spring Data MongoDB Repositories #### +#### 2.2.3. Spring Data MongoDB Repositories Spring Data includes repository support for MongoDB. As with the JPA repositories discussed earlier, the basic principle is that queries are constructed automatically, based on method names. @@ -1015,7 +936,7 @@ public interface CityRepository extends Repository { | |For complete details of Spring Data MongoDB, including its rich object mapping technologies, see its [reference documentation](https://spring.io/projects/spring-data-mongodb).| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#data.nosql.mongodb.embedded)2.2.4. Embedded Mongo #### +#### 2.2.4. Embedded Mongo Spring Boot offers auto-configuration for [Embedded Mongo](https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo). To use it in your Spring Boot application, add a dependency on `de.flapdoodle.embed:de.flapdoodle.embed.mongo` and set the `spring.mongodb.embedded.version` property to match the version of MongoDB that your application will use in production. @@ -1035,12 +956,12 @@ If you have SLF4J on the classpath, the output produced by Mongo is automaticall You can declare your own `IMongodConfig` and `IRuntimeConfig` beans to take control of the Mongo instance’s configuration and logging routing. The download configuration can be customized by declaring a `DownloadConfigBuilderCustomizer` bean. -### [](#data.nosql.neo4j)2.3. Neo4j ### +### 2.3. Neo4j [Neo4j](https://neo4j.com/) is an open-source NoSQL graph database that uses a rich data model of nodes connected by first class relationships, which is better suited for connected big data than traditional RDBMS approaches. Spring Boot offers several conveniences for working with Neo4j, including the `spring-boot-starter-data-neo4j` “Starter”. -#### [](#data.nosql.neo4j.connecting)2.3.1. Connecting to a Neo4j Database #### +#### 2.3.1. Connecting to a Neo4j Database To access a Neo4j server, you can inject an auto-configured `org.neo4j.driver.Driver`. By default, the instance tries to connect to a Neo4j server at `localhost:7687` using the Bolt protocol. @@ -1103,7 +1024,7 @@ The auto-configured `Driver` is created using `ConfigBuilder`. To fine-tune its configuration, declare one or more `ConfigBuilderCustomizer` beans. Each will be called in order with the `ConfigBuilder` that is used to build the `Driver`. -#### [](#data.nosql.neo4j.repositories)2.3.2. Spring Data Neo4j Repositories #### +#### 2.3.2. Spring Data Neo4j Repositories Spring Data includes repository support for Neo4j. For complete details of Spring Data Neo4j, see the [reference documentation](https://docs.spring.io/spring-data/neo4j/docs/6.2.2/reference/html/). @@ -1133,12 +1054,12 @@ You can customize the locations to look for repositories and entities by using ` | |In an application using the reactive style, a `ReactiveTransactionManager` is not auto-configured.
To enable transaction management, the following bean must be defined in your configuration:

```
import org.neo4j.driver.Driver;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neo4j.core.ReactiveDatabaseSelectionProvider;
import org.springframework.data.neo4j.core.transaction.ReactiveNeo4jTransactionManager;

@Configuration(proxyBeanMethods = false)
public class MyNeo4jConfiguration {

@Bean
public ReactiveNeo4jTransactionManager reactiveTransactionManager(Driver driver,
ReactiveDatabaseSelectionProvider databaseNameProvider) {
return new ReactiveNeo4jTransactionManager(driver, databaseNameProvider);
}

}

```| |---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#data.nosql.solr)2.4. Solr ### +### 2.4. Solr [Apache Solr](https://lucene.apache.org/solr/) is a search engine. Spring Boot offers basic auto-configuration for the Solr 5 client library. -#### [](#data.nosql.solr.connecting)2.4.1. Connecting to Solr #### +#### 2.4.1. Connecting to Solr You can inject an auto-configured `SolrClient` instance as you would any other Spring bean. By default, the instance tries to connect to a server at `[localhost:8983/solr](http://localhost:8983/solr)`. @@ -1174,7 +1095,7 @@ public class MyBean { If you add your own `@Bean` of type `SolrClient`, it replaces the default. -### [](#data.nosql.elasticsearch)2.5. Elasticsearch ### +### 2.5. Elasticsearch [Elasticsearch](https://www.elastic.co/products/elasticsearch) is an open source, distributed, RESTful search and analytics engine. Spring Boot offers basic auto-configuration for Elasticsearch clients. @@ -1187,7 +1108,7 @@ Spring Boot supports several clients: Spring Boot provides a dedicated “Starter”, `spring-boot-starter-data-elasticsearch`. -#### [](#data.nosql.elasticsearch.connecting-using-rest)2.5.1. Connecting to Elasticsearch using REST clients #### +#### 2.5.1. Connecting to Elasticsearch using REST clients Elasticsearch ships [two different REST clients](https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/index.html) that you can use to query a cluster: the "Low Level" client and the "High Level" client. Spring Boot provides support for the "High Level" client, which ships with `org.elasticsearch.client:elasticsearch-rest-high-level-client`. @@ -1215,7 +1136,7 @@ spring: password: "secret" ``` -##### [](#data.nosql.elasticsearch.connecting-using-rest.restclient)Connecting to Elasticsearch using RestHighLevelClient ##### +##### Connecting to Elasticsearch using RestHighLevelClient ##### If you have `elasticsearch-rest-high-level-client` on the classpath, Spring Boot will auto-configure and register a `RestHighLevelClient` bean. In addition to the properties described previously, to fine-tune the `RestHighLevelClient`, you can register an arbitrary number of beans that implement `RestClientBuilderCustomizer` for more advanced customizations. @@ -1245,7 +1166,7 @@ spring: delay-after-failure: "30s" ``` -##### [](#data.nosql.elasticsearch.connecting-using-rest.webclient)Connecting to Elasticsearch using ReactiveElasticsearchClient ##### +##### Connecting to Elasticsearch using ReactiveElasticsearchClient ##### [Spring Data Elasticsearch](https://spring.io/projects/spring-data-elasticsearch) ships `ReactiveElasticsearchClient` for querying Elasticsearch instances in a reactive fashion. It is built on top of WebFlux’s `WebClient`, so both `spring-boot-starter-elasticsearch` and `spring-boot-starter-webflux` dependencies are useful to enable this support. @@ -1270,7 +1191,7 @@ spring: If the `spring.elasticsearch.` **and `spring.elasticsearch.webclient.`** configuration properties are not enough and you’d like to fully control the client configuration, you can register a custom `ClientConfiguration` bean. -#### [](#data.nosql.elasticsearch.connecting-using-spring-data)2.5.2. Connecting to Elasticsearch by Using Spring Data #### +#### 2.5.2. Connecting to Elasticsearch by Using Spring Data #### To connect to Elasticsearch, a `RestHighLevelClient` bean must be defined, auto-configured by Spring Boot or manually provided by the application (see previous sections). @@ -1303,7 +1224,7 @@ public class MyBean { In the presence of `spring-data-elasticsearch` and the required dependencies for using a `WebClient` (typically `spring-boot-starter-webflux`), Spring Boot can also auto-configure a [ReactiveElasticsearchClient](features.html#data.nosql.elasticsearch.connecting-using-rest.webclient) and a `ReactiveElasticsearchTemplate` as beans. They are the reactive equivalent of the other REST clients. -#### [](#data.nosql.elasticsearch.repositories)2.5.3. Spring Data Elasticsearch Repositories #### +#### 2.5.3. Spring Data Elasticsearch Repositories Spring Data includes repository support for Elasticsearch. As with the JPA repositories discussed earlier, the basic principle is that queries are constructed for you automatically based on method names. @@ -1338,13 +1259,13 @@ spring: enabled: false ``` -### [](#data.nosql.cassandra)2.6. Cassandra ### +### 2.6. Cassandra [Cassandra](https://cassandra.apache.org/) 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 [Spring Data Cassandra](https://github.com/spring-projects/spring-data-cassandra). There is a `spring-boot-starter-data-cassandra` “Starter” for collecting the dependencies in a convenient way. -#### [](#data.nosql.cassandra.connecting)2.6.1. Connecting to Cassandra #### +#### 2.6.1. Connecting to Cassandra You can inject an auto-configured `CassandraTemplate` or a Cassandra `CqlSession` instance as you would with any other Spring Bean. The `spring.data.cassandra.*` properties can be used to customize the connection. @@ -1426,7 +1347,7 @@ public class MyBean { If you add your own `@Bean` of type `CassandraTemplate`, it replaces the default. -#### [](#data.nosql.cassandra.repositories)2.6.2. Spring Data Cassandra Repositories #### +#### 2.6.2. Spring Data Cassandra Repositories Spring Data includes basic repository support for Cassandra. Currently, this is more limited than the JPA repositories discussed earlier and needs to annotate finder methods with `@Query`. @@ -1434,13 +1355,13 @@ Currently, this is more limited than the JPA repositories discussed earlier and | |For complete details of Spring Data Cassandra, see the [reference documentation](https://docs.spring.io/spring-data/cassandra/docs/).| |---|-------------------------------------------------------------------------------------------------------------------------------------| -### [](#data.nosql.couchbase)2.7. Couchbase ### +### 2.7. Couchbase [Couchbase](https://www.couchbase.com/) 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 [Spring Data Couchbase](https://github.com/spring-projects/spring-data-couchbase). There are `spring-boot-starter-data-couchbase` and `spring-boot-starter-data-couchbase-reactive` “Starters” for collecting the dependencies in a convenient way. -#### [](#data.nosql.couchbase.connecting)2.7.1. Connecting to Couchbase #### +#### 2.7.1. Connecting to Couchbase You can get a `Cluster` by adding the Couchbase SDK and some configuration. The `spring.couchbase.*` properties can be used to customize the connection. @@ -1491,7 +1412,7 @@ spring: | |Check the `spring.couchbase.env.*` properties for more details.
To take more control, one or more `ClusterEnvironmentBuilderCustomizer` beans can be used.| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#data.nosql.couchbase.repositories)2.7.2. Spring Data Couchbase Repositories #### +#### 2.7.2. Spring Data Couchbase Repositories Spring Data includes repository support for Couchbase. For complete details of Spring Data Couchbase, see the [reference documentation](https://docs.spring.io/spring-data/couchbase/docs/4.3.2/reference/html/). @@ -1570,7 +1491,7 @@ public class MyCouchbaseConfiguration { ``` -### [](#data.nosql.ldap)2.8. LDAP ### +### 2.8. LDAP [LDAP](https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol) (Lightweight Directory Access Protocol) is an open, vendor-neutral, industry standard application protocol for accessing and maintaining distributed directory information services over an IP network. Spring Boot offers auto-configuration for any compliant LDAP server as well as support for the embedded in-memory LDAP server from [UnboundID](https://ldap.com/unboundid-ldap-sdk-for-java/). @@ -1578,7 +1499,7 @@ Spring Boot offers auto-configuration for any compliant LDAP server as well as s LDAP abstractions are provided by [Spring Data LDAP](https://github.com/spring-projects/spring-data-ldap). There is a `spring-boot-starter-data-ldap` “Starter” for collecting the dependencies in a convenient way. -#### [](#data.nosql.ldap.connecting)2.8.1. Connecting to an LDAP Server #### +#### 2.8.1. 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: @@ -1607,7 +1528,7 @@ If a `DirContextAuthenticationStrategy` bean is available, it is associated to t If you need to customize it, for instance to use a `PooledContextSource`, you can still inject the auto-configured `LdapContextSource`. Make sure to flag your customized `ContextSource` as `@Primary` so that the auto-configured `LdapTemplate` uses it. -#### [](#data.nosql.ldap.repositories)2.8.2. Spring Data LDAP Repositories #### +#### 2.8.2. Spring Data LDAP Repositories Spring Data includes repository support for LDAP. For complete details of Spring Data LDAP, see the [reference documentation](https://docs.spring.io/spring-data/ldap/docs/1.0.x/reference/html/). @@ -1639,7 +1560,7 @@ public class MyBean { ``` -#### [](#data.nosql.ldap.embedded)2.8.3. Embedded In-memory LDAP Server #### +#### 2.8.3. Embedded In-memory LDAP Server For testing purposes, Spring Boot supports auto-configuration of an in-memory LDAP server from [UnboundID](https://ldap.com/unboundid-ldap-sdk-for-java/). To configure the server, add a dependency to `com.unboundid:unboundid-ldapsdk` and declare a `spring.ldap.embedded.base-dn` property, as follows: @@ -1672,11 +1593,11 @@ 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. -### [](#data.nosql.influxdb)2.9. InfluxDB ### +### 2.9. InfluxDB [InfluxDB](https://www.influxdata.com/) is an open-source time series database optimized for fast, high-availability storage and retrieval of time series data in fields such as operations monitoring, application metrics, Internet-of-Things sensor data, and real-time analytics. -#### [](#data.nosql.influxdb.connecting)2.9.1. Connecting to InfluxDB #### +#### 2.9.1. 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: @@ -1701,7 +1622,7 @@ If you need to tune the http client `InfluxDB` uses behind the scenes, you can r If you need more control over the configuration, consider registering an `InfluxDbCustomizer` bean. -[](#data.whats-next)3. What to Read Next +## 3. What to Read Next ---------- You should now have a feeling for how to use Spring Boot with various data technologies. diff --git a/docs/en/spring-boot/deployment.md b/docs/en/spring-boot/deployment.md index 3423a9297ce70ef058ff99beb90b899338973d27..7538cd067824b12d52904981a127b15a9468b9dd 100644 --- a/docs/en/spring-boot/deployment.md +++ b/docs/en/spring-boot/deployment.md @@ -1,52 +1,11 @@ -Deploying Spring Boot Applications -========== - -Table of Contents - -[Back to index](index.html) - -* [1. Deploying to the Cloud](#deployment.cloud) - * [1.1. Cloud Foundry](#deployment.cloud.cloud-foundry) - * [1.1.1. Binding to Services](#deployment.cloud.cloud-foundry.binding-to-services) - - * [1.2. Kubernetes](#deployment.cloud.kubernetes) - * [1.2.1. Kubernetes Container Lifecycle](#deployment.cloud.kubernetes.container-lifecycle) - - * [1.3. Heroku](#deployment.cloud.heroku) - * [1.4. OpenShift](#deployment.cloud.openshift) - * [1.5. Amazon Web Services (AWS)](#deployment.cloud.aws) - * [1.5.1. AWS Elastic Beanstalk](#deployment.cloud.aws.beanstalk) - * [Using the Tomcat Platform](#deployment.cloud.aws.beanstalk.tomcat-platform) - * [Using the Java SE Platform](#deployment.cloud.aws.beanstalk.java-se-platform) - - * [1.5.2. Summary](#deployment.cloud.aws.summary) - - * [1.6. CloudCaptain and Amazon Web Services](#deployment.cloud.boxfuse) - * [1.7. Azure](#deployment.cloud.azure) - * [1.8. Google Cloud](#deployment.cloud.google) - -* [2. Installing Spring Boot Applications](#deployment.installing) - * [2.1. Supported Operating Systems](#deployment.installing.supported-operating-systems) - * [2.2. Unix/Linux Services](#deployment.installing.nix-services) - * [2.2.1. Installation as an init.d Service (System V)](#deployment.installing.nix-services.init-d) - * [Securing an init.d Service](#deployment.installing.nix-services.init-d.securing) - - * [2.2.2. Installation as a systemd Service](#deployment.installing.nix-services.system-d) - * [2.2.3. Customizing the Startup Script](#deployment.installing.nix-services.script-customization) - * [Customizing the Start Script When It Is Written](#deployment.installing.nix-services.script-customization.when-written) - * [Customizing a Script When It Runs](#deployment.installing.nix-services.script-customization.when-running) - - * [2.3. Microsoft Windows Services](#deployment.installing.windows-services) - -* [3. What to Read Next](#deployment.whats-next) +# Deploying Spring Boot Applications Spring Boot’s flexible packaging options provide a great deal of choice when it comes to deploying your application. You can deploy Spring Boot applications to a variety of cloud platforms, to virtual/real machines, or make them fully executable for Unix systems. This section covers some of the more common deployment scenarios. -[](#deployment.cloud)1. Deploying to the Cloud ----------- +## 1. Deploying to the Cloud 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”. @@ -63,7 +22,7 @@ Ideally, your application, like a Spring Boot executable jar, has everything tha In this section, we look at what it takes to get the [application that we developed](getting-started.html#getting-started.first-application) in the “Getting Started” section up and running in the Cloud. -### [](#deployment.cloud.cloud-foundry)1.1. Cloud Foundry ### +### 1.1. Cloud Foundry Cloud Foundry provides default buildpacks that come into play if no other buildpack is specified. The Cloud Foundry [Java buildpack](https://github.com/cloudfoundry/java-buildpack) has excellent support for Spring applications, including Spring Boot. @@ -127,7 +86,7 @@ acloudyspringtime started 1/1 512M 1G acloudyspring Once Cloud Foundry acknowledges that your application has been deployed, you should be able to find the application at the URI given. In the preceding example, you could find it at `https://acloudyspringtime.cfapps.io/`. -#### [](#deployment.cloud.cloud-foundry.binding-to-services)1.1.1. Binding to Services #### +#### 1.1.1. Binding to Services By default, metadata about the running application as well as service connection information is exposed to the application as environment variables (for example: `$VCAP_SERVICES`). This architecture decision is due to Cloud Foundry’s polyglot (any language and platform can be supported as a buildpack) nature. @@ -163,14 +122,14 @@ See the [‘CloudFoundryVcapEnvironmentPostProcessor’](https://docs.spring.io/ | |The [Java CFEnv](https://github.com/pivotal-cf/java-cfenv/) project is a better fit for tasks such as configuring a DataSource.| |---|-------------------------------------------------------------------------------------------------------------------------------| -### [](#deployment.cloud.kubernetes)1.2. Kubernetes ### +### 1.2. Kubernetes Spring Boot auto-detects Kubernetes deployment environments by checking the environment for `"*_SERVICE_HOST"` and `"*_SERVICE_PORT"` variables. You can override this detection with the `spring.main.cloud-platform` configuration property. Spring Boot helps you to [manage the state of your application](features.html#features.spring-application.application-availability) and export it with [HTTP Kubernetes Probes using Actuator](actuator.html#actuator.endpoints.kubernetes-probes). -#### [](#deployment.cloud.kubernetes.container-lifecycle)1.2.1. Kubernetes Container Lifecycle #### +#### 1.2.1. Kubernetes Container Lifecycle When Kubernetes deletes an application instance, the shutdown process involves several subsystems concurrently: shutdown hooks, unregistering the service, removing the instance from the load-balancer…​ Because this shutdown processing happens in parallel (and due to the nature of distributed systems), there is a window during which traffic can be routed to a pod that has also begun its shutdown processing. @@ -195,7 +154,7 @@ Once the pre-stop hook has completed, SIGTERM will be sent to the container and | |When Kubernetes sends a SIGTERM signal to the pod, it waits for a specified time called the termination grace period (the default for which is 30 seconds).
If the containers are still running after the grace period, they are sent the SIGKILL signal and forcibly removed.
If the pod takes longer than 30 seconds to shut down, which could be because you have increased `spring.lifecycle.timeout-per-shutdown-phase`, make sure to increase the termination grace period by setting the `terminationGracePeriodSeconds` option in the Pod YAML.| |---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#deployment.cloud.heroku)1.3. Heroku ### +### 1.3. Heroku Heroku is another popular PaaS platform. To customize Heroku builds, you provide a `Procfile`, which provides the incantation required to deploy an application. @@ -264,7 +223,7 @@ To [email protected]:agile-sierra-1405.git Your application should now be up and running on Heroku. For more details, see [Deploying Spring Boot Applications to Heroku](https://devcenter.heroku.com/articles/deploying-spring-boot-apps-to-heroku). -### [](#deployment.cloud.openshift)1.4. OpenShift ### +### 1.4. OpenShift [OpenShift](https://www.openshift.com/) has many resources describing how to deploy Spring Boot applications, including: @@ -276,7 +235,7 @@ For more details, see [Deploying Spring Boot Applications to Heroku](https://dev * [OpenShift Commons Briefing](https://blog.openshift.com/openshift-commons-briefing-96-cloud-native-applications-spring-rhoar/) -### [](#deployment.cloud.aws)1.5. Amazon Web Services (AWS) ### +### 1.5. Amazon Web Services (AWS) Amazon Web Services offers multiple ways to install Spring Boot-based applications, either as traditional web applications (war) or as executable jar files with an embedded web server. The options include: @@ -294,18 +253,18 @@ The options include: Each has different features and pricing models. In this document, we describe to approach using AWS Elastic Beanstalk. -#### [](#deployment.cloud.aws.beanstalk)1.5.1. AWS Elastic Beanstalk #### +#### 1.5.1. AWS Elastic Beanstalk As described in the official [Elastic Beanstalk Java guide](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_Java.html), there are two main options to deploy a Java application. You can either use the “Tomcat Platform” or the “Java SE platform”. -##### [](#deployment.cloud.aws.beanstalk.tomcat-platform)Using the Tomcat Platform ##### +##### Using the Tomcat Platform This option applies to Spring Boot projects that produce a war file. No special configuration is required. You need only follow the official guide. -##### [](#deployment.cloud.aws.beanstalk.java-se-platform)Using the Java SE Platform ##### +##### Using the Java SE Platform This option applies to Spring Boot projects that produce a jar file and run an embedded web container. Elastic Beanstalk environments run an nginx instance on port 80 to proxy the actual application, running on port 5000. @@ -321,12 +280,12 @@ server.port=5000 | |Reduce costs by setting the environment type

By default an Elastic Beanstalk environment is load balanced.
The load balancer has a significant cost.
To avoid that cost, set the environment type to “Single instance”, as described in [the Amazon documentation](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environments-create-wizard.html#environments-create-wizard-capacity).
You can also create single instance environments by using the CLI and the following command:

```
eb create -s
```| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#deployment.cloud.aws.summary)1.5.2. Summary #### +#### 1.5.2. Summary This is one of the easiest ways to get to AWS, but there are more things to cover, such as how to integrate Elastic Beanstalk into any CI / CD tool, use the Elastic Beanstalk Maven plugin instead of the CLI, and others. There is a [blog post](https://exampledriven.wordpress.com/2017/01/09/spring-boot-aws-elastic-beanstalk-example/) covering these topics more in detail. -### [](#deployment.cloud.boxfuse)1.6. CloudCaptain and Amazon Web Services ### +### 1.6. CloudCaptain and Amazon Web Services [CloudCaptain](https://cloudcaptain.sh/) works by turning your Spring Boot executable jar or war into a minimal VM image that can be deployed unchanged either on VirtualBox or on AWS. CloudCaptain comes with deep integration for Spring Boot and uses the information from your Spring Boot configuration file to automatically configure ports and health check URLs. @@ -370,11 +329,11 @@ Your application should now be up and running on AWS. See the blog post on [deploying Spring Boot apps on EC2](https://cloudcaptain.sh/blog/spring-boot-ec2.html) as well as the [documentation for the CloudCaptain Spring Boot integration](https://cloudcaptain.sh/docs/payloads/springboot.html) to get started with a Maven build to run the app. -### [](#deployment.cloud.azure)1.7. Azure ### +### 1.7. Azure This [Getting Started guide](https://spring.io/guides/gs/spring-boot-for-azure/) walks you through deploying your Spring Boot application to either [Azure Spring Cloud](https://azure.microsoft.com/en-us/services/spring-cloud/) or [Azure App Service](https://docs.microsoft.com/en-us/azure/app-service/overview). -### [](#deployment.cloud.google)1.8. Google Cloud ### +### 1.8. Google Cloud Google Cloud has several options that can be used to launch Spring Boot applications. The easiest to get started with is probably App Engine, but you could also find ways to run Spring Boot in a container with Container Engine or on a virtual machine with Compute Engine. @@ -426,8 +385,7 @@ You can deploy the app (for example, with a Maven plugin) by adding the project Then deploy with `mvn appengine:deploy` (if you need to authenticate first, the build fails). -[](#deployment.installing)2. Installing Spring Boot Applications ----------- +## 2. Installing Spring Boot Applications In addition to running Spring Boot applications by using `java -jar`, it is also possible to make fully executable applications for Unix systems. A fully executable jar can be executed like any other executable binary or it can be [registered with `init.d` or `systemd`](#deployment.installing.nix-services). @@ -462,16 +420,16 @@ bootJar { You can then run your application by typing `./my-application.jar` (where `my-application` is the name of your artifact). The directory containing the jar is used as your application’s working directory. -### [](#deployment.installing.supported-operating-systems)2.1. Supported Operating Systems ### +### 2.1. Supported Operating Systems The default script supports most Linux distributions and is tested on CentOS and Ubuntu. Other platforms, such as OS X and FreeBSD, require the use of a custom `embeddedLaunchScript`. -### [](#deployment.installing.nix-services)2.2. Unix/Linux Services ### +### 2.2. Unix/Linux Services Spring Boot application can be easily started as Unix/Linux services by using either `init.d` or `systemd`. -#### [](#deployment.installing.nix-services.init-d)2.2.1. Installation as an init.d Service (System V) #### +#### 2.2.1. Installation as an init.d Service (System V) If you configured Spring Boot’s Maven or Gradle plugin to generate a [fully executable jar](#deployment.installing), 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. @@ -507,7 +465,7 @@ For example, on Debian, you could use the following command: $ update-rc.d myapp defaults ``` -##### [](#deployment.installing.nix-services.init-d.securing)Securing an init.d Service ##### +##### Securing an init.d Service | |The following is a set of guidelines on how to secure a Spring Boot application that runs as an init.d service.
It is not intended to be an exhaustive list of everything that should be done to harden an application and the environment in which it runs.| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| @@ -552,7 +510,7 @@ $ chmod 400 your-app.conf $ sudo chown root:root your-app.conf ``` -#### [](#deployment.installing.nix-services.system-d)2.2.2. Installation as a systemd Service #### +#### 2.2.2. Installation as a systemd Service `systemd` is the successor of the System V init system and is now being used by many modern Linux distributions. Although you can continue to use `init.d` scripts with `systemd`, it is also possible to launch Spring Boot applications by using `systemd` ‘service’ scripts. @@ -591,13 +549,13 @@ $ systemctl enable myapp.service Run `man systemctl` for more details. -#### [](#deployment.installing.nix-services.script-customization)2.2.3. Customizing the Startup Script #### +#### 2.2.3. Customizing the Startup Script 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, use the `embeddedLaunchScript` option to write your own file entirely. -##### [](#deployment.installing.nix-services.script-customization.when-written)Customizing the Start Script When It Is Written ##### +##### Customizing the Start Script When It Is Written ##### It often makes sense to customize elements of the start script as it is written into the jar file. For example, init.d scripts can provide a “description”. @@ -627,7 +585,7 @@ The following property substitutions are supported with the default script: | `useStartStopDaemon` | Whether the `start-stop-daemon` command, when it is available, should be used to control the process | `true` | `true` | | `stopWaitTime` | Default value for `STOP_WAIT_TIME` in seconds.
Only valid for an `init.d` service | 60 | 60 | -##### [](#deployment.installing.nix-services.script-customization.when-running)Customizing a Script When It Runs ##### +##### Customizing a Script When It Runs ##### For items of the script that need to be customized *after* the jar has been written, you can use environment variables or a [config file](#deployment.installing.nix-services.script-customization.when-running.conf-file). @@ -669,14 +627,13 @@ LOG_FOLDER=/custom/log/folder To learn about securing this file appropriately, see [the guidelines for securing an init.d service](#deployment.installing.nix-services.init-d.securing). -### [](#deployment.installing.windows-services)2.3. Microsoft Windows Services ### +### 2.3. Microsoft Windows Services A Spring Boot application can be started as a Windows service by using [`winsw`](https://github.com/kohsuke/winsw). A ([separately maintained sample](https://github.com/snicoll/spring-boot-daemon)) describes step-by-step how you can create a Windows service for your Spring Boot application. -[](#deployment.whats-next)3. What to Read Next ----------- +## 3. What to Read Next See the [Cloud Foundry](https://www.cloudfoundry.org/), [Heroku](https://www.heroku.com/), [OpenShift](https://www.openshift.com), and [Boxfuse](https://boxfuse.com) web sites for more information about the kinds of features that a PaaS can offer. These are just four of the most popular Java PaaS providers. diff --git a/docs/en/spring-boot/documentation.md b/docs/en/spring-boot/documentation.md index e6b330bda9839cffc295c561bbec29bb8d2ef747..3c484c4c4876ecb2eef30ea67b9172ff46718192 100644 --- a/docs/en/spring-boot/documentation.md +++ b/docs/en/spring-boot/documentation.md @@ -1,28 +1,11 @@ -Documentation Overview -========== - -Table of Contents - -[Back to index](index.html) - -* [1. First Steps](#documentation.first-steps) -* [2. Upgrading From an Earlier Version](#documentation.upgrading) -* [3. Developing with Spring Boot](#documentation.using) -* [4. Learning About Spring Boot Features](#documentation.features) -* [5. Web](#documentation.web) -* [6. Data](#documentation.data) -* [7. Messaging](#documentation.messaging) -* [8. IO](#documentation.io) -* [9. Container Images](#documentation.container-images) -* [10. Advanced Topics](#documentation.advanced) +# Documentation Overview This section provides a brief overview of Spring Boot reference documentation. It serves as a map for the rest of the document. The latest copy of this document is available at [docs.spring.io/spring-boot/docs/current/reference/](https://docs.spring.io/spring-boot/docs/current/reference/). -[](#documentation.first-steps)1. First Steps ----------- +## 1. First Steps If you are getting started with Spring Boot or 'Spring' in general, start with [the following topics](getting-started.html#getting-started): @@ -32,8 +15,7 @@ If you are getting started with Spring Boot or 'Spring' in general, start with [ * **Running your example:** [Part 1](getting-started.html#getting-started.first-application.run) | [Part 2](getting-started.html#getting-started.first-application.executable-jar) -[](#documentation.upgrading)2. Upgrading From an Earlier Version ----------- +## 2. Upgrading From an Earlier Version You should always ensure that you are running a [supported version](https://github.com/spring-projects/spring-boot/wiki/Supported-Versions) of Spring Boot. @@ -45,8 +27,7 @@ Depending on the version that you are upgrading to, you can find some additional * **Spring Boot CLI:** [Upgrading the Spring Boot CLI](upgrading.html#upgrading.cli) -[](#documentation.using)3. Developing with Spring Boot ----------- +## 3. Developing with Spring Boot Ready to actually start using Spring Boot? [We have you covered](using.html#using): @@ -60,8 +41,7 @@ Ready to actually start using Spring Boot? [We have you covered](using.html#usin * **Spring Boot CLI:** [Using the CLI](cli.html#cli) -[](#documentation.features)4. Learning About Spring Boot Features ----------- +## 4. Learning About Spring Boot Features Need more details about Spring Boot’s core features?[The following content is for you](features.html#features): @@ -73,8 +53,7 @@ Need more details about Spring Boot’s core features?[The following content is * **Logging:** [Logging](features.html#features.logging) -[](#documentation.web)5. Web ----------- +## 5. Web- If you develop Spring Boot web applications, take a look at the following content: @@ -90,8 +69,7 @@ If you develop Spring Boot web applications, take a look at the following conten * **Spring HATEOAS:** [Auto-configuration for Spring HATEOAS](web.html#web.spring-hateoas) -[](#documentation.data)6. Data ----------- +## 6. Data If your application deals with a datastore, you can see how to configure that here: @@ -99,8 +77,7 @@ If your application deals with a datastore, you can see how to configure that he * **NOSQL:** [Auto-configuration for NOSQL stores such as Redis, MongoDB, Neo4j, and others.](data.html#data.nosql) -[](#documentation.messaging)7. Messaging ----------- +## 7. Messaging If your application uses any messaging protocol, see one or more of the following sections: @@ -114,8 +91,7 @@ If your application uses any messaging protocol, see one or more of the followin * **Spring Integration:** [Auto-configuration for Spring Integration](messaging.html#messaging.spring-integration) -[](#documentation.io)8. IO ----------- +## 8. IO-- If your application needs IO capabilities, see one or more of the following sections: @@ -133,8 +109,7 @@ If your application needs IO capabilities, see one or more of the following sect * **JTA:** [Distributed Transactions with JTA](io.html#io.jta) -[](#documentation.container-images)9. Container Images ----------- +## 9. Container Images Spring Boot provides first-class support for building efficient container images. You can read more about it here: @@ -144,8 +119,7 @@ Spring Boot provides first-class support for building efficient container images * **Cloud Native Buildpacks:** [Support for Cloud Native Buildpacks with Maven and Gradle](container-images.html#container-images.buildpacks) -[](#documentation.advanced)10. Advanced Topics ----------- +## 10. Advanced Topics Finally, we have a few topics for more advanced users: diff --git a/docs/en/spring-boot/features.md b/docs/en/spring-boot/features.md index c0a204658e0d7dba756d85c29632eb204aa4bfad..2abd21de2f2eba65ef4870e157cdd77b1cfabebd 100644 --- a/docs/en/spring-boot/features.md +++ b/docs/en/spring-boot/features.md @@ -1,187 +1,11 @@ -Core Features -========== - -Table of Contents - -[Back to index](index.html) - -* [1. SpringApplication](#features.spring-application) - * [1.1. Startup Failure](#features.spring-application.startup-failure) - * [1.2. Lazy Initialization](#features.spring-application.lazy-initialization) - * [1.3. Customizing the Banner](#features.spring-application.banner) - * [1.4. Customizing SpringApplication](#features.spring-application.customizing-spring-application) - * [1.5. Fluent Builder API](#features.spring-application.fluent-builder-api) - * [1.6. Application Availability](#features.spring-application.application-availability) - * [1.6.1. Liveness State](#features.spring-application.application-availability.liveness) - * [1.6.2. Readiness State](#features.spring-application.application-availability.readiness) - * [1.6.3. Managing the Application Availability State](#features.spring-application.application-availability.managing) - - * [1.7. Application Events and Listeners](#features.spring-application.application-events-and-listeners) - * [1.8. Web Environment](#features.spring-application.web-environment) - * [1.9. Accessing Application Arguments](#features.spring-application.application-arguments) - * [1.10. Using the ApplicationRunner or CommandLineRunner](#features.spring-application.command-line-runner) - * [1.11. Application Exit](#features.spring-application.application-exit) - * [1.12. Admin Features](#features.spring-application.admin) - * [1.13. Application Startup tracking](#features.spring-application.startup-tracking) - -* [2. Externalized Configuration](#features.external-config) - * [2.1. Accessing Command Line Properties](#features.external-config.command-line-args) - * [2.2. JSON Application Properties](#features.external-config.application-json) - * [2.3. External Application Properties ](#features.external-config.files) - * [2.3.1. Optional Locations](#features.external-config.files.optional-prefix) - * [2.3.2. Wildcard Locations](#features.external-config.files.wildcard-locations) - * [2.3.3. Profile Specific Files](#features.external-config.files.profile-specific) - * [2.3.4. Importing Additional Data](#features.external-config.files.importing) - * [2.3.5. Importing Extensionless Files](#features.external-config.files.importing-extensionless) - * [2.3.6. Using Configuration Trees](#features.external-config.files.configtree) - * [2.3.7. Property Placeholders](#features.external-config.files.property-placeholders) - * [2.3.8. Working with Multi-Document Files](#features.external-config.files.multi-document) - * [2.3.9. Activation Properties](#features.external-config.files.activation-properties) - - * [2.4. Encrypting Properties](#features.external-config.encrypting) - * [2.5. Working with YAML](#features.external-config.yaml) - * [2.5.1. Mapping YAML to Properties](#features.external-config.yaml.mapping-to-properties) - * [2.5.2. Directly Loading YAML](#features.external-config.yaml.directly-loading) - - * [2.6. Configuring Random Values](#features.external-config.random-values) - * [2.7. Configuring System Environment Properties](#features.external-config.system-environment) - * [2.8. Type-safe Configuration Properties](#features.external-config.typesafe-configuration-properties) - * [2.8.1. JavaBean properties binding](#features.external-config.typesafe-configuration-properties.java-bean-binding) - * [2.8.2. Constructor binding](#features.external-config.typesafe-configuration-properties.constructor-binding) - * [2.8.3. Enabling @ConfigurationProperties-annotated types](#features.external-config.typesafe-configuration-properties.enabling-annotated-types) - * [2.8.4. Using @ConfigurationProperties-annotated types](#features.external-config.typesafe-configuration-properties.using-annotated-types) - * [2.8.5. Third-party Configuration](#features.external-config.typesafe-configuration-properties.third-party-configuration) - * [2.8.6. Relaxed Binding](#features.external-config.typesafe-configuration-properties.relaxed-binding) - * [Binding Maps](#features.external-config.typesafe-configuration-properties.relaxed-binding.maps) - * [Binding from Environment Variables](#features.external-config.typesafe-configuration-properties.relaxed-binding.environment-variables) - - * [2.8.7. Merging Complex Types](#features.external-config.typesafe-configuration-properties.merging-complex-types) - * [2.8.8. Properties Conversion](#features.external-config.typesafe-configuration-properties.conversion) - * [Converting Durations](#features.external-config.typesafe-configuration-properties.conversion.durations) - * [Converting periods](#features.external-config.typesafe-configuration-properties.conversion.periods) - * [Converting Data Sizes](#features.external-config.typesafe-configuration-properties.conversion.data-sizes) - - * [2.8.9. @ConfigurationProperties Validation](#features.external-config.typesafe-configuration-properties.validation) - * [2.8.10. @ConfigurationProperties vs. @Value](#features.external-config.typesafe-configuration-properties.vs-value-annotation) - -* [3. Profiles](#features.profiles) - * [3.1. Adding Active Profiles](#features.profiles.adding-active-profiles) - * [3.2. Profile Groups](#features.profiles.groups) - * [3.3. Programmatically Setting Profiles](#features.profiles.programmatically-setting-profiles) - * [3.4. Profile-specific Configuration Files](#features.profiles.profile-specific-configuration-files) - -* [4. Logging](#features.logging) - * [4.1. Log Format](#features.logging.log-format) - * [4.2. Console Output](#features.logging.console-output) - * [4.2.1. Color-coded Output](#features.logging.console-output.color-coded) - - * [4.3. File Output](#features.logging.file-output) - * [4.4. File Rotation](#features.logging.file-rotation) - * [4.5. Log Levels](#features.logging.log-levels) - * [4.6. Log Groups](#features.logging.log-groups) - * [4.7. Using a Log Shutdown Hook](#features.logging.shutdown-hook) - * [4.8. Custom Log Configuration](#features.logging.custom-log-configuration) - * [4.9. Logback Extensions](#features.logging.logback-extensions) - * [4.9.1. Profile-specific Configuration](#features.logging.logback-extensions.profile-specific) - * [4.9.2. Environment Properties](#features.logging.logback-extensions.environment-properties) - -* [5. Internationalization](#features.internationalization) -* [6. JSON](#features.json) - * [6.1. Jackson](#features.json.jackson) - * [6.2. Gson](#features.json.gson) - * [6.3. JSON-B](#features.json.json-b) - -* [7. Task Execution and Scheduling](#features.task-execution-and-scheduling) -* [8. Testing](#features.testing) - * [8.1. Test Scope Dependencies](#features.testing.test-scope-dependencies) - * [8.2. Testing Spring Applications](#features.testing.spring-applications) - * [8.3. Testing Spring Boot Applications](#features.testing.spring-boot-applications) - * [8.3.1. Detecting Web Application Type](#features.testing.spring-boot-applications.detecting-web-app-type) - * [8.3.2. Detecting Test Configuration](#features.testing.spring-boot-applications.detecting-configuration) - * [8.3.3. Excluding Test Configuration](#features.testing.spring-boot-applications.excluding-configuration) - * [8.3.4. Using Application Arguments](#features.testing.spring-boot-applications.using-application-arguments) - * [8.3.5. Testing with a mock environment](#features.testing.spring-boot-applications.with-mock-environment) - * [8.3.6. Testing with a running server](#features.testing.spring-boot-applications.with-running-server) - * [8.3.7. Customizing WebTestClient](#features.testing.spring-boot-applications.customizing-web-test-client) - * [8.3.8. Using JMX](#features.testing.spring-boot-applications.jmx) - * [8.3.9. Using Metrics](#features.testing.spring-boot-applications.metrics) - * [8.3.10. Mocking and Spying Beans](#features.testing.spring-boot-applications.mocking-beans) - * [8.3.11. Auto-configured Tests](#features.testing.spring-boot-applications.autoconfigured-tests) - * [8.3.12. Auto-configured JSON Tests](#features.testing.spring-boot-applications.json-tests) - * [8.3.13. Auto-configured Spring MVC Tests](#features.testing.spring-boot-applications.spring-mvc-tests) - * [8.3.14. Auto-configured Spring WebFlux Tests](#features.testing.spring-boot-applications.spring-webflux-tests) - * [8.3.15. Auto-configured Data Cassandra Tests](#features.testing.spring-boot-applications.autoconfigured-spring-data-cassandra) - * [8.3.16. Auto-configured Data JPA Tests](#features.testing.spring-boot-applications.autoconfigured-spring-data-jpa) - * [8.3.17. Auto-configured JDBC Tests](#features.testing.spring-boot-applications.autoconfigured-jdbc) - * [8.3.18. Auto-configured Data JDBC Tests](#features.testing.spring-boot-applications.autoconfigured-spring-data-jdbc) - * [8.3.19. Auto-configured jOOQ Tests](#features.testing.spring-boot-applications.autoconfigured-jooq) - * [8.3.20. Auto-configured Data MongoDB Tests](#features.testing.spring-boot-applications.autoconfigured-spring-data-mongodb) - * [8.3.21. Auto-configured Data Neo4j Tests](#features.testing.spring-boot-applications.autoconfigured-spring-data-neo4j) - * [8.3.22. Auto-configured Data Redis Tests](#features.testing.spring-boot-applications.autoconfigured-spring-data-redis) - * [8.3.23. Auto-configured Data LDAP Tests](#features.testing.spring-boot-applications.autoconfigured-spring-data-ldap) - * [8.3.24. Auto-configured REST Clients](#features.testing.spring-boot-applications.autoconfigured-rest-client) - * [8.3.25. Auto-configured Spring REST Docs Tests](#features.testing.spring-boot-applications.autoconfigured-spring-restdocs) - * [Auto-configured Spring REST Docs Tests with Mock MVC](#features.testing.spring-boot-applications.autoconfigured-spring-restdocs.with-mock-mvc) - * [Auto-configured Spring REST Docs Tests with WebTestClient](#features.testing.spring-boot-applications.autoconfigured-spring-restdocs.with-web-test-client) - * [Auto-configured Spring REST Docs Tests with REST Assured](#features.testing.spring-boot-applications.autoconfigured-spring-restdocs.with-rest-assured) - - * [8.3.26. Auto-configured Spring Web Services Tests](#features.testing.spring-boot-applications.autoconfigured-webservices) - * [Auto-configured Spring Web Services Client Tests](#features.testing.spring-boot-applications.autoconfigured-webservices.client) - * [Auto-configured Spring Web Services Server Tests](#features.testing.spring-boot-applications.autoconfigured-webservices.server) - - * [8.3.27. Additional Auto-configuration and Slicing](#features.testing.spring-boot-applications.additional-autoconfiguration-and-slicing) - * [8.3.28. User Configuration and Slicing](#features.testing.spring-boot-applications.user-configuration-and-slicing) - * [8.3.29. Using Spock to Test Spring Boot Applications](#features.testing.spring-boot-applications.spock) - - * [8.4. Test Utilities](#features.testing.utilities) - * [8.4.1. ConfigDataApplicationContextInitializer](#features.testing.utilities.config-data-application-context-initializer) - * [8.4.2. TestPropertyValues](#features.testing.utilities.test-property-values) - * [8.4.3. OutputCapture](#features.testing.utilities.output-capture) - * [8.4.4. TestRestTemplate](#features.testing.utilities.test-rest-template) - -* [9. Creating Your Own Auto-configuration](#features.developing-auto-configuration) - * [9.1. Understanding Auto-configured Beans](#features.developing-auto-configuration.understanding-auto-configured-beans) - * [9.2. Locating Auto-configuration Candidates](#features.developing-auto-configuration.locating-auto-configuration-candidates) - * [9.3. Condition Annotations](#features.developing-auto-configuration.condition-annotations) - * [9.3.1. Class Conditions](#features.developing-auto-configuration.condition-annotations.class-conditions) - * [9.3.2. Bean Conditions](#features.developing-auto-configuration.condition-annotations.bean-conditions) - * [9.3.3. Property Conditions](#features.developing-auto-configuration.condition-annotations.property-conditions) - * [9.3.4. Resource Conditions](#features.developing-auto-configuration.condition-annotations.resource-conditions) - * [9.3.5. Web Application Conditions](#features.developing-auto-configuration.condition-annotations.web-application-conditions) - * [9.3.6. SpEL Expression Conditions](#features.developing-auto-configuration.condition-annotations.spel-conditions) - - * [9.4. Testing your Auto-configuration](#features.developing-auto-configuration.testing) - * [9.4.1. Simulating a Web Context](#features.developing-auto-configuration.testing.simulating-a-web-context) - * [9.4.2. Overriding the Classpath](#features.developing-auto-configuration.testing.overriding-classpath) - - * [9.5. Creating Your Own Starter](#features.developing-auto-configuration.custom-starter) - * [9.5.1. Naming](#features.developing-auto-configuration.custom-starter.naming) - * [9.5.2. Configuration keys](#features.developing-auto-configuration.custom-starter.configuration-keys) - * [9.5.3. The “autoconfigure” Module](#features.developing-auto-configuration.custom-starter.autoconfigure-module) - * [9.5.4. Starter Module](#features.developing-auto-configuration.custom-starter.starter-module) - -* [10. Kotlin support](#features.kotlin) - * [10.1. Requirements](#features.kotlin.requirements) - * [10.2. Null-safety](#features.kotlin.null-safety) - * [10.3. Kotlin API](#features.kotlin.api) - * [10.3.1. runApplication](#features.kotlin.api.run-application) - * [10.3.2. Extensions](#features.kotlin.api.extensions) - - * [10.4. Dependency management](#features.kotlin.dependency-management) - * [10.5. @ConfigurationProperties](#features.kotlin.configuration-properties) - * [10.6. Testing](#features.kotlin.testing) - * [10.7. Resources](#features.kotlin.resources) - * [10.7.1. Further reading](#features.kotlin.resources.further-reading) - * [10.7.2. Examples](#features.kotlin.resources.examples) - -* [11. What to Read Next](#features.whats-next) +# Core Features 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 "[getting-started.html](getting-started.html#getting-started)" and "[using.html](using.html#using)" sections, so that you have a good grounding of the basics. -[](#features.spring-application)1. SpringApplication ----------- +## 1. SpringApplication + The `SpringApplication` class provides a convenient way to bootstrap a Spring application that is started from a `main()` method. In many situations, you can delegate to the static `SpringApplication.run` method, as shown in the following example: @@ -233,7 +57,7 @@ This will also turn off logging of the application’s active profiles. | |To add additional logging during startup, you can override `logStartupInfo(boolean)` in a subclass of `SpringApplication`.| |---|--------------------------------------------------------------------------------------------------------------------------| -### [](#features.spring-application.startup-failure)1.1. Startup Failure ### +### 1.1. Startup Failure If your application fails to start, registered `FailureAnalyzers` get a chance to provide a dedicated error message and a concrete action to fix the problem. For instance, if you start a web application on port `8080` and that port is already in use, you should see something similar to the following message: @@ -264,7 +88,7 @@ For instance, if you are running your application by using `java -jar`, you can $ java -jar myproject-0.0.1-SNAPSHOT.jar --debug ``` -### [](#features.spring-application.lazy-initialization)1.2. Lazy Initialization ### +### 1.2. Lazy Initialization `SpringApplication` allows an application to be initialized lazily. When lazy initialization is enabled, beans are created as they are needed rather than during application startup. @@ -296,7 +120,7 @@ spring: | |If you want to disable lazy initialization for certain beans while using lazy initialization for the rest of the application, you can explicitly set their lazy attribute to false using the `@Lazy(false)` annotation.| |---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#features.spring-application.banner)1.3. Customizing the Banner ### +### 1.3. Customizing the Banner The banner that is printed on start up can be changed by adding a `banner.txt` file to your classpath or by setting the `spring.banner.location` property to the location of such a file. If the file has an encoding other than UTF-8, you can set `spring.banner.charset`. @@ -324,7 +148,7 @@ The printed banner is registered as a singleton bean under the following name: ` | |The `${application.version}` and `${application.formatted-version}` properties are only available if you are using Spring Boot launchers.
The values will not be resolved if you are running an unpacked jar and starting it with `java -cp `.

This is why we recommend that you always launch unpacked jars using `java org.springframework.boot.loader.JarLauncher`.
This will initialize the `application.*` banner variables before building the classpath and launching your app.| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#features.spring-application.customizing-spring-application)1.4. Customizing SpringApplication ### +### 1.4. Customizing SpringApplication If the `SpringApplication` defaults are not to your taste, you can instead create a local instance and customize it. For example, to turn off the banner, you could write: @@ -355,7 +179,7 @@ See *[Externalized Configuration](#features.external-config)* for details. For a complete list of the configuration options, see the [`SpringApplication` Javadoc](https://docs.spring.io/spring-boot/docs/2.6.4/api/org/springframework/boot/SpringApplication.html). -### [](#features.spring-application.fluent-builder-api)1.5. Fluent Builder API ### +### 1.5. Fluent Builder API If you need to build an `ApplicationContext` hierarchy (multiple contexts with a parent/child relationship) or if you prefer using a “fluent” builder API, you can use the `SpringApplicationBuilder`. @@ -373,7 +197,7 @@ new SpringApplicationBuilder() | |There are some restrictions when creating an `ApplicationContext` hierarchy.
For example, Web components **must** be contained within the child context, and the same `Environment` is used for both parent and child contexts.
See the [`SpringApplicationBuilder` Javadoc](https://docs.spring.io/spring-boot/docs/2.6.4/api/org/springframework/boot/builder/SpringApplicationBuilder.html) for full details.| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#features.spring-application.application-availability)1.6. Application Availability ### +### 1.6. Application Availability When deployed on platforms, applications can provide information about their availability to the platform using infrastructure such as [Kubernetes Probes](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/). Spring Boot includes out-of-the box support for the commonly used “liveness” and “readiness” availability states. @@ -381,7 +205,7 @@ If you are using Spring Boot’s “actuator” support then these states are ex In addition, you can also obtain availability states by injecting the `ApplicationAvailability` interface into your own beans. -#### [](#features.spring-application.application-availability.liveness)1.6.1. Liveness State #### +#### 1.6.1. Liveness State The “Liveness” state of an application tells whether its internal state allows it to work correctly, or recover by itself if it is currently failing. A broken “Liveness” state means that the application is in a state that it cannot recover from, and the infrastructure should restart the application. @@ -393,7 +217,7 @@ The internal state of Spring Boot applications is mostly represented by the Spri If the application context has started successfully, Spring Boot assumes that the application is in a valid state. An application is considered live as soon as the context has been refreshed, see [Spring Boot application lifecycle and related Application Events](#features.spring-application.application-events-and-listeners). -#### [](#features.spring-application.application-availability.readiness)1.6.2. Readiness State #### +#### 1.6.2. Readiness State The “Readiness” state of an application tells whether the application is ready to handle traffic. A failing “Readiness” state tells the platform that it should not route traffic to the application for now. @@ -404,7 +228,7 @@ An application is considered ready as soon as application and command-line runne | |Tasks expected to run during startup should be executed by `CommandLineRunner` and `ApplicationRunner` components instead of using Spring component lifecycle callbacks such as `@PostConstruct`.| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.spring-application.application-availability.managing)1.6.3. Managing the Application Availability State #### +#### 1.6.3. Managing the Application Availability State Application components can retrieve the current availability state at any time, by injecting the `ApplicationAvailability` interface and calling methods on it. More often, applications will want to listen to state updates or update the state of the application. @@ -469,7 +293,7 @@ public class MyLocalCacheVerifier { Spring Boot provides [Kubernetes HTTP probes for "Liveness" and "Readiness" with Actuator Health Endpoints](actuator.html#actuator.endpoints.kubernetes-probes). You can get more guidance about [deploying Spring Boot applications on Kubernetes in the dedicated section](deployment.html#deployment.cloud.kubernetes). -### [](#features.spring-application.application-events-and-listeners)1.7. Application Events and Listeners ### +### 1.7. Application Events and Listeners In addition to the usual Spring Framework events, such as [`ContextRefreshedEvent`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/context/event/ContextRefreshedEvent.html), a `SpringApplication` sends some additional application events. @@ -516,7 +340,7 @@ As a result of this, if your application uses a hierarchy of `SpringApplication` To allow your listener to distinguish between an event for its context and an event for a descendant context, it should request that its application context is injected and then compare the injected context with the context of the event. The context can be injected by implementing `ApplicationContextAware` or, if the listener is a bean, by using `@Autowired`. -### [](#features.spring-application.web-environment)1.8. Web Environment ### +### 1.8. Web Environment A `SpringApplication` attempts to create the right type of `ApplicationContext` on your behalf. The algorithm used to determine a `WebApplicationType` is the following: @@ -535,7 +359,7 @@ It is also possible to take complete control of the `ApplicationContext` type th | |It is often desirable to call `setWebApplicationType(WebApplicationType.NONE)` when using `SpringApplication` within a JUnit test.| |---|----------------------------------------------------------------------------------------------------------------------------------| -### [](#features.spring-application.application-arguments)1.9. Accessing Application Arguments ### +### 1.9. Accessing Application Arguments If you need to access the application arguments that were passed to `SpringApplication.run(…​)`, you can inject a `org.springframework.boot.ApplicationArguments` bean. The `ApplicationArguments` interface provides access to both the raw `String[]` arguments as well as parsed `option` and `non-option` arguments, as shown in the following example: @@ -565,7 +389,7 @@ public class MyBean { | |Spring Boot also registers a `CommandLinePropertySource` with the Spring `Environment`.
This lets you also inject single application arguments by using the `@Value` annotation.| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#features.spring-application.command-line-runner)1.10. Using the ApplicationRunner or CommandLineRunner ### +### 1.10. Using the ApplicationRunner or CommandLineRunner If you need to run some specific code once the `SpringApplication` has started, you can implement the `ApplicationRunner` or `CommandLineRunner` interfaces. Both interfaces work in the same way and offer a single `run` method, which is called just before `SpringApplication.run(…​)` completes. @@ -594,7 +418,7 @@ public class MyCommandLineRunner implements CommandLineRunner { 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. -### [](#features.spring-application.application-exit)1.11. Application Exit ### +### 1.11. Application Exit Each `SpringApplication` registers a shutdown hook with the JVM to ensure that the `ApplicationContext` closes gracefully on exit. All the standard Spring lifecycle callbacks (such as the `DisposableBean` interface or the `@PreDestroy` annotation) can be used. @@ -627,7 +451,7 @@ public class MyApplication { Also, the `ExitCodeGenerator` interface may be implemented by exceptions. When such an exception is encountered, Spring Boot returns the exit code provided by the implemented `getExitCode()` method. -### [](#features.spring-application.admin)1.12. Admin Features ### +### 1.12. Admin Features It is possible to enable admin-related features for the application by specifying the `spring.application.admin.enabled` property. This exposes the [`SpringApplicationAdminMXBean`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/admin/SpringApplicationAdminMXBean.java) on the platform `MBeanServer`. @@ -637,7 +461,7 @@ This feature could also be useful for any service wrapper implementation. | |If you want to know on which HTTP port the application is running, get the property with a key of `local.server.port`.| |---|----------------------------------------------------------------------------------------------------------------------| -### [](#features.spring-application.startup-tracking)1.13. Application Startup tracking ### +### 1.13. Application Startup tracking During the application startup, the `SpringApplication` and the `ApplicationContext` perform many tasks related to the application lifecycle, the beans lifecycle or even processing application events. @@ -678,8 +502,8 @@ Applications can ask for the bean of type `BufferingApplicationStartup` in any c Spring Boot can also be configured to expose a [`startup` endpoint](https://docs.spring.io/spring-boot/docs/2.6.4/actuator-api/htmlsingle/#startup) that provides this information as a JSON document. -[](#features.external-config)2. Externalized Configuration ----------- +## 2. Externalized Configuration + Spring Boot lets you externalize your configuration so that you can work with the same application code in different environments. You can use a variety of external configuration sources, include Java properties files, YAML files, environment variables, and command-line arguments. @@ -758,14 +582,14 @@ For one-off testing, you can launch with a specific command line switch (for exa | |The `env` and `configprops` endpoints can be useful in determining why a property has a particular value.
You can use these two endpoints to diagnose unexpected property values.
See the "[Production ready features](actuator.html#actuator.endpoints)" section for details.| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#features.external-config.command-line-args)2.1. Accessing Command Line Properties ### +### 2.1. Accessing Command Line Properties By default, `SpringApplication` converts any command line option arguments (that is, arguments starting with `--`, such as `--server.port=9000`) to a `property` and adds them to the Spring `Environment`. As mentioned previously, command line properties always take precedence over file-based 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)`. -### [](#features.external-config.application-json)2.2. JSON Application Properties ### +### 2.2. JSON Application Properties Environment variables and system properties often have restrictions that mean some property names cannot be used. To help with this, Spring Boot allows you to encode a block of properties into a single JSON structure. @@ -797,7 +621,7 @@ If you are deploying to a classic Application Server, you could also use a JNDI | |Although `null` values from the JSON will be added to the resulting property source, the `PropertySourcesPropertyResolver` treats `null` properties as missing values.
This means that the JSON cannot override properties from lower order property sources with a `null` value.| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#features.external-config.files)2.3. External Application Properties []() ### +### 2.3. External Application Properties Spring Boot will automatically find and load `application.properties` and `application.yaml` files from the following locations when your application starts: @@ -887,7 +711,7 @@ These default values can then be overridden at runtime with a different file loc | |If your application runs in a servlet container or application server, then JNDI properties (in `java:comp/env`) or servlet context initialization parameters can be used instead of, or as well as, environment variables or system properties.| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.external-config.files.optional-prefix)2.3.1. Optional Locations #### +#### 2.3.1. Optional Locations By default, when a specified config data location does not exist, Spring Boot will throw a `ConfigDataLocationNotFoundException` and your application will not start. @@ -899,7 +723,7 @@ For example, a `spring.config.import` value of `optional:file:./myconfig.propert If you want to ignore all `ConfigDataLocationNotFoundExceptions` and always continue to start your application, you can use the `spring.config.on-not-found` property. Set the value to `ignore` using `SpringApplication.setDefaultProperties(…​)` or with a system/environment variable. -#### [](#features.external-config.files.wildcard-locations)2.3.2. Wildcard Locations #### +#### 2.3.2. Wildcard Locations If a config file location includes the `*` character for the last path segment, it is considered a wildcard location. Wildcards are expanded when the config is loaded so that immediate subdirectories are also checked. @@ -920,7 +744,7 @@ You can use wildcard locations yourself with the `spring.config.location` and `s | |Wildcard locations only work with external directories.
You cannot use a wildcard in a `classpath:` location.| |---|-----------------------------------------------------------------------------------------------------------------| -#### [](#features.external-config.files.profile-specific)2.3.3. Profile Specific Files #### +#### 2.3.3. Profile Specific Files As well as `application` property files, Spring Boot will also attempt to load profile-specific files using the naming convention `application-{profile}`. For example, if your application activates a profile named `prod` and uses YAML files, then both `application.yml` and `application-prod.yml` will be considered. @@ -938,7 +762,7 @@ In other words, if no profiles are explicitly activated, then properties from `a | |Properties files are only ever loaded once.
If you have already directly [imported](#features.external-config.files.importing) a profile specific property files then it will not be imported a second time.| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.external-config.files.importing)2.3.4. Importing Additional Data #### +#### 2.3.4. Importing Additional Data Application properties may import further config data from other locations using the `spring.config.import` property. Imports are processed as they are discovered, and are treated as additional documents inserted immediately below the one that declares the import. @@ -1015,7 +839,7 @@ Locations will be processed in the order that they are defined, with later impor | |Spring Boot includes pluggable API that allows various different location addresses to be supported.
By default you can import Java Properties, YAML and “[configuration trees](#features.external-config.files.configtree)”.

Third-party jars can offer support for additional technologies (there is no requirement for files to be local).
For example, you can imagine config data being from external stores such as Consul, Apache ZooKeeper or Netflix Archaius.

If you want to support your own locations, see the `ConfigDataLocationResolver` and `ConfigDataLoader` classes in the `org.springframework.boot.context.config` package.| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.external-config.files.importing-extensionless)2.3.5. Importing Extensionless Files #### +#### 2.3.5. Importing Extensionless Files Some cloud platforms cannot add a file extension to volume mounted files. To import these extensionless files, you need to give Spring Boot a hint so that it knows how to load them. @@ -1038,7 +862,7 @@ spring: import: "file:/etc/config/myconfig[.yaml]" ``` -#### [](#features.external-config.files.configtree)2.3.6. Using Configuration Trees #### +#### 2.3.6. Using Configuration Trees When running applications on a cloud platform (such as Kubernetes) you often need to read config values that the platform supplies. It is not uncommon to use environment variables for such purposes, but this can have drawbacks, especially if the value is supposed to be kept secret. @@ -1151,7 +975,7 @@ spring: import: "optional:configtree:/run/secrets/" ``` -#### [](#features.external-config.files.property-placeholders)2.3.7. Property Placeholders #### +#### 2.3.7. Property Placeholders The values in `application.properties` and `application.yml` are filtered through the existing `Environment` when they are used, so you can refer back to previously defined values (for example, from System properties). The standard `${name}` property-placeholder syntax can be used anywhere within a value. @@ -1176,7 +1000,7 @@ app: | |You can also use this technique to create “short” variants of existing Spring Boot properties.
See the *[howto.html](howto.html#howto.properties-and-configuration.short-command-line-arguments)* how-to for details.| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.external-config.files.multi-document)2.3.8. Working with Multi-Document Files #### +#### 2.3.8. Working with Multi-Document Files Spring Boot allows you to split a single physical file into multiple logical documents which are each added independently. Documents are processed in order, from top to bottom. @@ -1218,7 +1042,7 @@ spring.config.activate.on-cloud-platform=kubernetes | |Multi-document property files cannot be loaded by using the `@PropertySource` or `@TestPropertySource` annotations.| |---|-------------------------------------------------------------------------------------------------------------------| -#### [](#features.external-config.files.activation-properties)2.3.9. Activation Properties #### +#### 2.3.9. Activation Properties It is sometimes useful to only activate a given set of properties when certain conditions are met. For example, you might have properties that are only relevant when a specific profile is active. @@ -1258,7 +1082,7 @@ spring: myotherprop: "sometimes-set" ``` -### [](#features.external-config.encrypting)2.4. Encrypting Properties ### +### 2.4. Encrypting Properties Spring Boot does not provide any built in support for encrypting property values, however, it does provide the hook points necessary to modify values contained in the Spring `Environment`. The `EnvironmentPostProcessor` interface allows you to manipulate the `Environment` before the application starts. @@ -1266,7 +1090,7 @@ See [howto.html](howto.html#howto.application.customize-the-environment-or-appli If you need a secure way to store credentials and passwords, the [Spring Cloud Vault](https://cloud.spring.io/spring-cloud-vault/) project provides support for storing externalized configuration in [HashiCorp Vault](https://www.vaultproject.io/). -### [](#features.external-config.yaml)2.5. Working with YAML ### +### 2.5. Working with YAML [YAML](https://yaml.org) 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 [SnakeYAML](https://bitbucket.org/asomov/snakeyaml) library on your classpath. @@ -1274,7 +1098,7 @@ The `SpringApplication` class automatically supports YAML as an alternative to p | |If you use “Starters”, SnakeYAML is automatically provided by `spring-boot-starter`.| |---|------------------------------------------------------------------------------------| -#### [](#features.external-config.yaml.mapping-to-properties)2.5.1. Mapping YAML to Properties #### +#### 2.5.1. Mapping YAML to Properties YAML documents need to be converted from their hierarchical format to a flat structure that can be used with the Spring `Environment`. For example, consider the following YAML document: @@ -1322,14 +1146,14 @@ my.servers[1]=another.example.com | |YAML files cannot be loaded by using the `@PropertySource` or `@TestPropertySource` annotations.
So, in the case that you need to load values that way, you need to use a properties file.| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.external-config.yaml.directly-loading)2.5.2. Directly Loading YAML #### +#### 2.5.2. Directly Loading YAML Spring Framework provides two convenient classes that can be used to load YAML documents. The `YamlPropertiesFactoryBean` loads YAML as `Properties` and the `YamlMapFactoryBean` loads YAML as a `Map`. You can also use the `YamlPropertySourceLoader` class if you want to load YAML as a Spring `PropertySource`. -### [](#features.external-config.random-values)2.6. Configuring Random Values ### +### 2.6. Configuring Random Values The `RandomValuePropertySource` is useful for injecting random values (for example, into secrets or test cases). It can produce integers, longs, uuids, or strings, as shown in the following example: @@ -1360,7 +1184,7 @@ my: The `random.int*` syntax is `OPEN value (,max) CLOSE` where the `OPEN,CLOSE` are any character and `value,max` are integers. If `max` is provided, then `value` is the minimum value and `max` is the maximum value (exclusive). -### [](#features.external-config.system-environment)2.7. Configuring System Environment Properties ### +### 2.7. Configuring System Environment Properties Spring Boot supports setting a prefix for environment properties. This is useful if the system environment is shared by multiple Spring Boot applications with different configuration requirements. @@ -1368,7 +1192,7 @@ The prefix for system environment properties can be set directly on `SpringAppli For example, if you set the prefix to `input`, a property such as `remote.timeout` will also be resolved as `input.remote.timeout` in the system environment. -### [](#features.external-config.typesafe-configuration-properties)2.8. Type-safe Configuration Properties ### +### 2.8. Type-safe Configuration Properties Using the `@Value("${property}")` annotation to inject configuration properties can sometimes be cumbersome, especially if you are working with multiple properties or your data is hierarchical in nature. Spring Boot provides an alternative method of working with properties that lets strongly typed beans govern and validate the configuration of your application. @@ -1376,7 +1200,7 @@ Spring Boot provides an alternative method of working with properties that lets | |See also the [differences between `@Value` and type-safe configuration properties](#features.external-config.typesafe-configuration-properties.vs-value-annotation).| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.external-config.typesafe-configuration-properties.java-bean-binding)2.8.1. JavaBean properties binding #### +#### 2.8.1. JavaBean properties binding It is possible to bind a bean declaring standard JavaBean properties as shown in the following example: @@ -1478,7 +1302,7 @@ The preceding POJO defines the following properties: | |Such arrangement relies on a default empty constructor and getters and setters are usually mandatory, since binding is through standard Java Beans property descriptors, just like in Spring MVC.
A setter may be omitted in the following cases:

* Maps, as long as they are initialized, need a getter but not necessarily a setter, since they can be mutated by the binder.

* Collections and arrays can be accessed either through an index (typically with YAML) or by using a single comma-separated value (properties).
In the latter case, a setter is mandatory.
We recommend to always add a setter for such types.
If you initialize a collection, make sure it is not immutable (as in the preceding example).

* If nested POJO properties are initialized (like the `Security` field in the preceding example), a setter is not required.
If you want the binder to create the instance on the fly by using its default constructor, you need a setter.

Some people use Project Lombok to add getters and setters automatically.
Make sure that Lombok does not generate any particular constructor for such a type, as it is used automatically by the container to instantiate the object.

Finally, only standard Java Bean properties are considered and binding on static properties is not supported.| |---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.external-config.typesafe-configuration-properties.constructor-binding)2.8.2. Constructor binding #### +#### 2.8.2. Constructor binding The example in the previous section can be rewritten in an immutable fashion as shown in the following example: @@ -1587,7 +1411,7 @@ public MyProperties(boolean enabled, InetAddress remoteAddress, @DefaultValue Se | |The use of `java.util.Optional` with `@ConfigurationProperties` is not recommended as it is primarily intended for use as a return type.
As such, it is not well-suited to configuration property injection.
For consistency with properties of other types, if you do declare an `Optional` property and it has no value, `null` rather than an empty `Optional` will be bound.| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.external-config.typesafe-configuration-properties.enabling-annotated-types)2.8.3. Enabling @ConfigurationProperties-annotated types #### +#### 2.8.3. Enabling @ConfigurationProperties-annotated types Spring Boot provides infrastructure to bind `@ConfigurationProperties` types and register them as beans. You can either enable configuration properties on a class-by-class basis or enable configuration property scanning that works in a similar manner to component scanning. @@ -1632,7 +1456,7 @@ We recommend that `@ConfigurationProperties` only deal with the environment and, For corner cases, setter injection can be used or any of the `*Aware` interfaces provided by the framework (such as `EnvironmentAware` if you need access to the `Environment`). If you still want to inject other beans using the constructor, the configuration properties bean must be annotated with `@Component` and use JavaBean-based property binding. -#### [](#features.external-config.typesafe-configuration-properties.using-annotated-types)2.8.4. Using @ConfigurationProperties-annotated types #### +#### 2.8.4. Using @ConfigurationProperties-annotated types This style of configuration works particularly well with the `SpringApplication` external YAML configuration, as shown in the following example: @@ -1676,7 +1500,7 @@ public class MyService { | |Using `@ConfigurationProperties` also lets you generate metadata files that can be used by IDEs to offer auto-completion for your own keys.
See the [appendix](configuration-metadata.html#appendix.configuration-metadata) for details.| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.external-config.typesafe-configuration-properties.third-party-configuration)2.8.5. Third-party Configuration #### +#### 2.8.5. Third-party Configuration As well as using `@ConfigurationProperties` to annotate a class, you can also use it on public `@Bean` methods. Doing so can be particularly useful when you want to bind properties to third-party components that are outside of your control. @@ -1703,7 +1527,7 @@ public class ThirdPartyConfiguration { Any JavaBean property defined with the `another` prefix is mapped onto that `AnotherComponent` bean in manner similar to the preceding `SomeProperties` example. -#### [](#features.external-config.typesafe-configuration-properties.relaxed-binding)2.8.6. Relaxed Binding #### +#### 2.8.6. Relaxed Binding Spring Boot uses some relaxed rules for binding `Environment` properties to `@ConfigurationProperties` beans, so there does not need to be an exact match between the `Environment` property name and the bean property name. Common examples where this is useful include dash-separated environment properties (for example, `context-path` binds to `contextPath`), and capitalized environment properties (for example, `PORT` binds to `port`). @@ -1752,7 +1576,7 @@ With the preceding code, the following properties names can all be used: | |We recommend that, when possible, properties are stored in lower-case kebab format, such as `my.person.first-name=Rod`.| |---|-----------------------------------------------------------------------------------------------------------------------| -##### [](#features.external-config.typesafe-configuration-properties.relaxed-binding.maps)Binding Maps ##### +##### Binding Maps# When binding to `Map` properties you may need to use a special bracket notation so that the original `key` value is preserved. If the key is not surrounded by `[]`, any characters that are not alpha-numeric, `-` or `.` are removed. @@ -1786,7 +1610,7 @@ The slash has been removed from `key3` because it was not surrounded by square b You may also occasionally need to use the bracket notation if your `key` contains a `.` and you are binding to non-scalar value. For example, binding `a.b=c` to `Map` will return a Map with the entry `{"a"={"b"="c"}}` whereas `[a.b]=c` will return a Map with the entry `{"a.b"="c"}`. -##### [](#features.external-config.typesafe-configuration-properties.relaxed-binding.environment-variables)Binding from Environment Variables ##### +##### Binding from Environment Variables Most operating systems impose strict rules around the names that can be used for environment variables. For example, Linux shell variables can contain only letters (`a` to `z` or `A` to `Z`), numbers (`0` to `9`) or the underscore character (`_`). @@ -1809,7 +1633,7 @@ To bind to a `List`, the element number should be surrounded with underscores in For example, the configuration property `my.service[0].other` would use an environment variable named `MY_SERVICE_0_OTHER`. -#### [](#features.external-config.typesafe-configuration-properties.merging-complex-types)2.8.7. Merging Complex Types #### +#### 2.8.7. Merging Complex Types When lists are configured in more than one place, overriding works by replacing the entire list. @@ -1970,7 +1794,7 @@ If the `dev` profile is enabled, however, `map` contains two entries with keys ` | |The preceding merging rules apply to properties from all property sources, and not just files.| |---|----------------------------------------------------------------------------------------------| -#### [](#features.external-config.typesafe-configuration-properties.conversion)2.8.8. Properties Conversion #### +#### 2.8.8. Properties Conversion Spring Boot attempts to coerce the external application properties to the right type when it binds to the `@ConfigurationProperties` beans. If you need custom type conversion, you can provide a `ConversionService` bean (with a bean named `conversionService`) or custom property editors (through a `CustomEditorConfigurer` bean) or custom `Converters` (with bean definitions annotated as `@ConfigurationPropertiesBinding`). @@ -1978,7 +1802,7 @@ If you need custom type conversion, you can provide a `ConversionService` bean ( | |As this bean is requested very early during the application lifecycle, make sure to limit the dependencies that your `ConversionService` is using.
Typically, any dependency that you require may not be fully initialized at creation time.
You may want to rename your custom `ConversionService` if it is not required for configuration keys coercion and only rely on custom converters qualified with `@ConfigurationPropertiesBinding`.| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -##### [](#features.external-config.typesafe-configuration-properties.conversion.durations)Converting Durations ##### +##### Converting Durations Spring Boot has dedicated support for expressing durations. If you expose a `java.time.Duration` property, the following formats in application properties are available: @@ -2094,7 +1918,7 @@ public class MyProperties { | |If you are upgrading a `Long` property, make sure to define the unit (using `@DurationUnit`) if it is not milliseconds.
Doing so gives a transparent upgrade path while supporting a much richer format.| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -##### [](#features.external-config.typesafe-configuration-properties.conversion.periods)Converting periods ##### +##### Converting periods In addition to durations, Spring Boot can also work with `java.time.Period` type. The following formats can be used in application properties: @@ -2118,7 +1942,7 @@ The following units are supported with the simple format: | |The `java.time.Period` type never actually stores the number of weeks, it is a shortcut that means “7 days”.| |---|------------------------------------------------------------------------------------------------------------| -##### [](#features.external-config.typesafe-configuration-properties.conversion.data-sizes)Converting Data Sizes ##### +##### Converting Data Sizes Spring Framework has a `DataSize` value type that expresses a size in bytes. If you expose a `DataSize` property, the following formats in application properties are available: @@ -2226,7 +2050,7 @@ public class MyProperties { | |If you are upgrading a `Long` property, make sure to define the unit (using `@DataSizeUnit`) if it is not bytes.
Doing so gives a transparent upgrade path while supporting a much richer format.| |---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.external-config.typesafe-configuration-properties.validation)2.8.9. @ConfigurationProperties Validation #### +#### 2.8.9. @ConfigurationProperties Validation Spring Boot attempts to validate `@ConfigurationProperties` classes whenever they are annotated with Spring’s `@Validated` annotation. You can use JSR-303 `javax.validation` constraint annotations directly on your configuration class. @@ -2330,7 +2154,7 @@ Doing so avoids any problems that may be caused by early instantiation. | |The `spring-boot-actuator` module includes an endpoint that exposes all `@ConfigurationProperties` beans.
Point your web browser to `/actuator/configprops` or use the equivalent JMX endpoint.
See the "[Production ready features](actuator.html#actuator.endpoints)" section for details.| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.external-config.typesafe-configuration-properties.vs-value-annotation)2.8.10. @ConfigurationProperties vs. @Value #### +#### 2.8.10. @ConfigurationProperties vs. @Value The `@Value` annotation is a core container feature, and it does not provide the same features as type-safe configuration properties. The following table summarizes the features that are supported by `@ConfigurationProperties` and `@Value`: @@ -2351,8 +2175,8 @@ Doing so will provide you with structured, type-safe object that you can inject However, it is possible to write a `SpEL` expression in `@Value`. If the value of a property from an application property file is a `SpEL` expression, it will be evaluated when consumed through `@Value`. -[](#features.profiles)3. Profiles ----------- +## 3. Profiles + Spring Profiles provide a way to segregate parts of your application configuration and make it be available only in certain environments. Any `@Component`, `@Configuration` or `@ConfigurationProperties` can be marked with `@Profile` to limit when it is loaded, as shown in the following example: @@ -2411,7 +2235,7 @@ spring: default: "none" ``` -### [](#features.profiles.adding-active-profiles)3.1. Adding Active Profiles ### +### 3.1. Adding Active Profiles The `spring.profiles.active` property follows the same ordering rules as other properties: The highest `PropertySource` wins. This means that you can specify active profiles in `application.properties` and then **replace** them by using the command line switch. @@ -2421,7 +2245,7 @@ The `SpringApplication` entry point has a Java API for setting additional profil See the `setAdditionalProfiles()` method in [SpringApplication](https://docs.spring.io/spring-boot/docs/2.6.4/api/org/springframework/boot/SpringApplication.html). Profile groups, which are described in the [next section](#features.profiles.groups) can also be used to add active profiles if a given profile is active. -### [](#features.profiles.groups)3.2. Profile Groups ### +### 3.2. Profile Groups Occasionally the profiles that you define and use in your application are too fine-grained and become cumbersome to use. For example, you might have `proddb` and `prodmq` profiles that you use to enable database and messaging features independently. @@ -2451,18 +2275,17 @@ spring: Our application can now be started using `--spring.profiles.active=production` to active the `production`, `proddb` and `prodmq` profiles in one hit. -### [](#features.profiles.programmatically-setting-profiles)3.3. Programmatically Setting Profiles ### +### 3.3. Programmatically Setting Profiles You can programmatically set active profiles by calling `SpringApplication.setAdditionalProfiles(…​)` before your application runs. It is also possible to activate profiles by using Spring’s `ConfigurableEnvironment` interface. -### [](#features.profiles.profile-specific-configuration-files)3.4. Profile-specific Configuration Files ### +### 3.4. Profile-specific Configuration Files Profile-specific variants of both `application.properties` (or `application.yml`) and files referenced through `@ConfigurationProperties` are considered as files and loaded. See "[Profile Specific Files](#features.external-config.files.profile-specific)" for details. -[](#features.logging)4. Logging ----------- +## 4. Logging Spring Boot uses [Commons Logging](https://commons.apache.org/logging) for all internal logging but leaves the underlying log implementation open. Default configurations are provided for [Java Util Logging](https://docs.oracle.com/javase/8/docs/api/java/util/logging/package-summary.html), [Log4J2](https://logging.apache.org/log4j/2.x/), and [Logback](https://logback.qos.ch/). @@ -2477,7 +2300,7 @@ Appropriate Logback routing is also included to ensure that dependent libraries | |When you deploy your application to a servlet container or application server, logging performed with the Java Util Logging API is not routed into your application’s logs.
This prevents logging performed by the container or other applications that have been deployed to it from appearing in your application’s logs.| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#features.logging.log-format)4.1. Log Format ### +### 4.1. Log Format The default log output from Spring Boot resembles the following example: @@ -2508,7 +2331,7 @@ The following items are output: | |Logback does not have a `FATAL` level.
It is mapped to `ERROR`.| |---|-------------------------------------------------------------------| -### [](#features.logging.console-output)4.2. Console Output ### +### 4.2. Console Output The default log configuration echoes messages to the console as they are written. By default, `ERROR`-level, `WARN`-level, and `INFO`-level messages are logged. @@ -2527,7 +2350,7 @@ Enabling the debug mode does *not* configure your application to log all message Alternatively, you can enable a “trace” mode by starting your application with a `--trace` flag (or `trace=true` in your `application.properties`). Doing so enables trace logging for a selection of core loggers (embedded container, Hibernate schema generation, and the whole Spring portfolio). -#### [](#features.logging.console-output.color-coded)4.2.1. Color-coded Output #### +#### 4.2.1. Color-coded Output If your terminal supports ANSI, color output is used to aid readability. You can set `spring.output.ansi.enabled` to a [supported value](https://docs.spring.io/spring-boot/docs/2.6.4/api/org/springframework/boot/ansi/AnsiOutput.Enabled.html) to override the auto-detection. @@ -2573,7 +2396,7 @@ The following colors and styles are supported: * `yellow` -### [](#features.logging.file-output)4.3. File Output ### +### 4.3. File Output By default, Spring Boot logs only to the console and does not write log files. If you want to write log files in addition to the console output, you need to set a `logging.file.name` or `logging.file.path` property (for example, in your `application.properties`). @@ -2591,7 +2414,7 @@ Log files rotate when they reach 10 MB and, as with console output, `ERROR`-leve | |Logging properties are independent of the actual logging infrastructure.
As a result, specific configuration keys (such as `logback.configurationFile` for Logback) are not managed by spring Boot.| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#features.logging.file-rotation)4.4. File Rotation ### +### 4.4. File Rotation If you are using the Logback, it is possible to fine-tune log rotation settings using your `application.properties` or `application.yaml` file. For all other logging system, you will need to configure rotation settings directly yourself (for example, if you use Log4J2 then you could add a `log4j2.xml` or `log4j2-spring.xml` file). @@ -2606,7 +2429,7 @@ The following rotation policy properties are supported: | `logging.logback.rollingpolicy.total-size-cap` |The maximum amount of size log archives can take before being deleted.| | `logging.logback.rollingpolicy.max-history` | The maximum number of archive log files to keep (defaults to 7). | -### [](#features.logging.log-levels)4.5. Log Levels ### +### 4.5. Log Levels All the supported logging systems can have the logger levels set in the Spring `Environment` (for example, in `application.properties`) by using `logging.level.=` where `level` is one of TRACE, DEBUG, INFO, WARN, ERROR, FATAL, or OFF. The `root` logger can be configured by using `logging.level.root`. @@ -2637,7 +2460,7 @@ For example, `LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_WEB=DEBUG` will set `org.springf | |The above approach will only work for package level logging.
Since relaxed binding always converts environment variables to lowercase, it is not possible to configure logging for an individual class in this way.
If you need to configure logging for a class, you can use [the `SPRING_APPLICATION_JSON`](#features.external-config.application-json) variable.| |---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#features.logging.log-groups)4.6. Log Groups ### +### 4.6. Log Groups It is often useful to be able to group related loggers together so that they can all be configured at the same time. For example, you might commonly change the logging levels for *all* Tomcat related loggers, but you can not easily remember top level packages. @@ -2682,7 +2505,7 @@ Spring Boot includes the following pre-defined logging groups that can be used o |web |`org.springframework.core.codec`, `org.springframework.http`, `org.springframework.web`, `org.springframework.boot.actuate.endpoint.web`, `org.springframework.boot.web.servlet.ServletContextInitializerBeans`| |sql | `org.springframework.jdbc.core`, `org.hibernate.SQL`, `org.jooq.tools.LoggerListener` | -### [](#features.logging.shutdown-hook)4.7. Using a Log Shutdown Hook ### +### 4.7. Using a Log Shutdown Hook In order to release logging resources when your application terminates, a shutdown hook that will trigger log system cleanup when the JVM exits is provided. This shutdown hook is registered automatically unless your application is deployed as a war file. @@ -2706,7 +2529,7 @@ logging: register-shutdown-hook: false ``` -### [](#features.logging.custom-log-configuration)4.8. Custom Log Configuration ### +### 4.8. Custom Log Configuration The various logging systems can be activated by including the appropriate libraries on the classpath and can be further customized by providing a suitable configuration file in the root of the classpath or in a location specified by the following Spring `Environment` property: `logging.config`. @@ -2771,7 +2594,7 @@ See the default configurations in `spring-boot.jar` for examples: | |You can add MDC and other ad-hoc content to log lines by overriding only the `LOG_LEVEL_PATTERN` (or `logging.pattern.level` with Logback).
For example, if you use `logging.pattern.level=user:%X{user} %5p`, then the default log format contains an MDC entry for "user", if it exists, as shown in the following example.

```
2019-08-30 12:30:04.031 user:someone INFO 22174 --- [ nio-8080-exec-0] demo.Controller
Handling authenticated request
```| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#features.logging.logback-extensions)4.9. Logback Extensions ### +### 4.9. Logback Extensions Spring Boot includes a number of extensions to Logback that can help with advanced configuration. You can use these extensions in your `logback-spring.xml` configuration file. @@ -2787,7 +2610,7 @@ ERROR in [email protected]:71 - no applicable action for [springProperty], curr ERROR in ch.qos.logback.core.joran.spi.Interpret[email protected]:71 - no applicable action for [springProfile], current ElementPath is [[configuration][springProfile]] ``` -#### [](#features.logging.logback-extensions.profile-specific)4.9.1. Profile-specific Configuration #### +#### 4.9.1. Profile-specific Configuration The `` tag lets you optionally include or exclude sections of configuration based on the active Spring profiles. Profile sections are supported anywhere within the `` element. @@ -2811,7 +2634,7 @@ The following listing shows three sample profiles: ``` -#### [](#features.logging.logback-extensions.environment-properties)4.9.2. Environment Properties #### +#### 4.9.2. Environment Properties The `` tag lets you expose properties from the Spring `Environment` for use within Logback. Doing so can be useful if you want to access values from your `application.properties` file in your Logback configuration. @@ -2833,8 +2656,7 @@ The following example shows how to expose properties for use within Logback: | |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.| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------| -[](#features.internationalization)5. Internationalization ----------- +## 5. Internationalization Spring Boot supports localized messages so that your application can cater to users of different language preferences. By default, Spring Boot looks for the presence of a `messages` resource bundle at the root of the classpath. @@ -2865,8 +2687,7 @@ spring: See [`MessageSourceProperties`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceProperties.java) for more supported options. -[](#features.json)6. JSON ----------- +## 6. JSON Spring Boot provides integration with three JSON mapping libraries: @@ -2878,27 +2699,26 @@ Spring Boot provides integration with three JSON mapping libraries: Jackson is the preferred and default library. -### [](#features.json.jackson)6.1. Jackson ### +### 6.1. Jackson Auto-configuration for Jackson is provided and Jackson is part of `spring-boot-starter-json`. When Jackson is on the classpath an `ObjectMapper` bean is automatically configured. Several configuration properties are provided for [customizing the configuration of the `ObjectMapper`](howto.html#howto.spring-mvc.customize-jackson-objectmapper). -### [](#features.json.gson)6.2. Gson ### +### 6.2. Gson Auto-configuration for Gson is provided. When Gson is on the classpath a `Gson` bean is automatically configured. Several `spring.gson.*` configuration properties are provided for customizing the configuration. To take more control, one or more `GsonBuilderCustomizer` beans can be used. -### [](#features.json.json-b)6.3. JSON-B ### +### 6.3. JSON-B Auto-configuration for JSON-B is provided. When the JSON-B API and an implementation are on the classpath a `Jsonb` bean will be automatically configured. The preferred JSON-B implementation is Apache Johnzon for which dependency management is provided. -[](#features.task-execution-and-scheduling)7. Task Execution and Scheduling ----------- +## 7. Task Execution and Scheduling In the absence of an `Executor` bean in the context, Spring Boot auto-configures a `ThreadPoolTaskExecutor` with sensible defaults that can be automatically associated to asynchronous task execution (`@EnableAsync`) and Spring MVC asynchronous request processing. @@ -2954,8 +2774,7 @@ spring: Both a `TaskExecutorBuilder` bean and a `TaskSchedulerBuilder` bean are made available in the context if a custom executor or scheduler needs to be created. -[](#features.testing)8. Testing ----------- +## 8. Testing Spring Boot provides a number of utilities and annotations to help when testing your application. Test support is provided by two modules: `spring-boot-test` contains core items, and `spring-boot-test-autoconfigure` supports auto-configuration for tests. @@ -2967,7 +2786,7 @@ Most developers use the `spring-boot-starter-test` “Starter”, which imports `hamcrest-core` is excluded in favor of `org.hamcrest:hamcrest` that is part of `spring-boot-starter-test`. -### [](#features.testing.test-scope-dependencies)8.1. Test Scope Dependencies ### +### 8.1. Test Scope Dependencies The `spring-boot-starter-test` “Starter” (in the `test` `scope`) contains the following provided libraries: @@ -2988,7 +2807,7 @@ The `spring-boot-starter-test` “Starter” (in the `test` `scope`) contains th 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. -### [](#features.testing.spring-applications)8.2. Testing Spring Applications ### +### 8.2. Testing Spring Applications One of the major advantages of dependency injection is that it should make your code easier to unit test. You can instantiate objects by using the `new` operator without even involving Spring. @@ -3002,7 +2821,7 @@ You can declare a dependency directly to `org.springframework:spring-test` or us If you have not used the `spring-test` module before, you should start by reading the [relevant section](https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/testing.html#testing) of the Spring Framework reference documentation. -### [](#features.testing.spring-boot-applications)8.3. Testing Spring Boot Applications ### +### 8.3. 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. @@ -3038,7 +2857,7 @@ You can use the `webEnvironment` attribute of `@SpringBootTest` to further refin | |`@SpringBootTest` with `webEnvironment = WebEnvironment.RANDOM_PORT` will also start the management server on a separate random port if your application uses a different port for the management server.| |---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.testing.spring-boot-applications.detecting-web-app-type)8.3.1. Detecting Web Application Type #### +#### 8.3.1. Detecting Web Application Type If Spring MVC is available, a regular MVC-based application context is configured. If you have only Spring WebFlux, we will detect that and configure a WebFlux-based application context instead. @@ -3058,7 +2877,7 @@ class MyWebFluxTests { ``` -#### [](#features.testing.spring-boot-applications.detecting-configuration)8.3.2. Detecting Test Configuration #### +#### 8.3.2. Detecting Test Configuration If you are familiar with the Spring Test Framework, you may be used to using `@ContextConfiguration(classes=…​)` in order to specify which Spring `@Configuration` to load. Alternatively, you might have often used nested `@Configuration` classes within your test. @@ -3078,7 +2897,7 @@ Unlike a nested `@Configuration` class, which would be used instead of your appl | |Spring’s test framework caches application contexts between tests.
Therefore, as long as your tests share the same configuration (no matter how it is discovered), the potentially time-consuming process of loading the context happens only once.| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.testing.spring-boot-applications.excluding-configuration)8.3.3. Excluding Test Configuration #### +#### 8.3.3. Excluding Test Configuration If your application uses component scanning (for example, if you use `@SpringBootApplication` or `@ComponentScan`), you may find top-level configuration classes that you created only for specific tests accidentally get picked up everywhere. @@ -3108,7 +2927,7 @@ class MyTests { | |If you directly use `@ComponentScan` (that is, not through `@SpringBootApplication`) you need to register the `TypeExcludeFilter` with it.
See [the Javadoc](https://docs.spring.io/spring-boot/docs/2.6.4/api/org/springframework/boot/context/TypeExcludeFilter.html) for details.| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.testing.spring-boot-applications.using-application-arguments)8.3.4. Using Application Arguments #### +#### 8.3.4. Using Application Arguments If your application expects [arguments](#features.spring-application.application-arguments), you can have `@SpringBootTest` inject them using the `args` attribute. @@ -3135,7 +2954,7 @@ class MyApplicationArgumentTests { ``` -#### [](#features.testing.spring-boot-applications.with-mock-environment)8.3.5. Testing with a mock environment #### +#### 8.3.5. Testing with a mock environment By default, `@SpringBootTest` does not start the server but instead sets up a mock environment for testing web endpoints. @@ -3210,7 +3029,7 @@ class MyMockWebTestClientTests { | |Testing within a mocked environment is usually faster than running with a full servlet container.
However, since mocking occurs at the Spring MVC layer, code that relies on lower-level servlet container behavior cannot be directly tested with MockMvc.

For example, Spring Boot’s error handling is based on the “error page” support provided by the servlet container.
This means that, whilst you can test your MVC layer throws and handles exceptions as expected, you cannot directly test that a specific [custom error page](web.html#web.servlet.spring-mvc.error-handling.error-pages) is rendered.
If you need to test these lower-level concerns, you can start a fully running server as described in the next section.| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.testing.spring-boot-applications.with-running-server)8.3.6. Testing with a running server #### +#### 8.3.6. Testing with a running server If you need to start a full running server, we recommend that you use random ports. If you use `@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)`, an available port is picked at random each time your test runs. @@ -3271,12 +3090,12 @@ class MyRandomPortTestRestTemplateTests { ``` -#### [](#features.testing.spring-boot-applications.customizing-web-test-client)8.3.7. Customizing WebTestClient #### +#### 8.3.7. Customizing WebTestClient To customize the `WebTestClient` bean, configure a `WebTestClientBuilderCustomizer` bean. Any such beans are called with the `WebTestClient.Builder` that is used to create the `WebTestClient`. -#### [](#features.testing.spring-boot-applications.jmx)8.3.8. Using JMX #### +#### 8.3.8. Using JMX As the test context framework caches context, JMX is disabled by default to prevent identical components to register on the same domain. If such test needs access to an `MBeanServer`, consider marking it dirty as well: @@ -3313,13 +3132,13 @@ class MyJmxTests { ``` -#### [](#features.testing.spring-boot-applications.metrics)8.3.9. Using Metrics #### +#### 8.3.9. Using Metrics Regardless of your classpath, meter registries, except the in-memory backed, are not auto-configured when using `@SpringBootTest`. If you need to export metrics to a different backend as part of an integration test, annotate it with `@AutoConfigureMetrics`. -#### [](#features.testing.spring-boot-applications.mocking-beans)8.3.10. Mocking and Spying Beans #### +#### 8.3.10. Mocking and Spying Beans When running tests, it is sometimes necessary to mock certain components within your application context. For example, you may have a facade over some remote service that is unavailable during development. @@ -3384,7 +3203,7 @@ See the [Javadoc](https://docs.spring.io/spring-boot/docs/2.6.4/api/org/springfr | |When you are using `@SpyBean` to spy on a bean that is proxied by Spring, you may need to remove Spring’s proxy in some situations, for example when setting expectations using `given` or `when`.
Use `AopTestUtils.getTargetObject(yourProxiedSpy)` to do so.| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.testing.spring-boot-applications.autoconfigured-tests)8.3.11. Auto-configured Tests #### +#### 8.3.11. 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. @@ -3402,7 +3221,7 @@ Each of them works in a similar way, providing a `@…​Test` annotation that l | |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.| |---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.testing.spring-boot-applications.json-tests)8.3.12. Auto-configured JSON Tests #### +#### 8.3.12. Auto-configured JSON Tests To test that object JSON serialization and deserialization is working as expected, you can use the `@JsonTest` annotation.`@JsonTest` auto-configures the available supported JSON mapper, which can be one of the following libraries: @@ -3475,7 +3294,7 @@ void someTest() throws Exception { ``` -#### [](#features.testing.spring-boot-applications.spring-mvc-tests)8.3.13. Auto-configured Spring MVC Tests #### +#### 8.3.13. Auto-configured Spring MVC Tests To test whether Spring MVC controllers are working as expected, use the `@WebMvcTest` annotation.`@WebMvcTest` auto-configures the Spring MVC infrastructure and limits scanned beans to `@Controller`, `@ControllerAdvice`, `@JsonComponent`, `Converter`, `GenericConverter`, `Filter`, `HandlerInterceptor`, `WebMvcConfigurer`, `WebMvcRegistrations`, and `HandlerMethodArgumentResolver`. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@WebMvcTest` annotation is used.`@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. @@ -3581,7 +3400,7 @@ More details on how to use Spring Security’s `MockMvc` support can be found in | |Sometimes writing Spring MVC tests is not enough; Spring Boot can help you run [full end-to-end tests with an actual server](#features.testing.spring-boot-applications.with-running-server).| |---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.testing.spring-boot-applications.spring-webflux-tests)8.3.14. Auto-configured Spring WebFlux Tests #### +#### 8.3.14. Auto-configured Spring WebFlux Tests To test that [Spring WebFlux](https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/web-reactive.html) 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`, `WebFilter`, and `WebFluxConfigurer`. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@WebFluxTest` annotation is used.`@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. @@ -3644,7 +3463,7 @@ class MyControllerTests { | |Sometimes writing Spring WebFlux tests is not enough; Spring Boot can help you run [full end-to-end tests with an actual server](#features.testing.spring-boot-applications.with-running-server).| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.testing.spring-boot-applications.autoconfigured-spring-data-cassandra)8.3.15. Auto-configured Data Cassandra Tests #### +#### 8.3.15. Auto-configured Data Cassandra Tests You can use `@DataCassandraTest` to test Cassandra applications. By default, it configures a `CassandraTemplate`, scans for `@Table` classes, and configures Spring Data Cassandra repositories. @@ -3670,7 +3489,7 @@ class MyDataCassandraTests { ``` -#### [](#features.testing.spring-boot-applications.autoconfigured-spring-data-jpa)8.3.16. Auto-configured Data JPA Tests #### +#### 8.3.16. Auto-configured Data JPA Tests You can use the `@DataJpaTest` annotation to test JPA applications. By default, it scans for `@Entity` classes and configures Spring Data JPA repositories. @@ -3758,7 +3577,7 @@ class MyRepositoryTests { ``` -#### [](#features.testing.spring-boot-applications.autoconfigured-jdbc)8.3.17. Auto-configured JDBC Tests #### +#### 8.3.17. Auto-configured JDBC Tests `@JdbcTest` is similar to `@DataJpaTest` but is for tests that only require a `DataSource` and do not use Spring Data JDBC. By default, it configures an in-memory embedded database and a `JdbcTemplate`. @@ -3787,7 +3606,7 @@ class MyTransactionalTests { If you prefer your test to run against a real database, you can use the `@AutoConfigureTestDatabase` annotation in the same way as for `DataJpaTest`. (See "[Auto-configured Data JPA Tests](#features.testing.spring-boot-applications.autoconfigured-spring-data-jpa)".) -#### [](#features.testing.spring-boot-applications.autoconfigured-spring-data-jdbc)8.3.18. Auto-configured Data JDBC Tests #### +#### 8.3.18. Auto-configured Data JDBC Tests `@DataJdbcTest` is similar to `@JdbcTest` but is for tests that use Spring Data JDBC repositories. By default, it configures an in-memory embedded database, a `JdbcTemplate`, and Spring Data JDBC repositories. @@ -3803,7 +3622,7 @@ If that is not what you want, you can disable transaction management for a test 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 "[Auto-configured Data JPA Tests](#features.testing.spring-boot-applications.autoconfigured-spring-data-jpa)".) -#### [](#features.testing.spring-boot-applications.autoconfigured-jooq)8.3.19. Auto-configured jOOQ Tests #### +#### 8.3.19. Auto-configured jOOQ Tests You can use `@JooqTest` in a similar fashion as `@JdbcTest` but for jOOQ-related tests. As jOOQ relies heavily on a Java-based schema that corresponds with the database schema, the existing `DataSource` is used. @@ -3838,7 +3657,7 @@ class MyJooqTests { JOOQ tests are transactional and roll back at the end of each test by default. If that is not what you want, you can disable transaction management for a test or for the whole test class as [shown in the JDBC example](#features.testing.spring-boot-applications.autoconfigured-jdbc). -#### [](#features.testing.spring-boot-applications.autoconfigured-spring-data-mongodb)8.3.20. Auto-configured Data MongoDB Tests #### +#### 8.3.20. Auto-configured Data MongoDB Tests You can use `@DataMongoTest` to test MongoDB applications. By default, it configures an in-memory embedded MongoDB (if available), configures a `MongoTemplate`, scans for `@Document` classes, and configures Spring Data MongoDB repositories. @@ -3883,7 +3702,7 @@ class MyDataMongoDbTests { ``` -#### [](#features.testing.spring-boot-applications.autoconfigured-spring-data-neo4j)8.3.21. Auto-configured Data Neo4j Tests #### +#### 8.3.21. Auto-configured Data Neo4j Tests You can use `@DataNeo4jTest` to test Neo4j applications. By default, it scans for `@Node` classes, and configures Spring Data Neo4j repositories. @@ -3931,7 +3750,7 @@ class MyDataNeo4jTests { | |Transactional tests are not supported with reactive access.
If you are using this style, you must configure `@DataNeo4jTest` tests as described above.| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.testing.spring-boot-applications.autoconfigured-spring-data-redis)8.3.22. Auto-configured Data Redis Tests #### +#### 8.3.22. 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. @@ -3959,7 +3778,7 @@ class MyDataRedisTests { ``` -#### [](#features.testing.spring-boot-applications.autoconfigured-spring-data-ldap)8.3.23. Auto-configured Data LDAP Tests #### +#### 8.3.23. Auto-configured Data LDAP Tests You can use `@DataLdapTest` to test LDAP applications. By default, it configures an in-memory embedded LDAP (if available), configures an `LdapTemplate`, scans for `@Entry` classes, and configures Spring Data LDAP repositories. @@ -4004,7 +3823,7 @@ class MyDataLdapTests { ``` -#### [](#features.testing.spring-boot-applications.autoconfigured-rest-client)8.3.24. Auto-configured REST Clients #### +#### 8.3.24. Auto-configured REST Clients You can use the `@RestClientTest` annotation to test REST clients. By default, it auto-configures Jackson, GSON, and Jsonb support, configures a `RestTemplateBuilder`, and adds support for `MockRestServiceServer`. @@ -4047,7 +3866,7 @@ class MyRestClientTests { ``` -#### [](#features.testing.spring-boot-applications.autoconfigured-spring-restdocs)8.3.25. Auto-configured Spring REST Docs Tests #### +#### 8.3.25. Auto-configured Spring REST Docs Tests You can use the `@AutoConfigureRestDocs` annotation to use [Spring REST Docs](https://spring.io/projects/spring-restdocs) in your tests with Mock MVC, REST Assured, or WebTestClient. It removes the need for the JUnit extension in Spring REST Docs. @@ -4055,7 +3874,7 @@ It removes the need for the JUnit extension in Spring REST Docs. `@AutoConfigureRestDocs` can be used to override the default output directory (`target/generated-snippets` if you are using Maven or `build/generated-snippets` if you are using Gradle). It can also be used to configure the host, scheme, and port that appears in any documented URIs. -##### [](#features.testing.spring-boot-applications.autoconfigured-spring-restdocs.with-mock-mvc)Auto-configured Spring REST Docs Tests with Mock MVC ##### +##### Auto-configured Spring REST Docs Tests with Mock MVC `@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: @@ -4133,7 +3952,7 @@ public class MyResultHandlerConfiguration { ``` -##### [](#features.testing.spring-boot-applications.autoconfigured-spring-restdocs.with-web-test-client)Auto-configured Spring REST Docs Tests with WebTestClient ##### +##### Auto-configured Spring REST Docs Tests with WebTestClient `@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: @@ -4211,7 +4030,7 @@ public class MyWebTestClientBuilderCustomizerConfiguration { ``` -##### [](#features.testing.spring-boot-applications.autoconfigured-spring-restdocs.with-rest-assured)Auto-configured Spring REST Docs Tests with REST Assured ##### +##### Auto-configured Spring REST Docs Tests with REST Assured `@AutoConfigureRestDocs` makes a `RequestSpecification` bean, preconfigured to use Spring REST Docs, available to your tests. You can inject it by using `@Autowired` and use it in your tests as you normally would when using REST Assured and Spring REST Docs, as shown in the following example: @@ -4269,9 +4088,9 @@ public class MyRestDocsConfiguration implements RestDocsRestAssuredConfiguration ``` -#### [](#features.testing.spring-boot-applications.autoconfigured-webservices)8.3.26. Auto-configured Spring Web Services Tests #### +#### 8.3.26. Auto-configured Spring Web Services Tests -##### [](#features.testing.spring-boot-applications.autoconfigured-webservices.client)Auto-configured Spring Web Services Client Tests ##### +##### Auto-configured Spring Web Services Client Tests You can use `@WebServiceClientTest` to test applications that call web services using the Spring Web Services project. By default, it configures a mock `WebServiceServer` bean and automatically customizes your `WebServiceTemplateBuilder`. @@ -4317,7 +4136,7 @@ class MyWebServiceClientTests { ``` -##### [](#features.testing.spring-boot-applications.autoconfigured-webservices.server)Auto-configured Spring Web Services Server Tests ##### +##### Auto-configured Spring Web Services Server Tests You can use `@WebServiceServerTest` to test applications that implement web services using the Spring Web Services project. By default, it configures a `MockWebServiceClient` bean that can be used to call your web service endpoints. @@ -4355,7 +4174,7 @@ class MyWebServiceServerTests { ``` -#### [](#features.testing.spring-boot-applications.additional-autoconfiguration-and-slicing)8.3.27. Additional Auto-configuration and Slicing #### +#### 8.3.27. Additional Auto-configuration and Slicing Each slice provides one or more `@AutoConfigure…​` annotations that namely defines the auto-configurations that should be included as part of a slice. Additional auto-configurations can be added 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: @@ -4385,7 +4204,7 @@ org.springframework.boot.test.autoconfigure.jdbc.JdbcTest=com.example.Integratio | |A slice or `@AutoConfigure…​` annotation can be customized this way as long as it is meta-annotated with `@ImportAutoConfiguration`.| |---|------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.testing.spring-boot-applications.user-configuration-and-slicing)8.3.28. User Configuration and Slicing #### +#### 8.3.28. User Configuration and Slicing If you [structure your code](using.html#using.structuring-your-code) in a sensible way, your `@SpringBootApplication` class is [used by default](#features.testing.spring-boot-applications.detecting-configuration) as the configuration of your tests. @@ -4490,17 +4309,17 @@ Again, moving the custom directive to a separate class is a good way to fix this | |If this is not an option for you, you can create a `@SpringBootConfiguration` somewhere in the hierarchy of your test so that it is used instead.
Alternatively, you can specify a source for your test, which disables the behavior of finding a default one.| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.testing.spring-boot-applications.spock)8.3.29. Using Spock to Test Spring Boot Applications #### +#### 8.3.29. Using Spock to Test Spring Boot Applications Spock 2.x can be used to test a Spring Boot application. To do so, add a dependency on Spock’s `spock-spring` module to your application’s build.`spock-spring` integrates Spring’s test framework into Spock. See [the documentation for Spock’s Spring module](https://spockframework.org/spock/docs/2.0/modules.html#_spring_module) for further details. -### [](#features.testing.utilities)8.4. Test Utilities ### +### 8.4. Test Utilities A few test utility classes that are generally useful when testing your application are packaged as part of `spring-boot`. -#### [](#features.testing.utilities.config-data-application-context-initializer)8.4.1. ConfigDataApplicationContextInitializer #### +#### 8.4.1. ConfigDataApplicationContextInitializer `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: @@ -4521,7 +4340,7 @@ class MyConfigFileTests { | |Using `ConfigDataApplicationContextInitializer` alone does not provide support for `@Value("${…​}")` injection.
Its only job is to ensure that `application.properties` files are loaded into Spring’s `Environment`.
For `@Value` support, you need to either additionally configure a `PropertySourcesPlaceholderConfigurer` or use `@SpringBootTest`, which auto-configures one for you.| |---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.testing.utilities.test-property-values)8.4.2. TestPropertyValues #### +#### 8.4.2. TestPropertyValues `TestPropertyValues` lets you quickly add properties to a `ConfigurableEnvironment` or `ConfigurableApplicationContext`. You can call it with `key=value` strings, as follows: @@ -4547,7 +4366,7 @@ class MyEnvironmentTests { ``` -#### [](#features.testing.utilities.output-capture)8.4.3. OutputCapture #### +#### 8.4.3. OutputCapture `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: @@ -4574,7 +4393,7 @@ class MyOutputCaptureTests { ``` -#### [](#features.testing.utilities.test-rest-template)8.4.4. TestRestTemplate #### +#### 8.4.4. TestRestTemplate `TestRestTemplate` is a convenience alternative to Spring’s `RestTemplate` that is useful in integration tests. You can get a vanilla template or one that sends Basic HTTP authentication (with a username and password). @@ -4664,8 +4483,7 @@ class MySpringBootTests { ``` -[](#features.developing-auto-configuration)9. Creating Your Own Auto-configuration ----------- +## 9. Creating Your Own Auto-configuration If you work in a company that develops shared libraries, or if you work on an open-source or commercial library, you might want to develop your own auto-configuration. Auto-configuration classes can be bundled in external jars and still be picked-up by Spring Boot. @@ -4676,7 +4494,7 @@ We first cover what you need to know to build your own auto-configuration and th | |A [demo project](https://github.com/snicoll-demos/spring-boot-master-auto-configuration) is available to showcase how you can create a starter step-by-step.| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#features.developing-auto-configuration.understanding-auto-configured-beans)9.1. Understanding Auto-configured Beans ### +### 9.1. Understanding Auto-configured Beans Under the hood, auto-configuration is implemented with standard `@Configuration` classes. Additional `@Conditional` annotations are used to constrain when the auto-configuration should apply. @@ -4685,7 +4503,7 @@ This ensures that auto-configuration applies only when relevant classes are foun You can browse the source code of [`spring-boot-autoconfigure`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure) to see the `@Configuration` classes that Spring provides (see the [`META-INF/spring.factories`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories) file). -### [](#features.developing-auto-configuration.locating-auto-configuration-candidates)9.2. Locating Auto-configuration Candidates ### +### 9.2. Locating Auto-configuration Candidates Spring Boot checks for the presence of a `META-INF/spring.factories` file within your published jar. The file should list your configuration classes under the `EnableAutoConfiguration` key, as shown in the following example: @@ -4708,7 +4526,7 @@ That annotation has the same semantic as the regular `@Order` annotation but pro As with standard `@Configuration` classes, the order in which auto-configuration classes are applied only affects the order in which their beans are defined. The order in which those beans are subsequently created is unaffected and is determined by each bean’s dependencies and any `@DependsOn` relationships. -### [](#features.developing-auto-configuration.condition-annotations)9.3. Condition Annotations ### +### 9.3. Condition Annotations You almost always want to include one or more `@Conditional` annotations on your auto-configuration class. The `@ConditionalOnMissingBean` annotation is one common example that is used to allow developers to override auto-configuration if they are not happy with your defaults. @@ -4728,7 +4546,7 @@ These annotations include: * [SpEL Expression Conditions](#features.developing-auto-configuration.condition-annotations.spel-conditions) -#### [](#features.developing-auto-configuration.condition-annotations.class-conditions)9.3.1. Class Conditions #### +#### 9.3.1. Class Conditions The `@ConditionalOnClass` and `@ConditionalOnMissingClass` annotations let `@Configuration` classes be included based on the presence or absence of specific classes. Due to the fact that annotation metadata is parsed by using [ASM](https://asm.ow2.io/), you can use the `value` attribute to refer to the real class, even though that class might not actually appear on the running application classpath. @@ -4769,7 +4587,7 @@ public class MyAutoConfiguration { | |If you use `@ConditionalOnClass` or `@ConditionalOnMissingClass` as a part of a meta-annotation to compose your own composed annotations, you must use `name` as referring to the class in such a case is not handled.| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.developing-auto-configuration.condition-annotations.bean-conditions)9.3.2. Bean Conditions #### +#### 9.3.2. Bean Conditions The `@ConditionalOnBean` and `@ConditionalOnMissingBean` annotations let a bean be included based on the presence or absence of specific beans. You can use the `value` attribute to specify beans by type or `name` to specify beans by name. @@ -4806,19 +4624,19 @@ In the preceding example, the `someService` bean is going to be created if no be | |When declaring a `@Bean` method, provide as much type information as possible in the method’s return type.
For example, if your bean’s concrete class implements an interface the bean method’s return type should be the concrete class and not the interface.
Providing as much type information as possible in `@Bean` methods is particularly important when using bean conditions as their evaluation can only rely upon to type information that is available in the method signature.| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#features.developing-auto-configuration.condition-annotations.property-conditions)9.3.3. Property Conditions #### +#### 9.3.3. Property Conditions The `@ConditionalOnProperty` annotation lets configuration be included based on a Spring Environment property. Use the `prefix` and `name` attributes to specify the property that should be checked. By default, any property that exists and is not equal to `false` is matched. You can also create more advanced checks by using the `havingValue` and `matchIfMissing` attributes. -#### [](#features.developing-auto-configuration.condition-annotations.resource-conditions)9.3.4. Resource Conditions #### +#### 9.3.4. Resource Conditions The `@ConditionalOnResource` annotation lets configuration be included only when a specific resource is present. Resources can be specified by using the usual Spring conventions, as shown in the following example: `file:/home/user/test.dat`. -#### [](#features.developing-auto-configuration.condition-annotations.web-application-conditions)9.3.5. Web Application Conditions #### +#### 9.3.5. Web Application Conditions The `@ConditionalOnWebApplication` and `@ConditionalOnNotWebApplication` annotations let configuration be included depending on whether the application is a “web application”. A servlet-based web application is any application that uses a Spring `WebApplicationContext`, defines a `session` scope, or has a `ConfigurableWebEnvironment`. @@ -4827,14 +4645,14 @@ A reactive web application is any application that uses a `ReactiveWebApplicatio The `@ConditionalOnWarDeployment` annotation lets configuration be included depending on whether the application is a traditional WAR application that is deployed to a container. This condition will not match for applications that are run with an embedded server. -#### [](#features.developing-auto-configuration.condition-annotations.spel-conditions)9.3.6. SpEL Expression Conditions #### +#### 9.3.6. SpEL Expression Conditions The `@ConditionalOnExpression` annotation lets configuration be included based on the result of a [SpEL expression](https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/core.html#expressions). | |Referencing a bean in the expression will cause that bean to be initialized very early in context refresh processing.
As a result, the bean won’t be eligible for post-processing (such as configuration properties binding) and its state may be incomplete.| |---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#features.developing-auto-configuration.testing)9.4. Testing your Auto-configuration ### +### 9.4. Testing your Auto-configuration An auto-configuration can be affected by many factors: user configuration (`@Bean` definition and `Environment` customization), condition evaluation (presence of a particular library), and others. Concretely, each test should create a well defined `ApplicationContext` that represents a combination of those customizations.`ApplicationContextRunner` provides a great way to achieve that. @@ -4915,11 +4733,11 @@ class MyConditionEvaluationReportingTests { ``` -#### [](#features.developing-auto-configuration.testing.simulating-a-web-context)9.4.1. Simulating a Web Context #### +#### 9.4.1. 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. -#### [](#features.developing-auto-configuration.testing.overriding-classpath)9.4.2. Overriding the Classpath #### +#### 9.4.2. 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. @@ -4934,7 +4752,7 @@ void serviceIsIgnoredIfLibraryIsNotPresent() { ``` -### [](#features.developing-auto-configuration.custom-starter)9.5. Creating Your Own Starter ### +### 9.5. Creating Your Own Starter A typical Spring Boot starter contains code to auto-configure and customize the infrastructure of a given technology, let’s call that "acme". To make it easily extensible, a number of configuration keys in a dedicated namespace can be exposed to the environment. @@ -4954,7 +4772,7 @@ At the same time, others can rely only on the `autoconfigure` module and craft t If the auto-configuration is relatively straightforward and does not have optional feature, merging the two modules in the starter is definitely an option. -#### [](#features.developing-auto-configuration.custom-starter.naming)9.5.1. Naming #### +#### 9.5.1. Naming You should make sure to provide a proper namespace for your starter. Do not start your module names with `spring-boot`, even if you use a different Maven `groupId`. @@ -4964,7 +4782,7 @@ As a rule of thumb, you should name a combined module after the starter. For example, assume that you are creating a starter for "acme" and that you name the auto-configure module `acme-spring-boot` and the starter `acme-spring-boot-starter`. If you only have one module that combines the two, name it `acme-spring-boot-starter`. -#### [](#features.developing-auto-configuration.custom-starter.configuration-keys)9.5.2. Configuration keys #### +#### 9.5.2. Configuration keys 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). @@ -5032,7 +4850,7 @@ Make sure to [trigger meta-data generation](configuration-metadata.html#appendix You may want to review the generated metadata (`META-INF/spring-configuration-metadata.json`) to make sure your keys are properly documented. Using your own starter in a compatible IDE is also a good idea to validate that quality of the metadata. -#### [](#features.developing-auto-configuration.custom-starter.autoconfigure-module)9.5.3. The “autoconfigure” Module #### +#### 9.5.3. The “autoconfigure” Module The `autoconfigure` module contains everything that is necessary to get started with the library. It may also contain configuration key definitions (such as `@ConfigurationProperties`) and any callback interface that can be used to further customize how the components are initialized. @@ -5091,7 +4909,7 @@ dependencies { } ``` -#### [](#features.developing-auto-configuration.custom-starter.starter-module)9.5.4. Starter Module #### +#### 9.5.4. Starter Module The starter is really an empty jar. Its only purpose is to provide the necessary dependencies to work with the library. @@ -5105,8 +4923,7 @@ In other words, you should not include optional dependencies. | |Either way, your starter must reference the core Spring Boot starter (`spring-boot-starter`) directly or indirectly (there is no need to add it if your starter relies on another starter).
If a project is created with only your custom starter, Spring Boot’s core features will be honoured by the presence of the core starter.| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -[](#features.kotlin)10. Kotlin support ----------- +## 10. Kotlin support [Kotlin](https://kotlinlang.org) is a statically-typed language targeting the JVM (and other platforms) which allows writing concise and elegant code while providing [interoperability](https://kotlinlang.org/docs/reference/java-interop.html) with existing libraries written in Java. @@ -5117,7 +4934,7 @@ The easiest way to start with Spring Boot and Kotlin is to follow [this comprehe You can create new Kotlin projects by using [start.spring.io](https://start.spring.io/#!language=kotlin). Feel free to join the #spring channel of [Kotlin Slack](https://slack.kotlinlang.org/) or ask a question with the `spring` and `kotlin` tags on [Stack Overflow](https://stackoverflow.com/questions/tagged/spring+kotlin) if you need support. -### [](#features.kotlin.requirements)10.1. Requirements ### +### 10.1. Requirements Spring Boot requires at least Kotlin 1.3.x and manages a suitable Kotlin version through dependency management. To use Kotlin, `org.jetbrains.kotlin:kotlin-stdlib` and `org.jetbrains.kotlin:kotlin-reflect` must be present on the classpath. @@ -5132,7 +4949,7 @@ A warning message is logged if Jackson and Kotlin are present but the Jackson Ko | |These dependencies and plugins are provided by default if one bootstraps a Kotlin project on [start.spring.io](https://start.spring.io/#!language=kotlin).| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#features.kotlin.null-safety)10.2. Null-safety ### +### 10.2. Null-safety One of Kotlin’s key features is [null-safety](https://kotlinlang.org/docs/reference/null-safety.html). It deals with `null` values at compile time rather than deferring the problem to runtime and encountering a `NullPointerException`. @@ -5149,9 +4966,9 @@ The `strict` value is required to have null-safety taken in account in Kotlin ty | |Generic type arguments, varargs and array elements nullability are not yet supported.
See [SPR-15942](https://jira.spring.io/browse/SPR-15942) for up-to-date information.
Also be aware that Spring Boot’s own API is [not yet annotated](https://github.com/spring-projects/spring-boot/issues/10712).| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#features.kotlin.api)10.3. Kotlin API ### +### 10.3. Kotlin API -#### [](#features.kotlin.api.run-application)10.3.1. runApplication #### +#### 10.3.1. runApplication Spring Boot provides an idiomatic way to run an application with `runApplication(*args)` as shown in the following example: @@ -5178,7 +4995,7 @@ runApplication(*args) { ``` -#### [](#features.kotlin.api.extensions)10.3.2. Extensions #### +#### 10.3.2. Extensions Kotlin [extensions](https://kotlinlang.org/docs/reference/extensions.html) provide the ability to extend existing classes with additional functionality. The Spring Boot Kotlin API makes use of these extensions to add new Kotlin specific conveniences to existing APIs. @@ -5186,7 +5003,7 @@ The Spring Boot Kotlin API makes use of these extensions to add new Kotlin speci `TestRestTemplate` extensions, similar to those provided by Spring Framework for `RestOperations` in Spring Framework, are provided. Among other things, the extensions make it possible to take advantage of Kotlin reified type parameters. -### [](#features.kotlin.dependency-management)10.4. Dependency management ### +### 10.4. Dependency management In order to avoid mixing different versions of Kotlin dependencies on the classpath, Spring Boot imports the Kotlin BOM. @@ -5199,7 +5016,7 @@ The version can be customized by setting the `kotlin-coroutines.version` propert | |`org.jetbrains.kotlinx:kotlinx-coroutines-reactor` dependency is provided by default if one bootstraps a Kotlin project with at least one reactive dependency on [start.spring.io](https://start.spring.io/#!language=kotlin).| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#features.kotlin.configuration-properties)10.5. @ConfigurationProperties ### +### 10.5. @ConfigurationProperties `@ConfigurationProperties` when used in combination with [`@ConstructorBinding`](#features.external-config.typesafe-configuration-properties.constructor-binding) supports classes with immutable `val` properties as shown in the following example: @@ -5222,7 +5039,7 @@ data class KotlinExampleProperties( | |To generate [your own metadata](configuration-metadata.html#appendix.configuration-metadata.annotation-processor) using the annotation processor, [`kapt` should be configured](https://kotlinlang.org/docs/reference/kapt.html) with the `spring-boot-configuration-processor` dependency.
Note that some features (such as detecting the default value or deprecated items) are not working due to limitations in the model kapt provides.| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#features.kotlin.testing)10.6. Testing ### +### 10.6. Testing While it is possible to use JUnit 4 to test Kotlin code, JUnit 5 is provided by default and is recommended. JUnit 5 enables a test class to be instantiated once and reused for all of the class’s tests. @@ -5231,9 +5048,9 @@ This makes it possible to use `@BeforeAll` and `@AfterAll` annotations on non-st To mock Kotlin classes, [MockK](https://mockk.io/) is recommended. If you need the `Mockk` equivalent of the Mockito specific [`@MockBean` and `@SpyBean` annotations](#features.testing.spring-boot-applications.mocking-beans), you can use [SpringMockK](https://github.com/Ninja-Squad/springmockk) which provides similar `@MockkBean` and `@SpykBean` annotations. -### [](#features.kotlin.resources)10.7. Resources ### +### 10.7. Resources -#### [](#features.kotlin.resources.further-reading)10.7.1. Further reading #### +#### 10.7.1. Further reading * [Kotlin language reference](https://kotlinlang.org/docs/reference/) @@ -5257,7 +5074,7 @@ If you need the `Mockk` equivalent of the Mockito specific [`@MockBean` and `@Sp * [Spring Framework 5 Kotlin APIs, the functional way](https://spring.io/blog/2017/08/01/spring-framework-5-kotlin-apis-the-functional-way) -#### [](#features.kotlin.resources.examples)10.7.2. Examples #### +#### 10.7.2. Examples * [spring-boot-kotlin-demo](https://github.com/sdeleuze/spring-boot-kotlin-demo): regular Spring Boot + Spring Data JPA project @@ -5271,8 +5088,7 @@ If you need the `Mockk` equivalent of the Mockito specific [`@MockBean` and `@Sp * [spring-boot-coroutines-demo](https://github.com/sdeleuze/spring-boot-coroutines-demo): Coroutines sample project -[](#features.whats-next)11. What to Read Next ----------- +## 11. What to Read Next If you want to learn more about any of the classes discussed in this section, see the [Spring Boot API documentation](https://docs.spring.io/spring-boot/docs/2.6.4/api/) or you can browse the [source code directly](https://github.com/spring-projects/spring-boot/tree/v2.6.4). If you have specific questions, see the [how-to](howto.html#howto) section. diff --git a/docs/en/spring-boot/getting-help.md b/docs/en/spring-boot/getting-help.md index a99152ff4c8207187fae4104791161a21f919a0c..c433bcdc81fa138a9625ec5b1ad1fd53aa821300 100644 --- a/docs/en/spring-boot/getting-help.md +++ b/docs/en/spring-boot/getting-help.md @@ -1,5 +1,4 @@ -Getting Help -========== +# Getting Help If you have trouble with Spring Boot, we would like to help. diff --git a/docs/en/spring-boot/getting-started.md b/docs/en/spring-boot/getting-started.md index 5aa4c0e2b3541bf47c548593b81decbd27ca9ab0..2ae725b45a965454644aadfff501017ba0d4c444 100644 --- a/docs/en/spring-boot/getting-started.md +++ b/docs/en/spring-boot/getting-started.md @@ -1,48 +1,11 @@ -Getting Started -========== - -Table of Contents - -[Back to index](index.html) - -* [1. Introducing Spring Boot](#getting-started.introducing-spring-boot) -* [2. System Requirements](#getting-started.system-requirements) - * [2.1. Servlet Containers](#getting-started.system-requirements.servlet-containers) - -* [3. Installing Spring Boot](#getting-started.installing) - * [3.1. Installation Instructions for the Java Developer](#getting-started.installing.java) - * [3.1.1. Maven Installation](#getting-started.installing.java.maven) - * [3.1.2. Gradle Installation](#getting-started.installing.java.gradle) - - * [3.2. Installing the Spring Boot CLI](#getting-started.installing.cli) - * [3.2.1. Manual Installation](#getting-started.installing.cli.manual-installation) - * [3.2.2. Installation with SDKMAN!](#getting-started.installing.cli.sdkman) - * [3.2.3. OSX Homebrew Installation](#getting-started.installing.cli.homebrew) - * [3.2.4. MacPorts Installation](#getting-started.installing.cli.macports) - * [3.2.5. Command-line Completion](#getting-started.installing.cli.completion) - * [3.2.6. Windows Scoop Installation](#getting-started.installing.cli.scoop) - * [3.2.7. Quick-start Spring CLI Example](#getting-started.installing.cli.quick-start) - -* [4. Developing Your First Spring Boot Application](#getting-started.first-application) - * [4.1. Creating the POM](#getting-started.first-application.pom) - * [4.2. Adding Classpath Dependencies](#getting-started.first-application.dependencies) - * [4.3. Writing the Code](#getting-started.first-application.code) - * [4.3.1. The @RestController and @RequestMapping Annotations](#getting-started.first-application.code.mvc-annotations) - * [4.3.2. The @EnableAutoConfiguration Annotation](#getting-started.first-application.code.enable-auto-configuration) - * [4.3.3. The “main” Method](#getting-started.first-application.code.main-method) - - * [4.4. Running the Example](#getting-started.first-application.run) - * [4.5. Creating an Executable Jar](#getting-started.first-application.executable-jar) - -* [5. What to Read Next](#getting-started.whats-next) +# Getting Started If you are getting started with Spring Boot, or “Spring” in general, start by reading this section. It answers the basic “what?”, “how?” and “why?” questions. It includes an introduction to Spring Boot, along with installation instructions. We then walk you through building your first Spring Boot application, discussing some core principles as we go. -[](#getting-started.introducing-spring-boot)1. Introducing Spring Boot ----------- +## 1. Introducing Spring Boot Spring Boot helps you 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. @@ -61,8 +24,7 @@ Our primary goals are: * Absolutely no code generation and no requirement for XML configuration. -[](#getting-started.system-requirements)2. System Requirements ----------- +## 2. System Requirements Spring Boot 2.6.4 requires [Java 8](https://www.java.com) and is compatible up to and including Java 17.[Spring Framework 5.3.16](https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/) or above is also required. @@ -73,7 +35,7 @@ Explicit build support is provided for the following build tools: | Maven | 3.5+ | | Gradle |6.8.x, 6.9.x, and 7.x| -### [](#getting-started.system-requirements.servlet-containers)2.1. Servlet Containers ### +### 2.1. Servlet Containers Spring Boot supports the following embedded servlet containers: @@ -86,8 +48,7 @@ Spring Boot supports the following embedded servlet containers: You can also deploy Spring Boot applications to any servlet 3.1+ compatible container. -[](#getting-started.installing)3. Installing Spring Boot ----------- +## 3. Installing Spring Boot Spring Boot can be used with “classic” Java development tools or installed as a command line tool. Either way, you need [Java SDK v1.8](https://www.java.com) or higher. @@ -100,7 +61,7 @@ $ java -version If you are new to Java development or if you want to experiment with Spring Boot, you might want to try the [Spring Boot CLI](#getting-started.installing.cli) (Command Line Interface) first. Otherwise, read on for “classic” installation instructions. -### [](#getting-started.installing.java)3.1. Installation Instructions for the Java Developer ### +### 3.1. Installation Instructions for the Java Developer You can use Spring Boot in the same way as any standard Java library. To do so, include the appropriate `spring-boot-*.jar` files on your classpath. @@ -109,7 +70,7 @@ Also, there is nothing special about a Spring Boot application, so you can run a Although you *could* copy Spring Boot jars, we generally recommend that you use a build tool that supports dependency management (such as Maven or Gradle). -#### [](#getting-started.installing.java.maven)3.1.1. Maven Installation #### +#### 3.1.1. Maven Installation Spring Boot is compatible with Apache Maven 3.3 or above. If you do not already have Maven installed, you can follow the instructions at [maven.apache.org](https://maven.apache.org). @@ -123,7 +84,7 @@ Spring Boot also provides an optional [Maven plugin](build-tool-plugins.html#bui More details on getting started with Spring Boot and Maven can be found in the [Getting Started section](https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/reference/htmlsingle/#getting-started) of the Maven plugin’s reference guide. -#### [](#getting-started.installing.java.gradle)3.1.2. Gradle Installation #### +#### 3.1.2. Gradle Installation Spring Boot is compatible with Gradle 6.8, 6.9, and 7.x. If you do not already have Gradle installed, you can follow the instructions at [gradle.org](https://gradle.org). @@ -140,14 +101,14 @@ See [docs.gradle.org/current/userguide/gradle\_wrapper.html](https://docs.gradle More details on getting started with Spring Boot and Gradle can be found in the [Getting Started section](https://docs.spring.io/spring-boot/docs/2.6.4/gradle-plugin/reference/htmlsingle/#getting-started) of the Gradle plugin’s reference guide. -### [](#getting-started.installing.cli)3.2. Installing the Spring Boot CLI ### +### 3.2. Installing the Spring Boot CLI The Spring Boot CLI (Command Line Interface) is a command line tool that you can use to quickly prototype with Spring. It lets you run [Groovy](https://groovy-lang.org/) scripts, which means that you have a familiar Java-like syntax without so much boilerplate code. You do not need to use the CLI to work with Spring Boot, but it is a quick way to get a Spring application off the ground without an IDE. -#### [](#getting-started.installing.cli.manual-installation)3.2.1. Manual Installation #### +#### 3.2.1. Manual Installation You can download the Spring CLI distribution from the Spring software repository: @@ -161,7 +122,7 @@ Once downloaded, follow the [INSTALL.txt](https://raw.githubusercontent.com/spri In summary, there is a `spring` script (`spring.bat` for Windows) in a `bin/` directory in the `.zip` file. Alternatively, you can use `java -jar` with the `.jar` file (the script helps you to be sure that the classpath is set correctly). -#### [](#getting-started.installing.cli.sdkman)3.2.2. Installation with SDKMAN! #### +#### 3.2.2. Installation with SDKMAN! SDKMAN! (The Software Development Kit Manager) can be used for managing multiple versions of various binary SDKs, including Groovy and the Spring Boot CLI. Get SDKMAN! from [sdkman.io](https://sdkman.io) and install Spring Boot by using the following commands: @@ -202,7 +163,7 @@ Available Springboot Versions ================================================================================ ``` -#### [](#getting-started.installing.cli.homebrew)3.2.3. OSX Homebrew Installation #### +#### 3.2.3. OSX Homebrew Installation If you are on a Mac and use [Homebrew](https://brew.sh/), you can install the Spring Boot CLI by using the following commands: @@ -216,7 +177,7 @@ Homebrew installs `spring` to `/usr/local/bin`. | |If you do not see the formula, your installation of brew might be out-of-date.
In that case, run `brew update` and try again.| |---|---------------------------------------------------------------------------------------------------------------------------------| -#### [](#getting-started.installing.cli.macports)3.2.4. MacPorts Installation #### +#### 3.2.4. MacPorts Installation If you are on a Mac and use [MacPorts](https://www.macports.org/), you can install the Spring Boot CLI by using the following command: @@ -224,7 +185,7 @@ If you are on a Mac and use [MacPorts](https://www.macports.org/), you can insta $ sudo port install spring-boot-cli ``` -#### [](#getting-started.installing.cli.completion)3.2.5. Command-line Completion #### +#### 3.2.5. Command-line Completion The Spring Boot CLI includes scripts that provide command completion for the [BASH](https://en.wikipedia.org/wiki/Bash_%28Unix_shell%29) and [zsh](https://en.wikipedia.org/wiki/Z_shell) shells. You can `source` the script (also named `spring`) in any shell or put it in your personal or system-wide bash completion initialization. @@ -240,7 +201,7 @@ $ spring | |If you install the Spring Boot CLI by using Homebrew or MacPorts, the command-line completion scripts are automatically registered with your shell.| |---|---------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#getting-started.installing.cli.scoop)3.2.6. Windows Scoop Installation #### +#### 3.2.6. Windows Scoop Installation If you are on a Windows and use [Scoop](https://scoop.sh/), you can install the Spring Boot CLI by using the following commands: @@ -254,7 +215,7 @@ Scoop installs `spring` to `~/scoop/apps/springboot/current/bin`. | |If you do not see the app manifest, your installation of scoop might be out-of-date.
In that case, run `scoop update` and try again.| |---|----------------------------------------------------------------------------------------------------------------------------------------| -#### [](#getting-started.installing.cli.quick-start)3.2.7. Quick-start Spring CLI Example #### +#### 3.2.7. Quick-start Spring CLI Example You can use the following web application to test your installation. To start, create a file called `app.groovy`, as follows: @@ -288,8 +249,7 @@ You should see the following output: Hello World! ``` -[](#getting-started.first-application)4. Developing Your First Spring Boot Application ----------- +## 4. Developing Your First Spring Boot Application This section describes how to develop a small “Hello World!” web application that highlights some of Spring Boot’s key features. We use Maven to build this project, since most IDEs support it. @@ -316,7 +276,7 @@ Java version: 1.8.0_102, vendor: Oracle Corporation | |This sample needs to be created in its own directory.
Subsequent instructions assume that you have created a suitable directory and that it is your current directory.| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#getting-started.first-application.pom)4.1. Creating the POM ### +### 4.1. Creating the POM We need to start by creating a Maven `pom.xml` file. The `pom.xml` is the recipe that is used to build your project. @@ -349,7 +309,7 @@ You can test it by running `mvn package` (for now, you can ignore the “jar wil | |At this point, you could import the project into an IDE (most modern Java IDEs include built-in support for Maven).
For simplicity, we continue to use a plain text editor for this example.| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#getting-started.first-application.dependencies)4.2. Adding Classpath Dependencies ### +### 4.2. Adding Classpath Dependencies Spring Boot provides a number of “Starters” that let you add jars to your classpath. Our applications for smoke tests use the `spring-boot-starter-parent` in the `parent` section of the POM. @@ -381,7 +341,7 @@ To add the necessary dependencies, edit your `pom.xml` and add the `spring-boot- If you run `mvn dependency:tree` again, you see that there are now a number of additional dependencies, including the Tomcat web server and Spring Boot itself. -### [](#getting-started.first-application.code)4.3. Writing the Code ### +### 4.3. Writing the Code To finish our application, we need to create a single Java file. By default, Maven compiles sources from `src/main/java`, so you need to create that directory structure and then add a file named `src/main/java/MyApplication.java` to contain the following code: @@ -412,7 +372,7 @@ public class MyApplication { Although there is not much code here, quite a lot is going on. We step through the important parts in the next few sections. -#### [](#getting-started.first-application.code.mvc-annotations)4.3.1. The @RestController and @RequestMapping Annotations #### +#### 4.3.1. The @RestController and @RequestMapping Annotations #### The first annotation on our `MyApplication` class is `@RestController`. This is known as a *stereotype* annotation. @@ -426,7 +386,7 @@ The `@RestController` annotation tells Spring to render the resulting string dir | |The `@RestController` and `@RequestMapping` annotations are Spring MVC annotations (they are not specific to Spring Boot).
See the [MVC section](https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/web.html#mvc) in the Spring Reference Documentation for more details.| |---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#getting-started.first-application.code.enable-auto-configuration)4.3.2. The @EnableAutoConfiguration Annotation #### +#### 4.3.2. The @EnableAutoConfiguration Annotation #### The second class-level annotation is `@EnableAutoConfiguration`. This annotation tells Spring Boot to “guess” how you want to configure Spring, based on the jar dependencies that you have added. @@ -438,7 +398,7 @@ Auto-configuration is designed to work well with “Starters”, but the two con You are free to pick and choose jar dependencies outside of the starters. Spring Boot still does its best to auto-configure your application. -#### [](#getting-started.first-application.code.main-method)4.3.3. The “main” Method #### +#### 4.3.3. The “main” Method The final part of our application is the `main` method. This is a standard method that follows the Java convention for an application entry point. @@ -446,7 +406,7 @@ Our main method delegates to Spring Boot’s `SpringApplication` class by callin We need to pass `MyApplication.class` as an argument to the `run` method to tell `SpringApplication` which is the primary Spring component. The `args` array is also passed through to expose any command-line arguments. -### [](#getting-started.first-application.run)4.4. Running the Example ### +### 4.4. Running the Example At this point, your application should work. Since you used the `spring-boot-starter-parent` POM, you have a useful `run` goal that you can use to start the application. @@ -477,7 +437,7 @@ Hello World! To gracefully exit the application, press `ctrl-c`. -### [](#getting-started.first-application.executable-jar)4.5. Creating an Executable Jar ### +### 4.5. Creating an Executable Jar We finish our example by creating a completely self-contained executable jar file that we could run in production. Executable jars (sometimes called “fat jars”) are archives containing your compiled classes along with all of the jar dependencies that your code needs to run. @@ -562,8 +522,7 @@ $ java -jar target/myproject-0.0.1-SNAPSHOT.jar As before, to exit the application, press `ctrl-c`. -[](#getting-started.whats-next)5. What to Read Next ----------- +## 5. What to Read Next Hopefully, this section provided some of the Spring Boot basics and got you on your way to writing your own applications. If you are a task-oriented type of developer, you might want to jump over to [spring.io](https://spring.io) and follow some of the [getting started](https://spring.io/guides/) guides that solve specific “How do I do that with Spring?” problems. diff --git a/docs/en/spring-boot/howto.md b/docs/en/spring-boot/howto.md index e7b4ec6f193e8d2dbdb46482de94fb91242edc27..4e8e036be2f8e7dfc0d568c8ad06ce9bb4ad1a40 100644 --- a/docs/en/spring-boot/howto.md +++ b/docs/en/spring-boot/howto.md @@ -1,168 +1,4 @@ -“How-to” Guides -========== - -Table of Contents - -[Back to index](index.html) - -* [1. Spring Boot Application](#howto.application) - * [1.1. Create Your Own FailureAnalyzer](#howto.application.failure-analyzer) - * [1.2. Troubleshoot Auto-configuration](#howto.application.troubleshoot-auto-configuration) - * [1.3. Customize the Environment or ApplicationContext Before It Starts](#howto.application.customize-the-environment-or-application-context) - * [1.4. Build an ApplicationContext Hierarchy (Adding a Parent or Root Context)](#howto.application.context-hierarchy) - * [1.5. Create a Non-web Application](#howto.application.non-web-application) - -* [2. Properties and Configuration](#howto.properties-and-configuration) - * [2.1. Automatically Expand Properties at Build Time](#howto.properties-and-configuration.expand-properties) - * [2.1.1. Automatic Property Expansion Using Maven](#howto.properties-and-configuration.expand-properties.maven) - * [2.1.2. Automatic Property Expansion Using Gradle](#howto.properties-and-configuration.expand-properties.gradle) - - * [2.2. Externalize the Configuration of SpringApplication](#howto.properties-and-configuration.externalize-configuration) - * [2.3. Change the Location of External Properties of an Application](#howto.properties-and-configuration.external-properties-location) - * [2.4. Use ‘Short’ Command Line Arguments](#howto.properties-and-configuration.short-command-line-arguments) - * [2.5. Use YAML for External Properties](#howto.properties-and-configuration.yaml) - * [2.6. Set the Active Spring Profiles](#howto.properties-and-configuration.set-active-spring-profiles) - * [2.7. Set the Default Profile Name](#howto.properties-and-configuration.set-default-spring-profile-name) - * [2.8. Change Configuration Depending on the Environment](#howto.properties-and-configuration.change-configuration-depending-on-the-environment) - * [2.9. Discover Built-in Options for External Properties](#howto.properties-and-configuration.discover-build-in-options-for-external-properties) - -* [3. Embedded Web Servers](#howto.webserver) - * [3.1. Use Another Web Server](#howto.webserver.use-another) - * [3.2. Disabling the Web Server](#howto.webserver.disable) - * [3.3. Change the HTTP Port](#howto.webserver.change-port) - * [3.4. Use a Random Unassigned HTTP Port](#howto.webserver.use-random-port) - * [3.5. Discover the HTTP Port at Runtime](#howto.webserver.discover-port) - * [3.6. Enable HTTP Response Compression](#howto.webserver.enable-response-compression) - * [3.7. Configure SSL](#howto.webserver.configure-ssl) - * [3.8. Configure HTTP/2](#howto.webserver.configure-http2) - * [3.8.1. HTTP/2 with Tomcat](#howto.webserver.configure-http2.tomcat) - * [3.8.2. HTTP/2 with Jetty](#howto.webserver.configure-http2.jetty) - * [3.8.3. HTTP/2 with Reactor Netty](#howto.webserver.configure-http2.netty) - * [3.8.4. HTTP/2 with Undertow](#howto.webserver.configure-http2.undertow) - - * [3.9. Configure the Web Server](#howto.webserver.configure) - * [3.10. Add a Servlet, Filter, or Listener to an Application](#howto.webserver.add-servlet-filter-listener) - * [3.10.1. Add a Servlet, Filter, or Listener by Using a Spring Bean](#howto.webserver.add-servlet-filter-listener.spring-bean) - * [Disable Registration of a Servlet or Filter](#howto.webserver.add-servlet-filter-listener.spring-bean.disable) - - * [3.10.2. Add Servlets, Filters, and Listeners by Using Classpath Scanning](#howto.webserver.add-servlet-filter-listener.using-scanning) - - * [3.11. Configure Access Logging](#howto.webserver.configure-access-logs) - * [3.12. Running Behind a Front-end Proxy Server](#howto.webserver.use-behind-a-proxy-server) - * [3.12.1. Customize Tomcat’s Proxy Configuration](#howto.webserver.use-behind-a-proxy-server.tomcat) - - * [3.13. Enable Multiple Connectors with Tomcat](#howto.webserver.enable-multiple-connectors-in-tomcat) - * [3.14. Use Tomcat’s LegacyCookieProcessor](#howto.webserver.use-tomcat-legacycookieprocessor) - * [3.15. Enable Tomcat’s MBean Registry](#howto.webserver.enable-tomcat-mbean-registry) - * [3.16. Enable Multiple Listeners with Undertow](#howto.webserver.enable-multiple-listeners-in-undertow) - * [3.17. Create WebSocket Endpoints Using @ServerEndpoint](#howto.webserver.create-websocket-endpoints-using-serverendpoint) - -* [4. Spring MVC](#howto.spring-mvc) - * [4.1. Write a JSON REST Service](#howto.spring-mvc.write-json-rest-service) - * [4.2. Write an XML REST Service](#howto.spring-mvc.write-xml-rest-service) - * [4.3. Customize the Jackson ObjectMapper](#howto.spring-mvc.customize-jackson-objectmapper) - * [4.4. Customize the @ResponseBody Rendering](#howto.spring-mvc.customize-responsebody-rendering) - * [4.5. Handling Multipart File Uploads](#howto.spring-mvc.multipart-file-uploads) - * [4.6. Switch Off the Spring MVC DispatcherServlet](#howto.spring-mvc.switch-off-dispatcherservlet) - * [4.7. Switch off the Default MVC Configuration](#howto.spring-mvc.switch-off-default-configuration) - * [4.8. Customize ViewResolvers](#howto.spring-mvc.customize-view-resolvers) - -* [5. Jersey](#howto.jersey) - * [5.1. Secure Jersey endpoints with Spring Security](#howto.jersey.spring-security) - * [5.2. Use Jersey Alongside Another Web Framework](#howto.jersey.alongside-another-web-framework) - -* [6. HTTP Clients](#howto.http-clients) - * [6.1. Configure RestTemplate to Use a Proxy](#howto.http-clients.rest-template-proxy-configuration) - * [6.2. Configure the TcpClient used by a Reactor Netty-based WebClient](#howto.http-clients.webclient-reactor-netty-customization) - -* [7. Logging](#howto.logging) - * [7.1. Configure Logback for Logging](#howto.logging.logback) - * [7.1.1. Configure Logback for File-only Output](#howto.logging.logback.file-only-output) - - * [7.2. Configure Log4j for Logging](#howto.logging.log4j) - * [7.2.1. Use YAML or JSON to Configure Log4j 2](#howto.logging.log4j.yaml-or-json-config) - * [7.2.2. Use Composite Configuration to Configure Log4j 2](#howto.logging.log4j.composite-configuration) - -* [8. Data Access](#howto.data-access) - * [8.1. Configure a Custom DataSource](#howto.data-access.configure-custom-datasource) - * [8.2. Configure Two DataSources](#howto.data-access.configure-two-datasources) - * [8.3. Use Spring Data Repositories](#howto.data-access.spring-data-repositories) - * [8.4. Separate @Entity Definitions from Spring Configuration](#howto.data-access.separate-entity-definitions-from-spring-configuration) - * [8.5. Configure JPA Properties](#howto.data-access.jpa-properties) - * [8.6. Configure Hibernate Naming Strategy](#howto.data-access.configure-hibernate-naming-strategy) - * [8.7. Configure Hibernate Second-Level Caching](#howto.data-access.configure-hibernate-second-level-caching) - * [8.8. Use Dependency Injection in Hibernate Components](#howto.data-access.dependency-injection-in-hibernate-components) - * [8.9. Use a Custom EntityManagerFactory](#howto.data-access.use-custom-entity-manager) - * [8.10. Using Multiple EntityManagerFactories](#howto.data-access.use-multiple-entity-managers) - * [8.11. Use a Traditional persistence.xml File](#howto.data-access.use-traditional-persistence-xml) - * [8.12. Use Spring Data JPA and Mongo Repositories](#howto.data-access.use-spring-data-jpa-and-mongo-repositories) - * [8.13. Customize Spring Data’s Web Support](#howto.data-access.customize-spring-data-web-support) - * [8.14. Expose Spring Data Repositories as REST Endpoint](#howto.data-access.exposing-spring-data-repositories-as-rest) - * [8.15. Configure a Component that is Used by JPA](#howto.data-access.configure-a-component-that-is-used-by-jpa) - * [8.16. Configure jOOQ with Two DataSources](#howto.data-access.configure-jooq-with-multiple-datasources) - -* [9. Database Initialization](#howto.data-initialization) - * [9.1. Initialize a Database Using JPA](#howto.data-initialization.using-jpa) - * [9.2. Initialize a Database Using Hibernate](#howto.data-initialization.using-hibernate) - * [9.3. Initialize a Database Using Basic SQL Scripts](#howto.data-initialization.using-basic-sql-scripts) - * [9.4. Initialize a Spring Batch Database](#howto.data-initialization.batch) - * [9.5. Use a Higher-level Database Migration Tool](#howto.data-initialization.migration-tool) - * [9.5.1. Execute Flyway Database Migrations on Startup](#howto.data-initialization.migration-tool.flyway) - * [9.5.2. Execute Liquibase Database Migrations on Startup](#howto.data-initialization.migration-tool.liquibase) - - * [9.6. Depend Upon an Initialized Database](#howto.data-initialization.dependencies) - * [9.6.1. Detect a Database Initializer](#howto.data-initialization.dependencies.initializer-detection) - * [9.6.2. Detect a Bean That Depends On Database Initialization](#howto.data-initialization.dependencies.depends-on-initialization-detection) - -* [10. Messaging](#howto.messaging) - * [10.1. Disable Transacted JMS Session](#howto.messaging.disable-transacted-jms-session) - -* [11. Batch Applications](#howto.batch) - * [11.1. Specifying a Batch Data Source](#howto.batch.specifying-a-data-source) - * [11.2. Running Spring Batch Jobs on Startup](#howto.batch.running-jobs-on-startup) - * [11.3. Running from the Command Line](#howto.batch.running-from-the-command-line) - * [11.4. Storing the Job Repository](#howto.batch.storing-job-repository) - -* [12. Actuator](#howto.actuator) - * [12.1. Change the HTTP Port or Address of the Actuator Endpoints](#howto.actuator.change-http-port-or-address) - * [12.2. Customize the ‘whitelabel’ Error Page](#howto.actuator.customize-whitelabel-error-page) - * [12.3. Sanitize Sensitive Values](#howto.actuator.sanitize-sensitive-values) - * [12.4. Map Health Indicators to Micrometer Metrics](#howto.actuator.map-health-indicators-to-metrics) - -* [13. Security](#howto.security) - * [13.1. Switch off the Spring Boot Security Configuration](#howto.security.switch-off-spring-boot-configuration) - * [13.2. Change the UserDetailsService and Add User Accounts](#howto.security.change-user-details-service-and-add-user-accounts) - * [13.3. Enable HTTPS When Running behind a Proxy Server](#howto.security.enable-https) - -* [14. Hot Swapping](#howto.hotswapping) - * [14.1. Reload Static Content](#howto.hotswapping.reload-static-content) - * [14.2. Reload Templates without Restarting the Container](#howto.hotswapping.reload-templates) - * [14.2.1. Thymeleaf Templates](#howto.hotswapping.reload-templates.thymeleaf) - * [14.2.2. FreeMarker Templates](#howto.hotswapping.reload-templates.freemarker) - * [14.2.3. Groovy Templates](#howto.hotswapping.reload-templates.groovy) - - * [14.3. Fast Application Restarts](#howto.hotswapping.fast-application-restarts) - * [14.4. Reload Java Classes without Restarting the Container](#howto.hotswapping.reload-java-classes-without-restarting) - -* [15. Testing](#howto.testing) - * [15.1. Testing With Spring Security](#howto.testing.with-spring-security) - * [15.2. Use Testcontainers for Integration Testing](#howto.testing.testcontainers) - -* [16. Build](#howto.build) - * [16.1. Generate Build Information](#howto.build.generate-info) - * [16.2. Generate Git Information](#howto.build.generate-git-info) - * [16.3. Customize Dependency Versions](#howto.build.customize-dependency-versions) - * [16.4. Create an Executable JAR with Maven](#howto.build.create-an-executable-jar-with-maven) - * [16.5. Use a Spring Boot Application as a Dependency](#howto.build.use-a-spring-boot-application-as-dependency) - * [16.6. Extract Specific Libraries When an Executable Jar Runs](#howto.build.extract-specific-libraries-when-an-executable-jar-runs) - * [16.7. Create a Non-executable JAR with Exclusions](#howto.build.create-a-nonexecutable-jar) - * [16.8. Remote Debug a Spring Boot Application Started with Maven](#howto.build.remote-debug-maven) - * [16.9. Build an Executable Archive from Ant without Using spring-boot-antlib](#howto.build.build-an-executable-archive-with-ant-without-using-spring-boot-antlib) - -* [17. Traditional Deployment](#howto.traditional-deployment) - * [17.1. Create a Deployable War File](#howto.traditional-deployment.war) - * [17.2. Convert an Existing Application to Spring Boot](#howto.traditional-deployment.convert-existing-application) - * [17.3. Deploying a WAR to WebLogic](#howto.traditional-deployment.weblogic) +# “How-to” Guides This section provides answers to some common ‘how do I do that…​’ questions that often arise when using Spring Boot. Its coverage is not exhaustive, but it does cover quite a lot. @@ -173,12 +9,11 @@ This is also a great place to ask new questions (please use the `spring-boot` ta We are also more than happy to extend this section. If you want to add a ‘how-to’, send us a [pull request](https://github.com/spring-projects/spring-boot/tree/v2.6.4). -[](#howto.application)1. Spring Boot Application ----------- +## 1. Spring Boot Application This section includes topics relating directly to Spring Boot applications. -### [](#howto.application.failure-analyzer)1.1. Create Your Own FailureAnalyzer ### +### 1.1. Create Your Own FailureAnalyzer [`FailureAnalyzer`](https://docs.spring.io/spring-boot/docs/2.6.4/api/org/springframework/boot/diagnostics/FailureAnalyzer.html) is a great way to intercept an exception on startup and turn it into a human-readable message, wrapped in a [`FailureAnalysis`](https://docs.spring.io/spring-boot/docs/2.6.4/api/org/springframework/boot/diagnostics/FailureAnalysis.html). Spring Boot provides such an analyzer for application-context-related exceptions, JSR-303 validations, and more. @@ -199,7 +34,7 @@ com.example.ProjectConstraintViolationFailureAnalyzer | |If you need access to the `BeanFactory` or the `Environment`, your `FailureAnalyzer` can implement `BeanFactoryAware` or `EnvironmentAware` respectively.| |---|---------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#howto.application.troubleshoot-auto-configuration)1.2. Troubleshoot Auto-configuration ### +### 1.2. Troubleshoot Auto-configuration 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. @@ -228,7 +63,7 @@ When reading the code, remember the following rules of thumb: * Look for `@ConditionalOnExpression` annotations that switch features on and off in response to SpEL expressions, normally evaluated with placeholders resolved from the `Environment`. -### [](#howto.application.customize-the-environment-or-application-context)1.3. Customize the Environment or ApplicationContext Before It Starts ### +### 1.3. Customize the Environment or ApplicationContext Before It Starts ### 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`. @@ -296,12 +131,12 @@ public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor { | |While using `@PropertySource` on your `@SpringBootApplication` may seem to be a convenient way to load a custom resource in the `Environment`, we do not recommend it.
Such property sources are not added to the `Environment` until the application context is being refreshed.
This is too late to configure certain properties such as `logging.*` and `spring.main.*` which are read before refresh begins.| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#howto.application.context-hierarchy)1.4. Build an ApplicationContext Hierarchy (Adding a Parent or Root Context) ### +### 1.4. Build an ApplicationContext Hierarchy (Adding a Parent or Root Context) ### You can use the `ApplicationBuilder` class to create parent/child `ApplicationContext` hierarchies. See “[features.html](features.html#features.spring-application.fluent-builder-api)” in the ‘Spring Boot features’ section for more information. -### [](#howto.application.non-web-application)1.5. Create a Non-web Application ### +### 1.5. Create a Non-web Application Not all Spring applications have to be web applications (or web services). If you want to execute some code in a `main` method but also bootstrap a Spring application to set up the infrastructure to use, you can use the `SpringApplication` features of Spring Boot. @@ -310,17 +145,16 @@ The first thing you can do to help it is to leave server-related dependencies (s If you cannot do that (for example, you run two applications from the same code base) then you can explicitly call `setWebApplicationType(WebApplicationType.NONE)` on your `SpringApplication` instance or set the `applicationContextClass` property (through the Java API or with external properties). Application code that you want to run as your business logic can be implemented as a `CommandLineRunner` and dropped into the context as a `@Bean` definition. -[](#howto.properties-and-configuration)2. Properties and Configuration ----------- +## 2. Properties and Configuration This section includes topics about setting and reading properties and configuration settings and their interaction with Spring Boot applications. -### [](#howto.properties-and-configuration.expand-properties)2.1. Automatically Expand Properties at Build Time ### +### 2.1. Automatically Expand Properties at Build Time Rather than hardcoding some properties that are also specified in your project’s build configuration, you can automatically expand them by instead using the existing build configuration. This is possible in both Maven and Gradle. -#### [](#howto.properties-and-configuration.expand-properties.maven)2.1.1. Automatic Property Expansion Using Maven #### +#### 2.1.1. Automatic Property Expansion Using Maven #### 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 `@[[email protected]](/cdn-cgi/l/email-protection)` placeholders, as shown in the following example: @@ -377,7 +211,7 @@ You also need to include the following element inside ``: | |The `useDefaultDelimiters` property is important if you use standard Spring placeholders (such as `${placeholder}`) in your configuration.
If that property is not set to `false`, these may be expanded by the build.| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#howto.properties-and-configuration.expand-properties.gradle)2.1.2. Automatic Property Expansion Using Gradle #### +#### 2.1.2. 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: @@ -407,7 +241,7 @@ app: | |Gradle’s `expand` method uses Groovy’s `SimpleTemplateEngine`, which transforms `${..}` tokens.
The `${..}` style conflicts with Spring’s own property placeholder mechanism.
To use Spring property placeholders together with automatic expansion, escape the Spring property placeholders as follows: `\${..}`.| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#howto.properties-and-configuration.externalize-configuration)2.2. Externalize the Configuration of SpringApplication ### +### 2.2. Externalize the Configuration of SpringApplication ### A `SpringApplication` has bean property setters, so you can use its Java API as you create the application to modify its behavior. Alternatively, you can externalize the configuration by setting properties in `spring.main.*`. @@ -498,7 +332,7 @@ The application sources are: 3. `MyJmsConfig`(from the external config) -### [](#howto.properties-and-configuration.external-properties-location)2.3. Change the Location of External Properties of an Application ### +### 2.3. Change the Location of External Properties of an Application ### By default, properties from different sources are added to the Spring `Environment` in a defined order (see “[features.html](features.html#features.external-config)” in the ‘Spring Boot features’ section for the exact order). @@ -516,7 +350,7 @@ Spring Boot logs the configuration files that are loaded at the `DEBUG` level an See [`ConfigFileApplicationListener`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigFileApplicationListener.java) for more detail. -### [](#howto.properties-and-configuration.short-command-line-arguments)2.4. Use ‘Short’ Command Line Arguments ### +### 2.4. Use ‘Short’ Command Line Arguments Some people like to use (for example) `--port=9000` instead of `--server.port=9000` to set configuration properties on the command line. You can enable this behavior by using placeholders in `application.properties`, as shown in the following example: @@ -540,7 +374,7 @@ server: | |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 automatically and Spring can bind to capitalized synonyms for `Environment` properties.| |---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#howto.properties-and-configuration.yaml)2.5. Use YAML for External Properties ### +### 2.5. 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: @@ -570,7 +404,7 @@ server.port=9000 See “[features.html](features.html#features.external-config.yaml)” in the ‘Spring Boot features’ section for more information about YAML. -### [](#howto.properties-and-configuration.set-active-spring-profiles)2.6. Set the Active Spring Profiles ### +### 2.6. Set the Active Spring Profiles The Spring `Environment` has an API for this, but you would normally set a System property (`spring.profiles.active`) or an OS environment variable (`SPRING_PROFILES_ACTIVE`). Also, you can launch your application with a `-D` argument (remember to put it before the main class or jar archive), as follows: @@ -600,7 +434,7 @@ Thus, the latter Java API can be used to augment the profiles without changing t See “[features.html](features.html#features.profiles)” in the “Spring Boot features” section for more information. -### [](#howto.properties-and-configuration.set-default-spring-profile-name)2.7. Set the Default Profile Name ### +### 2.7. Set the Default Profile Name The default profile is a profile that is enabled if no profile is active. By default, the name of the default profile is `default`, but it could be changed using a System property (`spring.profiles.default`) or an OS environment variable (`SPRING_PROFILES_DEFAULT`). @@ -623,7 +457,7 @@ spring: See “[features.html](features.html#features.profiles)” in the “Spring Boot features” section for more information. -### [](#howto.properties-and-configuration.change-configuration-depending-on-the-environment)2.8. Change Configuration Depending on the Environment ### +### 2.8. Change Configuration Depending on the Environment ### Spring Boot supports multi-document YAML and Properties files (see [features.html](features.html#features.external-config.files.multi-document) for details) which can be activated conditionally based on the active profiles. @@ -670,7 +504,7 @@ If ‘production’ is active, then the port is 0. | |The documents are merged in the order in which they are encountered.
Later values override earlier values.| |---|--------------------------------------------------------------------------------------------------------------| -### [](#howto.properties-and-configuration.discover-build-in-options-for-external-properties)2.9. Discover Built-in Options for External Properties ### +### 2.9. Discover Built-in Options for External Properties ### 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. @@ -681,14 +515,13 @@ The appendix includes an [`application.properties`](application-properties.html# The definitive list comes from searching the source code for `@ConfigurationProperties` and `@Value` annotations as well as the occasional use of `Binder`. For more about the exact ordering of loading properties, see "[features.html](features.html#features.external-config)". -[](#howto.webserver)3. Embedded Web Servers ----------- +## 3. Embedded Web Servers Each Spring Boot web application includes an embedded web server. This feature leads to a number of how-to questions, including how to change the embedded server and how to configure the embedded server. This section answers those questions. -### [](#howto.webserver.use-another)3.1. Use Another Web Server ### +### 3.1. Use Another Web Server Many Spring Boot starters include default embedded containers. @@ -743,7 +576,7 @@ dependencies { | |`spring-boot-starter-reactor-netty` is required to use the `WebClient` class, so you may need to keep a dependency on Netty even when you need to include a different HTTP server.| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#howto.webserver.disable)3.2. Disabling the Web Server ### +### 3.2. Disabling the Web Server If your classpath contains the necessary bits to start a web server, Spring Boot will automatically start it. To disable this behavior configure the `WebApplicationType` in your `application.properties`, as shown in the following example: @@ -762,7 +595,7 @@ spring: web-application-type: "none" ``` -### [](#howto.webserver.change-port)3.3. Change the HTTP Port ### +### 3.3. 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). @@ -771,11 +604,11 @@ To switch off the HTTP endpoints completely but still create a `WebApplicationCo For more details, see “[web.html](web.html#web.servlet.embedded-container.customizing)” in the ‘Spring Boot Features’ section, or the [`ServerProperties`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java) source code. -### [](#howto.webserver.use-random-port)3.4. Use a Random Unassigned HTTP Port ### +### 3.4. Use a Random Unassigned HTTP Port To scan for a free port (using OS natives to prevent clashes) use `server.port=0`. -### [](#howto.webserver.discover-port)3.5. Discover the HTTP Port at Runtime ### +### 3.5. Discover the HTTP Port at Runtime You can access the port the server is running on from log output or from the `WebServerApplicationContext` through its `WebServer`. The best way to get that and be sure it has been initialized is to add a `@Bean` of type `ApplicationListener` and pull the container out of the event when it is published. @@ -802,7 +635,7 @@ public class MyWebIntegrationTests { | |`@LocalServerPort` is a meta-annotation for `@Value("${local.server.port}")`.
Do not try to inject the port in a regular application.
As we just saw, the value is set only after the container has been initialized.
Contrary to a test, application code callbacks are processed early (before the value is actually available).| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#howto.webserver.enable-response-compression)3.6. Enable HTTP Response Compression ### +### 3.6. Enable HTTP Response Compression HTTP response compression is supported by Jetty, Tomcat, and Undertow. It can be enabled in `application.properties`, as follows: @@ -844,7 +677,7 @@ By default, responses are compressed only if their content type is one of the fo You can configure this behavior by setting the `server.compression.mime-types` property. -### [](#howto.webserver.configure-ssl)3.7. Configure SSL ### +### 3.7. Configure SSL SSL can be configured declaratively by setting the various `server.ssl.*` properties, typically in `application.properties` or `application.yml`. The following example shows setting SSL properties in `application.properties`: @@ -876,7 +709,7 @@ Spring Boot does not support the configuration of both an HTTP connector and an 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. -### [](#howto.webserver.configure-http2)3.8. Configure HTTP/2 ### +### 3.8. Configure HTTP/2 You can enable HTTP/2 support in your Spring Boot application with the `server.http2.enabled` configuration property. Both `h2` (HTTP/2 over TLS) and `h2c` (HTTP/2 over TCP) are supported. @@ -884,7 +717,7 @@ To use `h2`, SSL must also be enabled. When SSL is not enabled, `h2c` will be used. The details of the `h2` support depend on the chosen web server and the application environment, since that protocol is not supported out-of-the-box by all JDK 8 releases. -#### [](#howto.webserver.configure-http2.tomcat)3.8.1. HTTP/2 with Tomcat #### +#### 3.8.1. HTTP/2 with Tomcat Spring Boot ships by default with Tomcat 9.0.x which supports `h2c` out of the box and `h2` out of the box when using JDK 9 or later. Alternatively, `h2` can be used on JDK 8 if the `libtcnative` library and its dependencies are installed on the host operating system. @@ -901,7 +734,7 @@ ERROR 8787 --- [ main] o.a.coyote.http11.Http11NioProtocol : The This error is not fatal, and the application still starts with HTTP/1.1 SSL support. -#### [](#howto.webserver.configure-http2.jetty)3.8.2. HTTP/2 with Jetty #### +#### 3.8.2. HTTP/2 with Jetty For HTTP/2 support, Jetty requires the additional `org.eclipse.jetty.http2:http2-server` dependency. To use `h2c` no other dependencies are required. @@ -913,7 +746,7 @@ To use `h2`, you also need to choose one of the following dependencies, dependin * `org.eclipse.jetty:jetty-alpn-conscrypt-server` and the [Conscrypt library](https://www.conscrypt.org/) with no JDK requirement -#### [](#howto.webserver.configure-http2.netty)3.8.3. HTTP/2 with Reactor Netty #### +#### 3.8.3. HTTP/2 with Reactor Netty The `spring-boot-webflux-starter` is using by default Reactor Netty as a server. Reactor Netty supports `h2c` using JDK 8 or later with no additional dependencies. @@ -924,11 +757,11 @@ To enable that, your application needs to have an additional dependency. Spring Boot manages the version for the `io.netty:netty-tcnative-boringssl-static` "uber jar", containing native libraries for all platforms. Developers can choose to import only the required dependencies using a classifier (see [the Netty official documentation](https://netty.io/wiki/forked-tomcat-native.html)). -#### [](#howto.webserver.configure-http2.undertow)3.8.4. HTTP/2 with Undertow #### +#### 3.8.4. HTTP/2 with Undertow As of Undertow 1.4.0+, both `h2` and `h2c` are supported on JDK 8 without any additional dependencies. -### [](#howto.webserver.configure)3.9. Configure the Web Server ### +### 3.9. Configure the Web Server Generally, you should first consider using one of the many available configuration keys and customize your web server by adding new entries in your `application.properties` or `application.yml` file. See “[Discover Built-in Options for External Properties](#howto.properties-and-configuration.discover-build-in-options-for-external-properties)”). @@ -975,7 +808,7 @@ In addition Spring Boot provides: As a last resort, you can also declare your own `WebServerFactory` bean, which will override the one provided by Spring Boot. When you do so, auto-configured customizers are still applied on your custom factory, so use that option carefully. -### [](#howto.webserver.add-servlet-filter-listener)3.10. Add a Servlet, Filter, or Listener to an Application ### +### 3.10. Add a Servlet, Filter, or Listener to an Application In a servlet stack application, that is with the `spring-boot-starter-web`, there are two ways to add `Servlet`, `Filter`, `ServletContextListener`, and the other listeners supported by the Servlet API to your application: @@ -983,7 +816,7 @@ In a servlet stack application, that is with the `spring-boot-starter-web`, ther * [Add Servlets, Filters, and Listeners by Using Classpath Scanning](#howto.webserver.add-servlet-filter-listener.using-scanning) -#### [](#howto.webserver.add-servlet-filter-listener.spring-bean)3.10.1. Add a Servlet, Filter, or Listener by Using a Spring Bean #### +#### 3.10.1. Add a Servlet, Filter, or Listener by Using a Spring Bean #### To add a `Servlet`, `Filter`, or servlet `*Listener` by using a Spring bean, you must provide a `@Bean` definition for it. Doing so can be very useful when you want to inject configuration or dependencies. @@ -998,7 +831,7 @@ In the case of filters and servlets, you can also add mappings and init paramete Like any other Spring bean, you can define the order of servlet filter beans; please make sure to check the “[web.html](web.html#web.servlet.embedded-container.servlets-filters-listeners.beans)” section. -##### [](#howto.webserver.add-servlet-filter-listener.spring-bean.disable)Disable Registration of a Servlet or Filter ##### +##### Disable Registration of a Servlet or Filter ##### As [described earlier](#howto.webserver.add-servlet-filter-listener.spring-bean), 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: @@ -1022,12 +855,12 @@ public class MyFilterConfiguration { ``` -#### [](#howto.webserver.add-servlet-filter-listener.using-scanning)3.10.2. Add Servlets, Filters, and Listeners by Using Classpath Scanning #### +#### 3.10.2. Add Servlets, Filters, and Listeners by Using Classpath Scanning #### `@WebServlet`, `@WebFilter`, and `@WebListener` annotated classes can be automatically registered with an embedded servlet container by annotating a `@Configuration` class with `@ServletComponentScan` and specifying the package(s) containing the components that you want to register. By default, `@ServletComponentScan` scans from the package of the annotated class. -### [](#howto.webserver.configure-access-logs)3.11. Configure Access Logging ### +### 3.11. Configure Access Logging Access logs can be configured for Tomcat, Undertow, and Jetty through their respective namespaces. @@ -1099,7 +932,7 @@ server: By default, logs are redirected to `System.err`. For more details, see the Jetty documentation. -### [](#howto.webserver.use-behind-a-proxy-server)3.12. Running Behind a Front-end Proxy Server ### +### 3.12. Running Behind a Front-end Proxy Server If your application is running behind a proxy, a load-balancer or in the cloud, the request information (like the host, port, scheme…​) might change along the way. Your application may be running on `10.10.10.10:8080`, but HTTP clients should only see `example.org`. @@ -1120,7 +953,7 @@ You can register it as a servlet filter in your application by setting `server.f | |If your application runs in Cloud Foundry or Heroku, the `server.forward-headers-strategy` property defaults to `NATIVE`.
In all other instances, it defaults to `NONE`.| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#howto.webserver.use-behind-a-proxy-server.tomcat)3.12.1. Customize Tomcat’s Proxy Configuration #### +#### 3.12.1. Customize Tomcat’s Proxy Configuration If you use Tomcat, you can additionally configure the names of the headers used to carry “forwarded” information, as shown in the following example: @@ -1165,7 +998,7 @@ server: You can take complete control of the configuration of Tomcat’s `RemoteIpValve` by switching the automatic one off (to do so, set `server.forward-headers-strategy=NONE`) and adding a new valve instance using a `WebServerFactoryCustomizer` bean. -### [](#howto.webserver.enable-multiple-connectors-in-tomcat)3.13. Enable Multiple Connectors with Tomcat ### +### 3.13. 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: @@ -1216,7 +1049,7 @@ public class MyTomcatConfiguration { ``` -### [](#howto.webserver.use-tomcat-legacycookieprocessor)3.14. Use Tomcat’s LegacyCookieProcessor ### +### 3.14. Use Tomcat’s LegacyCookieProcessor By default, the embedded Tomcat used by Spring Boot does not support "Version 0" of the Cookie format, so you may see the following error: @@ -1249,7 +1082,7 @@ public class MyLegacyCookieProcessorConfiguration { ``` -### [](#howto.webserver.enable-tomcat-mbean-registry)3.15. Enable Tomcat’s MBean Registry ### +### 3.15. Enable Tomcat’s MBean Registry Embedded Tomcat’s MBean registry is disabled by default. This minimizes Tomcat’s memory footprint. @@ -1270,7 +1103,7 @@ server: enabled: true ``` -### [](#howto.webserver.enable-multiple-listeners-in-undertow)3.16. Enable Multiple Listeners with Undertow ### +### 3.16. Enable Multiple Listeners with Undertow Add an `UndertowBuilderCustomizer` to the `UndertowServletWebServerFactory` and add a listener to the `Builder`, as shown in the following example: @@ -1298,7 +1131,7 @@ public class MyUndertowConfiguration { ``` -### [](#howto.webserver.create-websocket-endpoints-using-serverendpoint)3.17. Create WebSocket Endpoints Using @ServerEndpoint ### +### 3.17. 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: @@ -1322,14 +1155,13 @@ public class MyWebSocketConfiguration { The bean shown in the preceding example registers any `@ServerEndpoint` annotated beans with the underlying WebSocket container. When deployed to a standalone servlet container, this role is performed by a servlet container initializer, and the `ServerEndpointExporter` bean is not required. -[](#howto.spring-mvc)4. Spring MVC ----------- +## 4. Spring MVC Spring Boot has a number of starters that include Spring MVC. Note that some starters include a dependency on Spring MVC rather than include it directly. This section answers common questions about Spring MVC and Spring Boot. -### [](#howto.spring-mvc.write-json-rest-service)4.1. Write a JSON REST Service ### +### 4.1. 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: @@ -1352,7 +1184,7 @@ public class MyController { As long as `MyThing` can be serialized by Jackson2 (true for a normal POJO or Groovy object), then `[localhost:8080/thing](http://localhost:8080/thing)` serves a JSON representation of it by default. Note that, in a browser, you might sometimes see XML responses, because browsers tend to send accept headers that prefer XML. -### [](#howto.spring-mvc.write-xml-rest-service)4.2. Write an XML REST Service ### +### 4.2. Write an XML REST Service If you have the Jackson XML extension (`jackson-dataformat-xml`) on the classpath, you can use it to render XML responses. The previous example that we used for JSON would work. @@ -1402,7 +1234,7 @@ If you use a more recent Java generation, add the following dependency to your p | |To get the server to render XML instead of JSON, you might have to send an `Accept: text/xml` header (or use a browser).| |---|------------------------------------------------------------------------------------------------------------------------| -### [](#howto.spring-mvc.customize-jackson-objectmapper)4.3. Customize the Jackson ObjectMapper ### +### 4.3. Customize the Jackson ObjectMapper Spring MVC (client and server side) uses `HttpMessageConverters` to negotiate content conversion in an HTTP exchange. If Jackson is on the classpath, you already get the default converter(s) provided by `Jackson2ObjectMapperBuilder`, an instance of which is auto-configured for you. @@ -1450,7 +1282,7 @@ It has some useful methods to access the default and user-enhanced message conve See the “[Customize the @ResponseBody Rendering](#howto.spring-mvc.customize-responsebody-rendering)” section and the [`WebMvcAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java) source code for more details. -### [](#howto.spring-mvc.customize-responsebody-rendering)4.4. Customize the @ResponseBody Rendering ### +### 4.4. 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. @@ -1464,7 +1296,7 @@ Finally, if you opt out of the Spring Boot default MVC configuration by providin See the [`WebMvcAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java) source code for more details. -### [](#howto.spring-mvc.multipart-file-uploads)4.5. Handling Multipart File Uploads ### +### 4.5. Handling Multipart File Uploads Spring Boot embraces the servlet 3 `javax.servlet.http.Part` API to support uploading files. By default, Spring Boot configures Spring MVC with a maximum size of 1MB per file and a maximum of 10MB of file data in a single request. @@ -1478,7 +1310,7 @@ See the [`MultipartAutoConfiguration`](https://github.com/spring-projects/spring | |It is recommended to use the container’s built-in support for multipart uploads rather than introducing an additional dependency such as Apache Commons File Upload.| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#howto.spring-mvc.switch-off-dispatcherservlet)4.6. Switch Off the Spring MVC DispatcherServlet ### +### 4.6. Switch Off the Spring MVC DispatcherServlet By default, all content is served from the root of your application (`/`). If you would rather map to a different path, you can configure one as follows: @@ -1503,12 +1335,12 @@ Because servlets are registered that way, they can be mapped to a sub-context of Configuring the `DispatcherServlet` yourself is unusual but if you really need to do it, a `@Bean` of type `DispatcherServletPath` must be provided as well to provide the path of your custom `DispatcherServlet`. -### [](#howto.spring-mvc.switch-off-default-configuration)4.7. Switch off the Default MVC Configuration ### +### 4.7. Switch off the Default MVC Configuration The easiest way to take complete control over MVC configuration is to provide your own `@Configuration` with the `@EnableWebMvc` annotation. Doing so leaves all MVC configuration in your hands. -### [](#howto.spring-mvc.customize-view-resolvers)4.8. Customize ViewResolvers ### +### 4.8. Customize ViewResolvers A `ViewResolver` is a core component of Spring MVC, translating view names in `@Controller` to actual `View` implementations. Note that `ViewResolvers` are mainly used in UI applications, rather than REST-style services (a `View` is not used to render a `@ResponseBody`). @@ -1566,10 +1398,9 @@ For more detail, see the following sections: * [`GroovyTemplateAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfiguration.java) -[](#howto.jersey)5. Jersey ----------- +## 5. Jersey -### [](#howto.jersey.spring-security)5.1. Secure Jersey endpoints with Spring Security ### +### 5.1. Secure Jersey endpoints with Spring Security Spring Security can be used to secure a Jersey-based web application in much the same way as it can be used to secure a Spring MVC-based web application. However, if you want to use Spring Security’s method-level security with Jersey, you must configure Jersey to use `setStatus(int)` rather `sendError(int)`. @@ -1596,7 +1427,7 @@ public class JerseySetStatusOverSendErrorConfig extends ResourceConfig { ``` -### [](#howto.jersey.alongside-another-web-framework)5.2. Use Jersey Alongside Another Web Framework ### +### 5.2. Use Jersey Alongside Another Web Framework To use Jersey alongside another web framework, such as Spring MVC, it should be configured so that it will allow the other framework to handle requests that it cannot handle. First, configure Jersey to use a filter rather than a servlet by configuring the `spring.jersey.type` application property with a value of `filter`. @@ -1620,20 +1451,19 @@ public class JerseyConfig extends ResourceConfig { ``` -[](#howto.http-clients)6. HTTP Clients ----------- +## 6. HTTP Clients Spring Boot offers a number of starters that work with HTTP clients. This section answers questions related to using them. -### [](#howto.http-clients.rest-template-proxy-configuration)6.1. Configure RestTemplate to Use a Proxy ### +### 6.1. Configure RestTemplate to Use a Proxy As described in [io.html](io.html#io.rest-client.resttemplate.customization), you can use a `RestTemplateCustomizer` with `RestTemplateBuilder` to build a customized `RestTemplate`. This is the recommended approach for creating a `RestTemplate` configured to use a proxy. The exact details of the proxy configuration depend on the underlying client request factory that is being used. -### [](#howto.http-clients.webclient-reactor-netty-customization)6.2. Configure the TcpClient used by a Reactor Netty-based WebClient ### +### 6.2. Configure the TcpClient used by a Reactor Netty-based WebClient ### When Reactor Netty is on the classpath a Reactor Netty-based `WebClient` is auto-configured. To customize the client’s handling of network connections, provide a `ClientHttpConnector` bean. @@ -1669,8 +1499,7 @@ public class MyReactorNettyClientConfiguration { | |Note the use of `ReactorResourceFactory` for the connection provider and event loop resources.
This ensures efficient sharing of resources for the server receiving requests and the client making requests.| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -[](#howto.logging)7. Logging ----------- +## 7. Logging Spring Boot has no mandatory logging dependency, except for the Commons Logging API, which is typically provided by Spring Framework’s `spring-jcl` module. To use [Logback](https://logback.qos.ch), you need to include it and `spring-jcl` on the classpath. @@ -1711,7 +1540,7 @@ You can also set the location of a file to which to write the log (in addition t To configure the more fine-grained settings of a logging system, you need to use the native configuration format supported by the `LoggingSystem` in question. By default, Spring Boot picks up the native configuration from its default location for the system (such as `classpath:logback.xml` for Logback), but you can set the location of the config file by using the `logging.config` property. -### [](#howto.logging.logback)7.1. Configure Logback for Logging ### +### 7.1. Configure Logback for Logging If you need to apply customizations to logback beyond those that can be achieved with `application.properties`, you will need to add a standard logback configuration file. You can add a `logback.xml` file to the root of your classpath for logback to find. @@ -1768,7 +1597,7 @@ If present, this setting is given preference. | |Spring extensions are not supported with Groovy configuration.
Any `logback-spring.groovy` files will not be detected.| |---|--------------------------------------------------------------------------------------------------------------------------| -#### [](#howto.logging.logback.file-only-output)7.1.1. Configure Logback for File-only Output #### +#### 7.1.1. 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: @@ -1800,7 +1629,7 @@ logging: name: "myapplication.log" ``` -### [](#howto.logging.log4j)7.2. Configure Log4j for Logging ### +### 7.2. Configure Log4j for Logging Spring Boot supports [Log4j 2](https://logging.apache.org/log4j/2.x/) for logging configuration if it is on the classpath. If you use the starters for assembling dependencies, you have to exclude Logback and then include log4j 2 instead. @@ -1851,7 +1680,7 @@ dependencies { | |To ensure that debug logging performed using `java.util.logging` is routed into Log4j 2, configure its [JDK logging adapter](https://logging.apache.org/log4j/2.x/log4j-jul/index.html) by setting the `java.util.logging.manager` system property to `org.apache.logging.log4j.jul.LogManager`.| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#howto.logging.log4j.yaml-or-json-config)7.2.1. Use YAML or JSON to Configure Log4j 2 #### +#### 7.2.1. Use YAML or JSON to Configure Log4j 2 In addition to its default XML configuration format, Log4j 2 also supports YAML and JSON configuration files. To configure Log4j 2 to use an alternative configuration file format, add the appropriate dependencies to the classpath and name your configuration files to match your chosen file format, as shown in the following example: @@ -1861,19 +1690,18 @@ To configure Log4j 2 to use an alternative configuration file format, add the ap | YAML |`com.fasterxml.jackson.core:jackson-databind` + `com.fasterxml.jackson.dataformat:jackson-dataformat-yaml`|`log4j2.yaml` + `log4j2.yml`| | JSON | `com.fasterxml.jackson.core:jackson-databind` |`log4j2.json` + `log4j2.jsn`| -#### [](#howto.logging.log4j.composite-configuration)7.2.2. Use Composite Configuration to Configure Log4j 2 #### +#### 7.2.2. Use Composite Configuration to Configure Log4j 2 Log4j 2 has support for combining multiple configuration files into a single composite configuration. To use this support in Spring Boot, configure `logging.log4j2.config.override` with the locations of one or more secondary configuration files. The secondary configuration files will be merged with the primary configuration, whether the primary’s source is Spring Boot’s defaults, a standard location such as `log4j.xml`, or the location configured by the `logging.config` property. -[](#howto.data-access)8. Data Access ----------- +## 8. Data Access Spring Boot includes a number of starters for working with data sources. This section answers questions related to doing so. -### [](#howto.data-access.configure-custom-datasource)8.1. Configure a Custom DataSource ### +### 8.1. Configure a Custom DataSource To configure your own `DataSource`, define a `@Bean` of that type in your configuration. Spring Boot reuses your `DataSource` anywhere one is required, including database initialization. @@ -2091,7 +1919,7 @@ app: See “[data.html](data.html#data.sql.datasource)” in the “Spring Boot features” section and the [`DataSourceAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration.java) class for more details. -### [](#howto.data-access.configure-two-datasources)8.2. Configure Two DataSources ### +### 8.2. 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. @@ -2226,7 +2054,7 @@ public class MyCompleteDataSourcesConfiguration { The preceding example configures two data sources on custom namespaces with the same logic as Spring Boot would use in auto-configuration. Note that each `configuration` sub namespace provides advanced settings based on the chosen implementation. -### [](#howto.data-access.spring-data-repositories)8.3. Use Spring Data Repositories ### +### 8.3. Use Spring Data Repositories 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. @@ -2240,7 +2068,7 @@ To get more control, use the `@EnableJpaRepositories` annotation (from Spring Da For more about Spring Data, see the [Spring Data project page](https://spring.io/projects/spring-data). -### [](#howto.data-access.separate-entity-definitions-from-spring-configuration)8.4. Separate @Entity Definitions from Spring Configuration ### +### 8.4. Separate @Entity Definitions from Spring Configuration ### Spring Boot tries to guess the location of your `@Entity` definitions, based on the `@EnableAutoConfiguration` it finds. To get more control, you can use the `@EntityScan` annotation, as shown in the following example: @@ -2261,7 +2089,7 @@ public class MyApplication { ``` -### [](#howto.data-access.jpa-properties)8.5. Configure JPA Properties ### +### 8.5. 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. @@ -2301,7 +2129,7 @@ In addition, all properties in `spring.jpa.properties.*` are passed through as n | |If you need to apply advanced customization to Hibernate properties, consider registering a `HibernatePropertiesCustomizer` bean that will be invoked prior to creating the `EntityManagerFactory`.
This takes precedence to anything that is applied by the auto-configuration.| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#howto.data-access.configure-hibernate-naming-strategy)8.6. Configure Hibernate Naming Strategy ### +### 8.6. Configure Hibernate Naming Strategy Hibernate uses [two different naming strategies](https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#naming) to map names from the object model to the corresponding database names. The fully qualified class name of the physical and the implicit strategy implementations can be configured by setting the `spring.jpa.hibernate.naming.physical-strategy` and `spring.jpa.hibernate.naming.implicit-strategy` properties, respectively. @@ -2367,7 +2195,7 @@ class MyHibernateConfiguration { See [`HibernateJpaAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.java) and [`JpaBaseConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java) for more details. -### [](#howto.data-access.configure-hibernate-second-level-caching)8.7. Configure Hibernate Second-Level Caching ### +### 8.7. Configure Hibernate Second-Level Caching Hibernate [second-level cache](https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#caching) can be configured for a range of cache providers. Rather than configuring Hibernate to lookup the cache provider again, it is better to provide the one that is available in the context whenever possible. @@ -2399,18 +2227,18 @@ This customizer will configure Hibernate to use the same `CacheManager` as the o It is also possible to use separate `CacheManager` instances. For details, see [the Hibernate user guide](https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#caching-provider-jcache). -### [](#howto.data-access.dependency-injection-in-hibernate-components)8.8. Use Dependency Injection in Hibernate Components ### +### 8.8. Use Dependency Injection in Hibernate Components ### By default, Spring Boot registers a `BeanContainer` implementation that uses the `BeanFactory` so that converters and entity listeners can use regular dependency injection. You can disable or tune this behavior by registering a `HibernatePropertiesCustomizer` that removes or changes the `hibernate.resource.beans.container` property. -### [](#howto.data-access.use-custom-entity-manager)8.9. Use a Custom EntityManagerFactory ### +### 8.9. Use a Custom EntityManagerFactory To take full control of the configuration of the `EntityManagerFactory`, you need to add a `@Bean` named ‘entityManagerFactory’. Spring Boot auto-configuration switches off its entity manager in the presence of a bean of that type. -### [](#howto.data-access.use-multiple-entity-managers)8.10. Using Multiple EntityManagerFactories ### +### 8.10. Using Multiple EntityManagerFactories If you need to use JPA against multiple data sources, you likely need one `EntityManagerFactory` per data source. The `LocalContainerEntityManagerFactoryBean` from Spring ORM allows you to configure an `EntityManagerFactory` for your needs. @@ -2495,14 +2323,14 @@ public class CustomerConfiguration { ``` -### [](#howto.data-access.use-traditional-persistence-xml)8.11. Use a Traditional persistence.xml File ### +### 8.11. Use a Traditional persistence.xml File Spring Boot will not search for or use a `META-INF/persistence.xml` by default. If you prefer to use a traditional `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 [`JpaBaseConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java) for the default settings. -### [](#howto.data-access.use-spring-data-jpa-and-mongo-repositories)8.12. Use Spring Data JPA and Mongo Repositories ### +### 8.12. Use Spring Data JPA and Mongo Repositories ### 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 repositories to create. @@ -2514,13 +2342,13 @@ Doing so is useful, for instance, in case you want to switch off the Mongo repos 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. -### [](#howto.data-access.customize-spring-data-web-support)8.13. Customize Spring Data’s Web Support ### +### 8.13. Customize Spring Data’s Web Support Spring Data provides web support that simplifies the use of Spring Data repositories in a web application. Spring Boot provides properties in the `spring.data.web` namespace for customizing its configuration. Note that if you are using Spring Data REST, you must use the properties in the `spring.data.rest` namespace instead. -### [](#howto.data-access.exposing-spring-data-repositories-as-rest)8.14. Expose Spring Data Repositories as REST Endpoint ### +### 8.14. Expose Spring Data Repositories as REST Endpoint ### Spring Data REST can expose the `Repository` implementations as REST endpoints for you, provided Spring MVC has been enabled for the application. @@ -2531,7 +2359,7 @@ If you need to provide additional customization, you should use a [`RepositoryRe | |If you do not specify any order on your custom `RepositoryRestConfigurer`, it runs after the one Spring Boot uses internally.
If you need to specify an order, make sure it is higher than 0.| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#howto.data-access.configure-a-component-that-is-used-by-jpa)8.15. Configure a Component that is Used by JPA ### +### 8.15. Configure a Component that is Used by JPA ### If you want to configure a component that JPA uses, then you need to ensure that the component is initialized before JPA. When the component is auto-configured, Spring Boot takes care of this for you. @@ -2562,7 +2390,7 @@ public class ElasticsearchEntityManagerFactoryDependsOnPostProcessor ``` -### [](#howto.data-access.configure-jooq-with-multiple-datasources)8.16. Configure jOOQ with Two DataSources ### +### 8.16. Configure jOOQ with Two DataSources If you need to use jOOQ with multiple data sources, you should create your own `DSLContext` for each one. See [JooqAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfiguration.java) for more details. @@ -2570,14 +2398,13 @@ See [JooqAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/ | |In particular, `JooqExceptionTranslator` and `SpringTransactionProvider` can be reused to provide similar features to what the auto-configuration does with a single `DataSource`.| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -[](#howto.data-initialization)9. Database Initialization ----------- +## 9. Database Initialization An SQL database can be initialized in different ways depending on what your stack is. Of course, you can also do it manually, provided the database is a separate process. It is recommended to use a single mechanism for schema generation. -### [](#howto.data-initialization.using-jpa)9.1. Initialize a Database Using JPA ### +### 9.1. Initialize a Database Using JPA JPA has features for DDL generation, and these can be set up to run on startup against the database. This is controlled through two external properties: @@ -2587,7 +2414,7 @@ This is controlled through two external properties: * `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 this guide. -### [](#howto.data-initialization.using-hibernate)9.2. Initialize a Database Using Hibernate ### +### 9.2. 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. @@ -2603,7 +2430,7 @@ In addition, a file named `import.sql` in the root of the classpath is executed 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). -### [](#howto.data-initialization.using-basic-sql-scripts)9.3. Initialize a Database Using Basic SQL Scripts ### +### 9.3. Initialize a Database Using Basic SQL Scripts Spring Boot can automatically create the schema (DDL scripts) of your JDBC `DataSource` or R2DBC `ConnectionFactory` and initialize it (DML scripts). It loads SQL from the standard root classpath locations: `schema.sql` and `data.sql`, respectively. @@ -2624,7 +2451,7 @@ This will defer data source initialization until after any `EntityManagerFactory If you are using a [Higher-level Database Migration Tool](#howto.data-initialization.migration-tool), like Flyway or Liquibase, you should use them alone to create and initialize the schema. Using the basic `schema.sql` and `data.sql` scripts alongside Flyway or Liquibase is not recommended and support will be removed in a future release. -### [](#howto.data-initialization.batch)9.4. Initialize a Spring Batch Database ### +### 9.4. 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. @@ -2648,11 +2475,11 @@ spring: You can also switch off the initialization explicitly by setting `spring.batch.jdbc.initialize-schema` to `never`. -### [](#howto.data-initialization.migration-tool)9.5. Use a Higher-level Database Migration Tool ### +### 9.5. Use a Higher-level Database Migration Tool Spring Boot supports two higher-level migration tools: [Flyway](https://flywaydb.org/) and [Liquibase](https://www.liquibase.org/). -#### [](#howto.data-initialization.migration-tool.flyway)9.5.1. Execute Flyway Database Migrations on Startup #### +#### 9.5.1. Execute Flyway Database Migrations on Startup To automatically run Flyway database migrations on startup, add the `org.flywaydb:flyway-core` to your classpath. @@ -2739,7 +2566,7 @@ spring: With that setup, migrations in `dev/db/migration` run only when the `dev` profile is active. -#### [](#howto.data-initialization.migration-tool.liquibase)9.5.2. Execute Liquibase Database Migrations on Startup #### +#### 9.5.2. Execute Liquibase Database Migrations on Startup #### To automatically run Liquibase database migrations on startup, add the `org.liquibase:liquibase-core` to your classpath. @@ -2758,14 +2585,14 @@ If any of the three properties has not been set, the value of its equivalent `sp See [`LiquibaseProperties`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseProperties.java) for details about available settings such as contexts, the default schema, and others. -### [](#howto.data-initialization.dependencies)9.6. Depend Upon an Initialized Database ### +### 9.6. Depend Upon an Initialized Database Database initialization is performed while the application is starting up as part of application context refresh. To allow an initialized database to be accessed during startup, beans that act as database initializers and beans that require that database to have been initialized are detected automatically. Beans whose initialization depends upon the database having been initialized are configured to depend upon those that initialize it. If, during startup, your application tries to access the database and it has not been initialized, you can configure additional detection of beans that initialize the database and require the database to have been initialized. -#### [](#howto.data-initialization.dependencies.initializer-detection)9.6.1. Detect a Database Initializer #### +#### 9.6.1. Detect a Database Initializer Spring Boot will automatically detect beans of the following types that initialize an SQL database: @@ -2784,7 +2611,7 @@ Spring Boot will automatically detect beans of the following types that initiali If you are using a third-party starter for a database initialization library, it may provide a detector such that beans of other types are also detected automatically. To have other beans be detected, register an implementation of `DatabaseInitializerDetector` in `META-INF/spring-factories`. -#### [](#howto.data-initialization.dependencies.depends-on-initialization-detection)9.6.2. Detect a Bean That Depends On Database Initialization #### +#### 9.6.2. Detect a Bean That Depends On Database Initialization #### Spring Boot will automatically detect beans of the following types that depends upon database initialization: @@ -2802,13 +2629,12 @@ If you are using a third-party starter data access library, it may provide a det To have other beans be detected, register an implementation of `DependsOnDatabaseInitializationDetector` in `META-INF/spring-factories`. Alternatively, annotate the bean’s class or its `@Bean` method with `@DependsOnDatabaseInitialization`. -[](#howto.messaging)10. Messaging ----------- +## 10. Messaging Spring Boot offers a number of starters to support messaging. This section answers questions that arise from using messaging with Spring Boot. -### [](#howto.messaging.disable-transacted-jms-session)10.1. Disable Transacted JMS Session ### +### 10.1. Disable Transacted JMS Session 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. @@ -2841,13 +2667,12 @@ public class MyJmsConfiguration { The preceding example overrides the default factory, and it should be applied to any other factory that your application defines, if any. -[](#howto.batch)11. Batch Applications ----------- +## 11. Batch Applications A number of questions often arise when people use Spring Batch from within a Spring Boot application. This section addresses those questions. -### [](#howto.batch.specifying-a-data-source)11.1. Specifying a Batch Data Source ### +### 11.1. Specifying a Batch Data Source By default, batch applications require a `DataSource` to store job details. Spring Batch expects a single `DataSource` by default. @@ -2858,7 +2683,7 @@ See [The Javadoc of `@EnableBatchProcessing`](https://docs.spring.io/spring-batc For more info about Spring Batch, see the [Spring Batch project page](https://spring.io/projects/spring-batch). -### [](#howto.batch.running-jobs-on-startup)11.2. Running Spring Batch Jobs on Startup ### +### 11.2. Running Spring Batch Jobs on Startup Spring Batch auto-configuration is enabled by adding `@EnableBatchProcessing` to one of your `@Configuration` classes. @@ -2867,7 +2692,7 @@ You can narrow down to a specific job or jobs by specifying `spring.batch.job.na See [BatchAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfiguration.java) and [@EnableBatchProcessing](https://docs.spring.io/spring-batch/docs/4.3.5/api/org/springframework/batch/core/configuration/annotation/EnableBatchProcessing.html) for more details. -### [](#howto.batch.running-from-the-command-line)11.3. Running from the Command Line ### +### 11.3. Running from the Command Line Spring Boot converts any command line argument starting with `--` to a property to add to the `Environment`, see [accessing command line properties](features.html#features.external-config.command-line-args). This should not be used to pass arguments to batch jobs. @@ -2886,19 +2711,18 @@ $ java -jar myapp.jar --server.port=7070 someParameter=someValue This provides only one argument to the batch job: `someParameter=someValue`. -### [](#howto.batch.storing-job-repository)11.4. Storing the Job Repository ### +### 11.4. Storing the Job Repository Spring Batch requires a data store for the `Job` repository. If you use Spring Boot, you must use an actual database. Note that it can be an in-memory database, see [Configuring a Job Repository](https://docs.spring.io/spring-batch/docs/4.3.5/reference/html/job.html#configuringJobRepository). -[](#howto.actuator)12. Actuator ----------- +## 12. Actuator Spring Boot includes the Spring Boot Actuator. This section answers questions that often arise from its use. -### [](#howto.actuator.change-http-port-or-address)12.1. Change the HTTP Port or Address of the Actuator Endpoints ### +### 12.1. 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`. @@ -2906,7 +2730,7 @@ To listen on a completely different network address (such as when you have an in For more detail, see the [`ManagementServerProperties`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementServerProperties.java) source code and “[actuator.html](actuator.html#actuator.monitoring.customizing-management-server-port)” in the “Production-ready features” section. -### [](#howto.actuator.customize-whitelabel-error-page)12.2. Customize the ‘whitelabel’ Error Page ### +### 12.2. Customize the ‘whitelabel’ Error Page Spring Boot installs a ‘whitelabel’ error page that you see in a browser client if you encounter a server error (machine clients consuming JSON and other media types should see a sensible response with the right error code). @@ -2922,7 +2746,7 @@ See [`ErrorMvcAutoConfiguration`](https://github.com/spring-projects/spring-boot See also the section on “[Error Handling](web.html#web.servlet.spring-mvc.error-handling)” for details of how to register handlers in the servlet container. -### [](#howto.actuator.sanitize-sensitive-values)12.3. Sanitize Sensitive Values ### +### 12.3. Sanitize Sensitive Values Information returned by the `env` and `configprops` endpoints can be somewhat sensitive so keys matching certain patterns are sanitized by default (that is their values are replaced by `******`). Spring Boot uses sensible defaults for such keys: any key ending with the word "password", "secret", "key", "token", "vcap\_services", "sun.java.command" is entirely sanitized. @@ -2948,7 +2772,7 @@ For example, for the property `myclient.uri=http://user1:[[email protected]](/c The default patterns used by the `env` and `configprops` endpoints can be replaced using `management.endpoint.env.keys-to-sanitize` and `management.endpoint.configprops.keys-to-sanitize` respectively. Alternatively, additional patterns can be configured using `management.endpoint.env.additional-keys-to-sanitize` and `management.endpoint.configprops.additional-keys-to-sanitize`. -### [](#howto.actuator.map-health-indicators-to-metrics)12.4. Map Health Indicators to Micrometer Metrics ### +### 12.4. Map Health Indicators to Micrometer Metrics Spring Boot health indicators return a `Status` type to indicate the overall system health. If you want to monitor or alert on levels of health for a particular application, you can export these statuses as metrics with Micrometer. @@ -2991,25 +2815,24 @@ public class MyHealthMetricsExportConfiguration { ``` -[](#howto.security)13. Security ----------- +## 13. 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 project page](https://spring.io/projects/spring-security). -### [](#howto.security.switch-off-spring-boot-configuration)13.1. Switch off the Spring Boot Security Configuration ### +### 13.1. Switch off the Spring Boot Security Configuration ### If you define a `@Configuration` with a `WebSecurityConfigurerAdapter` or a `SecurityFilterChain` bean in your application, it switches off the default webapp security settings in Spring Boot. -### [](#howto.security.change-user-details-service-and-add-user-accounts)13.2. Change the UserDetailsService and Add User Accounts ### +### 13.2. Change the UserDetailsService and Add User Accounts ### If you provide a `@Bean` of type `AuthenticationManager`, `AuthenticationProvider`, or `UserDetailsService`, the default `@Bean` for `InMemoryUserDetailsManager` is not created. This means you have the full feature set of Spring Security available (such as [various authentication options](https://docs.spring.io/spring-security/reference/5.6.2/servlet/authentication/index.html)). The easiest way to add user accounts is to provide your own `UserDetailsService` bean. -### [](#howto.security.enable-https)13.3. Enable HTTPS When Running behind a Proxy Server ### +### 13.3. Enable HTTPS When Running behind a Proxy Server Ensuring that all your main endpoints are only available over HTTPS is an important chore for any application. If you use Tomcat as a servlet container, then Spring Boot adds Tomcat’s own `RemoteIpValve` automatically if it detects some environment settings, and you should be able to rely on the `HttpServletRequest` to report whether it is secure or not (even downstream of a proxy server that handles the real SSL termination). @@ -3058,13 +2881,12 @@ public class MySecurityConfig { ``` -[](#howto.hotswapping)14. Hot Swapping ----------- +## 14. Hot Swapping Spring Boot supports hot swapping. This section answers questions about how it works. -### [](#howto.hotswapping.reload-static-content)14.1. Reload Static Content ### +### 14.1. Reload Static Content There are several options for hot reloading. The recommended approach is to use [`spring-boot-devtools`](using.html#using.devtools), 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). @@ -3080,27 +2902,27 @@ Alternatively, running in an IDE (especially with debugging on) is a good way to Finally, the [Maven and Gradle plugins](build-tool-plugins.html#build-tool-plugins) can be configured (see the `addResources` property) to support running from the command line with reloading of static files directly from source. You can use that with an external css/js compiler process if you are writing that code with higher-level tools. -### [](#howto.hotswapping.reload-templates)14.2. Reload Templates without Restarting the Container ### +### 14.2. Reload Templates without Restarting the Container Most of the templating technologies supported by Spring Boot include a configuration option to disable caching (described later in this document). If you use the `spring-boot-devtools` module, these properties are [automatically configured](using.html#using.devtools.property-defaults) for you at development time. -#### [](#howto.hotswapping.reload-templates.thymeleaf)14.2.1. Thymeleaf Templates #### +#### 14.2.1. Thymeleaf Templates If you use Thymeleaf, set `spring.thymeleaf.cache` to `false`. See [`ThymeleafAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java) for other Thymeleaf customization options. -#### [](#howto.hotswapping.reload-templates.freemarker)14.2.2. FreeMarker Templates #### +#### 14.2.2. FreeMarker Templates If you use FreeMarker, set `spring.freemarker.cache` to `false`. See [`FreeMarkerAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfiguration.java) for other FreeMarker customization options. -#### [](#howto.hotswapping.reload-templates.groovy)14.2.3. Groovy Templates #### +#### 14.2.3. Groovy Templates If you use Groovy templates, set `spring.groovy.template.cache` to `false`. See [`GroovyTemplateAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfiguration.java) for other Groovy customization options. -### [](#howto.hotswapping.fast-application-restarts)14.3. Fast Application Restarts ### +### 14.3. Fast Application Restarts The `spring-boot-devtools` module includes support for automatic application restarts. While not as fast as technologies such as [JRebel](https://www.jrebel.com/products/jrebel) it is usually significantly faster than a “cold start”. @@ -3108,18 +2930,17 @@ You should probably give it a try before investigating some of the more complex For more details, see the [using.html](using.html#using.devtools) section. -### [](#howto.hotswapping.reload-java-classes-without-restarting)14.4. Reload Java Classes without Restarting the Container ### +### 14.4. Reload Java Classes without Restarting the Container ### 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. -[](#howto.testing)15. Testing ----------- +## 15. Testing Spring Boot includes a number of testing utilities and support classes as well as a dedicated starter that provides common test dependencies. This section answers common questions about testing. -### [](#howto.testing.with-spring-security)15.1. Testing With Spring Security ### +### 15.1. Testing With Spring Security Spring Security provides support for running tests as a specific user. For example, the test in the snippet below will run with an authenticated user that has the `ADMIN` role. @@ -3154,7 +2975,7 @@ Spring Security provides comprehensive integration with Spring MVC Test and this For additional details on Spring Security’s testing support, see Spring Security’s [reference documentation](https://docs.spring.io/spring-security/reference/5.6.2/servlet/test/index.html). -### [](#howto.testing.testcontainers)15.2. Use Testcontainers for Integration Testing ### +### 15.2. Use Testcontainers for Integration Testing The [Testcontainers](https://www.testcontainers.org/) library provides a way to manage services running inside Docker containers. It integrates with JUnit, allowing you to write a test class that can start up a container before any of the tests run. @@ -3223,13 +3044,12 @@ class MyIntegrationTests { The above configuration allows Neo4j-related beans in the application to communicate with Neo4j running inside the Testcontainers-managed Docker container. -[](#howto.build)16. Build ----------- +## 16. Build Spring Boot includes build plugins for Maven and Gradle. This section answers common questions about these plugins. -### [](#howto.build.generate-info)16.1. Generate Build Information ### +### 16.1. Generate Build Information Both the Maven plugin and the Gradle plugin allow generating build information containing the coordinates, name, and version of the project. The plugins can also be configured to add additional properties through configuration. @@ -3270,7 +3090,7 @@ springBoot { | |See the [Spring Boot Gradle Plugin documentation](https://docs.spring.io/spring-boot/docs/2.6.4/gradle-plugin/reference/htmlsingle/#integrating-with-actuator-build-info) for more details.| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#howto.build.generate-git-info)16.2. Generate Git Information ### +### 16.2. Generate Git Information Both Maven and Gradle allow generating a `git.properties` file containing information about the state of your `git` source code repository when the project was built. @@ -3301,7 +3121,7 @@ Both the Maven and Gradle plugins allow the properties that are included in `git | |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 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.build.customize-dependency-versions)16.3. Customize Dependency Versions ### +### 16.3. Customize Dependency Versions The `spring-boot-dependencies` POM manages the versions of common dependencies. The Spring Boot plugins for Maven and Gradle allow these managed dependency versions to be customized using build properties. @@ -3313,7 +3133,7 @@ To override dependency versions with Maven, see [this section](https://docs.spri To override dependency versions in Gradle, see [this section](https://docs.spring.io/spring-boot/docs/2.6.4/gradle-plugin/reference/htmlsingle/#managing-dependencies-dependency-management-plugin-customizing) of the Gradle plugin’s documentation. -### [](#howto.build.create-an-executable-jar-with-maven)16.4. Create an Executable JAR with Maven ### +### 16.4. Create an Executable JAR with Maven 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: @@ -3353,7 +3173,7 @@ However, you must additionally add an `` section, as follows: See the [plugin documentation](https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/reference/htmlsingle/#repackage) for full usage details. -### [](#howto.build.use-a-spring-boot-application-as-dependency)16.5. Use a Spring Boot Application as a Dependency ### +### 16.5. Use a Spring Boot Application as a Dependency ### Like a war file, a Spring Boot application is not intended to be used as a dependency. If your application contains classes that you want to share with other projects, the recommended approach is to move that code into a separate module. @@ -3382,7 +3202,7 @@ To configure a classifier of `exec` in Maven, you can use the following configur ``` -### [](#howto.build.extract-specific-libraries-when-an-executable-jar-runs)16.6. Extract Specific Libraries When an Executable Jar Runs ### +### 16.6. Extract Specific Libraries When an Executable Jar Runs ### Most nested libraries in an executable jar do not need to be unpacked in order to run. However, certain libraries can have problems. @@ -3415,7 +3235,7 @@ For example, to indicate that JRuby should be flagged for unpacking by using the ``` -### [](#howto.build.create-a-nonexecutable-jar)16.7. Create a Non-executable JAR with Exclusions ### +### 16.7. Create a Non-executable JAR with Exclusions 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 be excluded from the non-executable JAR. @@ -3451,13 +3271,13 @@ In Maven, the executable jar must be the main artifact and you can add a classif ``` -### [](#howto.build.remote-debug-maven)16.8. Remote Debug a Spring Boot Application Started with Maven ### +### 16.8. 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 [maven plugin](https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/reference/htmlsingle/). See [this example](https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/reference/htmlsingle/#run-example-debug) for more details. -### [](#howto.build.build-an-executable-archive-with-ant-without-using-spring-boot-antlib)16.9. Build an Executable Archive from Ant without Using spring-boot-antlib ### +### 16.9. Build an Executable Archive from Ant without Using spring-boot-antlib ### To build with Ant, you need to grab dependencies, compile, and then create a jar or war archive. To make it executable, you can either use the `spring-boot-antlib` module or you can follow these instructions: @@ -3501,13 +3321,12 @@ The following example shows how to build an executable archive with Ant: ``` -[](#howto.traditional-deployment)17. Traditional Deployment ----------- +## 17. Traditional Deployment Spring Boot supports traditional deployment as well as more modern forms of deployment. This section answers common questions about traditional deployment. -### [](#howto.traditional-deployment.war)17.1. Create a Deployable War File ### +### 17.1. Create a Deployable War File | |Because Spring WebFlux does not strictly depend on the servlet API and applications are deployed by default on an embedded Reactor Netty server, War deployment is not supported for WebFlux applications.| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| @@ -3584,7 +3403,7 @@ dependencies { If you use the [Spring Boot build tools](build-tool-plugins.html#build-tool-plugins), marking the embedded servlet container dependency as provided produces an executable war file with the provided dependencies packaged in a `lib-provided` directory. This means that, in addition to being deployable to a servlet container, you can also run your application by using `java -jar` on the command line. -### [](#howto.traditional-deployment.convert-existing-application)17.2. Convert an Existing Application to Spring Boot ### +### 17.2. Convert an Existing Application to Spring Boot ### To convert an existing non-web Spring application to a Spring Boot application, replace the code that creates your `ApplicationContext` and replace it with calls to `SpringApplication` or `SpringApplicationBuilder`. Spring MVC web applications are generally amenable to first creating a deployable war application and then migrating it later to an executable war or jar. @@ -3665,7 +3484,7 @@ Applications that are not already Spring applications might be convertible to Sp However, you may yet encounter problems. In that case, we suggest [asking questions on Stack Overflow with a tag of `spring-boot`](https://stackoverflow.com/questions/tagged/spring-boot). -### [](#howto.traditional-deployment.weblogic)17.3. Deploying a WAR to WebLogic ### +### 17.3. Deploying a WAR to WebLogic To deploy a Spring Boot application to WebLogic, you must ensure that your servlet initializer **directly** implements `WebApplicationInitializer` (even if you extend from a base class that already implements it). diff --git a/docs/en/spring-boot/io.md b/docs/en/spring-boot/io.md index 66af37040142468ed27f98a6cf8af980bdb8ff1b..9904e03b6d3cc94c9452a65d091ad8ee9e032804 100644 --- a/docs/en/spring-boot/io.md +++ b/docs/en/spring-boot/io.md @@ -1,53 +1,11 @@ -IO -========== - -Table of Contents - -[Back to index](index.html) - -* [1. Caching](#io.caching) - * [1.1. Supported Cache Providers](#io.caching.provider) - * [1.1.1. Generic](#io.caching.provider.generic) - * [1.1.2. JCache (JSR-107)](#io.caching.provider.jcache) - * [1.1.3. EhCache 2.x](#io.caching.provider.ehcache2) - * [1.1.4. Hazelcast](#io.caching.provider.hazelcast) - * [1.1.5. Infinispan](#io.caching.provider.infinispan) - * [1.1.6. Couchbase](#io.caching.provider.couchbase) - * [1.1.7. Redis](#io.caching.provider.redis) - * [1.1.8. Caffeine](#io.caching.provider.caffeine) - * [1.1.9. Simple](#io.caching.provider.simple) - * [1.1.10. None](#io.caching.provider.none) - -* [2. Hazelcast](#io.hazelcast) -* [3. Quartz Scheduler](#io.quartz) -* [4. Sending Email](#io.email) -* [5. Validation](#io.validation) -* [6. Calling REST Services](#io.rest-client) - * [6.1. RestTemplate](#io.rest-client.resttemplate) - * [6.1.1. RestTemplate Customization](#io.rest-client.resttemplate.customization) - - * [6.2. WebClient](#io.rest-client.webclient) - * [6.2.1. WebClient Runtime](#io.rest-client.webclient.runtime) - * [6.2.2. WebClient Customization](#io.rest-client.webclient.customization) - -* [7. Web Services](#io.webservices) - * [7.1. Calling Web Services with WebServiceTemplate](#io.webservices.template) - -* [8. Distributed Transactions with JTA](#io.jta) - * [8.1. Using an Atomikos Transaction Manager](#io.jta.atomikos) - * [8.2. Using a Java EE Managed Transaction Manager](#io.jta.javaee) - * [8.3. Mixing XA and Non-XA JMS Connections](#io.jta.mixing-xa-and-non-xa-connections) - * [8.4. Supporting an Alternative Embedded Transaction Manager](#io.jta.supporting-alternative-embedded-transaction-manager) - -* [9. What to Read Next](#io.whats-next) +# IO Most applications will need to deal with input and output concerns at some point. Spring Boot provides utilities and integrations with a range of technologies to help when you need IO capabilities. This section covers standard IO features such as caching and validation as well as more advanced topics such as scheduling and distributed transactions. We will also cover calling remote REST or SOAP services and sending email. -[](#io.caching)1. Caching ----------- +## 1. Caching The Spring Framework provides support for transparently adding caching to an application. At its core, the abstraction applies caching to methods, thus reducing the number of executions based on the information available in the cache. @@ -93,7 +51,7 @@ Some offer a way to customize the default caches defined by the `spring.cache.ca | |It is also possible to transparently [update](https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/integration.html#cache-annotations-put) or [evict](https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/integration.html#cache-annotations-evict) data from the cache.| |---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#io.caching.provider)1.1. Supported Cache Providers ### +### 1.1. Supported Cache Providers The cache abstraction does not provide an actual store and relies on abstraction materialized by the `org.springframework.cache.Cache` and `org.springframework.cache.CacheManager` interfaces. @@ -147,12 +105,12 @@ public class MyCacheManagerConfiguration { | |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`.| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#io.caching.provider.generic)1.1.1. Generic #### +#### 1.1.1. Generic Generic caching is used if the context defines *at least* one `org.springframework.cache.Cache` bean. A `CacheManager` wrapping all beans of that type is created. -#### [](#io.caching.provider.jcache)1.1.2. JCache (JSR-107) #### +#### 1.1.2. JCache (JSR-107) [JCache](https://jcp.org/en/jsr/detail?id=107) 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. @@ -196,7 +154,7 @@ There are two ways to customize the underlying `javax.cache.cacheManager`: | |If a standard `javax.cache.CacheManager` bean is defined, it is wrapped automatically in an `org.springframework.cache.CacheManager` implementation that the abstraction expects.
No further customization is applied to it.| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#io.caching.provider.ehcache2)1.1.3. EhCache 2.x #### +#### 1.1.3. EhCache 2.x [EhCache](https://www.ehcache.org/) 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. @@ -217,12 +175,12 @@ spring: config: "classpath:config/another-config.xml" ``` -#### [](#io.caching.provider.hazelcast)1.1.4. Hazelcast #### +#### 1.1.4. Hazelcast Spring Boot has [general support for Hazelcast](#io.hazelcast). If a `HazelcastInstance` has been auto-configured, it is automatically wrapped in a `CacheManager`. -#### [](#io.caching.provider.infinispan)1.1.5. Infinispan #### +#### 1.1.5. Infinispan [Infinispan](https://infinispan.org/) has no default configuration file location, so it must be specified explicitly. Otherwise, the default bootstrap is used. @@ -248,7 +206,7 @@ If a custom `ConfigurationBuilder` bean is defined, it is used to customize the | |The support of Infinispan in Spring Boot is restricted to the embedded mode and is quite basic.
If you want more options, you should use the official Infinispan Spring Boot starter instead.
See [Infinispan’s documentation](https://github.com/infinispan/infinispan-spring-boot) for more details.| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#io.caching.provider.couchbase)1.1.6. Couchbase #### +#### 1.1.6. Couchbase If Spring Data Couchbase is available and Couchbase is [configured](data.html#data.nosql.couchbase), a `CouchbaseCacheManager` 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.couchbase.*` properties. @@ -299,7 +257,7 @@ public class MyCouchbaseCacheManagerConfiguration { ``` -#### [](#io.caching.provider.redis)1.1.7. Redis #### +#### 1.1.7. Redis If [Redis](https://redis.io/) 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. @@ -356,7 +314,7 @@ public class MyRedisCacheManagerConfiguration { ``` -#### [](#io.caching.provider.caffeine)1.1.8. Caffeine #### +#### 1.1.8. Caffeine [Caffeine](https://github.com/ben-manes/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. @@ -391,7 +349,7 @@ If a `com.github.benmanes.caffeine.cache.CacheLoader` bean is defined, it is aut Since the `CacheLoader` is going to be associated with *all* caches managed by the cache manager, it must be defined as `CacheLoader`. The auto-configuration ignores any other generic type. -#### [](#io.caching.provider.simple)1.1.9. Simple #### +#### 1.1.9. Simple If none of the other providers can be found, a simple implementation using a `ConcurrentHashMap` as the cache store is configured. This is the default if no caching library is present in your application. @@ -415,7 +373,7 @@ spring: If you do so and your application uses a cache not listed, then it fails at runtime when the cache is needed, but not on startup. This is similar to the way the "real" cache providers behave if you use an undeclared cache. -#### [](#io.caching.provider.none)1.1.10. None #### +#### 1.1.10. None When `@EnableCaching` is present in your configuration, a suitable cache configuration is expected as well. If you need to disable caching altogether in certain environments, force the cache type to `none` to use a no-op implementation, as shown in the following example: @@ -434,8 +392,7 @@ spring: type: "none" ``` -[](#io.hazelcast)2. Hazelcast ----------- +## 2. Hazelcast If [Hazelcast](https://hazelcast.com/) is on the classpath and a suitable configuration is found, Spring Boot auto-configures a `HazelcastInstance` that you can inject in your application. @@ -481,8 +438,7 @@ See the [Hazelcast documentation](https://docs.hazelcast.org/docs/latest/manual/ | |Spring Boot also has [explicit caching support for Hazelcast](#io.caching.provider.hazelcast).
If caching is enabled, the `HazelcastInstance` is automatically wrapped in a `CacheManager` implementation.| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -[](#io.quartz)3. Quartz Scheduler ----------- +## 3. Quartz Scheduler Spring Boot offers several conveniences for working with the [Quartz scheduler](https://www.quartz-scheduler.org/), including the `spring-boot-starter-quartz` “Starter”. If Quartz is available, a `Scheduler` is auto-configured (through the `SchedulerFactoryBean` abstraction). @@ -581,8 +537,7 @@ public class MySampleJob extends QuartzJobBean { ``` -[](#io.email)4. Sending Email ----------- +## 4. Sending Email The Spring Framework provides an abstraction for sending email by using the `JavaMailSender` interface, and Spring Boot provides auto-configuration for it as well as a starter module. @@ -632,8 +587,7 @@ spring: When a `jndi-name` is set, it takes precedence over all other Session-related settings. -[](#io.validation)5. Validation ----------- +## 5. Validation The method validation feature supported by Bean Validation 1.1 is automatically enabled as long as a JSR-303 implementation (such as Hibernate validator) is on the classpath. This lets bean methods be annotated with `javax.validation` constraints on their parameters and/or on their return value. @@ -663,12 +617,11 @@ The application’s `MessageSource` is used when resolving `{parameters}` in con This allows you to use [your application’s `messages.properties` files](features.html#features.internationalization) for Bean Validation messages. Once the parameters have been resolved, message interpolation is completed using Bean Validation’s default interpolator. -[](#io.rest-client)6. Calling REST Services ----------- +## 6. Calling REST Services If your application calls remote REST services, Spring Boot makes that very convenient using a `RestTemplate` or a `WebClient`. -### [](#io.rest-client.resttemplate)6.1. RestTemplate ### +### 6.1. RestTemplate If you need to call remote REST services from your application, you can use the Spring Framework’s [`RestTemplate`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/client/RestTemplate.html) class. Since `RestTemplate` instances often need to be customized before being used, Spring Boot does not provide any single auto-configured `RestTemplate` bean. @@ -702,7 +655,7 @@ public class MyService { | |`RestTemplateBuilder` includes a number of useful methods that can be used to quickly configure a `RestTemplate`.
For example, to add BASIC auth support, you can use `builder.basicAuthentication("user", "password").build()`.| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#io.rest-client.resttemplate.customization)6.1.1. RestTemplate Customization #### +#### 6.1.1. RestTemplate Customization There are three main approaches to `RestTemplate` customization, depending on how broadly you want the customizations to apply. @@ -786,7 +739,7 @@ public class MyRestTemplateBuilderConfiguration { The most extreme (and rarely used) option is to create your own `RestTemplateBuilder` bean without using a configurer. In addition to replacing the auto-configured builder, this also prevents any `RestTemplateCustomizer` beans from being used. -### [](#io.rest-client.webclient)6.2. WebClient ### +### 6.2. WebClient If you have Spring WebFlux on your classpath, you can also choose to use `WebClient` to call remote REST services. Compared to `RestTemplate`, this client has a more functional feel and is fully reactive. @@ -822,7 +775,7 @@ public class MyService { ``` -#### [](#io.rest-client.webclient.runtime)6.2.1. WebClient Runtime #### +#### 6.2.1. WebClient Runtime Spring Boot will auto-detect which `ClientHttpConnector` to use to drive `WebClient`, depending on the libraries available on the application classpath. For now, Reactor Netty and Jetty RS client are supported. @@ -837,7 +790,7 @@ If you wish to override that choice for the client, you can define your own `Cli You can learn more about the [`WebClient` configuration options in the Spring Framework reference documentation](https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/web-reactive.html#webflux-client-builder). -#### [](#io.rest-client.webclient.customization)6.2.2. WebClient Customization #### +#### 6.2.2. WebClient Customization There are three main approaches to `WebClient` customization, depending on how broadly you want the customizations to apply. @@ -849,8 +802,7 @@ To make an application-wide, additive customization to all `WebClient.Builder` i Finally, you can fall back to the original API and use `WebClient.create()`. In that case, no auto-configuration or `WebClientCustomizer` is applied. -[](#io.webservices)7. Web Services ----------- +## 7. Web Services Spring Boot provides Web Services auto-configuration so that all you must do is define your `Endpoints`. @@ -873,7 +825,7 @@ spring: wsdl-locations: "classpath:/wsdl" ``` -### [](#io.webservices.template)7.1. Calling Web Services with WebServiceTemplate ### +### 7.1. Calling Web Services with WebServiceTemplate If you need to call remote Web services from your application, you can use the [`WebServiceTemplate`](https://docs.spring.io/spring-ws/docs/3.1.2/reference/html/#client-web-service-template) class. Since `WebServiceTemplate` instances often need to be customized before being used, Spring Boot does not provide any single auto-configured `WebServiceTemplate` bean. @@ -934,8 +886,7 @@ public class MyWebServiceTemplateConfiguration { ``` -[](#io.jta)8. Distributed Transactions with JTA ----------- +## 8. Distributed Transactions with JTA Spring Boot supports distributed JTA transactions across multiple XA resources by using an [Atomikos](https://www.atomikos.com/) embedded transaction manager. JTA transactions are also supported when deploying to a suitable Java EE Application Server. @@ -945,7 +896,7 @@ Auto-configured JMS, DataSource, and JPA beans are upgraded to support XA transa You can use standard Spring idioms, such as `@Transactional`, to participate in a distributed transaction. If you are within a JTA environment and still want to use local transactions, you can set the `spring.jta.enabled` property to `false` to disable the JTA auto-configuration. -### [](#io.jta.atomikos)8.1. Using an Atomikos Transaction Manager ### +### 8.1. Using an Atomikos Transaction Manager [Atomikos](https://www.atomikos.com/) 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. @@ -959,14 +910,14 @@ See the [`AtomikosProperties` Javadoc](https://docs.spring.io/spring-boot/docs/2 | |To ensure that multiple transaction managers can safely coordinate the same resource managers, each Atomikos instance must be configured with a unique ID.
By default, this ID is the IP address of the machine on which Atomikos is running.
To ensure uniqueness in production, you should configure the `spring.jta.transaction-manager-id` property with a different value for each instance of your application.| |---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#io.jta.javaee)8.2. Using a Java EE Managed Transaction Manager ### +### 8.2. Using a Java EE Managed Transaction Manager If you package your Spring Boot application as a `war` or `ear` file and deploy it to a Java EE application server, you can use your application server’s built-in transaction manager. Spring Boot tries to auto-configure a transaction manager by looking at common JNDI locations (`java:comp/UserTransaction`, `java:comp/TransactionManager`, and so on). If you use a transaction service provided by your application server, you generally also want to ensure that all resources are managed by the server and exposed over JNDI. Spring Boot tries to auto-configure JMS by looking for a `ConnectionFactory` at the JNDI path (`java:/JmsXA` or `java:/XAConnectionFactory`), and you can use the [`spring.datasource.jndi-name` property](data.html#data.sql.datasource.jndi) to configure your `DataSource`. -### [](#io.jta.mixing-xa-and-non-xa-connections)8.3. Mixing XA and Non-XA JMS Connections ### +### 8.3. Mixing XA and Non-XA JMS Connections When using JTA, the primary JMS `ConnectionFactory` bean is XA-aware and participates in distributed transactions. You can inject into your bean without needing to use any `@Qualifier`: @@ -999,7 +950,7 @@ public MyBean(@Qualifier("xaJmsConnectionFactory") ConnectionFactory connectionF ``` -### [](#io.jta.supporting-alternative-embedded-transaction-manager)8.4. Supporting an Alternative Embedded Transaction Manager ### +### 8.4. Supporting an Alternative Embedded Transaction Manager ### The [`XAConnectionFactoryWrapper`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jms/XAConnectionFactoryWrapper.java) and [`XADataSourceWrapper`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/XADataSourceWrapper.java) interfaces can be used to support alternative embedded transaction managers. The interfaces are responsible for wrapping `XAConnectionFactory` and `XADataSource` beans and exposing them as regular `ConnectionFactory` and `DataSource` beans, which transparently enroll in the distributed transaction. @@ -1007,8 +958,7 @@ DataSource and JMS auto-configuration use JTA variants, provided you have a `Jta The [AtomikosXAConnectionFactoryWrapper](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapper.java) and [AtomikosXADataSourceWrapper](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapper.java) provide good examples of how to write XA wrappers. -[](#io.whats-next)9. What to Read Next ----------- +## 9. What to Read Next You should now have a good understanding of Spring Boot’s [core features](features.html#features) and the various technologies that Spring Boot provides support for via auto-configuration. diff --git a/docs/en/spring-boot/legal.md b/docs/en/spring-boot/legal.md index dbbd57370ea3ff95daf7322dc1584cd00f9223a4..b458b7bafa9557184b42aeb2ab3b13e9e8487fbe 100644 --- a/docs/en/spring-boot/legal.md +++ b/docs/en/spring-boot/legal.md @@ -1,5 +1,4 @@ -Legal -========== +# Legal Copyright © 2012-2022 diff --git a/docs/en/spring-boot/messaging.md b/docs/en/spring-boot/messaging.md index 4f4954f7c26f823285475e893b3a5864361c6046..91cce40be4533f6185ef0dbd263d0d463910ea75 100644 --- a/docs/en/spring-boot/messaging.md +++ b/docs/en/spring-boot/messaging.md @@ -1,37 +1,4 @@ -Messaging -========== - -Table of Contents - -[Back to index](index.html) - -* [1. JMS](#messaging.jms) - * [1.1. ActiveMQ Support](#messaging.jms.activemq) - * [1.2. ActiveMQ Artemis Support](#messaging.jms.artemis) - * [1.3. Using a JNDI ConnectionFactory](#messaging.jms.jndi) - * [1.4. Sending a Message](#messaging.jms.sending) - * [1.5. Receiving a Message](#messaging.jms.receiving) - -* [2. AMQP](#messaging.amqp) - * [2.1. RabbitMQ support](#messaging.amqp.rabbitmq) - * [2.2. Sending a Message](#messaging.amqp.sending) - * [2.3. Receiving a Message](#messaging.amqp.receiving) - -* [3. Apache Kafka Support](#messaging.kafka) - * [3.1. Sending a Message](#messaging.kafka.sending) - * [3.2. Receiving a Message](#messaging.kafka.receiving) - * [3.3. Kafka Streams](#messaging.kafka.streams) - * [3.4. Additional Kafka Properties](#messaging.kafka.additional-properties) - * [3.5. Testing with Embedded Kafka](#messaging.kafka.embedded) - -* [4. RSocket](#messaging.rsocket) - * [4.1. RSocket Strategies Auto-configuration](#messaging.rsocket.strategies-auto-configuration) - * [4.2. RSocket server Auto-configuration](#messaging.rsocket.server-auto-configuration) - * [4.3. Spring Messaging RSocket support](#messaging.rsocket.messaging) - * [4.4. Calling RSocket Services with RSocketRequester](#messaging.rsocket.requester) - -* [5. Spring Integration](#messaging.spring-integration) -* [6. What to Read Next](#messaging.whats-next) +# Messaging The Spring Framework provides extensive support for integrating with messaging systems, from simplified use of the JMS API using `JmsTemplate` to a complete infrastructure to receive messages asynchronously. Spring AMQP provides a similar feature set for the Advanced Message Queuing Protocol. @@ -39,15 +6,14 @@ Spring Boot also provides auto-configuration options for `RabbitTemplate` and Ra 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. -[](#messaging.jms)1. JMS ----------- +## 1. JMS The `javax.jms.ConnectionFactory` interface provides a standard method of creating a `javax.jms.Connection` for interacting with a JMS broker. Although Spring needs a `ConnectionFactory` to work with JMS, you generally need not use it directly yourself and can instead rely on higher level messaging abstractions. (See the [relevant section](https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/integration.html#jms) of the Spring Framework reference documentation for details.) Spring Boot also auto-configures the necessary infrastructure to send and receive messages. -### [](#messaging.jms.activemq)1.1. ActiveMQ Support ### +### 1.1. ActiveMQ Support When [ActiveMQ](https://activemq.apache.org/) 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 and the embedded broker is not disabled in the configuration). @@ -138,7 +104,7 @@ spring: By default, ActiveMQ creates a destination if it does not yet exist so that destinations are resolved against their provided names. -### [](#messaging.jms.artemis)1.2. ActiveMQ Artemis Support ### +### 1.2. ActiveMQ Artemis Support Spring Boot can auto-configure a `ConnectionFactory` when it detects that [ActiveMQ Artemis](https://activemq.apache.org/components/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). @@ -214,7 +180,7 @@ See [`ArtemisProperties`](https://github.com/spring-projects/spring-boot/tree/v2 No JNDI lookup is involved, and destinations are resolved against their names, using either the `name` attribute in the Artemis configuration or the names provided through configuration. -### [](#messaging.jms.jndi)1.3. Using a JNDI ConnectionFactory ### +### 1.3. Using a JNDI ConnectionFactory If you are running your application in an application server, Spring Boot tries to locate a JMS `ConnectionFactory` by using JNDI. By default, the `java:/JmsXA` and `java:/XAConnectionFactory` location are checked. @@ -234,7 +200,7 @@ spring: jndi-name: "java:/MyConnectionFactory" ``` -### [](#messaging.jms.sending)1.4. Sending a Message ### +### 1.4. Sending a Message Spring’s `JmsTemplate` is auto-configured, and you can autowire it directly into your own beans, as shown in the following example: @@ -264,7 +230,7 @@ public class MyBean { | |[`JmsMessagingTemplate`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/jms/core/JmsMessagingTemplate.html) can be injected in a similar manner.
If a `DestinationResolver` or a `MessageConverter` bean is defined, it is associated automatically to the auto-configured `JmsTemplate`.| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#messaging.jms.receiving)1.5. Receiving a Message ### +### 1.5. 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. @@ -348,14 +314,13 @@ public class MyBean { ``` -[](#messaging.amqp)2. AMQP ----------- +## 2. AMQP The Advanced Message Queuing Protocol (AMQP) is a platform-neutral, wire-level protocol for message-oriented middleware. The Spring AMQP project applies core Spring concepts to the development of AMQP-based messaging solutions. Spring Boot offers several conveniences for working with AMQP through RabbitMQ, including the `spring-boot-starter-amqp` “Starter”. -### [](#messaging.amqp.rabbitmq)2.1. RabbitMQ support ### +### 2.1. RabbitMQ support [RabbitMQ](https://www.rabbitmq.com/) is a lightweight, reliable, scalable, and portable message broker based on the AMQP protocol. Spring uses `RabbitMQ` to communicate through the AMQP protocol. @@ -410,7 +375,7 @@ If a `ConnectionNameStrategy` bean exists in the context, it will be automatical | |See [Understanding AMQP, the protocol used by RabbitMQ](https://spring.io/blog/2010/06/14/understanding-amqp-the-protocol-used-by-rabbitmq/) for more details.| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#messaging.amqp.sending)2.2. Sending a Message ### +### 2.2. 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: @@ -475,7 +440,7 @@ You can also customize the `RetryTemplate` programmatically by declaring a `Rabb If you need to create more `RabbitTemplate` instances or if you want to override the default, Spring Boot provides a `RabbitTemplateConfigurer` bean that you can use to initialize a `RabbitTemplate` with the same settings as the factories used by the auto-configuration. -### [](#messaging.amqp.receiving)2.3. Receiving a Message ### +### 2.3. Receiving a Message When the Rabbit infrastructure is present, any bean can be annotated with `@RabbitListener` to create a listener endpoint. If no `RabbitListenerContainerFactory` has been defined, a default `SimpleRabbitListenerContainerFactory` is automatically configured and you can switch to a direct container using the `spring.rabbitmq.listener.type` property. @@ -563,8 +528,7 @@ You can also customize the `RetryTemplate` programmatically by declaring a `Rabb | |By default, if retries are disabled and the listener throws an exception, the delivery is retried indefinitely.
You can modify this behavior in two ways: Set the `defaultRequeueRejected` property to `false` so that zero re-deliveries are attempted or throw an `AmqpRejectAndDontRequeueException` to signal the message should be rejected.
The latter is the mechanism used when retries are enabled and the maximum number of delivery attempts is reached.| |---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -[](#messaging.kafka)3. Apache Kafka Support ----------- +## 3. Apache Kafka Support [Apache Kafka](https://kafka.apache.org/) is supported by providing auto-configuration of the `spring-kafka` project. @@ -593,7 +557,7 @@ spring: See [`KafkaProperties`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaProperties.java) for more supported options. -### [](#messaging.kafka.sending)3.1. Sending a Message ### +### 3.1. Sending a Message Spring’s `KafkaTemplate` is auto-configured, and you can autowire it directly in your own beans, as shown in the following example: @@ -623,7 +587,7 @@ public class MyBean { | |If the property `spring.kafka.producer.transaction-id-prefix` is defined, a `KafkaTransactionManager` is automatically configured.
Also, if a `RecordMessageConverter` bean is defined, it is automatically associated to the auto-configured `KafkaTemplate`.| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#messaging.kafka.receiving)3.2. Receiving a Message ### +### 3.2. Receiving a Message When the Apache Kafka infrastructure is present, any bean can be annotated with `@KafkaListener` to create a listener endpoint. If no `KafkaListenerContainerFactory` has been defined, a default one is automatically configured with keys defined in `spring.kafka.listener.*`. @@ -655,7 +619,7 @@ If only a `RecordMessageConverter` bean is present for a batch listener, it is w | |A custom `ChainedKafkaTransactionManager` must be marked `@Primary` as it usually references the auto-configured `KafkaTransactionManager` bean.| |---|------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#messaging.kafka.streams)3.3. Kafka Streams ### +### 3.3. Kafka Streams Spring for Apache Kafka provides a factory bean to create a `StreamsBuilder` object and manage the lifecycle of its streams. Spring Boot auto-configures the required `KafkaStreamsConfiguration` bean as long as `kafka-streams` is on the classpath and Kafka Streams is enabled by the `@EnableKafkaStreams` annotation. @@ -703,7 +667,7 @@ public class MyKafkaStreamsConfiguration { By default, the streams managed by the `StreamBuilder` object it creates are started automatically. You can customize this behavior using the `spring.kafka.streams.auto-startup` property. -### [](#messaging.kafka.additional-properties)3.4. Additional Kafka Properties ### +### 3.4. Additional Kafka Properties The properties supported by auto configuration are shown in the [“Integration Properties”](application-properties.html#appendix.application-properties.integration) section of the Appendix. Note that, for the most part, these properties (hyphenated or camelCase) map directly to the Apache Kafka dotted properties. @@ -794,7 +758,7 @@ spring: | |Properties set in this way override any configuration item that Spring Boot explicitly supports.| |---|------------------------------------------------------------------------------------------------| -### [](#messaging.kafka.embedded)3.5. Testing with Embedded Kafka ### +### 3.5. Testing with Embedded Kafka Spring for Apache Kafka provides a convenient way to test projects with an embedded Apache Kafka broker. To use this feature, annotate a test class with `@EmbeddedKafka` from the `spring-kafka-test` module. @@ -844,8 +808,7 @@ spring: bootstrap-servers: "${spring.embedded.kafka.brokers}" ``` -[](#messaging.rsocket)4. RSocket ----------- +## 4. RSocket [RSocket](https://rsocket.io) is a binary protocol for use on byte stream transports. It enables symmetric interaction models through async message passing over a single connection. @@ -853,7 +816,7 @@ It enables symmetric interaction models through async message passing over a sin The `spring-messaging` module of the Spring Framework provides support for RSocket requesters and responders, both on the client and on the server side. See the [RSocket section](https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/web-reactive.html#rsocket-spring) of the Spring Framework reference for more details, including an overview of the RSocket protocol. -### [](#messaging.rsocket.strategies-auto-configuration)4.1. RSocket Strategies Auto-configuration ### +### 4.1. RSocket Strategies Auto-configuration Spring Boot auto-configures an `RSocketStrategies` bean that provides all the required infrastructure for encoding and decoding RSocket payloads. By default, the auto-configuration will try to configure the following (in order): @@ -868,7 +831,7 @@ See the [Jackson support section](features.html#features.json.jackson) to know m Developers can customize the `RSocketStrategies` component by creating beans that implement the `RSocketStrategiesCustomizer` interface. Note that their `@Order` is important, as it determines the order of codecs. -### [](#messaging.rsocket.server-auto-configuration)4.2. RSocket server Auto-configuration ### +### 4.2. RSocket server Auto-configuration Spring Boot provides RSocket server auto-configuration. The required dependencies are provided by the `spring-boot-starter-rsocket`. @@ -916,13 +879,13 @@ spring: port: 9898 ``` -### [](#messaging.rsocket.messaging)4.3. Spring Messaging RSocket support ### +### 4.3. Spring Messaging RSocket support Spring Boot will auto-configure the Spring Messaging infrastructure for RSocket. This means that Spring Boot will create a `RSocketMessageHandler` bean that will handle RSocket requests to your application. -### [](#messaging.rsocket.requester)4.4. Calling RSocket Services with RSocketRequester ### +### 4.4. Calling RSocket Services with RSocketRequester Once the `RSocket` channel is established between server and client, any party can send or receive requests to the other. @@ -958,8 +921,7 @@ public class MyService { ``` -[](#messaging.spring-integration)5. Spring Integration ----------- +## 5. Spring Integration Spring Boot offers several conveniences for working with [Spring Integration](https://spring.io/projects/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. @@ -1032,8 +994,7 @@ spring: See the [`IntegrationAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfiguration.java) and [`IntegrationProperties`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationProperties.java) classes for more details. -[](#messaging.whats-next)6. What to Read Next ----------- +## 6. What to Read Next The next section describes how to enable [IO capabilities](io.html#io) in your application. You can read about [caching](io.html#io.caching), [mail](io.html#io.email), [validation](io.html#io.validation), [rest clients](io.html#io.rest-client) and more in this section. diff --git a/docs/en/spring-boot/upgrading.md b/docs/en/spring-boot/upgrading.md index c9525017d4aca1e63200a9270d3d7e4773953473..c647ed21342ca184622550219e16d70515786578 100644 --- a/docs/en/spring-boot/upgrading.md +++ b/docs/en/spring-boot/upgrading.md @@ -1,14 +1,4 @@ -Upgrading Spring Boot -========== - -Table of Contents - -[Back to index](index.html) - -* [1. Upgrading from 1.x](#upgrading.from-1x) -* [2. Upgrading to a new feature release](#upgrading.to-feature) -* [3. Upgrading the Spring Boot CLI](#upgrading.cli) -* [4. What to Read Next](#upgrading.whats-next) +# Upgrading Spring Boot Instructions for how to upgrade from earlier versions of Spring Boot are provided on the project [wiki](https://github.com/spring-projects/spring-boot/wiki). Follow the links in the [release notes](https://github.com/spring-projects/spring-boot/wiki#release-notes) section to find the version that you want to upgrade to. @@ -16,14 +6,12 @@ Follow the links in the [release notes](https://github.com/spring-projects/sprin Upgrading instructions are always the first item in the release notes. If you are more than one release behind, please make sure that you also review the release notes of the versions that you jumped. -[](#upgrading.from-1x)1. Upgrading from 1.x ----------- +## 1. Upgrading from 1.x If you are upgrading from the `1.x` release of Spring Boot, check the [“migration guide” on the project wiki](https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0-Migration-Guide) that provides detailed upgrade instructions. Check also the [“release notes”](https://github.com/spring-projects/spring-boot/wiki) for a list of “new and noteworthy” features for each release. -[](#upgrading.to-feature)2. Upgrading to a new feature release ----------- +## 2. Upgrading to a new feature release When upgrading to a new feature release, some properties may have been renamed or removed. Spring Boot provides a way to analyze your application’s environment and print diagnostics at startup, but also temporarily migrate properties at runtime for you. @@ -43,14 +31,12 @@ To enable that feature, add the following dependency to your project: | |Once you finish the migration, please make sure to remove this module from your project’s dependencies.| |---|-------------------------------------------------------------------------------------------------------| -[](#upgrading.cli)3. Upgrading the Spring Boot CLI ----------- +## 3. Upgrading the Spring Boot CLI To upgrade an existing CLI installation, use the appropriate package manager command (for example, `brew upgrade`). If you manually installed the CLI, follow the [standard instructions](getting-started.html#getting-started.installing.cli.manual-installation), remembering to update your `PATH` environment variable to remove any older references. -[](#upgrading.whats-next)4. What to Read Next ----------- +## 4. What to Read Next Once you’ve decided to upgrade your application, you can find detailed information regarding specific features in the rest of the document. diff --git a/docs/en/spring-boot/using.md b/docs/en/spring-boot/using.md index 3d4ccb8b6a52c2eca32ccf5b5c79530dcd44c6ac..99fcfa58568a6f6af7354982b4e2afe80c44b336 100644 --- a/docs/en/spring-boot/using.md +++ b/docs/en/spring-boot/using.md @@ -1,60 +1,4 @@ -Developing with Spring Boot -========== - -Table of Contents - -[Back to index](index.html) - -* [1. Build Systems](#using.build-systems) - * [1.1. Dependency Management](#using.build-systems.dependency-management) - * [1.2. Maven](#using.build-systems.maven) - * [1.3. Gradle](#using.build-systems.gradle) - * [1.4. Ant](#using.build-systems.ant) - * [1.5. Starters](#using.build-systems.starters) - -* [2. Structuring Your Code](#using.structuring-your-code) - * [2.1. Using the “default” Package](#using.structuring-your-code.using-the-default-package) - * [2.2. Locating the Main Application Class](#using.structuring-your-code.locating-the-main-class) - -* [3. Configuration Classes](#using.configuration-classes) - * [3.1. Importing Additional Configuration Classes](#using.configuration-classes.importing-additional-configuration) - * [3.2. Importing XML Configuration](#using.configuration-classes.importing-xml-configuration) - -* [4. Auto-configuration](#using.auto-configuration) - * [4.1. Gradually Replacing Auto-configuration](#using.auto-configuration.replacing) - * [4.2. Disabling Specific Auto-configuration Classes](#using.auto-configuration.disabling-specific) - -* [5. Spring Beans and Dependency Injection](#using.spring-beans-and-dependency-injection) -* [6. Using the @SpringBootApplication Annotation](#using.using-the-springbootapplication-annotation) -* [7. Running Your Application](#using.running-your-application) - * [7.1. Running from an IDE](#using.running-your-application.from-an-ide) - * [7.2. Running as a Packaged Application](#using.running-your-application.as-a-packaged-application) - * [7.3. Using the Maven Plugin](#using.running-your-application.with-the-maven-plugin) - * [7.4. Using the Gradle Plugin](#using.running-your-application.with-the-gradle-plugin) - * [7.5. Hot Swapping](#using.running-your-application.hot-swapping) - -* [8. Developer Tools](#using.devtools) - * [8.1. Diagnosing Classloading Issues](#using.devtools.diagnosing-classloading-issues) - * [8.2. Property Defaults](#using.devtools.property-defaults) - * [8.3. Automatic Restart](#using.devtools.restart) - * [8.3.1. Logging changes in condition evaluation](#using.devtools.restart.logging-condition-delta) - * [8.3.2. Excluding Resources](#using.devtools.restart.excluding-resources) - * [8.3.3. Watching Additional Paths](#using.devtools.restart.watching-additional-paths) - * [8.3.4. Disabling Restart](#using.devtools.restart.disable) - * [8.3.5. Using a Trigger File](#using.devtools.restart.triggerfile) - * [8.3.6. Customizing the Restart Classloader](#using.devtools.restart.customizing-the-classload) - * [8.3.7. Known Limitations](#using.devtools.restart.limitations) - - * [8.4. LiveReload](#using.devtools.livereload) - * [8.5. Global Settings](#using.devtools.globalsettings) - * [8.5.1. Configuring File System Watcher](#using.devtools.globalsettings.configuring-file-system-watcher) - - * [8.6. Remote Applications](#using.devtools.remote-applications) - * [8.6.1. Running the Remote Client Application](#using.devtools.remote-applications.client) - * [8.6.2. Remote Update](#using.devtools.remote-applications.update) - -* [9. Packaging Your Application for Production](#using.packaging-for-production) -* [10. What to Read Next](#using.whats-next) +# Developing with Spring Boot This section goes into more detail about how you should use Spring Boot. It covers topics such as build systems, auto-configuration, and how to run your applications. @@ -63,14 +7,13 @@ Although there is nothing particularly special about Spring Boot (it is just ano If you are starting out with Spring Boot, you should probably read the *[Getting Started](getting-started.html#getting-started)* guide before diving into this section. -[](#using.build-systems)1. Build Systems ----------- +## 1. Build Systems It is strongly recommended that you choose a build system that supports [*dependency management*](#using.build-systems.dependency-management) and that can consume artifacts published to the “Maven Central” repository. We would recommend that you choose Maven or Gradle. It is possible to get Spring Boot to work with other build systems (Ant, for example), but they are not particularly well supported. -### [](#using.build-systems.dependency-management)1.1. Dependency Management ### +### 1.1. Dependency Management Each release of Spring Boot provides a curated list of dependencies that it supports. In practice, you do not need to provide a version for any of these dependencies in your build configuration, as Spring Boot manages that for you. @@ -85,7 +28,7 @@ The list is available as a standard Bills of Materials (`spring-boot-dependencie | |Each release of Spring Boot is associated with a base version of the Spring Framework.
We **highly** recommend that you not specify its version.| |---|----------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#using.build-systems.maven)1.2. Maven ### +### 1.2. Maven To learn about using Spring Boot with Maven, see the documentation for Spring Boot’s Maven plugin: @@ -93,7 +36,7 @@ To learn about using Spring Boot with Maven, see the documentation for Spring Bo * [API](https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/api/) -### [](#using.build-systems.gradle)1.3. Gradle ### +### 1.3. Gradle To learn about using Spring Boot with Gradle, see the documentation for Spring Boot’s Gradle plugin: @@ -101,7 +44,7 @@ To learn about using Spring Boot with Gradle, see the documentation for Spring B * [API](https://docs.spring.io/spring-boot/docs/2.6.4/gradle-plugin/api/) -### [](#using.build-systems.ant)1.4. Ant ### +### 1.4. Ant It is possible to build a Spring Boot project using Apache Ant+Ivy. The `spring-boot-antlib` “AntLib” module is also available to help Ant create executable jars. @@ -163,7 +106,7 @@ A typical `build.xml` looks like the following example: | |If you do not want to use the `spring-boot-antlib` module, see the *[howto.html](howto.html#howto.build.build-an-executable-archive-with-ant-without-using-spring-boot-antlib)* “How-to” .| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#using.build-systems.starters)1.5. Starters ### +### 1.5. Starters Starters are a set of convenient dependency descriptors that you can include in your application. You get a one-stop shop for all the Spring and related technologies that you need without having to hunt through sample code and copy-paste loads of dependency descriptors. @@ -254,13 +197,12 @@ To learn how to swap technical facets, please see the how-to documentation for [ | |For a list of additional community contributed starters, see the [README file](https://github.com/spring-projects/spring-boot/tree/main/spring-boot-project/spring-boot-starters/README.adoc) in the `spring-boot-starters` module on GitHub.| |---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -[](#using.structuring-your-code)2. Structuring Your Code ----------- +## 2. Structuring Your Code Spring Boot does not require any specific code layout to work. However, there are some best practices that help. -### [](#using.structuring-your-code.using-the-default-package)2.1. Using the “default” Package ### +### 2.1. Using the “default” Package When a class does not include a `package` declaration, it is considered to be in the “default package”. The use of the “default package” is generally discouraged and should be avoided. @@ -269,7 +211,7 @@ It can cause particular problems for Spring Boot applications that use the `@Com | |We recommend that you follow Java’s recommended package naming conventions and use a reversed domain name (for example, `com.example.project`).| |---|-----------------------------------------------------------------------------------------------------------------------------------------------| -### [](#using.structuring-your-code.locating-the-main-class)2.2. Locating the Main Application Class ### +### 2.2. Locating the Main Application Class We generally recommend that you locate your main application class in a root package above other classes. The [`@SpringBootApplication` annotation](#using.using-the-springbootapplication-annotation) is often placed on your main class, and it implicitly defines a base “search package” for certain items. @@ -317,8 +259,7 @@ public class MyApplication { ``` -[](#using.configuration-classes)3. Configuration Classes ----------- +## 3. Configuration Classes Spring Boot favors Java-based configuration. Although it is possible to use `SpringApplication` with XML sources, we generally recommend that your primary source be a single `@Configuration` class. @@ -327,19 +268,18 @@ Usually the class that defines the `main` method is a good candidate as the prim | |Many Spring configuration examples have been published on the Internet that use XML configuration.
If possible, always try to use the equivalent Java-based configuration.
Searching for `Enable*` annotations can be a good starting point.| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#using.configuration-classes.importing-additional-configuration)3.1. Importing Additional Configuration Classes ### +### 3.1. Importing Additional Configuration Classes ### You need not put all your `@Configuration` into a single class. The `@Import` annotation can be used to import additional configuration classes. Alternatively, you can use `@ComponentScan` to automatically pick up all Spring components, including `@Configuration` classes. -### [](#using.configuration-classes.importing-xml-configuration)3.2. Importing XML Configuration ### +### 3.2. Importing XML Configuration If you absolutely must use XML based configuration, we recommend that you still start with a `@Configuration` class. You can then use an `@ImportResource` annotation to load XML configuration files. -[](#using.auto-configuration)4. Auto-configuration ----------- +## 4. Auto-configuration Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added. For example, if `HSQLDB` is on your classpath, and you have not manually configured any database connection beans, then Spring Boot auto-configures an in-memory database. @@ -349,7 +289,7 @@ You need to opt-in to auto-configuration by adding the `@EnableAutoConfiguration | |You should only ever add one `@SpringBootApplication` or `@EnableAutoConfiguration` annotation.
We generally recommend that you add one or the other to your primary `@Configuration` class only.| |---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#using.auto-configuration.replacing)4.1. Gradually Replacing Auto-configuration ### +### 4.1. Gradually Replacing Auto-configuration Auto-configuration is non-invasive. At any point, you can start to define your own configuration to replace specific parts of the auto-configuration. @@ -358,7 +298,7 @@ For example, if you add your own `DataSource` bean, the default embedded databas If you need to find out what auto-configuration is currently being applied, and why, start your application with the `--debug` switch. Doing so enables debug logs for a selection of core loggers and logs a conditions report to the console. -### [](#using.auto-configuration.disabling-specific)4.2. Disabling Specific Auto-configuration Classes ### +### 4.2. 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: @@ -383,8 +323,7 @@ Finally, you can also control the list of auto-configuration classes to exclude | |Even though auto-configuration classes are `public`, the only aspect of the class that is considered public API is the name of the class which can be used for disabling the auto-configuration.
The actual contents of those classes, such as nested configuration classes or bean methods are for internal use only and we do not recommend using those directly.| |---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -[](#using.spring-beans-and-dependency-injection)5. Spring Beans and Dependency Injection ----------- +## 5. Spring Beans and Dependency Injection You are free to use any of the standard Spring Framework techniques to define your beans and their injected dependencies. We generally recommend using constructor injection to wire up dependencies and `@ComponentScan` to find beans. @@ -447,8 +386,7 @@ public class MyAccountService implements AccountService { | |Notice how using constructor injection lets the `riskAssessor` field be marked as `final`, indicating that it cannot be subsequently changed.| |---|---------------------------------------------------------------------------------------------------------------------------------------------| -[](#using.using-the-springbootapplication-annotation)6. Using the @SpringBootApplication Annotation ----------- +## 6. Using the @SpringBootApplication Annotation Many Spring Boot developers like their apps to use auto-configuration, component scan and be able to define extra configuration on their "application class". A single `@SpringBootApplication` annotation can be used to enable those three features, that is: @@ -482,8 +420,7 @@ public class MyApplication { | |None of these features are mandatory and you may choose to replace this single annotation by any of the features that it enables.
For instance, you may not want to use component scan or configuration properties scan in your application:

```
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Import;

@SpringBootConfiguration(proxyBeanMethods = false)
@EnableAutoConfiguration
@Import({ SomeConfiguration.class, AnotherConfiguration.class })
public class MyApplication {

public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}

}

```

In this example, `MyApplication` is just like any other Spring Boot application except that `@Component`-annotated classes and `@ConfigurationProperties`-annotated classes are not detected automatically and the user-defined beans are imported explicitly (see `@Import`).| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -[](#using.running-your-application)7. Running Your Application ----------- +## 7. Running Your Application One of the biggest advantages of packaging your application as a jar and using an embedded HTTP server is that you can run your application as you would any other. The sample applies to debugging Spring Boot applications. @@ -492,7 +429,7 @@ You do not need any special IDE plugins or extensions. | |This section only covers jar-based packaging.
If you choose to package your application as a war file, see your server and IDE documentation.| |---|-------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#using.running-your-application.from-an-ide)7.1. Running from an IDE ### +### 7.1. Running from an IDE You can run a Spring Boot application from your IDE as a Java application. However, you first need to import your project. @@ -507,7 +444,7 @@ Gradle offers plugins for [various IDEs](https://docs.gradle.org/current/usergui | |If you accidentally run a web application twice, you see a “Port already in use” error.
Spring Tools users can use the `Relaunch` button rather than the `Run` button to ensure that any existing instance is closed.| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#using.running-your-application.as-a-packaged-application)7.2. Running as a Packaged Application ### +### 7.2. 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: @@ -523,7 +460,7 @@ $ java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n \ -jar target/myapplication-0.0.1-SNAPSHOT.jar ``` -### [](#using.running-your-application.with-the-maven-plugin)7.3. Using the Maven Plugin ### +### 7.3. Using the Maven Plugin The Spring Boot Maven plugin includes a `run` goal that can be used to quickly compile and run your application. Applications run in an exploded form, as they do in your IDE. @@ -539,7 +476,7 @@ You might also want to use the `MAVEN_OPTS` operating system environment variabl $ export MAVEN_OPTS=-Xmx1024m ``` -### [](#using.running-your-application.with-the-gradle-plugin)7.4. Using the Gradle Plugin ### +### 7.4. Using the Gradle Plugin The Spring Boot Gradle plugin also includes a `bootRun` task that can be used to run your application in an exploded form. The `bootRun` task is added whenever you apply the `org.springframework.boot` and `java` plugins and is shown in the following example: @@ -554,7 +491,7 @@ You might also want to use the `JAVA_OPTS` operating system environment variable $ export JAVA_OPTS=-Xmx1024m ``` -### [](#using.running-your-application.hot-swapping)7.5. Hot Swapping ### +### 7.5. Hot Swapping Since Spring Boot applications are plain Java applications, JVM hot-swapping should work out of the box. JVM hot swapping is somewhat limited with the bytecode that it can replace. @@ -563,8 +500,7 @@ For a more complete solution, [JRebel](https://www.jrebel.com/products/jrebel) c The `spring-boot-devtools` module also includes support for quick application restarts. See the [Hot swapping “How-to”](howto.html#howto.hotswapping) for details. -[](#using.devtools)8. Developer Tools ----------- +## 8. Developer Tools Spring Boot includes an additional set of tools that can make the application development experience a little more pleasant. The `spring-boot-devtools` module can be included in any project to provide additional development-time features. @@ -602,7 +538,7 @@ dependencies { | |Repackaged archives do not contain devtools by default.
If you want to use a [certain remote devtools feature](#using.devtools.remote-applications), you need to include it.
When using the Maven plugin, set the `excludeDevtools` property to `false`.
When using the Gradle plugin, [configure the task’s classpath to include the `developmentOnly` configuration](https://docs.spring.io/spring-boot/docs/2.6.4/gradle-plugin/reference/htmlsingle/#packaging-executable-configuring-including-development-only-dependencies).| |---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#using.devtools.diagnosing-classloading-issues)8.1. Diagnosing Classloading Issues ### +### 8.1. Diagnosing Classloading Issues As described in the [Restart vs Reload](#using.devtools.restart.restart-vs-reload) section, restart functionality is implemented by using two classloaders. For most applications, this approach works well. @@ -611,7 +547,7 @@ However, it can sometimes cause classloading issues, in particular in multi-modu To diagnose whether the classloading issues are indeed caused by devtools and its two classloaders, [try disabling restart](#using.devtools.restart.disable). If this solves your problems, [customize the restart classloader](#using.devtools.restart.customizing-the-classload) to include your entire project. -### [](#using.devtools.property-defaults)8.2. Property Defaults ### +### 8.2. Property Defaults Several of the libraries supported by Spring Boot use caches to improve performance. For example, [template engines](web.html#web.servlet.spring-mvc.template-engines) cache compiled templates to avoid repeatedly parsing template files. @@ -634,7 +570,7 @@ If you wish to log all request details (including potentially sensitive informat | |For a complete list of the properties that are applied by the devtools, see [DevToolsPropertyDefaultsPostProcessor](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java).| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -### [](#using.devtools.restart)8.3. Automatic Restart ### +### 8.3. Automatic Restart Applications that use `spring-boot-devtools` automatically restart whenever files on the classpath change. This can be a useful feature when working in an IDE, as it gives a very fast feedback loop for code changes. @@ -678,7 +614,7 @@ This approach means that application restarts are typically much faster than “ If you find that restarts are not quick enough for your applications or you encounter classloading issues, you could consider reloading technologies such as [JRebel](https://jrebel.com/software/jrebel/) from ZeroTurnaround. These work by rewriting classes as they are loaded to make them more amenable to reloading. -#### [](#using.devtools.restart.logging-condition-delta)8.3.1. Logging changes in condition evaluation #### +#### 8.3.1. Logging changes in condition evaluation By default, each time your application restarts, a report showing the condition evaluation delta is logged. The report shows the changes to your application’s auto-configuration as you make changes such as adding or removing beans and setting configuration properties. @@ -700,7 +636,7 @@ spring: log-condition-evaluation-delta: false ``` -#### [](#using.devtools.restart.excluding-resources)8.3.2. Excluding Resources #### +#### 8.3.2. Excluding Resources Certain resources do not necessarily need to trigger a restart when they are changed. For example, Thymeleaf templates can be edited in-place. @@ -726,13 +662,13 @@ spring: | |If you want to keep those defaults and *add* additional exclusions, use the `spring.devtools.restart.additional-exclude` property instead.| |---|------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#using.devtools.restart.watching-additional-paths)8.3.3. Watching Additional Paths #### +#### 8.3.3. Watching Additional Paths You may want your application to be restarted or reloaded when you make changes to files that are not on the classpath. To do so, use the `spring.devtools.restart.additional-paths` property to configure additional paths to watch for changes. You can use the `spring.devtools.restart.exclude` property [described earlier](#using.devtools.restart.excluding-resources) to control whether changes beneath the additional paths trigger a full restart or a [live reload](#using.devtools.livereload). -#### [](#using.devtools.restart.disable)8.3.4. Disabling Restart #### +#### 8.3.4. Disabling Restart If you do not want to use the restart feature, you can disable it by using the `spring.devtools.restart.enabled` property. In most cases, you can set this property in your `application.properties` (doing so still initializes the restart classloader, but it does not watch for file changes). @@ -755,7 +691,7 @@ public class MyApplication { ``` -#### [](#using.devtools.restart.triggerfile)8.3.5. Using a Trigger File #### +#### 8.3.5. Using a Trigger File If you work with an IDE that continuously compiles changed files, you might prefer to trigger restarts only at specific times. To do so, you can use a “trigger file”, which is a special file that must be modified when you want to actually trigger a restart check. @@ -801,7 +737,7 @@ Some IDEs have features that save you from needing to update your trigger file m With Spring Tools, you can use the “reload” button from the console view (as long as your `trigger-file` is named `.reloadtrigger`). For IntelliJ IDEA, you can follow the [instructions in their documentation](https://www.jetbrains.com/help/idea/spring-boot.html#application-update-policies). -#### [](#using.devtools.restart.customizing-the-classload)8.3.6. Customizing the Restart Classloader #### +#### 8.3.6. Customizing the Restart Classloader As described earlier in the [Restart vs Reload](#using.devtools.restart.restart-vs-reload) section, restart functionality is implemented by using two classloaders. If this causes issues, you might need to customize what gets loaded by which classloader. @@ -837,7 +773,7 @@ restart: | |All `META-INF/spring-devtools.properties` from the classpath are loaded.
You can package files inside your project, or in the libraries that the project consumes.| |---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#using.devtools.restart.limitations)8.3.7. Known Limitations #### +#### 8.3.7. Known Limitations Restart functionality does not work well with objects that are deserialized by using a standard `ObjectInputStream`. If you need to deserialize data, you may need to use Spring’s `ConfigurableObjectInputStream` in combination with `Thread.currentThread().getContextClassLoader()`. @@ -845,7 +781,7 @@ If you need to deserialize data, you may need to use Spring’s `ConfigurableObj Unfortunately, several third-party libraries deserialize without considering the context classloader. If you find such a problem, you need to request a fix with the original authors. -### [](#using.devtools.livereload)8.4. LiveReload ### +### 8.4. LiveReload The `spring-boot-devtools` module includes an embedded LiveReload server that can be used to trigger a browser refresh when a resource is changed. LiveReload browser extensions are freely available for Chrome, Firefox and Safari from [livereload.com](http://livereload.com/extensions/). @@ -858,7 +794,7 @@ If you do not want to start the LiveReload server when your application runs, yo | |To trigger LiveReload when a file changes, [Automatic Restart](#using.devtools.restart) must be enabled.| |---|--------------------------------------------------------------------------------------------------------| -### [](#using.devtools.globalsettings)8.5. Global Settings ### +### 8.5. Global Settings You can configure global devtools settings by adding any of the following files to the `$HOME/.config/spring-boot` directory: @@ -895,7 +831,7 @@ To customize this location, set the `SPRING_DEVTOOLS_HOME` environment variable | |Profiles are not supported in devtools properties/yaml files.

Any profiles activated in `.spring-boot-devtools.properties` will not affect the loading of [profile-specific configuration files](features.html#features.external-config.files.profile-specific).
Profile specific filenames (of the form `spring-boot-devtools-.properties`) and `spring.config.activate.on-profile` documents in both YAML and Properties files are not supported.| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#using.devtools.globalsettings.configuring-file-system-watcher)8.5.1. Configuring File System Watcher #### +#### 8.5.1. Configuring File System Watcher [FileSystemWatcher](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/FileSystemWatcher.java) works by polling the class changes with a certain time interval, and then waiting for a predefined quiet period to make sure there are no more changes. 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. @@ -920,7 +856,7 @@ spring: The monitored classpath directories are now polled every 2 seconds for changes, and a 1 second quiet period is maintained to make sure there are no additional class changes. -### [](#using.devtools.remote-applications)8.6. Remote Applications ### +### 8.6. Remote Applications The Spring Boot developer tools are not limited to local development. You can also use several features when running applications remotely. @@ -955,7 +891,7 @@ The client component must be launched manually. | |Remote devtools is not supported for Spring WebFlux applications.| |---|-----------------------------------------------------------------| -#### [](#using.devtools.remote-applications.client)8.6.1. Running the Remote Client Application #### +#### 8.6.1. Running the Remote Client Application The remote client application is designed to be run from within your IDE. You need to run `org.springframework.boot.devtools.RemoteSpringApplication` with the same classpath as the remote project that you connect to. @@ -1000,7 +936,7 @@ A running remote client might resemble the following listing: | |If you need to use a proxy to access the remote application, configure the `spring.devtools.remote.proxy.host` and `spring.devtools.remote.proxy.port` properties.| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#using.devtools.remote-applications.update)8.6.2. Remote Update #### +#### 8.6.2. Remote Update The remote client monitors your application classpath for changes in the same way as the [local restart](#using.devtools.restart). Any updated resource is pushed to the remote application and (*if required*) triggers a restart. @@ -1019,8 +955,7 @@ See the [Configuring File System Watcher](#using.devtools.globalsettings.configu | |Files are only monitored when the remote client is running.
If you change a file before starting the remote client, it is not pushed to the remote server.| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------| -[](#using.packaging-for-production)9. Packaging Your Application for Production ----------- +## 9. Packaging Your Application for Production Executable jars can be used for production deployment. As they are self-contained, they are also ideally suited for cloud-based deployment. @@ -1028,9 +963,7 @@ As they are self-contained, they are also ideally suited for cloud-based deploym For additional “production ready” features, such as health, auditing, and metric REST or JMX end-points, consider adding `spring-boot-actuator`. See *[actuator.html](actuator.html#actuator)* for details. -[](#using.whats-next)10. What to Read Next ----------- +## 10. What to Read Next You should now understand how you can use Spring Boot and some best practices that you should follow. You can now go on to learn about specific *[Spring Boot features](features.html#features)* in depth, or you could skip ahead and read about the “[production ready](actuator.html#actuator)” aspects of Spring Boot. - diff --git a/docs/en/spring-boot/web.md b/docs/en/spring-boot/web.md index c869256225f0c659ebb3c4bf41a90451d75aa323..caa98829252f321490a31c5ec016ed655f74af30 100644 --- a/docs/en/spring-boot/web.md +++ b/docs/en/spring-boot/web.md @@ -1,76 +1,4 @@ -Web -========== - -Table of Contents - -[Back to index](index.html) - -* [1. Servlet Web Applications](#web.servlet) - * [1.1. The “Spring Web MVC Framework”](#web.servlet.spring-mvc) - * [1.1.1. Spring MVC Auto-configuration](#web.servlet.spring-mvc.auto-configuration) - * [1.1.2. HttpMessageConverters](#web.servlet.spring-mvc.message-converters) - * [1.1.3. Custom JSON Serializers and Deserializers](#web.servlet.spring-mvc.json) - * [1.1.4. MessageCodesResolver](#web.servlet.spring-mvc.message-codes) - * [1.1.5. Static Content](#web.servlet.spring-mvc.static-content) - * [1.1.6. Welcome Page](#web.servlet.spring-mvc.welcome-page) - * [1.1.7. Path Matching and Content Negotiation](#web.servlet.spring-mvc.content-negotiation) - * [1.1.8. ConfigurableWebBindingInitializer](#web.servlet.spring-mvc.binding-initializer) - * [1.1.9. Template Engines](#web.servlet.spring-mvc.template-engines) - * [1.1.10. Error Handling](#web.servlet.spring-mvc.error-handling) - * [Custom Error Pages](#web.servlet.spring-mvc.error-handling.error-pages) - * [Mapping Error Pages outside of Spring MVC](#web.servlet.spring-mvc.error-handling.error-pages-without-spring-mvc) - * [Error handling in a war deployment](#web.servlet.spring-mvc.error-handling.in-a-war-deployment) - - * [1.1.11. CORS Support](#web.servlet.spring-mvc.cors) - - * [1.2. JAX-RS and Jersey](#web.servlet.jersey) - * [1.3. Embedded Servlet Container Support](#web.servlet.embedded-container) - * [1.3.1. Servlets, Filters, and listeners](#web.servlet.embedded-container.servlets-filters-listeners) - * [Registering Servlets, Filters, and Listeners as Spring Beans](#web.servlet.embedded-container.servlets-filters-listeners.beans) - - * [1.3.2. Servlet Context Initialization](#web.servlet.embedded-container.context-initializer) - * [Scanning for Servlets, Filters, and listeners](#web.servlet.embedded-container.context-initializer.scanning) - - * [1.3.3. The ServletWebServerApplicationContext](#web.servlet.embedded-container.application-context) - * [1.3.4. Customizing Embedded Servlet Containers](#web.servlet.embedded-container.customizing) - * [SameSite Cookies](#web.servlet.embedded-container.customizing.samesite) - * [Programmatic Customization](#web.servlet.embedded-container.customizing.programmatic) - * [Customizing ConfigurableServletWebServerFactory Directly](#web.servlet.embedded-container.customizing.direct) - - * [1.3.5. JSP Limitations](#web.servlet.embedded-container.jsp-limitations) - -* [2. Reactive Web Applications](#web.reactive) - * [2.1. The “Spring WebFlux Framework”](#web.reactive.webflux) - * [2.1.1. Spring WebFlux Auto-configuration](#web.reactive.webflux.auto-configuration) - * [2.1.2. HTTP Codecs with HttpMessageReaders and HttpMessageWriters](#web.reactive.webflux.httpcodecs) - * [2.1.3. Static Content](#web.reactive.webflux.static-content) - * [2.1.4. Welcome Page](#web.reactive.webflux.welcome-page) - * [2.1.5. Template Engines](#web.reactive.webflux.template-engines) - * [2.1.6. Error Handling](#web.reactive.webflux.error-handling) - * [Custom Error Pages](#web.reactive.webflux.error-handling.error-pages) - - * [2.1.7. Web Filters](#web.reactive.webflux.web-filters) - - * [2.2. Embedded Reactive Server Support](#web.reactive.reactive-server) - * [2.3. Reactive Server Resources Configuration](#web.reactive.reactive-server-resources-configuration) - -* [3. Graceful Shutdown](#web.graceful-shutdown) -* [4. Spring Security](#web.security) - * [4.1. MVC Security](#web.security.spring-mvc) - * [4.2. WebFlux Security](#web.security.spring-webflux) - * [4.3. OAuth2](#web.security.oauth2) - * [4.3.1. Client](#web.security.oauth2.client) - * [OAuth2 client registration for common providers](#web.security.oauth2.client.common-providers) - - * [4.3.2. Resource Server](#web.security.oauth2.server) - * [4.3.3. Authorization Server](#web.security.oauth2.authorization-server) - - * [4.4. SAML 2.0](#web.security.saml2) - * [4.4.1. Relying Party](#web.security.saml2.relying-party) - -* [5. Spring Session](#web.spring-session) -* [6. Spring HATEOAS](#web.spring-hateoas) -* [7. What to Read Next](#web.whats-next) +# Web Spring Boot is well suited for web application development. You can create a self-contained HTTP server by using embedded Tomcat, Jetty, Undertow, or Netty. @@ -79,12 +7,11 @@ You can also choose to build reactive web applications by using the `spring-boot If you have not yet developed a Spring Boot web application, you can follow the "Hello World!" example in the *[Getting started](getting-started.html#getting-started.first-application)* section. -[](#web.servlet)1. Servlet Web Applications ----------- +## 1. Servlet Web Applications If you want to build servlet-based web applications, you can take advantage of Spring Boot’s auto-configuration for Spring MVC or Jersey. -### [](#web.servlet.spring-mvc)1.1. The “Spring Web MVC Framework” ### +### 1.1. The “Spring Web MVC Framework” The [Spring Web MVC framework](https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/web.html#mvc) (often referred to as “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. @@ -197,7 +124,7 @@ There are also several guides that cover Spring MVC available at [spring.io/guid | |You can define as many `RouterFunction` beans as you like to modularize the definition of the router.
Beans can be ordered if you need to apply a precedence.| |---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#web.servlet.spring-mvc.auto-configuration)1.1.1. Spring MVC Auto-configuration #### +#### 1.1.1. Spring MVC Auto-configuration Spring Boot provides auto-configuration for Spring MVC that works well with most applications. @@ -226,7 +153,7 @@ If you want to take complete control of Spring MVC, you can add your own `@Confi | |Spring MVC uses a different `ConversionService` to the one used to convert values from your `application.properties` or `application.yaml` file.
It means that `Period`, `Duration` and `DataSize` converters are not available and that `@DurationUnit` and `@DataSizeUnit` annotations will be ignored.

If you want to customize the `ConversionService` used by Spring MVC, you can provide a `WebMvcConfigurer` bean with an `addFormatters` method.
From this method you can register any converter that you like, or you can delegate to the static methods available on `ApplicationConversionService`.| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#web.servlet.spring-mvc.message-converters)1.1.2. HttpMessageConverters #### +#### 1.1.2. HttpMessageConverters Spring MVC uses the `HttpMessageConverter` interface to convert HTTP requests and responses. Sensible defaults are included out of the box. @@ -258,7 +185,7 @@ public class MyHttpMessageConvertersConfiguration { Any `HttpMessageConverter` bean that is present in the context is added to the list of converters. You can also override default converters in the same way. -#### [](#web.servlet.spring-mvc.json)1.1.3. Custom JSON Serializers and Deserializers #### +#### 1.1.3. Custom JSON Serializers and Deserializers If you use Jackson to serialize and deserialize JSON data, you might want to write your own `JsonSerializer` and `JsonDeserializer` classes. Custom serializers are usually [registered with Jackson through a module](https://github.com/FasterXML/jackson-docs/wiki/JacksonHowToCustomSerializers), but Spring Boot provides an alternative `@JsonComponent` annotation that makes it easier to directly register Spring Beans. @@ -364,12 +291,12 @@ public class MyJsonComponent { ``` -#### [](#web.servlet.spring-mvc.message-codes)1.1.4. MessageCodesResolver #### +#### 1.1.4. MessageCodesResolver Spring MVC has a strategy for generating error codes for rendering error messages from binding errors: `MessageCodesResolver`. If you set the `spring.mvc.message-codes-resolver-format` property `PREFIX_ERROR_CODE` or `POSTFIX_ERROR_CODE`, Spring Boot creates one for you (see the enumeration in [`DefaultMessageCodesResolver.Format`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/validation/DefaultMessageCodesResolver.Format.html)). -#### [](#web.servlet.spring-mvc.static-content)1.1.5. Static Content #### +#### 1.1.5. Static Content By default, Spring Boot serves static content from a directory called `/static` (or `/public` or `/resources` or `/META-INF/resources`) in the classpath or from the root of the `ServletContext`. It uses the `ResourceHttpRequestHandler` from Spring MVC so that you can modify that behavior by adding your own `WebMvcConfigurer` and overriding the `addResourceHandlers` method. @@ -475,14 +402,14 @@ See [`WebProperties.Resources`](https://github.com/spring-projects/spring-boot/t | |This feature has been thoroughly described in a dedicated [blog post](https://spring.io/blog/2014/07/24/spring-framework-4-1-handling-static-web-resources) and in Spring Framework’s [reference documentation](https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/web.html#mvc-config-static-resources).| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#web.servlet.spring-mvc.welcome-page)1.1.6. Welcome Page #### +#### 1.1.6. Welcome Page Spring Boot supports both static and templated welcome pages. It first looks for an `index.html` file in the configured static content locations. If one is not found, it then looks for an `index` template. If either is found, it is automatically used as the welcome page of the application. -#### [](#web.servlet.spring-mvc.content-negotiation)1.1.7. Path Matching and Content Negotiation #### +#### 1.1.7. Path Matching and Content Negotiation Spring MVC can map incoming HTTP requests to handlers by looking at the request path and matching it to the mappings defined in your application (for example, `@GetMapping` annotations on Controller methods). @@ -611,12 +538,12 @@ For more details on why you should consider this new implementation, see the[ded | |`PathPatternParser` is an optimized implementation but restricts usage of[some path patterns variants](https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/web.html#mvc-ann-requestmapping-uri-templates)and is incompatible with suffix pattern matching (`spring.mvc.pathmatch.use-suffix-pattern`,`spring.mvc.pathmatch.use-registered-suffix-pattern`) or mapping the `DispatcherServlet`with a servlet prefix (`spring.mvc.servlet.path`).| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#web.servlet.spring-mvc.binding-initializer)1.1.8. ConfigurableWebBindingInitializer #### +#### 1.1.8. ConfigurableWebBindingInitializer Spring MVC uses a `WebBindingInitializer` to initialize a `WebDataBinder` for a particular request. If you create your own `ConfigurableWebBindingInitializer` `@Bean`, Spring Boot automatically configures Spring MVC to use it. -#### [](#web.servlet.spring-mvc.template-engines)1.1.9. Template Engines #### +#### 1.1.9. Template Engines As well as REST web services, you can also use Spring MVC to serve dynamic HTML content. Spring MVC supports a variety of templating technologies, including Thymeleaf, FreeMarker, and JSPs. @@ -640,7 +567,7 @@ When you use one of these templating engines with the default configuration, you | |Depending on how you run your application, your IDE may order the classpath differently.
Running your application in the IDE from its main method results in a different ordering than when you run your application by using Maven or Gradle or from its packaged jar.
This can cause Spring Boot to fail to find the expected template.
If you have this problem, you can reorder the classpath in the IDE to place the module’s classes and resources first.| |---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#web.servlet.spring-mvc.error-handling)1.1.10. Error Handling #### +#### 1.1.10. Error Handling By default, Spring Boot provides an `/error` mapping that handles all errors in a sensible way, and it is registered as a “global” error page in the servlet container. For machine clients, it produces a JSON response with details of the error, the HTTP status, and the exception message. @@ -712,7 +639,7 @@ public class MyController { ``` -##### [](#web.servlet.spring-mvc.error-handling.error-pages)Custom Error Pages ##### +##### Custom Error Pages If you want to display a custom HTML error page for a given status code, you can add a file to an `/error` directory. Error pages can either be static HTML (that is, added under any of the static resource directories) or be built by using templates. @@ -776,7 +703,7 @@ public class MyErrorViewResolver implements ErrorViewResolver { You can also use regular Spring MVC features such as [`@ExceptionHandler` methods](https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/web.html#mvc-exceptionhandlers) and [`@ControllerAdvice`](https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/web.html#mvc-ann-controller-advice). The `ErrorController` then picks up any unhandled exceptions. -##### [](#web.servlet.spring-mvc.error-handling.error-pages-without-spring-mvc)Mapping Error Pages outside of Spring MVC ##### +##### Mapping Error Pages outside of Spring MVC ##### For applications that do not use Spring MVC, you can use the `ErrorPageRegistrar` interface to directly register `ErrorPages`. This abstraction works directly with the underlying embedded servlet container and works even if you do not have a Spring MVC `DispatcherServlet`. @@ -834,7 +761,7 @@ public class MyFilterConfiguration { Note that the default `FilterRegistrationBean` does not include the `ERROR` dispatcher type. -##### [](#web.servlet.spring-mvc.error-handling.in-a-war-deployment)Error handling in a war deployment ##### +##### Error handling in a war deployment 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. This is necessary as the servlet specification does not provide an API for registering error pages. @@ -847,7 +774,7 @@ You should disable this behavior by setting `com.ibm.ws.webcontainer.invokeFlush If you are using Spring Security and want to access the principal in an error page, you must configure Spring Security’s filter to be invoked on error dispatches. To do so, set the `spring.security.filter.dispatcher-types` property to `async, error, forward, request`. -#### [](#web.servlet.spring-mvc.cors)1.1.11. CORS Support #### +#### 1.1.11. CORS Support [Cross-origin resource sharing](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) (CORS) is a [W3C specification](https://www.w3.org/TR/cors/) implemented by [most browsers](https://caniuse.com/#feat=cors) 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. @@ -879,7 +806,7 @@ public class MyCorsConfiguration { ``` -### [](#web.servlet.jersey)1.2. JAX-RS and Jersey ### +### 1.2. 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](https://jersey.github.io/) and [Apache CXF](https://cxf.apache.org/) work quite well out of the box. CXF requires you to register its `Servlet` or `Filter` as a `@Bean` in your application context. @@ -942,17 +869,17 @@ When using Jersey as a filter, a servlet that will handle any requests that are If your application does not contain such a servlet, you may want to enable the default servlet by setting `server.servlet.register-default-servlet` to `true`. Both the servlet and the filter registrations can be given init parameters by using `spring.jersey.init.*` to specify a map of properties. -### [](#web.servlet.embedded-container)1.3. Embedded Servlet Container Support ### +### 1.3. Embedded Servlet Container Support For servlet application, Spring Boot includes support for embedded [Tomcat](https://tomcat.apache.org/), [Jetty](https://www.eclipse.org/jetty/), and [Undertow](https://github.com/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`. -#### [](#web.servlet.embedded-container.servlets-filters-listeners)1.3.1. Servlets, Filters, and listeners #### +#### 1.3.1. Servlets, Filters, and listeners When using an embedded servlet container, you can register servlets, filters, and all the listeners (such as `HttpSessionListener`) from the servlet spec, either by using Spring beans or by scanning for servlet components. -##### [](#web.servlet.embedded-container.servlets-filters-listeners.beans)Registering Servlets, Filters, and Listeners as Spring Beans ##### +##### Registering Servlets, Filters, and Listeners as Spring Beans ##### Any `Servlet`, `Filter`, or servlet `*Listener` instance that is a Spring bean is registered with the embedded container. This can be particularly convenient if you want to refer to a value from your `application.properties` during configuration. @@ -976,7 +903,7 @@ If a servlet filter wraps the request, it should be configured with an order tha | |Take care when registering `Filter` beans since they are initialized very early in the application lifecycle.
If you need to register a `Filter` that interacts with other beans, consider using a [`DelegatingFilterProxyRegistrationBean`](https://docs.spring.io/spring-boot/docs/2.6.4/api/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBean.html) instead.| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#web.servlet.embedded-container.context-initializer)1.3.2. Servlet Context Initialization #### +#### 1.3.2. Servlet Context Initialization Embedded servlet containers do not directly execute the servlet 3.0+ `javax.servlet.ServletContainerInitializer` interface or Spring’s `org.springframework.web.WebApplicationInitializer` interface. This is an intentional design decision intended to reduce the risk that third party libraries designed to run inside a war may break Spring Boot applications. @@ -984,14 +911,14 @@ This is an intentional design decision intended to reduce the risk that third pa If you need to perform servlet context initialization in a Spring Boot application, you should register a bean that implements the `org.springframework.boot.web.servlet.ServletContextInitializer` interface. The single `onStartup` method provides access to the `ServletContext` and, if necessary, can easily be used as an adapter to an existing `WebApplicationInitializer`. -##### [](#web.servlet.embedded-container.context-initializer.scanning)Scanning for Servlets, Filters, and listeners ##### +##### Scanning for Servlets, Filters, and listeners ##### When using an embedded container, automatic registration of classes annotated with `@WebServlet`, `@WebFilter`, and `@WebListener` can be enabled by using `@ServletComponentScan`. | |`@ServletComponentScan` has no effect in a standalone container, where the container’s built-in discovery mechanisms are used instead.| |---|--------------------------------------------------------------------------------------------------------------------------------------| -#### [](#web.servlet.embedded-container.application-context)1.3.3. The ServletWebServerApplicationContext #### +#### 1.3.3. The ServletWebServerApplicationContext Under the hood, Spring Boot uses a different type of `ApplicationContext` for embedded servlet container support. The `ServletWebServerApplicationContext` is a special type of `WebApplicationContext` that bootstraps itself by searching for a single `ServletWebServerFactory` bean. @@ -1000,7 +927,7 @@ Usually a `TomcatServletWebServerFactory`, `JettyServletWebServerFactory`, or `U | |You usually do not need to be aware of these implementation classes.
Most applications are auto-configured, and the appropriate `ApplicationContext` and `ServletWebServerFactory` are created on your behalf.| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#web.servlet.embedded-container.customizing)1.3.4. Customizing Embedded Servlet Containers #### +#### 1.3.4. Customizing Embedded Servlet Containers Common servlet container settings can be configured by using Spring `Environment` properties. Usually, you would define the properties in your `application.properties` or `application.yaml` file. @@ -1024,7 +951,7 @@ For instance, [access logs](howto.html#howto.webserver.configure-access-logs) ca | |See the [`ServerProperties`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java) class for a complete list.| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -##### [](#web.servlet.embedded-container.customizing.samesite)SameSite Cookies ##### +##### SameSite Cookies The `SameSite` cookie attribute can be used by web browsers to control if and how cookies are submitted in cross-site requests. The attribute is particularly relevant for modern web browsers which have started to change the default value that is used when the attribute is missing. @@ -1074,7 +1001,7 @@ public class MySameSiteConfiguration { ``` -##### [](#web.servlet.embedded-container.customizing.programmatic)Programmatic Customization ##### +##### Programmatic Customization If you need to programmatically configure your embedded servlet container, you can register a Spring bean that implements the `WebServerFactoryCustomizer` interface.`WebServerFactoryCustomizer` provides access to the `ConfigurableServletWebServerFactory`, which includes numerous customization setter methods. The following example shows programmatically setting the port: @@ -1118,7 +1045,7 @@ public class MyTomcatWebServerFactoryCustomizer implements WebServerFactoryCusto ``` -##### [](#web.servlet.embedded-container.customizing.direct)Customizing ConfigurableServletWebServerFactory Directly ##### +##### Customizing ConfigurableServletWebServerFactory Directly ##### For more advanced use cases that require you to extend from `ServletWebServerFactory`, you can expose a bean of such type yourself. @@ -1129,7 +1056,7 @@ See the [source code documentation](https://docs.spring.io/spring-boot/docs/2.6. | |Auto-configured customizers are still applied on your custom factory, so use that option carefully.| |---|---------------------------------------------------------------------------------------------------| -#### [](#web.servlet.embedded-container.jsp-limitations)1.3.5. JSP Limitations #### +#### 1.3.5. JSP Limitations When running a Spring Boot application that uses an embedded servlet container (and is packaged as an executable archive), there are some limitations in the JSP support. @@ -1141,12 +1068,11 @@ When running a Spring Boot application that uses an embedded servlet container ( * Creating a custom `error.jsp` page does not override the default view for [error handling](#web.servlet.spring-mvc.error-handling).[Custom error pages](#web.servlet.spring-mvc.error-handling.error-pages) should be used instead. -[](#web.reactive)2. Reactive Web Applications ----------- +## 2. Reactive Web Applications Spring Boot simplifies development of reactive web applications by providing auto-configuration for Spring Webflux. -### [](#web.reactive.webflux)2.1. The “Spring WebFlux Framework” ### +### 2.1. The “Spring WebFlux Framework” Spring WebFlux is the new reactive web framework introduced in Spring Framework 5.0. Unlike Spring MVC, it does not require the servlet API, is fully asynchronous and non-blocking, and implements the [Reactive Streams](https://www.reactive-streams.org/) specification through [the Reactor project](https://projectreactor.io/). @@ -1330,7 +1256,7 @@ To get started, add the `spring-boot-starter-webflux` module to your application | |Adding both `spring-boot-starter-web` and `spring-boot-starter-webflux` modules in your application results in Spring Boot auto-configuring Spring MVC, not WebFlux.
This behavior has been chosen because many Spring developers add `spring-boot-starter-webflux` to their Spring MVC application to use the reactive `WebClient`.
You can still enforce your choice by setting the chosen application type to `SpringApplication.setWebApplicationType(WebApplicationType.REACTIVE)`.| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#web.reactive.webflux.auto-configuration)2.1.1. Spring WebFlux Auto-configuration #### +#### 2.1.1. Spring WebFlux Auto-configuration Spring Boot provides auto-configuration for Spring WebFlux that works well with most applications. @@ -1344,7 +1270,7 @@ If you want to keep Spring Boot WebFlux features and you want to add additional If you want to take complete control of Spring WebFlux, you can add your own `@Configuration` annotated with `@EnableWebFlux`. -#### [](#web.reactive.webflux.httpcodecs)2.1.2. HTTP Codecs with HttpMessageReaders and HttpMessageWriters #### +#### 2.1.2. HTTP Codecs with HttpMessageReaders and HttpMessageWriters Spring WebFlux uses the `HttpMessageReader` and `HttpMessageWriter` interfaces to convert HTTP requests and responses. They are configured with `CodecConfigurer` to have sensible defaults by looking at the libraries available in your classpath. @@ -1379,7 +1305,7 @@ public class MyCodecsConfiguration { You can also leverage [Boot’s custom JSON serializers and deserializers](#web.servlet.spring-mvc.json). -#### [](#web.reactive.webflux.static-content)2.1.3. Static Content #### +#### 2.1.3. Static Content By default, Spring Boot serves static content from a directory called `/static` (or `/public` or `/resources` or `/META-INF/resources`) in the classpath. It uses the `ResourceWebHandler` from Spring WebFlux so that you can modify that behavior by adding your own `WebFluxConfigurer` and overriding the `addResourceHandlers` method. @@ -1412,14 +1338,14 @@ Any resources with a path in `/webjars/**` are served from jar files if they are | |Spring WebFlux applications do not strictly depend on the servlet API, so they cannot be deployed as war files and do not use the `src/main/webapp` directory.| |---|--------------------------------------------------------------------------------------------------------------------------------------------------------------| -#### [](#web.reactive.webflux.welcome-page)2.1.4. Welcome Page #### +#### 2.1.4. Welcome Page Spring Boot supports both static and templated welcome pages. It first looks for an `index.html` file in the configured static content locations. If one is not found, it then looks for an `index` template. If either is found, it is automatically used as the welcome page of the application. -#### [](#web.reactive.webflux.template-engines)2.1.5. Template Engines #### +#### 2.1.5. Template Engines As well as REST web services, you can also use Spring WebFlux to serve dynamic HTML content. Spring WebFlux supports a variety of templating technologies, including Thymeleaf, FreeMarker, and Mustache. @@ -1434,7 +1360,7 @@ Spring Boot includes auto-configuration support for the following templating eng When you use one of these templating engines with the default configuration, your templates are picked up automatically from `src/main/resources/templates`. -#### [](#web.reactive.webflux.error-handling)2.1.6. Error Handling #### +#### 2.1.6. Error Handling Spring Boot provides a `WebExceptionHandler` that handles all errors in a sensible way. Its position in the processing order is immediately before the handlers provided by WebFlux, which are considered last. @@ -1523,7 +1449,7 @@ public class MyExceptionHandlingController { ``` -##### [](#web.reactive.webflux.error-handling.error-pages)Custom Error Pages ##### +##### Custom Error Pages If you want to display a custom HTML error page for a given status code, you can add a file to an `/error` directory. Error pages can either be static HTML (that is, added under any of the static resource directories) or built with templates. @@ -1557,7 +1483,7 @@ src/ +- ``` -#### [](#web.reactive.webflux.web-filters)2.1.7. Web Filters #### +#### 2.1.7. Web Filters Spring WebFlux provides a `WebFilter` interface that can be implemented to filter HTTP request-response exchanges.`WebFilter` beans found in the application context will be automatically used to filter each exchange. @@ -1571,13 +1497,13 @@ When it does so, the orders shown in the following table will be used: |`WebFilterChainProxy` (Spring Security)| `-100` | | `HttpTraceWebFilter` |`Ordered.LOWEST_PRECEDENCE - 10`| -### [](#web.reactive.reactive-server)2.2. Embedded Reactive Server Support ### +### 2.2. Embedded Reactive Server Support Spring Boot includes support for the following embedded reactive web servers: Reactor Netty, Tomcat, Jetty, and Undertow. Most developers use the appropriate “Starter” to obtain a fully configured instance. By default, the embedded server listens for HTTP requests on port 8080. -### [](#web.reactive.reactive-server-resources-configuration)2.3. Reactive Server Resources Configuration ### +### 2.3. Reactive Server Resources Configuration When auto-configuring a Reactor Netty or Jetty server, Spring Boot will create specific beans that will provide HTTP resources to the server instance: `ReactorResourceFactory` or `JettyResourceFactory`. @@ -1591,8 +1517,7 @@ Developers can override the resource configuration for Jetty and Reactor Netty b You can learn more about the resource configuration on the client side in the [WebClient Runtime section](io.html#io.rest-client.webclient.runtime). -[](#web.graceful-shutdown)3. Graceful Shutdown ----------- +## 3. Graceful Shutdown Graceful shutdown is supported with all four embedded web servers (Jetty, Reactor Netty, Tomcat, and Undertow) and with both reactive and servlet-based web applications. It occurs as part of closing the application context and is performed in the earliest phase of stopping `SmartLifecycle` beans. @@ -1638,8 +1563,7 @@ spring: | |Using graceful shutdown with your IDE may not work properly if it does not send a proper `SIGTERM` signal.
See the documentation of your IDE for more details.| |---|------------------------------------------------------------------------------------------------------------------------------------------------------------------| -[](#web.security)4. Spring Security ----------- +## 4. Spring Security If [Spring Security](https://spring.io/projects/spring-security) is on the classpath, then web applications are secured by default. Spring Boot relies on Spring Security’s content-negotiation strategy to determine whether to use `httpBasic` or `formLogin`. @@ -1668,7 +1592,7 @@ The basic features you get by default in a web application are: You can provide a different `AuthenticationEventPublisher` by adding a bean for it. -### [](#web.security.spring-mvc)4.1. MVC Security ### +### 4.1. MVC Security The default security configuration is implemented in `SecurityAutoConfiguration` and `UserDetailsServiceAutoConfiguration`.`SecurityAutoConfiguration` imports `SpringBootWebSecurityConfiguration` for web security and `UserDetailsServiceAutoConfiguration` configures authentication, which is also relevant in non-web applications. To switch off the default web application security configuration completely or to combine multiple Spring Security components such as OAuth2 Client and Resource Server, add a bean of type `SecurityFilterChain` (doing so does not disable the `UserDetailsService` configuration or Actuator’s security). @@ -1678,7 +1602,7 @@ To also switch off the `UserDetailsService` configuration, you can add a bean of Access rules can be overridden by adding a custom `SecurityFilterChain` or `WebSecurityConfigurerAdapter` bean. Spring Boot provides convenience methods that can be used to override access rules for actuator endpoints and static resources.`EndpointRequest` can be used to create a `RequestMatcher` that is based on the `management.endpoints.web.base-path` property.`PathRequest` can be used to create a `RequestMatcher` for resources in commonly used locations. -### [](#web.security.spring-webflux)4.2. WebFlux Security ### +### 4.2. WebFlux Security Similar to Spring MVC applications, you can secure your WebFlux applications by adding the `spring-boot-starter-security` dependency. The default security configuration is implemented in `ReactiveSecurityAutoConfiguration` and `UserDetailsServiceAutoConfiguration`.`ReactiveSecurityAutoConfiguration` imports `WebFluxSecurityConfiguration` for web security and `UserDetailsServiceAutoConfiguration` configures authentication, which is also relevant in non-web applications. @@ -1717,11 +1641,11 @@ public class MyWebFluxSecurityConfiguration { ``` -### [](#web.security.oauth2)4.3. OAuth2 ### +### 4.3. OAuth2 [OAuth2](https://oauth.net/2/) is a widely used authorization framework that is supported by Spring. -#### [](#web.security.oauth2.client)4.3.1. Client #### +#### 4.3.1. Client If you have `spring-security-oauth2-client` on your classpath, you can take advantage of some auto-configuration to set up an OAuth2/Open ID Connect clients. This configuration makes use of the properties under `OAuth2ClientProperties`. @@ -1847,7 +1771,7 @@ public class MyOAuthClientConfiguration { | |Spring Boot auto-configures an `InMemoryOAuth2AuthorizedClientService` which is used by Spring Security for the management of client registrations.
The `InMemoryOAuth2AuthorizedClientService` has limited capabilities and we recommend using it only for development environments.
For production environments, consider using a `JdbcOAuth2AuthorizedClientService` or creating your own implementation of `OAuth2AuthorizedClientService`.| |---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -##### [](#web.security.oauth2.client.common-providers)OAuth2 client registration for common providers ##### +##### OAuth2 client registration for common providers For common OAuth2 and OpenID providers, including Google, Github, Facebook, and Okta, we provide a set of provider defaults (`google`, `github`, `facebook`, and `okta`, respectively). @@ -1883,7 +1807,7 @@ spring: client-secret: "password" ``` -#### [](#web.security.oauth2.server)4.3.2. Resource Server #### +#### 4.3.2. Resource Server If you have `spring-security-oauth2-resource-server` on your classpath, Spring Boot can set up an OAuth2 Resource Server. For JWT configuration, a JWK Set URI or OIDC Issuer URI needs to be specified, as shown in the following examples: @@ -1956,15 +1880,15 @@ Again, the same properties are applicable for both servlet and reactive applicat Alternatively, you can define your own `OpaqueTokenIntrospector` bean for servlet applications or a `ReactiveOpaqueTokenIntrospector` for reactive applications. -#### [](#web.security.oauth2.authorization-server)4.3.3. Authorization Server #### +#### 4.3.3. Authorization Server Currently, Spring Security does not provide support for implementing an OAuth 2.0 Authorization Server. However, this functionality is available from the [Spring Security OAuth](https://spring.io/projects/spring-security-oauth) project, which will eventually be superseded by Spring Security completely. Until then, you can use the `spring-security-oauth2-autoconfigure` module to easily set up an OAuth 2.0 authorization server; see its [documentation](https://docs.spring.io/spring-security-oauth2-boot/) for instructions. -### [](#web.security.saml2)4.4. SAML 2.0 ### +### 4.4. SAML 2.0 -#### [](#web.security.saml2.relying-party)4.4.1. Relying Party #### +#### 4.4.1. Relying Party If you have `spring-security-saml2-service-provider` on your classpath, you can take advantage of some auto-configuration to set up a SAML 2.0 Relying Party. This configuration makes use of the properties under `Saml2RelyingPartyProperties`. @@ -2033,8 +1957,7 @@ spring: sso-url: "https://remoteidp2.sso.url" ``` -[](#web.spring-session)5. Spring Session ----------- +## 5. Spring Session Spring Boot provides [Spring Session](https://spring.io/projects/spring-session) auto-configuration for a wide range of data stores. When building a servlet web application, the following stores can be auto-configured: @@ -2103,8 +2026,7 @@ You can take control over Spring Session’s configuration using `@Enable*HttpSe This will cause the auto-configuration to back off. Spring Session can then be configured using the annotation’s attributes rather than the previously described configuration properties. -[](#web.spring-hateoas)6. Spring HATEOAS ----------- +## 6. Spring HATEOAS If you develop a RESTful API that makes use of hypermedia, Spring Boot provides auto-configuration for Spring HATEOAS that works well with most applications. The auto-configuration replaces the need to use `@EnableHypermediaSupport` and registers a number of beans to ease building hypermedia-based applications, including a `LinkDiscoverers` (for client side support) and an `ObjectMapper` configured to correctly marshal responses into the desired representation. @@ -2116,8 +2038,7 @@ Note that doing so disables the `ObjectMapper` customization described earlier. | |`spring-boot-starter-hateoas` is specific to Spring MVC and should not be combined with Spring WebFlux.
In order to use Spring HATEOAS with Spring WebFlux, you can add a direct dependency on `org.springframework.hateoas:spring-hateoas` along with `spring-boot-starter-webflux`.| |---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -[](#web.whats-next)7. What to Read Next ----------- +## 7. What to Read Next You should now have a good understanding of how to develop web applications with Spring Boot. The next few sections describe how Spring Boot integrates with various [data technologies](data.html#data), [messaging systems](messaging.html#messaging), and other IO capabilities. diff --git a/docs/intellij_idea.md b/docs/intellij_idea.md index 709a73097f59e3e44c952a3563e7781152739be9..68f3eea046d600c6180815300e18275f7bfc3e6d 100644 --- a/docs/intellij_idea.md +++ b/docs/intellij_idea.md @@ -1,12 +1,12 @@ -# 使用 IntelliJ IDEA 编写入门指南 +# 使用 IntelliJ IDEA 运行一个入门指南 -本指南将引导您使用 IntelliJ IDEA 构建入门指南之一。 +本指南将引导您使用 IntelliJ IDEA 构建一个入门指南。 ## 您将构建什么 您将选择一个 Spring 指南并将其导入 IntelliJ IDEA。然后,您可以阅读指南、编写代码并运行项目。 -## 你需要什么 +## 您需要什么 - 约15分钟 - [IntelliJ IDEA](https://www.jetbrains.com/idea/download/) @@ -14,13 +14,13 @@ ## 安装 IntelliJ IDEA -如果您尚未安装 IntelliJ IDEA(终极版),请访问上面的链接。从那里,您可以下载适用于您平台的副本。要安装它,只需解压缩下载的存档。 +如果您尚未安装 IntelliJ IDEA(终极版),请访问上面的链接。您可以从那里下载适用于您平台的版本。只需解压缩下载的文件就可以安装它。 -完成后,继续启动 IntelliJ IDEA。 +安装完成后,启动 IntelliJ IDEA。 -## 导入入门指南 +## 导入一个入门指南 -要导入现有项目,您需要一些代码,因此请克隆或复制入门指南之一,例如[REST 服务](https://spring.io/guides/gs/rest-service/)指南: +您需要有代码才能在 IntelliJ IDEA 中导入现有项目,因此请克隆或复制入门指南之一,例如[REST 服务](https://spring.io/guides/gs/rest-service/)指南: ``` $ git clone https://github.com/spring-guides/gs-rest-service.git复制 @@ -30,15 +30,15 @@ $ git clone https://github.com/spring-guides/gs-rest-service.git复制 ![spring_guide_welcome_import](./intellij_idea/spring_guide_welcome_import.png) -在弹出对话框中,确保选择**完整**文件夹下的[Maven](https://spring.io/guides/gs/maven)的**pom.xml**或[Gradle](https://spring.io/guides/gs/gradle)的**build.gradle**文件: +在弹出对话框中,选择**complete**文件夹下的[Maven](https://spring.io/guides/gs/maven)的**pom.xml**或[Gradle](https://spring.io/guides/gs/gradle)的**build.gradle**文件: ![spring_guide_select_gradle_file](./intellij_idea/spring_guide_select_gradle_file.png) -IntelliJ IDEA 将创建一个项目,其中包含准备运行的指南中的所有代码。 +IntelliJ IDEA 将创建一个项目,其中包含了运行指南需要的所有代码。 ## 从头开始创建项目 -如果您想从一个空项目开始并通过指南复制粘贴,请在**项目向导中创建一个新的****Maven**或**Gradle**项目: +如果您想从一个空项目开始并通过复制粘贴的方式运行指南,请在**项目向导中创建一个新的****Maven**或**Gradle**项目: ![spring_guide_new_project](./intellij_idea/spring_guide_new_project.png) diff --git a/docs/why-spring.md b/docs/why-spring.md index 5a6e45b57793419f4cbb5fb20d804741e4d175fb..b3b87e0629a7a5accfda5ffa5b9053b11ebb75e5 100644 --- a/docs/why-spring.md +++ b/docs/why-spring.md @@ -8,45 +8,45 @@ Spring 让每个人都可以更快、更轻松、更安全地编写 Java。Sprin ## Spring无处不在 -Spring 的灵活库受到全世界开发人员的信赖。Spring 每天为数百万最终用户提供令人愉悦的体验——无论是[流媒体电视](https://medium.com/netflix-techblog/netflix-oss-and-spring-boot-coming-full-circle-4855947713a0),[网上购物](https://tech.target.com/2018/12/18/spring-feign.html),或无数其他创新解决方案。Spring 也有来自所有科技巨头的贡献,包括阿里巴巴、亚马逊、谷歌、微软等。 +Spring灵活的库受到全世界开发人员的信赖。Spring每天为数百万终端用户提供令人愉悦的体验,无论是[流媒体电视](https://medium.com/netflix-techblog/netflix-oss-and-spring-boot-coming-full-circle-4855947713a0),[网上购物](https://tech.target.com/2018/12/18/spring-feign.html),或无数其他创新解决方案。Spring 也有来自所有科技巨头的贡献,包括阿里巴巴、亚马逊、谷歌、微软等。 ## Spring很灵活 -Spring 灵活而全面的扩展集和第三方库让开发人员可以构建几乎任何可以想象的应用程序。Spring 框架的核心是[控制反转 (IoC)](https://en.wikipedia.org/wiki/Inversion_of_control)和[依赖注入 (DI)](https://en.wikipedia.org/wiki/Dependency_injection)特性为广泛的特性和功能集提供了基础。无论您是为 Web 构建安全、反应式、基于云的微服务,还是为企业构建复杂的流数据流,Spring 都有可以提供帮助的工具。 +Spring 灵活而全面的扩展集和第三方库让开发人员可以构建几乎任何可以想象到的应用程序。从框架核心原理来看,Spring框架的[控制反转 (IoC)](https://en.wikipedia.org/wiki/Inversion_of_control)和[依赖注入 (DI)](https://en.wikipedia.org/wiki/Dependency_injection)特性,为其广泛的特性和功能集提供了基础能力。无论您是为 Web 构建安全、反应式、基于云的微服务,还是为企业构建复杂的流式数据处理流程,Spring 都有可以提供支持的工具。 ## Spring是生产力 -[弹簧靴](https://spring.io/guides/gs/spring-boot/)改变您处理 Java 编程任务的方式,从根本上简化您的体验。Spring Boot 结合了应用程序上下文和自动配置的嵌入式 Web 服务器等必需品,[微服务](https://spring.io/microservices)发展小菜一碟。为了更快,您可以将 Spring Boot 与 Spring Cloud 丰富的支持库、服务器、模式和模板集相结合,以安全地将整个基于微服务的架构部署到[云](https://spring.io/cloud),在创纪录的时间内。 +[Spring Boot](https://spring.io/guides/gs/spring-boot/)改变您处理 Java 编程任务的方式,从根本上简化您的体验。Spring Boot将一些必备功能,比如应用程序上下文、自动配置的嵌入式Web服务器等整合到一起,从而使[微服务](https://spring.io/microservices)开发变得非常简单。为了让开发速度更快,您可以将Spring Boot与Spring Cloud丰富的支持库、服务、模式和模板集相结合,以便在极短时间安全地将整个基于微服务的架构部署到[云](https://spring.io/cloud) -## Spring来得很快 +## Spring非常快 -我们的工程师非常关心性能。使用 Spring,您会注意到默认情况下快速启动、快速关闭和优化执行。Spring 项目也越来越多地支持[反应式](https://spring.io/reactive)(非阻塞)编程模型,效率更高。开发人员的生产力是 Spring 的超能力。Spring Boot 可帮助开发人员轻松构建应用程序,并且比其他竞争范式更省力。嵌入式 Web 服务器、自动配置和“fat jars”可帮助您快速入门,创新如[Spring DevTools 中的 LiveReload](https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-devtools-livereload)意味着开发人员可以比以往更快地迭代。您甚至可以在几秒钟内启动一个新的 Spring 项目,Spring Initializr 位于[启动.spring.io](https://start.spring.io/). +我们的工程师非常关心性能。使用 Spring,您会注意到默认情况下快速启动、快速关闭和优化执行。Spring 项目也越来越多地支持[响应式](https://spring.io/reactive)(非阻塞)编程模型,效率更高。开发人员的生产力是 Spring 的超能力。Spring Boot 可帮助开发人员轻松构建应用程序,并且比其他竞品更省力。嵌入式 Web 服务器、自动配置和“fat jars”可帮助您快速入门,[Spring DevTools 中的 LiveReload](https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-devtools-livereload)等创新功能意味着开发人员可以比以往更快地迭代。您甚至可以使用Spring Initializr(Spring Boot项目构建工具,位于[启动.spring.io](https://start.spring.io/))在几秒钟内启动一个新的 Spring 项目. ## Spring是安全的 Spring 在快速、负责任地处理安全问题方面有着良好的记录。Spring 提交者与安全专家合作,修补和测试任何报告的漏洞。第三方依赖项也受到密切监控,并定期发布更新以帮助确保您的数据和应用程序尽可能安全。此外,[Spring安全](https://spring.io/projects/spring-security)让您更轻松地与行业标准的安全方案集成,并提供默认安全的值得信赖的解决方案。 -## Spring是支持的 +## Spring相关支撑非常完善 -这[Spring社区](https://spring.io/community)是巨大的、全球性的、多样化的,涵盖了所有年龄和能力的人,从完全的初学者到经验丰富的专业人士。无论您在旅途中的哪个阶段,都可以找到使您更上一层楼所需的支持和资源:[快速入门](https://spring.io/quickstart),[指南和教程](https://spring.io/guides),[视频](https://www.youtube.com/channel/UC7yfnfvEUlXUIfm8rGLwZdA),[聚会](https://spring.io/events),[支持](https://spring.io/support),甚至是正式的[培训和认证](https://spring.io/training). +[Spring社区](https://spring.io/community)是庞大的、全球性的、多样化的,涵盖了所有年龄和能力的人,从完全的初学者到经验丰富的专业人士。无论您在旅途中的哪个阶段,都可以找到使您更上一层楼所需的支持和资源:[快速入门](https://spring.io/quickstart),[指南和教程](https://spring.io/guides),[视频](https://www.youtube.com/channel/UC7yfnfvEUlXUIfm8rGLwZdA),[聚会](https://spring.io/events),[支持](https://spring.io/support),甚至是正式的[培训和认证](https://spring.io/training). -# What can Spring do? +# Spring能干什么? ## Microservices -使用可独立发展的微服务快速交付生产级功能。 +通过可独立开发的微服务快速交付生产级功能。 ## Reactive -Spring 的异步、非阻塞架构意味着您可以从计算资源中获得更多收益。 +Spring的异步、非阻塞架构意味着您可以从计算资源中获得更多收益。 ## Cloud -您的代码,任何云——我们已经为您服务。无论您的平台如何,都可以连接和扩展您的服务。 +您的代码与任何云的对接我们都已经为您覆盖。无论您的使用什么平台,都可以连接并扩展您的服务。 ## Web apps -用于连接到任何数据存储的快速、安全和响应式 Web 应用程序的框架。 +连接到任何数据存储的快速,安全和响应式Web应用程序的框架。 ## Serverless @@ -58,6 +58,6 @@ Spring 的异步、非阻塞架构意味着您可以从计算资源中获得更 ## Batch -自动化任务。一次离线处理数据以适合您。 +自动化任务。一次适合您的离线数据处理。 -原文链接: https://spring.io/why-spring \ No newline at end of file +原文链接: https://spring.io/why-spring