Migrate spring-boot-docs to Antora
See gh-33766
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
[[actuator.auditing]]
|
||||
= Auditing
|
||||
|
||||
Once Spring Security is in play, Spring Boot Actuator has a flexible audit framework that publishes events (by default, "`authentication success`", "`failure`" and "`access denied`" exceptions).
|
||||
This feature can be very useful for reporting and for implementing a lock-out policy based on authentication failures.
|
||||
|
||||
You can enable auditing by providing a bean of type `AuditEventRepository` in your application's configuration.
|
||||
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]]
|
||||
== 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`).
|
||||
@@ -0,0 +1,58 @@
|
||||
[[actuator.cloud-foundry]]
|
||||
= 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.
|
||||
|
||||
The extended support lets Cloud Foundry management UIs (such as the web application that you can use to view deployed applications) be augmented with Spring Boot actuator information.
|
||||
For example, an application status page can include full health information instead of the typical "`running`" or "`stopped`" status.
|
||||
|
||||
NOTE: 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]]
|
||||
== 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:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
management:
|
||||
cloudfoundry:
|
||||
enabled: false
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[actuator.cloud-foundry.ssl]]
|
||||
== 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:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
management:
|
||||
cloudfoundry:
|
||||
skip-ssl-validation: true
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[actuator.cloud-foundry.custom-context-path]]
|
||||
== 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/*`.
|
||||
|
||||
If you expect the Cloud Foundry endpoints to always be available at `/cloudfoundryapplication/*`, regardless of the server's context-path, you need to explicitly configure that in your application.
|
||||
The configuration differs, depending on the web server in use.
|
||||
For Tomcat, you can add the following configuration:
|
||||
|
||||
include-code::MyCloudFoundryConfiguration[]
|
||||
|
||||
If you're using a Webflux based application, you can use the following configuration:
|
||||
|
||||
include-code::MyReactiveCloudFoundryConfiguration[]
|
||||
@@ -0,0 +1,32 @@
|
||||
[[actuator.enabling]]
|
||||
= Enabling Production-ready Features
|
||||
|
||||
The {code-spring-boot}/spring-boot-project/spring-boot-actuator[`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`".
|
||||
|
||||
.Definition of Actuator
|
||||
****
|
||||
An actuator is a manufacturing term that refers to a mechanical device for moving or controlling something.
|
||||
Actuators can generate a large amount of motion from a small change.
|
||||
****
|
||||
|
||||
To add the actuator to a Maven-based project, add the following "`Starter`" dependency:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
----
|
||||
|
||||
For Gradle, use the following declaration:
|
||||
|
||||
[source,gradle]
|
||||
----
|
||||
dependencies {
|
||||
implementation 'org.springframework.boot:spring-boot-starter-actuator'
|
||||
}
|
||||
----
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,19 @@
|
||||
[[actuator.http-exchanges]]
|
||||
= Recording HTTP Exchanges
|
||||
|
||||
You can enable recording of HTTP exchanges by providing a bean of type `HttpExchangeRepository` in your application's configuration.
|
||||
For convenience, Spring Boot offers `InMemoryHttpExchangeRepository`, which, by default, stores the last 100 request-response exchanges.
|
||||
`InMemoryHttpExchangeRepository` is limited compared to tracing solutions, and we recommend using it only for development environments.
|
||||
For production environments, we recommend using a production-ready tracing or observability solution, such as Zipkin or OpenTelemetry.
|
||||
Alternatively, you can create your own `HttpExchangeRepository`.
|
||||
|
||||
You can use the `httpexchanges` endpoint to obtain information about the request-response exchanges that are stored in the `HttpExchangeRepository`.
|
||||
|
||||
|
||||
|
||||
[[actuator.http-exchanges.custom]]
|
||||
== Custom HTTP Exchange Recording
|
||||
|
||||
To customize the items that are included in each recorded exchange, use the configprop:management.httpexchanges.recording.include[] configuration property.
|
||||
|
||||
To disable recoding entirely, set configprop:management.httpexchanges.recording.enabled[] to `false`.
|
||||
@@ -0,0 +1,8 @@
|
||||
|
||||
[[actuator]]
|
||||
= 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.
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
[[actuator.jmx]]
|
||||
= 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.
|
||||
You can turn it on by setting the configprop:spring.jmx.enabled[] configuration property to `true`.
|
||||
Spring Boot exposes the most suitable `MBeanServer` as a bean with an ID of `mbeanServer`.
|
||||
Any of your beans that are annotated with Spring JMX annotations (`@ManagedResource`, `@ManagedAttribute`, or `@ManagedOperation`) are exposed to it.
|
||||
|
||||
If your platform provides a standard `MBeanServer`, Spring Boot uses that and defaults to the VM `MBeanServer`, if necessary.
|
||||
If all that fails, a new `MBeanServer` is created.
|
||||
|
||||
See the {code-spring-boot-autoconfigure-src}/jmx/JmxAutoConfiguration.java[`JmxAutoConfiguration`] class for more details.
|
||||
|
||||
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]]
|
||||
== 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`.
|
||||
|
||||
If your application contains more than one Spring `ApplicationContext`, you may find that names clash.
|
||||
To solve this problem, you can set the configprop:spring.jmx.unique-names[] property to `true` so that MBean names are always unique.
|
||||
|
||||
You can also customize the JMX domain under which endpoints are exposed.
|
||||
The following settings show an example of doing so in `application.properties`:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
jmx:
|
||||
unique-names: true
|
||||
management:
|
||||
endpoints:
|
||||
jmx:
|
||||
domain: "com.example.myapp"
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[actuator.jmx.disable-jmx-endpoints]]
|
||||
== Disabling JMX Endpoints
|
||||
|
||||
If you do not want to expose endpoints over JMX, you can set the configprop:management.endpoints.jmx.exposure.exclude[] property to `*`, as the following example shows:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
management:
|
||||
endpoints:
|
||||
jmx:
|
||||
exposure:
|
||||
exclude: "*"
|
||||
----
|
||||
@@ -0,0 +1,33 @@
|
||||
[[actuator.loggers]]
|
||||
= 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.
|
||||
These levels can be one of:
|
||||
|
||||
* `TRACE`
|
||||
* `DEBUG`
|
||||
* `INFO`
|
||||
* `WARN`
|
||||
* `ERROR`
|
||||
* `FATAL`
|
||||
* `OFF`
|
||||
* `null`
|
||||
|
||||
`null` indicates that there is no explicit configuration.
|
||||
|
||||
|
||||
|
||||
[[actuator.loggers.configure]]
|
||||
== Configure a Logger
|
||||
|
||||
To configure a given logger, `POST` a partial entity to the resource's URI, as the following example shows:
|
||||
|
||||
[source,json]
|
||||
----
|
||||
{
|
||||
"configuredLevel": "DEBUG"
|
||||
}
|
||||
----
|
||||
|
||||
TIP: To "`reset`" the specific level of the logger (and use the default configuration instead), you can pass a value of `null` as the `configuredLevel`.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,154 @@
|
||||
[[actuator.monitoring]]
|
||||
= 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.
|
||||
For example, `health` is exposed as `/actuator/health`.
|
||||
|
||||
TIP: Actuator is supported natively with Spring MVC, Spring WebFlux, and Jersey.
|
||||
If both Jersey and Spring MVC are available, Spring MVC is used.
|
||||
|
||||
NOTE: Jackson is a required dependency in order to get the correct JSON responses as documented in the xref:api:rest/actuator/index.adoc[API documentation].
|
||||
|
||||
|
||||
|
||||
[[actuator.monitoring.customizing-management-server-context-path]]
|
||||
== 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.
|
||||
You can use the configprop:management.endpoints.web.base-path[] property to change the prefix for your management endpoint, as the following example shows:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
management:
|
||||
endpoints:
|
||||
web:
|
||||
base-path: "/manage"
|
||||
----
|
||||
|
||||
The preceding `application.properties` example changes the endpoint from `/actuator/\{id}` to `/manage/\{id}` (for example, `/manage/info`).
|
||||
|
||||
NOTE: Unless the management port has been configured to xref:actuator/monitoring.adoc#actuator.monitoring.customizing-management-server-port[expose endpoints by using a different HTTP port], `management.endpoints.web.base-path` is relative to `server.servlet.context-path` (for servlet web applications) or `spring.webflux.base-path` (for reactive web applications).
|
||||
If `management.server.port` is configured, `management.endpoints.web.base-path` is relative to `management.server.base-path`.
|
||||
|
||||
If you want to map endpoints to a different path, you can use the configprop:management.endpoints.web.path-mapping[] property.
|
||||
|
||||
The following example remaps `/actuator/health` to `/healthcheck`:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
management:
|
||||
endpoints:
|
||||
web:
|
||||
base-path: "/"
|
||||
path-mapping:
|
||||
health: "healthcheck"
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[actuator.monitoring.customizing-management-server-port]]
|
||||
== Customizing the Management Server Port
|
||||
|
||||
Exposing management endpoints by using the default HTTP port is a sensible choice for cloud-based deployments.
|
||||
If, however, your application runs inside your own data center, you may prefer to expose endpoints by using a different HTTP port.
|
||||
|
||||
You can set the configprop:management.server.port[] property to change the HTTP port, as the following example shows:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
management:
|
||||
server:
|
||||
port: 8081
|
||||
----
|
||||
|
||||
NOTE: 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]]
|
||||
== 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:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
server:
|
||||
port: 8443
|
||||
ssl:
|
||||
enabled: true
|
||||
key-store: "classpath:store.jks"
|
||||
key-password: "secret"
|
||||
management:
|
||||
server:
|
||||
port: 8080
|
||||
ssl:
|
||||
enabled: false
|
||||
----
|
||||
|
||||
Alternatively, both the main server and the management server can use SSL but with different key stores, as follows:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
server:
|
||||
port: 8443
|
||||
ssl:
|
||||
enabled: true
|
||||
key-store: "classpath:main.jks"
|
||||
key-password: "secret"
|
||||
management:
|
||||
server:
|
||||
port: 8080
|
||||
ssl:
|
||||
enabled: true
|
||||
key-store: "classpath:management.jks"
|
||||
key-password: "secret"
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[actuator.monitoring.customizing-management-server-address]]
|
||||
== Customizing the Management Server Address
|
||||
|
||||
You can customize the address on which the management endpoints are available by setting the configprop: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`.
|
||||
|
||||
NOTE: You can listen on a different address only when the port differs from the main server port.
|
||||
|
||||
The following example `application.properties` does not allow remote management connections:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
management:
|
||||
server:
|
||||
port: 8081
|
||||
address: "127.0.0.1"
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[actuator.monitoring.disabling-http-endpoints]]
|
||||
== 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:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
management:
|
||||
server:
|
||||
port: -1
|
||||
----
|
||||
|
||||
You can also achieve this by using the configprop:management.endpoints.web.exposure.exclude[] property, as the following example shows:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
management:
|
||||
endpoints:
|
||||
web:
|
||||
exposure:
|
||||
exclude: "*"
|
||||
----
|
||||
@@ -0,0 +1,102 @@
|
||||
[[actuator.observability]]
|
||||
= Observability
|
||||
|
||||
Observability is the ability to observe the internal state of a running system from the outside.
|
||||
It consists of the three pillars logging, metrics and traces.
|
||||
|
||||
For metrics and traces, Spring Boot uses https://micrometer.io/docs/observation[Micrometer Observation].
|
||||
To create your own observations (which will lead to metrics and traces), you can inject an `ObservationRegistry`.
|
||||
|
||||
include-code::MyCustomObservation[]
|
||||
|
||||
NOTE: Low cardinality tags will be added to metrics and traces, while high cardinality tags will only be added to traces.
|
||||
|
||||
Beans of type `ObservationPredicate`, `GlobalObservationConvention`, `ObservationFilter` and `ObservationHandler` will be automatically registered on the `ObservationRegistry`.
|
||||
You can additionally register any number of `ObservationRegistryCustomizer` beans to further configure the registry.
|
||||
|
||||
Observability support relies on the https://github.com/micrometer-metrics/context-propagation[Context Propagation library] for forwarding the current observation across threads and reactive pipelines.
|
||||
By default, `ThreadLocal` values are not automatically reinstated in reactive operators.
|
||||
This behavior is controlled with the configprop:spring.reactor.context-propagation[] property, which can be set to `auto` to enable automatic propagation.
|
||||
|
||||
For more details about observations please see the https://micrometer.io/docs/observation[Micrometer Observation documentation].
|
||||
|
||||
TIP: Observability for JDBC can be configured using a separate project.
|
||||
The https://github.com/jdbc-observations/datasource-micrometer[Datasource Micrometer project] provides a Spring Boot starter which automatically creates observations when JDBC operations are invoked.
|
||||
Read more about it https://jdbc-observations.github.io/datasource-micrometer/docs/current/docs/html/[in the reference documentation].
|
||||
|
||||
TIP: Observability for R2DBC is built into Spring Boot.
|
||||
To enable it, add the `io.r2dbc:r2dbc-proxy` dependency to your project.
|
||||
|
||||
|
||||
|
||||
[[actuator.observability.common-tags]]
|
||||
== Common tags
|
||||
|
||||
Common tags are generally used for dimensional drill-down on the operating environment, such as host, instance, region, stack, and others.
|
||||
Common tags are applied to all observations as low cardinality tags and can be configured, as the following example shows:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
management:
|
||||
observations:
|
||||
key-values:
|
||||
region: "us-east-1"
|
||||
stack: "prod"
|
||||
----
|
||||
|
||||
The preceding example adds `region` and `stack` tags to all observations with a value of `us-east-1` and `prod`, respectively.
|
||||
|
||||
|
||||
|
||||
[[actuator.observability.preventing-observations]]
|
||||
== Preventing Observations
|
||||
|
||||
If you'd like to prevent some observations from being reported, you can use the configprop:management.observations.enable[] properties:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
management:
|
||||
observations:
|
||||
enable:
|
||||
denied:
|
||||
prefix: false
|
||||
another:
|
||||
denied:
|
||||
prefix: false
|
||||
----
|
||||
|
||||
The preceding example will prevent all observations with a name starting with `denied.prefix` or `another.denied.prefix`.
|
||||
|
||||
TIP: If you want to prevent Spring Security from reporting observations, set the property configprop:management.observations.enable.spring.security[] to `false`.
|
||||
|
||||
If you need greater control over the prevention of observations, you can register beans of type `ObservationPredicate`.
|
||||
Observations are only reported if all the `ObservationPredicate` beans return `true` for that observation.
|
||||
|
||||
include-code::MyObservationPredicate[]
|
||||
|
||||
The preceding example will prevent all observations whose name contains "denied".
|
||||
|
||||
|
||||
|
||||
[[actuator.observability.opentelemetry]]
|
||||
== OpenTelemetry Support
|
||||
|
||||
Spring Boot's actuator module includes basic support for https://opentelemetry.io/[OpenTelemetry].
|
||||
|
||||
It provides a bean of type `OpenTelemetry`, and if there are beans of type `SdkTracerProvider`, `ContextPropagators`, `SdkLoggerProvider` or `SdkMeterProvider` in the application context, they automatically get registered.
|
||||
Additionally, it provides a `Resource` bean.
|
||||
The attributes of the auto-configured `Resource` can be configured via the configprop:management.opentelemetry.resource-attributes[] configuration property.
|
||||
If you have defined your own `Resource` bean, this will no longer be the case.
|
||||
|
||||
NOTE: Spring Boot does not provide auto-configuration for OpenTelemetry metrics or logging.
|
||||
OpenTelemetry tracing is only auto-configured when used together with xref:actuator/tracing.adoc[Micrometer Tracing].
|
||||
|
||||
The next sections will provide more details about logging, metrics and traces.
|
||||
|
||||
|
||||
|
||||
[[actuator.observability.annotations]]
|
||||
== Micrometer Observation Annotations support
|
||||
|
||||
To enable scanning of metrics and tracing annotations like `@Timed`, `@Counted`, `@MeterTag` and `@NewSpan` annotations, you will need to set the configprop:management.observations.annotations.enabled[] property to `true`.
|
||||
This feature is supported Micrometer directly, please refer to the {url-micrometer-docs-concepts}#_the_timed_annotation[Micrometer] and {url-micrometer-tracing-docs}/api.html#_aspect_oriented_programming[Micrometer Tracing] reference docs.
|
||||
@@ -0,0 +1,34 @@
|
||||
[[actuator.process-monitoring]]
|
||||
= Process Monitoring
|
||||
|
||||
In the `spring-boot` module, you can find two classes to create files that are often useful for process monitoring:
|
||||
|
||||
* `ApplicationPidFileWriter` creates a file that contains the application PID (by default, in the application directory with a file name of `application.pid`).
|
||||
* `WebServerPortFileWriter` creates a file (or files) that contain the ports of the running web server (by default, in the application directory with a file name of `application.port`).
|
||||
|
||||
By default, these writers are not activated, but you can enable them:
|
||||
|
||||
* xref:actuator/process-monitoring.adoc#actuator.process-monitoring.configuration[By Extending Configuration]
|
||||
* xref:actuator/process-monitoring.adoc#actuator.process-monitoring.programmatically[Programmatically Enabling Process Monitoring]
|
||||
|
||||
|
||||
|
||||
[[actuator.process-monitoring.configuration]]
|
||||
== Extending Configuration
|
||||
|
||||
In the `META-INF/spring.factories` file, you can activate the listener (or listeners) that writes a PID file:
|
||||
|
||||
[source]
|
||||
----
|
||||
org.springframework.context.ApplicationListener=\
|
||||
org.springframework.boot.context.ApplicationPidFileWriter,\
|
||||
org.springframework.boot.web.context.WebServerPortFileWriter
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[actuator.process-monitoring.programmatically]]
|
||||
== 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.
|
||||
@@ -0,0 +1,221 @@
|
||||
[[actuator.micrometer-tracing]]
|
||||
= Tracing
|
||||
|
||||
Spring Boot Actuator provides dependency management and auto-configuration for https://micrometer.io/docs/tracing[Micrometer Tracing], a facade for popular tracer libraries.
|
||||
|
||||
TIP: To learn more about Micrometer Tracing capabilities, see its https://micrometer.io/docs/tracing[reference documentation].
|
||||
|
||||
|
||||
|
||||
[[actuator.micrometer-tracing.tracers]]
|
||||
== Supported Tracers
|
||||
|
||||
Spring Boot ships auto-configuration for the following tracers:
|
||||
|
||||
* https://opentelemetry.io/[OpenTelemetry] with https://zipkin.io/[Zipkin], https://docs.wavefront.com/[Wavefront], or https://opentelemetry.io/docs/reference/specification/protocol/[OTLP]
|
||||
* https://github.com/openzipkin/brave[OpenZipkin Brave] with https://zipkin.io/[Zipkin] or https://docs.wavefront.com/[Wavefront]
|
||||
|
||||
|
||||
|
||||
[[actuator.micrometer-tracing.getting-started]]
|
||||
== Getting Started
|
||||
|
||||
We need an example application that we can use to get started with tracing.
|
||||
For our purposes, the simple "`Hello World!`" web application that's covered in the "`xref:tutorial:first-application/index.adoc[Developing Your First Spring Boot Application]`" section will suffice.
|
||||
We're going to use the OpenTelemetry tracer with Zipkin as trace backend.
|
||||
|
||||
To recap, our main application code looks like this:
|
||||
|
||||
include-code::MyApplication[]
|
||||
|
||||
NOTE: There's an added logger statement in the `home()` method, which will be important later.
|
||||
|
||||
Now we have to add the following dependencies:
|
||||
|
||||
* `org.springframework.boot:spring-boot-starter-actuator`
|
||||
* `io.micrometer:micrometer-tracing-bridge-otel` - bridges the Micrometer Observation API to OpenTelemetry.
|
||||
* `io.opentelemetry:opentelemetry-exporter-zipkin` - reports https://micrometer.io/docs/tracing#_glossary[traces] to Zipkin.
|
||||
|
||||
Add the following application properties:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
management:
|
||||
tracing:
|
||||
sampling:
|
||||
probability: 1.0
|
||||
----
|
||||
|
||||
By default, Spring Boot samples only 10% of requests to prevent overwhelming the trace backend.
|
||||
This property switches it to 100% so that every request is sent to the trace backend.
|
||||
|
||||
To collect and visualize the traces, we need a running trace backend.
|
||||
We use Zipkin as our trace backend here.
|
||||
The https://zipkin.io/pages/quickstart[Zipkin Quickstart guide] provides instructions how to start Zipkin locally.
|
||||
|
||||
After Zipkin is running, you can start your application.
|
||||
|
||||
If you open a web browser to `http://localhost:8080`, you should see the following output:
|
||||
|
||||
[source]
|
||||
----
|
||||
Hello World!
|
||||
----
|
||||
|
||||
Behind the scenes, an observation has been created for the HTTP request, which in turn gets bridged to OpenTelemetry, which reports a new trace to Zipkin.
|
||||
|
||||
Now open the Zipkin UI at `http://localhost:9411` and press the "Run Query" button to list all collected traces.
|
||||
You should see one trace.
|
||||
Press the "Show" button to see the details of that trace.
|
||||
|
||||
|
||||
|
||||
[[actuator.micrometer-tracing.logging]]
|
||||
== Logging Correlation IDs
|
||||
|
||||
Correlation IDs provide a helpful way to link lines in your log files to spans/traces.
|
||||
If you are using Micrometer Tracing, Spring Boot will include correlation IDs in your logs by default.
|
||||
|
||||
The default correlation ID is built from `traceId` and `spanId` https://logback.qos.ch/manual/mdc.html[MDC] values.
|
||||
For example, if Micrometer Tracing has added an MDC `traceId` of `803B448A0489F84084905D3093480352` and an MDC `spanId` of `3425F23BB2432450` the log output will include the correlation ID `[803B448A0489F84084905D3093480352-3425F23BB2432450]`.
|
||||
|
||||
If you prefer to use a different format for your correlation ID, you can use the configprop:logging.pattern.correlation[] property to define one.
|
||||
For example, the following will provide a correlation ID for Logback in format previously used by Spring Cloud Sleuth:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
logging:
|
||||
pattern:
|
||||
correlation: "[${spring.application.name:},%X{traceId:-},%X{spanId:-}] "
|
||||
include-application-name: false
|
||||
----
|
||||
|
||||
NOTE: In the example above, configprop:logging.include-application-name[] is set to `false` to avoid the application name being duplicated in the log messages (configprop:logging.pattern.correlation[] already contains it).
|
||||
It's also worth mentioning that configprop:logging.pattern.correlation[] contains a trailing space so that it is separated from the logger name that comes right after it by default.
|
||||
|
||||
|
||||
|
||||
[[actuator.micrometer-tracing.propagating-traces]]
|
||||
== Propagating Traces
|
||||
|
||||
To automatically propagate traces over the network, use the auto-configured xref:io/rest-client.adoc#io.rest-client.resttemplate[`RestTemplateBuilder`] or xref:io/rest-client.adoc#io.rest-client.webclient[`WebClient.Builder`] to construct the client.
|
||||
|
||||
WARNING: If you create the `WebClient` or the `RestTemplate` without using the auto-configured builders, automatic trace propagation won't work!
|
||||
|
||||
|
||||
|
||||
[[actuator.micrometer-tracing.tracer-implementations]]
|
||||
== Tracer Implementations
|
||||
|
||||
As Micrometer Tracer supports multiple tracer implementations, there are multiple dependency combinations possible with Spring Boot.
|
||||
|
||||
All tracer implementations need the `org.springframework.boot:spring-boot-starter-actuator` dependency.
|
||||
|
||||
|
||||
|
||||
[[actuator.micrometer-tracing.tracer-implementations.otel-zipkin]]
|
||||
=== OpenTelemetry With Zipkin
|
||||
|
||||
Tracing with OpenTelemetry and reporting to Zipkin requires the following dependencies:
|
||||
|
||||
* `io.micrometer:micrometer-tracing-bridge-otel` - bridges the Micrometer Observation API to OpenTelemetry.
|
||||
* `io.opentelemetry:opentelemetry-exporter-zipkin` - reports traces to Zipkin.
|
||||
|
||||
Use the `management.zipkin.tracing.*` configuration properties to configure reporting to Zipkin.
|
||||
|
||||
|
||||
|
||||
[[actuator.micrometer-tracing.tracer-implementations.otel-wavefront]]
|
||||
=== OpenTelemetry With Wavefront
|
||||
|
||||
Tracing with OpenTelemetry and reporting to Wavefront requires the following dependencies:
|
||||
|
||||
* `io.micrometer:micrometer-tracing-bridge-otel` - bridges the Micrometer Observation API to OpenTelemetry.
|
||||
* `io.micrometer:micrometer-tracing-reporter-wavefront` - reports traces to Wavefront.
|
||||
|
||||
Use the `management.wavefront.*` configuration properties to configure reporting to Wavefront.
|
||||
|
||||
|
||||
|
||||
[[actuator.micrometer-tracing.tracer-implementations.otel-otlp]]
|
||||
=== OpenTelemetry With OTLP
|
||||
|
||||
Tracing with OpenTelemetry and reporting using OTLP requires the following dependencies:
|
||||
|
||||
* `io.micrometer:micrometer-tracing-bridge-otel` - bridges the Micrometer Observation API to OpenTelemetry.
|
||||
* `io.opentelemetry:opentelemetry-exporter-otlp` - reports traces to a collector that can accept OTLP.
|
||||
|
||||
Use the `management.otlp.tracing.*` configuration properties to configure reporting using OTLP.
|
||||
|
||||
|
||||
|
||||
[[actuator.micrometer-tracing.tracer-implementations.brave-zipkin]]
|
||||
=== OpenZipkin Brave With Zipkin
|
||||
|
||||
Tracing with OpenZipkin Brave and reporting to Zipkin requires the following dependencies:
|
||||
|
||||
* `io.micrometer:micrometer-tracing-bridge-brave` - bridges the Micrometer Observation API to Brave.
|
||||
* `io.zipkin.reporter2:zipkin-reporter-brave` - reports traces to Zipkin.
|
||||
|
||||
NOTE: If your project doesn't use Spring MVC or Spring WebFlux, the `io.zipkin.reporter2:zipkin-sender-urlconnection` dependency is needed, too.
|
||||
|
||||
Use the `management.zipkin.tracing.*` configuration properties to configure reporting to Zipkin.
|
||||
|
||||
|
||||
|
||||
[[actuator.micrometer-tracing.tracer-implementations.brave-wavefront]]
|
||||
=== OpenZipkin Brave With Wavefront
|
||||
|
||||
Tracing with OpenZipkin Brave and reporting to Wavefront requires the following dependencies:
|
||||
|
||||
* `io.micrometer:micrometer-tracing-bridge-brave` - bridges the Micrometer Observation API to Brave.
|
||||
* `io.micrometer:micrometer-tracing-reporter-wavefront` - reports traces to Wavefront.
|
||||
|
||||
Use the `management.wavefront.*` configuration properties to configure reporting to Wavefront.
|
||||
|
||||
|
||||
|
||||
[[actuator.micrometer-tracing.micrometer-observation]]
|
||||
== Integration with Micrometer Observation
|
||||
|
||||
A `TracingAwareMeterObservationHandler` is automatically registered on the `ObservationRegistry`, which creates spans for every completed observation.
|
||||
|
||||
|
||||
|
||||
[[actuator.micrometer-tracing.creating-spans]]
|
||||
== Creating Custom Spans
|
||||
|
||||
You can create your own spans by starting an observation.
|
||||
For this, inject `ObservationRegistry` into your component:
|
||||
|
||||
include-code::CustomObservation[]
|
||||
|
||||
This will create an observation named "some-operation" with the tag "some-tag=some-value".
|
||||
|
||||
TIP: If you want to create a span without creating a metric, you need to use the https://micrometer.io/docs/tracing#_using_micrometer_tracing_directly[lower-level `Tracer` API] from Micrometer.
|
||||
|
||||
|
||||
|
||||
[[actuator.micrometer-tracing.baggage]]
|
||||
== Baggage
|
||||
|
||||
You can create baggage with the `Tracer` API:
|
||||
|
||||
include-code::CreatingBaggage[]
|
||||
|
||||
This example creates baggage named `baggage1` with the value `value1`.
|
||||
The baggage is automatically propagated over the network if you're using W3C propagation.
|
||||
If you're using B3 propagation, baggage is not automatically propagated.
|
||||
To manually propagate baggage over the network, use the configprop:management.tracing.baggage.remote-fields[] configuration property (this works for W3C, too).
|
||||
For the example above, setting this property to `baggage1` results in an HTTP header `baggage1: value1`.
|
||||
|
||||
If you want to propagate the baggage to the MDC, use the configprop:management.tracing.baggage.correlation.fields[] configuration property.
|
||||
For the example above, setting this property to `baggage1` results in an MDC entry named `baggage1`.
|
||||
|
||||
|
||||
|
||||
[[actuator.micrometer-tracing.tests]]
|
||||
== Tests
|
||||
|
||||
Tracing components which are reporting data are not auto-configured when using `@SpringBootTest`.
|
||||
See xref:features/testing.adoc#features.testing.spring-boot-applications.tracing[the testing section] for more details.
|
||||
@@ -0,0 +1,20 @@
|
||||
[[container-images.buildpacks]]
|
||||
= 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.
|
||||
If you’ve ever used an application platform such as Cloud Foundry or Heroku then you’ve probably used a buildpack.
|
||||
Buildpacks are the part of the platform that takes your application and converts it into something that the platform can actually run.
|
||||
For example, Cloud Foundry’s Java buildpack will notice that you’re pushing a `.jar` file and automatically add a relevant JRE.
|
||||
|
||||
With Cloud Native Buildpacks, you can create Docker compatible images that you can run anywhere.
|
||||
Spring Boot includes buildpack support directly for both Maven and Gradle.
|
||||
This means you can just type a single command and quickly get a sensible image into your locally running Docker daemon.
|
||||
|
||||
See the individual plugin documentation on how to use buildpacks with xref:maven-plugin:build-image.adoc#build-image[Maven] and xref:gradle-plugin:packaging-oci-image.adoc[Gradle].
|
||||
|
||||
NOTE: The https://github.com/paketo-buildpacks/spring-boot[Paketo Spring Boot buildpack] supports the `layers.idx` file, so any customization that is applied to it will be reflected in the image created by the buildpack.
|
||||
|
||||
NOTE: 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 configprop:spring.web.resources.cache.use-last-modified[].
|
||||
@@ -0,0 +1,64 @@
|
||||
[[container-images.dockerfiles]]
|
||||
= Dockerfiles
|
||||
|
||||
While it is possible to convert a Spring Boot uber jar into a docker image with just a few lines in the Dockerfile, we will use the xref:container-images/efficient-images.adoc#container-images.efficient-images.layering[layering feature] 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.
|
||||
With this jar on the classpath, you can launch your application in a special mode which allows the bootstrap code to run something entirely different from your application, for example, something that extracts the layers.
|
||||
|
||||
CAUTION: The `layertools` mode can not be used with a xref:deployment/installing.adoc[fully executable Spring Boot archive] that includes a launch script.
|
||||
Disable launch script configuration when building a jar file that is intended to be used with `layertools`.
|
||||
|
||||
Here’s how you can launch your jar with a `layertools` jar mode:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ java -Djarmode=layertools -jar my-app.jar
|
||||
----
|
||||
|
||||
This will provide the following output:
|
||||
|
||||
[subs="verbatim"]
|
||||
----
|
||||
Usage:
|
||||
java -Djarmode=layertools -jar my-app.jar
|
||||
|
||||
Available commands:
|
||||
list List layers from the jar that can be extracted
|
||||
extract Extracts layers from the jar for image creation
|
||||
help Help about any command
|
||||
----
|
||||
|
||||
The `extract` command can be used to easily split the application into layers to be added to the dockerfile.
|
||||
Here is an example of a Dockerfile using `jarmode`.
|
||||
|
||||
[source,dockerfile]
|
||||
----
|
||||
FROM eclipse-temurin:17-jre as builder
|
||||
WORKDIR application
|
||||
ARG JAR_FILE=target/*.jar
|
||||
COPY ${JAR_FILE} application.jar
|
||||
RUN java -Djarmode=layertools -jar application.jar extract
|
||||
|
||||
FROM eclipse-temurin:17-jre
|
||||
WORKDIR application
|
||||
COPY --from=builder application/dependencies/ ./
|
||||
COPY --from=builder application/spring-boot-loader/ ./
|
||||
COPY --from=builder application/snapshot-dependencies/ ./
|
||||
COPY --from=builder application/application/ ./
|
||||
ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"]
|
||||
----
|
||||
|
||||
Assuming the above `Dockerfile` is in the current directory, your docker image can be built with `docker build .`, or optionally specifying the path to your application jar, as shown in the following example:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ docker build --build-arg JAR_FILE=path/to/myapp.jar .
|
||||
----
|
||||
|
||||
This is a multi-stage dockerfile.
|
||||
The builder stage extracts the directories that are needed later.
|
||||
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.
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
[[container-images.efficient-images]]
|
||||
= Efficient Container Images
|
||||
|
||||
It is easily possible to package a Spring Boot uber jar as a docker image.
|
||||
However, there are various downsides to copying and running the uber jar as is in the docker image.
|
||||
There’s always a certain amount of overhead when running a uber jar without unpacking it, and in a containerized environment this can be noticeable.
|
||||
The other issue is that putting your application's code and all its dependencies in one layer in the Docker image is sub-optimal.
|
||||
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.layering]]
|
||||
== 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.
|
||||
The list of layers in the index is ordered based on the order in which the layers should be added to the Docker/OCI image.
|
||||
Out-of-the-box, the following layers are supported:
|
||||
|
||||
* `dependencies` (for regular released dependencies)
|
||||
* `spring-boot-loader` (for everything under `org/springframework/boot/loader`)
|
||||
* `snapshot-dependencies` (for snapshot dependencies)
|
||||
* `application` (for application classes and resources)
|
||||
|
||||
The following shows an example of a `layers.idx` file:
|
||||
|
||||
[source,yaml]
|
||||
----
|
||||
- "dependencies":
|
||||
- BOOT-INF/lib/library1.jar
|
||||
- BOOT-INF/lib/library2.jar
|
||||
- "spring-boot-loader":
|
||||
- org/springframework/boot/loader/launch/JarLauncher.class
|
||||
- ... <other classes>
|
||||
- "snapshot-dependencies":
|
||||
- BOOT-INF/lib/library3-SNAPSHOT.jar
|
||||
- "application":
|
||||
- META-INF/MANIFEST.MF
|
||||
- BOOT-INF/classes/a/b/C.class
|
||||
----
|
||||
|
||||
This layering is designed to separate code based on how likely it is to change between application builds.
|
||||
Library code is less likely to change between builds, so it is placed in its own layers to allow tooling to re-use the layers from cache.
|
||||
Application code is more likely to change between builds so it is isolated in a separate layer.
|
||||
|
||||
Spring Boot also supports layering for war files with the help of a `layers.idx`.
|
||||
|
||||
For Maven, see the xref:maven-plugin:packaging.adoc#packaging.layers[packaging layered jar or war section] for more details on adding a layer index to the archive.
|
||||
For Gradle, see the xref:gradle-plugin:packaging.adoc#packaging-executable.configuring.layered-archives[packaging layered jar or war section] of the Gradle plugin documentation.
|
||||
@@ -0,0 +1,4 @@
|
||||
[[container-images]]
|
||||
= Container Images
|
||||
|
||||
Spring Boot applications can be containerized xref:container-images/dockerfiles.adoc[using Dockerfiles], or by xref:container-images/cloud-native-buildpacks.adoc[using Cloud Native Buildpacks to create optimized docker compatible container images that you can run anywhere].
|
||||
@@ -0,0 +1,4 @@
|
||||
[[data]]
|
||||
= Data
|
||||
|
||||
Spring Boot integrates with a number of data technologies, both SQL and NoSQL.
|
||||
@@ -0,0 +1,712 @@
|
||||
[[data.nosql]]
|
||||
= Working with NoSQL Technologies
|
||||
|
||||
Spring Data provides additional projects that help you access a variety of NoSQL technologies, including:
|
||||
|
||||
* {url-spring-data-cassandra-site}[Cassandra]
|
||||
* {url-spring-data-couchbase-site}[Couchbase]
|
||||
* {url-spring-data-elasticsearch-site}[Elasticsearch]
|
||||
* {url-spring-data-gemfire-site}[GemFire] or {url-spring-data-geode-site}[Geode]
|
||||
* {url-spring-data-ldap-site}[LDAP]
|
||||
* {url-spring-data-mongodb-site}[MongoDB]
|
||||
* {url-spring-data-neo4j-site}[Neo4J]
|
||||
* {url-spring-data-redis-site}[Redis]
|
||||
|
||||
Of these, Spring Boot provides auto-configuration for Cassandra, Couchbase, Elasticsearch, LDAP, MongoDB, Neo4J and Redis.
|
||||
Additionally, {url-spring-boot-for-apache-geode-site}[Spring Boot for Apache Geode] provides {url-spring-boot-for-apache-geode-docs}#geode-repositories[auto-configuration for Apache Geode].
|
||||
You can make use of the other projects, but you must configure them yourself.
|
||||
See the appropriate reference documentation at {url-spring-data-site}.
|
||||
|
||||
Spring Boot also provides auto-configuration for the InfluxDB client but it is deprecated in favor of https://github.com/influxdata/influxdb-client-java[the new InfluxDB Java client] that provides its own Spring Boot integration.
|
||||
|
||||
|
||||
|
||||
[[data.nosql.redis]]
|
||||
== Redis
|
||||
|
||||
https://redis.io/[Redis] is a cache, message broker, and richly-featured key-value store.
|
||||
Spring Boot offers basic auto-configuration for the https://github.com/lettuce-io/lettuce-core/[Lettuce] and https://github.com/xetorthio/jedis/[Jedis] client libraries and the abstractions on top of them provided by https://github.com/spring-projects/spring-data-redis[Spring Data Redis].
|
||||
|
||||
There is a `spring-boot-starter-data-redis` "`Starter`" for collecting the dependencies in a convenient way.
|
||||
By default, it uses https://github.com/lettuce-io/lettuce-core/[Lettuce].
|
||||
That starter handles both traditional and reactive applications.
|
||||
|
||||
TIP: We also provide a `spring-boot-starter-data-redis-reactive` "`Starter`" for consistency with the other stores with reactive support.
|
||||
|
||||
|
||||
|
||||
[[data.nosql.redis.connecting]]
|
||||
=== Connecting to Redis
|
||||
|
||||
You can inject an auto-configured `RedisConnectionFactory`, `StringRedisTemplate`, or vanilla `RedisTemplate` instance as you would any other Spring Bean.
|
||||
The following listing shows an example of such a bean:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
By default, the instance tries to connect to a Redis server at `localhost:6379`.
|
||||
You can specify custom connection details using `spring.data.redis.*` properties, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
data:
|
||||
redis:
|
||||
host: "localhost"
|
||||
port: 6379
|
||||
database: 0
|
||||
username: "user"
|
||||
password: "secret"
|
||||
----
|
||||
|
||||
TIP: You can also register an arbitrary number of beans that implement `LettuceClientConfigurationBuilderCustomizer` for more advanced customizations.
|
||||
`ClientResources` can also be customized using `ClientResourcesBuilderCustomizer`.
|
||||
If you use Jedis, `JedisClientConfigurationBuilderCustomizer` is also available.
|
||||
Alternatively, you can register a bean of type `RedisStandaloneConfiguration`, `RedisSentinelConfiguration`, or `RedisClusterConfiguration` to take full control over the configuration.
|
||||
|
||||
If you add your own `@Bean` of any of the auto-configured types, it replaces the default (except in the case of `RedisTemplate`, when the exclusion is based on the bean name, `redisTemplate`, not its type).
|
||||
|
||||
By default, a pooled connection factory is auto-configured if `commons-pool2` is on the classpath.
|
||||
|
||||
The auto-configured `RedisConnectionFactory` can be configured to use SSL for communication with the server by setting the properties as shown in this example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
data:
|
||||
redis:
|
||||
ssl:
|
||||
enabled: true
|
||||
----
|
||||
|
||||
Custom SSL trust material can be configured in an xref:features/ssl.adoc[SSL bundle] and applied to the `RedisConnectionFactory` as shown in this example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
data:
|
||||
redis:
|
||||
ssl:
|
||||
bundle: "example"
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[data.nosql.mongodb]]
|
||||
== MongoDB
|
||||
|
||||
https://www.mongodb.com/[MongoDB] is an open-source NoSQL document database that uses a JSON-like schema instead of traditional table-based relational data.
|
||||
Spring Boot offers several conveniences for working with MongoDB, including the `spring-boot-starter-data-mongodb` and `spring-boot-starter-data-mongodb-reactive` "`Starters`".
|
||||
|
||||
|
||||
|
||||
[[data.nosql.mongodb.connecting]]
|
||||
=== 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`.
|
||||
The following example shows how to connect to a MongoDB database:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
If you have defined your own `MongoClient`, it will be used to auto-configure a suitable `MongoDatabaseFactory`.
|
||||
|
||||
The auto-configured `MongoClient` is created using a `MongoClientSettings` bean.
|
||||
If you have defined your own `MongoClientSettings`, it will be used without modification and the `spring.data.mongodb` properties will be ignored.
|
||||
Otherwise a `MongoClientSettings` will be auto-configured and will have the `spring.data.mongodb` properties applied to it.
|
||||
In either case, you can declare one or more `MongoClientSettingsBuilderCustomizer` beans to fine-tune the `MongoClientSettings` configuration.
|
||||
Each will be called in order with the `MongoClientSettings.Builder` that is used to build the `MongoClientSettings`.
|
||||
|
||||
You can set the configprop:spring.data.mongodb.uri[] property to change the URL and configure additional settings such as the _replica set_, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
data:
|
||||
mongodb:
|
||||
uri: "mongodb://user:secret@mongoserver1.example.com:27017,mongoserver2.example.com:23456/test"
|
||||
----
|
||||
|
||||
Alternatively, you can specify connection details using discrete properties.
|
||||
For example, you might declare the following settings in your `application.properties`:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
data:
|
||||
mongodb:
|
||||
host: "mongoserver1.example.com"
|
||||
port: 27017
|
||||
additional-hosts:
|
||||
- "mongoserver2.example.com:23456"
|
||||
database: "test"
|
||||
username: "user"
|
||||
password: "secret"
|
||||
----
|
||||
|
||||
The auto-configured `MongoClient` can be configured to use SSL for communication with the server by setting the properties as shown in this example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
data:
|
||||
mongodb:
|
||||
uri: "mongodb://user:secret@mongoserver1.example.com:27017,mongoserver2.example.com:23456/test"
|
||||
ssl:
|
||||
enabled: true
|
||||
----
|
||||
|
||||
Custom SSL trust material can be configured in an xref:features/ssl.adoc[SSL bundle] and applied to the `MongoClient` as shown in this example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
data:
|
||||
mongodb:
|
||||
uri: "mongodb://user:secret@mongoserver1.example.com:27017,mongoserver2.example.com:23456/test"
|
||||
ssl:
|
||||
bundle: "example"
|
||||
----
|
||||
|
||||
|
||||
[TIP]
|
||||
====
|
||||
If `spring.data.mongodb.port` is not specified, the default of `27017` is used.
|
||||
You could delete this line from the example shown earlier.
|
||||
|
||||
You can also specify the port as part of the host address by using the `host:port` syntax.
|
||||
This format should be used if you need to change the port of an `additional-hosts` entry.
|
||||
====
|
||||
|
||||
TIP: If you do not use Spring Data MongoDB, you can inject a `MongoClient` bean instead of using `MongoDatabaseFactory`.
|
||||
If you want to take complete control of establishing the MongoDB connection, you can also declare your own `MongoDatabaseFactory` or `MongoClient` bean.
|
||||
|
||||
NOTE: If you are using the reactive driver, Netty is required for SSL.
|
||||
The auto-configuration configures this factory automatically if Netty is available and the factory to use has not been customized already.
|
||||
|
||||
|
||||
|
||||
[[data.nosql.mongodb.template]]
|
||||
=== MongoTemplate
|
||||
|
||||
{url-spring-data-mongodb-site}[Spring Data MongoDB] provides a {url-spring-data-mongodb-javadoc}/org/springframework/data/mongodb/core/MongoTemplate.html[`MongoTemplate`] class that is very similar in its design to Spring's `JdbcTemplate`.
|
||||
As with `JdbcTemplate`, Spring Boot auto-configures a bean for you to inject the template, as follows:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
See the {url-spring-data-mongodb-javadoc}/org/springframework/data/mongodb/core/MongoOperations.html[`MongoOperations` Javadoc] for complete details.
|
||||
|
||||
|
||||
|
||||
[[data.nosql.mongodb.repositories]]
|
||||
=== Spring Data MongoDB Repositories
|
||||
|
||||
Spring Data includes repository support for MongoDB.
|
||||
As with the JPA repositories discussed earlier, the basic principle is that queries are constructed automatically, based on method names.
|
||||
|
||||
In fact, both Spring Data JPA and Spring Data MongoDB share the same common infrastructure.
|
||||
You could take the JPA example from earlier and, assuming that `City` is now a MongoDB data class rather than a JPA `@Entity`, it works in the same way, as shown in the following example:
|
||||
|
||||
include-code::CityRepository[]
|
||||
|
||||
Repositories and documents are found through scanning.
|
||||
By default, the xref:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages] are scanned.
|
||||
You can customize the locations to look for repositories and documents by using `@EnableMongoRepositories` and `@EntityScan` respectively.
|
||||
|
||||
TIP: For complete details of Spring Data MongoDB, including its rich object mapping technologies, see its {url-spring-data-mongodb-docs}[reference documentation].
|
||||
|
||||
|
||||
|
||||
[[data.nosql.neo4j]]
|
||||
== Neo4j
|
||||
|
||||
https://neo4j.com/[Neo4j] is an open-source NoSQL graph database that uses a rich data model of nodes connected by first class relationships, which is better suited for connected big data than traditional RDBMS approaches.
|
||||
Spring Boot offers several conveniences for working with Neo4j, including the `spring-boot-starter-data-neo4j` "`Starter`".
|
||||
|
||||
|
||||
|
||||
[[data.nosql.neo4j.connecting]]
|
||||
=== 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.
|
||||
The following example shows how to inject a Neo4j `Driver` that gives you access, amongst other things, to a `Session`:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
You can configure various aspects of the driver using `spring.neo4j.*` properties.
|
||||
The following example shows how to configure the uri and credentials to use:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
neo4j:
|
||||
uri: "bolt://my-server:7687"
|
||||
authentication:
|
||||
username: "neo4j"
|
||||
password: "secret"
|
||||
----
|
||||
|
||||
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]]
|
||||
=== Spring Data Neo4j Repositories
|
||||
|
||||
Spring Data includes repository support for Neo4j.
|
||||
For complete details of Spring Data Neo4j, see the {url-spring-data-neo4j-docs}[reference documentation].
|
||||
|
||||
Spring Data Neo4j shares the common infrastructure with Spring Data JPA as many other Spring Data modules do.
|
||||
You could take the JPA example from earlier and define `City` as Spring Data Neo4j `@Node` rather than JPA `@Entity` and the repository abstraction works in the same way, as shown in the following example:
|
||||
|
||||
include-code::CityRepository[]
|
||||
|
||||
The `spring-boot-starter-data-neo4j` "`Starter`" enables the repository support as well as transaction management.
|
||||
Spring Boot supports both classic and reactive Neo4j repositories, using the `Neo4jTemplate` or `ReactiveNeo4jTemplate` beans.
|
||||
When Project Reactor is available on the classpath, the reactive style is also auto-configured.
|
||||
|
||||
Repositories and entities are found through scanning.
|
||||
By default, the xref:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages] are scanned.
|
||||
You can customize the locations to look for repositories and entities by using `@EnableNeo4jRepositories` and `@EntityScan` respectively.
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
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:
|
||||
|
||||
include-code::MyNeo4jConfiguration[]
|
||||
====
|
||||
|
||||
|
||||
|
||||
[[data.nosql.elasticsearch]]
|
||||
== Elasticsearch
|
||||
|
||||
https://www.elastic.co/products/elasticsearch[Elasticsearch] is an open source, distributed, RESTful search and analytics engine.
|
||||
Spring Boot offers basic auto-configuration for Elasticsearch clients.
|
||||
|
||||
Spring Boot supports several clients:
|
||||
|
||||
* The official low-level REST client
|
||||
* The official Java API client
|
||||
* The `ReactiveElasticsearchClient` provided by Spring Data Elasticsearch
|
||||
|
||||
Spring Boot provides a dedicated "`Starter`", `spring-boot-starter-data-elasticsearch`.
|
||||
|
||||
|
||||
|
||||
[[data.nosql.elasticsearch.connecting-using-rest]]
|
||||
=== Connecting to Elasticsearch Using REST clients
|
||||
|
||||
Elasticsearch ships two different REST clients that you can use to query a cluster: the https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/java-rest-low.html[low-level client] from the `org.elasticsearch.client:elasticsearch-rest-client` module and the https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/index.html[Java API client] from the `co.elastic.clients:elasticsearch-java` module.
|
||||
Additionally, Spring Boot provides support for a reactive client from the `org.springframework.data:spring-data-elasticsearch` module.
|
||||
By default, the clients will target `http://localhost:9200`.
|
||||
You can use `spring.elasticsearch.*` properties to further tune how the clients are configured, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
elasticsearch:
|
||||
uris: "https://search.example.com:9200"
|
||||
socket-timeout: "10s"
|
||||
username: "user"
|
||||
password: "secret"
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[data.nosql.elasticsearch.connecting-using-rest.restclient]]
|
||||
==== Connecting to Elasticsearch Using RestClient
|
||||
|
||||
If you have `elasticsearch-rest-client` on the classpath, Spring Boot will auto-configure and register a `RestClient` bean.
|
||||
In addition to the properties described previously, to fine-tune the `RestClient` you can register an arbitrary number of beans that implement `RestClientBuilderCustomizer` for more advanced customizations.
|
||||
To take full control over the clients' configuration, define a `RestClientBuilder` bean.
|
||||
|
||||
|
||||
|
||||
Additionally, if `elasticsearch-rest-client-sniffer` is on the classpath, a `Sniffer` is auto-configured to automatically discover nodes from a running Elasticsearch cluster and set them on the `RestClient` bean.
|
||||
You can further tune how `Sniffer` is configured, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
elasticsearch:
|
||||
restclient:
|
||||
sniffer:
|
||||
interval: "10m"
|
||||
delay-after-failure: "30s"
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[data.nosql.elasticsearch.connecting-using-rest.javaapiclient]]
|
||||
==== Connecting to Elasticsearch Using ElasticsearchClient
|
||||
|
||||
If you have `co.elastic.clients:elasticsearch-java` on the classpath, Spring Boot will auto-configure and register an `ElasticsearchClient` bean.
|
||||
|
||||
The `ElasticsearchClient` uses a transport that depends upon the previously described `RestClient`.
|
||||
Therefore, the properties described previously can be used to configure the `ElasticsearchClient`.
|
||||
Furthermore, you can define a `RestClientOptions` bean to take further control of the behavior of the transport.
|
||||
|
||||
|
||||
|
||||
[[data.nosql.elasticsearch.connecting-using-rest.reactiveclient]]
|
||||
==== Connecting to Elasticsearch using ReactiveElasticsearchClient
|
||||
|
||||
{url-spring-data-elasticsearch-site}[Spring Data Elasticsearch] ships `ReactiveElasticsearchClient` for querying Elasticsearch instances in a reactive fashion.
|
||||
If you have Spring Data Elasticsearch and Reactor on the classpath, Spring Boot will auto-configure and register a `ReactiveElasticsearchClient`.
|
||||
|
||||
The `ReactiveElasticsearchclient` uses a transport that depends upon the previously described `RestClient`.
|
||||
Therefore, the properties described previously can be used to configure the `ReactiveElasticsearchClient`.
|
||||
Furthermore, you can define a `RestClientOptions` bean to take further control of the behavior of the transport.
|
||||
|
||||
|
||||
|
||||
[[data.nosql.elasticsearch.connecting-using-spring-data]]
|
||||
=== Connecting to Elasticsearch by Using Spring Data
|
||||
|
||||
To connect to Elasticsearch, an `ElasticsearchClient` bean must be defined,
|
||||
auto-configured by Spring Boot or manually provided by the application (see previous sections).
|
||||
With this configuration in place, an
|
||||
`ElasticsearchTemplate` can be injected like any other Spring bean,
|
||||
as shown in the following example:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
In the presence of `spring-data-elasticsearch` and Reactor, Spring Boot can also auto-configure a xref:data/nosql.adoc#data.nosql.elasticsearch.connecting-using-rest.reactiveclient[ReactiveElasticsearchClient] and a `ReactiveElasticsearchTemplate` as beans.
|
||||
They are the reactive equivalent of the other REST clients.
|
||||
|
||||
|
||||
|
||||
[[data.nosql.elasticsearch.repositories]]
|
||||
=== Spring Data Elasticsearch Repositories
|
||||
|
||||
Spring Data includes repository support for Elasticsearch.
|
||||
As with the JPA repositories discussed earlier, the basic principle is that queries are constructed for you automatically based on method names.
|
||||
|
||||
In fact, both Spring Data JPA and Spring Data Elasticsearch share the same common infrastructure.
|
||||
You could take the JPA example from earlier and, assuming that `City` is now an Elasticsearch `@Document` class rather than a JPA `@Entity`, it works in the same way.
|
||||
|
||||
Repositories and documents are found through scanning.
|
||||
By default, the xref:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages] are scanned.
|
||||
You can customize the locations to look for repositories and documents by using `@EnableElasticsearchRepositories` and `@EntityScan` respectively.
|
||||
|
||||
TIP: For complete details of Spring Data Elasticsearch, see the {url-spring-data-elasticsearch-docs}[reference documentation].
|
||||
|
||||
Spring Boot supports both classic and reactive Elasticsearch repositories, using the `ElasticsearchRestTemplate` or `ReactiveElasticsearchTemplate` beans.
|
||||
Most likely those beans are auto-configured by Spring Boot given the required dependencies are present.
|
||||
|
||||
If you wish to use your own template for backing the Elasticsearch repositories, you can add your own `ElasticsearchRestTemplate` or `ElasticsearchOperations` `@Bean`, as long as it is named `"elasticsearchTemplate"`.
|
||||
Same applies to `ReactiveElasticsearchTemplate` and `ReactiveElasticsearchOperations`, with the bean name `"reactiveElasticsearchTemplate"`.
|
||||
|
||||
You can choose to disable the repositories support with the following property:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
data:
|
||||
elasticsearch:
|
||||
repositories:
|
||||
enabled: false
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[data.nosql.cassandra]]
|
||||
== Cassandra
|
||||
|
||||
https://cassandra.apache.org/[Cassandra] is an open source, distributed database management system designed to handle large amounts of data across many commodity servers.
|
||||
Spring Boot offers auto-configuration for Cassandra and the abstractions on top of it provided by {url-spring-data-cassandra-site}[Spring Data Cassandra].
|
||||
There is a `spring-boot-starter-data-cassandra` "`Starter`" for collecting the dependencies in a convenient way.
|
||||
|
||||
|
||||
|
||||
[[data.nosql.cassandra.connecting]]
|
||||
=== 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.cassandra.*` properties can be used to customize the connection.
|
||||
Generally, you provide `keyspace-name` and `contact-points` as well the local datacenter name, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
cassandra:
|
||||
keyspace-name: "mykeyspace"
|
||||
contact-points: "cassandrahost1:9042,cassandrahost2:9042"
|
||||
local-datacenter: "datacenter1"
|
||||
----
|
||||
|
||||
If the port is the same for all your contact points you can use a shortcut and only specify the host names, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
cassandra:
|
||||
keyspace-name: "mykeyspace"
|
||||
contact-points: "cassandrahost1,cassandrahost2"
|
||||
local-datacenter: "datacenter1"
|
||||
----
|
||||
|
||||
TIP: Those two examples are identical as the port default to `9042`.
|
||||
If you need to configure the port, use `spring.cassandra.port`.
|
||||
|
||||
The auto-configured `CqlSession` can be configured to use SSL for communication with the server by setting the properties as shown in this example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
cassandra:
|
||||
keyspace-name: "mykeyspace"
|
||||
contact-points: "cassandrahost1,cassandrahost2"
|
||||
local-datacenter: "datacenter1"
|
||||
ssl:
|
||||
enabled: true
|
||||
----
|
||||
|
||||
Custom SSL trust material can be configured in an xref:features/ssl.adoc[SSL bundle] and applied to the `CqlSession` as shown in this example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
cassandra:
|
||||
keyspace-name: "mykeyspace"
|
||||
contact-points: "cassandrahost1,cassandrahost2"
|
||||
local-datacenter: "datacenter1"
|
||||
ssl:
|
||||
bundle: "example"
|
||||
----
|
||||
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
The Cassandra driver has its own configuration infrastructure that loads an `application.conf` at the root of the classpath.
|
||||
|
||||
Spring Boot does not look for such a file by default but can load one using `spring.cassandra.config`.
|
||||
If a property is both present in `+spring.cassandra.*+` and the configuration file, the value in `+spring.cassandra.*+` takes precedence.
|
||||
|
||||
For more advanced driver customizations, you can register an arbitrary number of beans that implement `DriverConfigLoaderBuilderCustomizer`.
|
||||
The `CqlSession` can be customized with a bean of type `CqlSessionBuilderCustomizer`.
|
||||
====
|
||||
|
||||
NOTE: If you use `CqlSessionBuilder` to create multiple `CqlSession` beans, keep in mind the builder is mutable so make sure to inject a fresh copy for each session.
|
||||
|
||||
The following code listing shows how to inject a Cassandra bean:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
If you add your own `@Bean` of type `CassandraTemplate`, it replaces the default.
|
||||
|
||||
|
||||
|
||||
[[data.nosql.cassandra.repositories]]
|
||||
=== Spring Data Cassandra Repositories
|
||||
|
||||
Spring Data includes basic repository support for Cassandra.
|
||||
Currently, this is more limited than the JPA repositories discussed earlier and needs `@Query` annotated finder methods.
|
||||
|
||||
Repositories and entities are found through scanning.
|
||||
By default, the xref:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages] are scanned.
|
||||
You can customize the locations to look for repositories and entities by using `@EnableCassandraRepositories` and `@EntityScan` respectively.
|
||||
|
||||
TIP: For complete details of Spring Data Cassandra, see the https://docs.spring.io/spring-data/cassandra/docs/[reference documentation].
|
||||
|
||||
|
||||
|
||||
[[data.nosql.couchbase]]
|
||||
== Couchbase
|
||||
|
||||
https://www.couchbase.com/[Couchbase] is an open-source, distributed, multi-model NoSQL document-oriented database that is optimized for interactive applications.
|
||||
Spring Boot offers auto-configuration for Couchbase and the abstractions on top of it provided by https://github.com/spring-projects/spring-data-couchbase[Spring Data Couchbase].
|
||||
There are `spring-boot-starter-data-couchbase` and `spring-boot-starter-data-couchbase-reactive` "`Starters`" for collecting the dependencies in a convenient way.
|
||||
|
||||
|
||||
|
||||
[[data.nosql.couchbase.connecting]]
|
||||
=== 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.
|
||||
Generally, you provide the https://github.com/couchbaselabs/sdk-rfcs/blob/master/rfc/0011-connection-string.md[connection string], username, and password, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
couchbase:
|
||||
connection-string: "couchbase://192.168.1.123"
|
||||
username: "user"
|
||||
password: "secret"
|
||||
----
|
||||
|
||||
It is also possible to customize some of the `ClusterEnvironment` settings.
|
||||
For instance, the following configuration changes the timeout to open a new `Bucket` and enables SSL support with a reference to a configured xref:features/ssl.adoc[SSL bundle]:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
couchbase:
|
||||
env:
|
||||
timeouts:
|
||||
connect: "3s"
|
||||
ssl:
|
||||
bundle: "example"
|
||||
----
|
||||
|
||||
TIP: 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]]
|
||||
=== Spring Data Couchbase Repositories
|
||||
|
||||
Spring Data includes repository support for Couchbase.
|
||||
|
||||
Repositories and documents are found through scanning.
|
||||
By default, the xref:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages] are scanned.
|
||||
You can customize the locations to look for repositories and documents by using `@EnableCouchbaseRepositories` and `@EntityScan` respectively.
|
||||
|
||||
For complete details of Spring Data Couchbase, see the {url-spring-data-couchbase-docs}[reference documentation].
|
||||
|
||||
You can inject an auto-configured `CouchbaseTemplate` instance as you would with any other Spring Bean, provided a `CouchbaseClientFactory` bean is available.
|
||||
This happens when a `Cluster` is available, as described above, and a bucket name has been specified:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
data:
|
||||
couchbase:
|
||||
bucket-name: "my-bucket"
|
||||
----
|
||||
|
||||
The following examples shows how to inject a `CouchbaseTemplate` bean:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
There are a few beans that you can define in your own configuration to override those provided by the auto-configuration:
|
||||
|
||||
* A `CouchbaseMappingContext` `@Bean` with a name of `couchbaseMappingContext`.
|
||||
* A `CustomConversions` `@Bean` with a name of `couchbaseCustomConversions`.
|
||||
* A `CouchbaseTemplate` `@Bean` with a name of `couchbaseTemplate`.
|
||||
|
||||
To avoid hard-coding those names in your own config, you can reuse `BeanNames` provided by Spring Data Couchbase.
|
||||
For instance, you can customize the converters to use, as follows:
|
||||
|
||||
include-code::MyCouchbaseConfiguration[]
|
||||
|
||||
|
||||
|
||||
[[data.nosql.ldap]]
|
||||
== LDAP
|
||||
|
||||
https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol[LDAP] (Lightweight Directory Access Protocol) is an open, vendor-neutral, industry standard application protocol for accessing and maintaining distributed directory information services over an IP network.
|
||||
Spring Boot offers auto-configuration for any compliant LDAP server as well as support for the embedded in-memory LDAP server from https://ldap.com/unboundid-ldap-sdk-for-java/[UnboundID].
|
||||
|
||||
LDAP abstractions are provided by https://github.com/spring-projects/spring-data-ldap[Spring Data LDAP].
|
||||
There is a `spring-boot-starter-data-ldap` "`Starter`" for collecting the dependencies in a convenient way.
|
||||
|
||||
|
||||
|
||||
[[data.nosql.ldap.connecting]]
|
||||
=== Connecting to an LDAP Server
|
||||
|
||||
To connect to an LDAP server, make sure you declare a dependency on the `spring-boot-starter-data-ldap` "`Starter`" or `spring-ldap-core` and then declare the URLs of your server in your application.properties, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
ldap:
|
||||
urls: "ldap://myserver:1235"
|
||||
username: "admin"
|
||||
password: "secret"
|
||||
----
|
||||
|
||||
If you need to customize connection settings, you can use the `spring.ldap.base` and `spring.ldap.base-environment` properties.
|
||||
|
||||
An `LdapContextSource` is auto-configured based on these settings.
|
||||
If a `DirContextAuthenticationStrategy` bean is available, it is associated to the auto-configured `LdapContextSource`.
|
||||
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]]
|
||||
=== Spring Data LDAP Repositories
|
||||
|
||||
Spring Data includes repository support for LDAP.
|
||||
|
||||
Repositories and documents are found through scanning.
|
||||
By default, the xref:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages] are scanned.
|
||||
You can customize the locations to look for repositories and documents by using `@EnableLdapRepositories` and `@EntityScan` respectively.
|
||||
|
||||
For complete details of Spring Data LDAP, see the https://docs.spring.io/spring-data/ldap/docs/1.0.x/reference/html/[reference documentation].
|
||||
|
||||
You can also inject an auto-configured `LdapTemplate` instance as you would with any other Spring Bean, as shown in the following example:
|
||||
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
|
||||
|
||||
[[data.nosql.ldap.embedded]]
|
||||
=== Embedded In-memory LDAP Server
|
||||
|
||||
For testing purposes, Spring Boot supports auto-configuration of an in-memory LDAP server from https://ldap.com/unboundid-ldap-sdk-for-java/[UnboundID].
|
||||
To configure the server, add a dependency to `com.unboundid:unboundid-ldapsdk` and declare a configprop:spring.ldap.embedded.base-dn[] property, as follows:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
ldap:
|
||||
embedded:
|
||||
base-dn: "dc=spring,dc=io"
|
||||
----
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
It is possible to define multiple base-dn values, however, since distinguished names usually contain commas, they must be defined using the correct notation.
|
||||
|
||||
In yaml files, you can use the yaml list notation. In properties files, you must include the index as part of the property name:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring.ldap.embedded.base-dn:
|
||||
- "dc=spring,dc=io"
|
||||
- "dc=vmware,dc=com"
|
||||
----
|
||||
====
|
||||
|
||||
By default, the server starts on a random port and triggers the regular LDAP support.
|
||||
There is no need to specify a configprop:spring.ldap.urls[] property.
|
||||
|
||||
If there is a `schema.ldif` file on your classpath, it is used to initialize the server.
|
||||
If you want to load the initialization script from a different resource, you can also use the configprop:spring.ldap.embedded.ldif[] property.
|
||||
|
||||
By default, a standard schema is used to validate `LDIF` files.
|
||||
You can turn off validation altogether by setting the configprop:spring.ldap.embedded.validation.enabled[] property.
|
||||
If you have custom attributes, you can use configprop:spring.ldap.embedded.validation.schema[] to define your custom attribute types or object classes.
|
||||
|
||||
|
||||
|
||||
[[data.nosql.influxdb]]
|
||||
== InfluxDB
|
||||
|
||||
WARNING: Auto-configuration for InfluxDB is deprecated and scheduled for removal in Spring Boot 3.4 in favor of https://github.com/influxdata/influxdb-client-java[the new InfluxDB Java client] that provides its own Spring Boot integration.
|
||||
|
||||
https://www.influxdata.com/[InfluxDB] is an open-source time series database optimized for fast, high-availability storage and retrieval of time series data in fields such as operations monitoring, application metrics, Internet-of-Things sensor data, and real-time analytics.
|
||||
|
||||
|
||||
|
||||
[[data.nosql.influxdb.connecting]]
|
||||
=== 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 using configprop:spring.influx.url[deprecated].
|
||||
|
||||
If the connection to InfluxDB requires a user and password, you can set the configprop:spring.influx.user[deprecated] and configprop:spring.influx.password[deprecated] properties accordingly.
|
||||
|
||||
InfluxDB relies on OkHttp.
|
||||
If you need to tune the http client `InfluxDB` uses behind the scenes, you can register an `InfluxDbOkHttpClientBuilderProvider` bean.
|
||||
|
||||
If you need more control over the configuration, consider registering an `InfluxDbCustomizer` bean.
|
||||
@@ -0,0 +1,554 @@
|
||||
[[data.sql]]
|
||||
= SQL Databases
|
||||
|
||||
The {url-spring-framework-site}[Spring Framework] provides extensive support for working with SQL databases, from direct JDBC access using `JdbcClient` or `JdbcTemplate` to complete "`object relational mapping`" technologies such as Hibernate.
|
||||
{url-spring-data-site}[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]]
|
||||
== Configure a DataSource
|
||||
|
||||
Java's `javax.sql.DataSource` interface provides a standard method of working with database connections.
|
||||
Traditionally, a `DataSource` uses a `URL` along with some credentials to establish a database connection.
|
||||
|
||||
TIP: See xref:how-to:data-access.adoc#howto.data-access.configure-custom-datasource[the "`How-to`" section] for more advanced examples, typically to take full control over the configuration of the DataSource.
|
||||
|
||||
|
||||
|
||||
[[data.sql.datasource.embedded]]
|
||||
=== Embedded Database Support
|
||||
|
||||
It is often convenient to develop applications by using an in-memory embedded database.
|
||||
Obviously, in-memory databases do not provide persistent storage.
|
||||
You need to populate your database when your application starts and be prepared to throw away data when your application ends.
|
||||
|
||||
TIP: The "`How-to`" section includes a xref:how-to:data-initialization.adoc[section on how to initialize a database].
|
||||
|
||||
Spring Boot can auto-configure embedded https://www.h2database.com[H2], https://hsqldb.org/[HSQL], and https://db.apache.org/derby/[Derby] databases.
|
||||
You need not provide any connection URLs.
|
||||
You need only include a build dependency to the embedded database that you want to use.
|
||||
If there are multiple embedded databases on the classpath, set the configprop:spring.datasource.embedded-database-connection[] configuration property to control which one is used.
|
||||
Setting the property to `none` disables auto-configuration of an embedded database.
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
If you are using this feature in your tests, you may notice that the same database is reused by your whole test suite regardless of the number of application contexts that you use.
|
||||
If you want to make sure that each context has a separate embedded database, you should set `spring.datasource.generate-unique-name` to `true`.
|
||||
====
|
||||
|
||||
For example, the typical POM dependencies would be as follows:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hsqldb</groupId>
|
||||
<artifactId>hsqldb</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
----
|
||||
|
||||
NOTE: You need a dependency on `spring-jdbc` for an embedded database to be auto-configured.
|
||||
In this example, it is pulled in transitively through `spring-boot-starter-data-jpa`.
|
||||
|
||||
TIP: If, for whatever reason, you do configure the connection URL for an embedded database, take care to ensure that the database's automatic shutdown is disabled.
|
||||
If you use H2, you should use `DB_CLOSE_ON_EXIT=FALSE` to do so.
|
||||
If you use HSQLDB, you should ensure that `shutdown=true` is not used.
|
||||
Disabling the database's automatic shutdown lets Spring Boot control when the database is closed, thereby ensuring that it happens once access to the database is no longer needed.
|
||||
|
||||
|
||||
|
||||
[[data.sql.datasource.production]]
|
||||
=== Connection to a Production Database
|
||||
|
||||
Production database connections can also be auto-configured by using a pooling `DataSource`.
|
||||
|
||||
|
||||
|
||||
[[data.sql.datasource.configuration]]
|
||||
=== DataSource Configuration
|
||||
|
||||
DataSource configuration is controlled by external configuration properties in `+spring.datasource.*+`.
|
||||
For example, you might declare the following section in `application.properties`:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
datasource:
|
||||
url: "jdbc:mysql://localhost/test"
|
||||
username: "dbuser"
|
||||
password: "dbpass"
|
||||
----
|
||||
|
||||
NOTE: You should at least specify the URL by setting the configprop:spring.datasource.url[] property.
|
||||
Otherwise, Spring Boot tries to auto-configure an embedded database.
|
||||
|
||||
TIP: Spring Boot can deduce the JDBC driver class for most databases from the URL.
|
||||
If you need to specify a specific class, you can use the configprop:spring.datasource.driver-class-name[] property.
|
||||
|
||||
NOTE: For a pooling `DataSource` to be created, we need to be able to verify that a valid `Driver` class is available, so we check for that before doing anything.
|
||||
In other words, if you set `spring.datasource.driver-class-name=com.mysql.jdbc.Driver`, then that class has to be loadable.
|
||||
|
||||
See {code-spring-boot-autoconfigure-src}/jdbc/DataSourceProperties.java[`DataSourceProperties`] for more of the supported options.
|
||||
These are the standard options that work regardless of xref:data/sql.adoc#data.sql.datasource.connection-pool[the actual implementation].
|
||||
It is also possible to fine-tune implementation-specific settings by using their respective prefix (`+spring.datasource.hikari.*+`, `+spring.datasource.tomcat.*+`, `+spring.datasource.dbcp2.*+`, and `+spring.datasource.oracleucp.*+`).
|
||||
See the documentation of the connection pool implementation you are using for more details.
|
||||
|
||||
For instance, if you use the {url-tomcat-docs}/jdbc-pool.html#Common_Attributes[Tomcat connection pool], you could customize many additional settings, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
datasource:
|
||||
tomcat:
|
||||
max-wait: 10000
|
||||
max-active: 50
|
||||
test-on-borrow: true
|
||||
----
|
||||
|
||||
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]]
|
||||
=== Supported Connection Pools
|
||||
|
||||
Spring Boot uses the following algorithm for choosing a specific implementation:
|
||||
|
||||
. We prefer https://github.com/brettwooldridge/HikariCP[HikariCP] for its performance and concurrency.
|
||||
If HikariCP is available, we always choose it.
|
||||
. Otherwise, if the Tomcat pooling `DataSource` is available, we use it.
|
||||
. Otherwise, if https://commons.apache.org/proper/commons-dbcp/[Commons DBCP2] is available, we use it.
|
||||
. If none of HikariCP, Tomcat, and DBCP2 are available and if Oracle UCP is available, we use it.
|
||||
|
||||
NOTE: If you use the `spring-boot-starter-jdbc` or `spring-boot-starter-data-jpa` "`starters`", you automatically get a dependency to `HikariCP`.
|
||||
|
||||
You can bypass that algorithm completely and specify the connection pool to use by setting the configprop:spring.datasource.type[] property.
|
||||
This is especially important if you run your application in a Tomcat container, as `tomcat-jdbc` is provided by default.
|
||||
|
||||
Additional connection pools can always be configured manually, using `DataSourceBuilder`.
|
||||
If you define your own `DataSource` bean, auto-configuration does not occur.
|
||||
The following connection pools are supported by `DataSourceBuilder`:
|
||||
|
||||
* HikariCP
|
||||
* Tomcat pooling `Datasource`
|
||||
* Commons DBCP2
|
||||
* Oracle UCP & `OracleDataSource`
|
||||
* Spring Framework's `SimpleDriverDataSource`
|
||||
* H2 `JdbcDataSource`
|
||||
* PostgreSQL `PGSimpleDataSource`
|
||||
* C3P0
|
||||
|
||||
|
||||
|
||||
[[data.sql.datasource.jndi]]
|
||||
=== Connection to a JNDI DataSource
|
||||
|
||||
If you deploy your Spring Boot application to an Application Server, you might want to configure and manage your DataSource by using your Application Server's built-in features and access it by using JNDI.
|
||||
|
||||
The configprop:spring.datasource.jndi-name[] property can be used as an alternative to the configprop:spring.datasource.url[], configprop:spring.datasource.username[], and configprop:spring.datasource.password[] properties to access the `DataSource` from a specific JNDI location.
|
||||
For example, the following section in `application.properties` shows how you can access a JBoss AS defined `DataSource`:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
datasource:
|
||||
jndi-name: "java:jboss/datasources/customers"
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[data.sql.jdbc-template]]
|
||||
== Using JdbcTemplate
|
||||
|
||||
Spring's `JdbcTemplate` and `NamedParameterJdbcTemplate` classes are auto-configured, and you can `@Autowire` them directly into your own beans, as shown in the following example:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
You can customize some properties of the template by using the `spring.jdbc.template.*` properties, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
jdbc:
|
||||
template:
|
||||
max-rows: 500
|
||||
----
|
||||
|
||||
NOTE: The `NamedParameterJdbcTemplate` reuses the same `JdbcTemplate` instance behind the scenes.
|
||||
If more than one `JdbcTemplate` is defined and no primary candidate exists, the `NamedParameterJdbcTemplate` is not auto-configured.
|
||||
|
||||
|
||||
|
||||
[[data.sql.jdbc-client]]
|
||||
== Using JdbcClient
|
||||
|
||||
Spring's `JdbcClient` is auto-configured based on the presence of a `NamedParameterJdbcTemplate`.
|
||||
You can inject it directly in your own beans as well, as shown in the following example:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
If you rely on auto-configuration to create the underlying `JdbcTemplate`, any customization using `spring.jdbc.template.*` properties is taken into account in the client as well.
|
||||
|
||||
|
||||
|
||||
[[data.sql.jpa-and-spring-data]]
|
||||
== JPA and Spring Data JPA
|
||||
|
||||
The Java Persistence API is a standard technology that lets you "`map`" objects to relational databases.
|
||||
The `spring-boot-starter-data-jpa` POM provides a quick way to get started.
|
||||
It provides the following key dependencies:
|
||||
|
||||
* Hibernate: One of the most popular JPA implementations.
|
||||
* Spring Data JPA: Helps you to implement JPA-based repositories.
|
||||
* Spring ORM: Core ORM support from the Spring Framework.
|
||||
|
||||
TIP: We do not go into too many details of JPA or {url-spring-data-site}[Spring Data] here.
|
||||
You can follow the https://spring.io/guides/gs/accessing-data-jpa/["`Accessing Data with JPA`"] guide from https://spring.io and read the {url-spring-data-jpa-site}[Spring Data JPA] and https://hibernate.org/orm/documentation/[Hibernate] reference documentation.
|
||||
|
||||
|
||||
|
||||
[[data.sql.jpa-and-spring-data.entity-classes]]
|
||||
=== Entity Classes
|
||||
|
||||
Traditionally, JPA "`Entity`" classes are specified in a `persistence.xml` file.
|
||||
With Spring Boot, this file is not necessary and "`Entity Scanning`" is used instead.
|
||||
By default the xref:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages] are scanned.
|
||||
|
||||
Any classes annotated with `@Entity`, `@Embeddable`, or `@MappedSuperclass` are considered.
|
||||
A typical entity class resembles the following example:
|
||||
|
||||
include-code::City[]
|
||||
|
||||
TIP: You can customize entity scanning locations by using the `@EntityScan` annotation.
|
||||
See the "`xref:how-to:data-access.adoc#howto.data-access.separate-entity-definitions-from-spring-configuration[Separate @Entity Definitions from Spring Configuration]`" how-to.
|
||||
|
||||
|
||||
|
||||
[[data.sql.jpa-and-spring-data.repositories]]
|
||||
=== Spring Data JPA Repositories
|
||||
|
||||
{url-spring-data-jpa-site}[Spring Data JPA] repositories are interfaces that you can define to access data.
|
||||
JPA queries are created automatically from your method names.
|
||||
For example, a `CityRepository` interface might declare a `findAllByState(String state)` method to find all the cities in a given state.
|
||||
|
||||
For more complex queries, you can annotate your method with Spring Data's {url-spring-data-jpa-javadoc}/org/springframework/data/jpa/repository/Query.html[`Query`] annotation.
|
||||
|
||||
Spring Data repositories usually extend from the {url-spring-data-commons-javadoc}/org/springframework/data/repository/Repository.html[`Repository`] or {url-spring-data-commons-javadoc}/org/springframework/data/repository/CrudRepository.html[`CrudRepository`] interfaces.
|
||||
If you use auto-configuration, the xref:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages] are searched for repositories.
|
||||
|
||||
TIP: You can customize the locations to look for repositories using `@EnableJpaRepositories`.
|
||||
|
||||
The following example shows a typical Spring Data repository interface definition:
|
||||
|
||||
include-code::CityRepository[]
|
||||
|
||||
Spring Data JPA repositories support three different modes of bootstrapping: default, deferred, and lazy.
|
||||
To enable deferred or lazy bootstrapping, set the configprop:spring.data.jpa.repositories.bootstrap-mode[] property to `deferred` or `lazy` respectively.
|
||||
When using deferred or lazy bootstrapping, the auto-configured `EntityManagerFactoryBuilder` will use the context's `AsyncTaskExecutor`, if any, as the bootstrap executor.
|
||||
If more than one exists, the one named `applicationTaskExecutor` will be used.
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
When using deferred or lazy bootstrapping, make sure to defer any access to the JPA infrastructure after the application context bootstrap phase.
|
||||
You can use `SmartInitializingSingleton` to invoke any initialization that requires the JPA infrastructure.
|
||||
For JPA components (such as converters) that are created as Spring beans, use `ObjectProvider` to delay the resolution of dependencies, if any.
|
||||
====
|
||||
|
||||
TIP: We have barely scratched the surface of Spring Data JPA.
|
||||
For complete details, see the {url-spring-data-jpa-docs}[Spring Data JPA reference documentation].
|
||||
|
||||
|
||||
|
||||
[[data.sql.jpa-and-spring-data.envers-repositories]]
|
||||
=== Spring Data Envers Repositories
|
||||
|
||||
If {url-spring-data-envers-site}[Spring Data Envers] is available, JPA repositories are auto-configured to support typical Envers queries.
|
||||
|
||||
To use Spring Data Envers, make sure your repository extends from `RevisionRepository` as shown in the following example:
|
||||
|
||||
include-code::CountryRepository[]
|
||||
|
||||
NOTE: For more details, check the {url-spring-data-jpa-docs}/envers.html[Spring Data Envers reference documentation].
|
||||
|
||||
|
||||
|
||||
[[data.sql.jpa-and-spring-data.creating-and-dropping]]
|
||||
=== Creating and Dropping JPA Databases
|
||||
|
||||
By default, JPA databases are automatically created *only* if you use an embedded database (H2, HSQL, or Derby).
|
||||
You can explicitly configure JPA settings by using `+spring.jpa.*+` properties.
|
||||
For example, to create and drop tables you can add the following line to your `application.properties`:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
jpa:
|
||||
hibernate.ddl-auto: "create-drop"
|
||||
----
|
||||
|
||||
NOTE: Hibernate's own internal property name for this (if you happen to remember it better) is `hibernate.hbm2ddl.auto`.
|
||||
You can set it, along with other Hibernate native properties, by using `+spring.jpa.properties.*+` (the prefix is stripped before adding them to the entity manager).
|
||||
The following line shows an example of setting JPA properties for Hibernate:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
jpa:
|
||||
properties:
|
||||
hibernate:
|
||||
"globally_quoted_identifiers": "true"
|
||||
----
|
||||
|
||||
The line in the preceding example passes a value of `true` for the `hibernate.globally_quoted_identifiers` property to the Hibernate entity manager.
|
||||
|
||||
By default, the DDL execution (or validation) is deferred until the `ApplicationContext` has started.
|
||||
There is also a `spring.jpa.generate-ddl` flag, but it is not used if Hibernate auto-configuration is active, because the `ddl-auto` settings are more fine-grained.
|
||||
|
||||
|
||||
|
||||
[[data.sql.jpa-and-spring-data.open-entity-manager-in-view]]
|
||||
=== Open EntityManager in View
|
||||
|
||||
If you are running a web application, Spring Boot by default registers {url-spring-framework-javadoc}/org/springframework/orm/jpa/support/OpenEntityManagerInViewInterceptor.html[`OpenEntityManagerInViewInterceptor`] to apply the "`Open EntityManager in View`" pattern, to allow for lazy loading in web views.
|
||||
If you do not want this behavior, you should set `spring.jpa.open-in-view` to `false` in your `application.properties`.
|
||||
|
||||
|
||||
|
||||
[[data.sql.jdbc]]
|
||||
== Spring Data JDBC
|
||||
|
||||
Spring Data includes repository support for JDBC and will automatically generate SQL for the methods on `CrudRepository`.
|
||||
For more advanced queries, a `@Query` annotation is provided.
|
||||
|
||||
Spring Boot will auto-configure Spring Data's JDBC repositories when the necessary dependencies are on the classpath.
|
||||
They can be added to your project with a single dependency on `spring-boot-starter-data-jdbc`.
|
||||
If necessary, you can take control of Spring Data JDBC's configuration by adding the `@EnableJdbcRepositories` annotation or an `AbstractJdbcConfiguration` subclass to your application.
|
||||
|
||||
TIP: For complete details of Spring Data JDBC, see the {url-spring-data-jdbc-docs}[reference documentation].
|
||||
|
||||
|
||||
|
||||
[[data.sql.h2-web-console]]
|
||||
== Using H2's Web Console
|
||||
|
||||
The https://www.h2database.com[H2 database] provides a https://www.h2database.com/html/quickstart.html#h2_console[browser-based console] that Spring Boot can auto-configure for you.
|
||||
The console is auto-configured when the following conditions are met:
|
||||
|
||||
* You are developing a servlet-based web application.
|
||||
* `com.h2database:h2` is on the classpath.
|
||||
* You are using xref:using/devtools.adoc[Spring Boot's developer tools].
|
||||
|
||||
TIP: If you are not using Spring Boot's developer tools but would still like to make use of H2's console, you can configure the configprop:spring.h2.console.enabled[] property with a value of `true`.
|
||||
|
||||
NOTE: The H2 console is only intended for use during development, so you should take care to ensure that `spring.h2.console.enabled` is not set to `true` in production.
|
||||
|
||||
|
||||
|
||||
[[data.sql.h2-web-console.custom-path]]
|
||||
=== Changing the H2 Console's Path
|
||||
|
||||
By default, the console is available at `/h2-console`.
|
||||
You can customize the console's path by using the configprop:spring.h2.console.path[] property.
|
||||
|
||||
|
||||
|
||||
[[data.sql.h2-web-console.spring-security]]
|
||||
=== Accessing the H2 Console in a Secured Application
|
||||
|
||||
H2 Console uses frames and, as it is intended for development only, does not implement CSRF protection measures.
|
||||
If your application uses Spring Security, you need to configure it to
|
||||
|
||||
* disable CSRF protection for requests against the console,
|
||||
* set the header `X-Frame-Options` to `SAMEORIGIN` on responses from the console.
|
||||
|
||||
More information on {url-spring-security-docs}/features/exploits/csrf.html[CSRF] and the header {url-spring-security-docs}/features/exploits/headers.html#headers-frame-options[X-Frame-Options] can be found in the Spring Security Reference Guide.
|
||||
|
||||
In simple setups, a `SecurityFilterChain` like the following can be used:
|
||||
|
||||
include-code::DevProfileSecurityConfiguration[tag=!customizer]
|
||||
|
||||
WARNING: The H2 console is only intended for use during development.
|
||||
In production, disabling CSRF protection or allowing frames for a website may create severe security risks.
|
||||
|
||||
TIP: `PathRequest.toH2Console()` returns the correct request matcher also when the console's path has been customized.
|
||||
|
||||
|
||||
|
||||
[[data.sql.jooq]]
|
||||
== Using jOOQ
|
||||
|
||||
jOOQ Object Oriented Querying (https://www.jooq.org/[jOOQ]) is a popular product from https://www.datageekery.com/[Data Geekery] which generates Java code from your database and lets you build type-safe SQL queries through its fluent API.
|
||||
Both the commercial and open source editions can be used with Spring Boot.
|
||||
|
||||
|
||||
|
||||
[[data.sql.jooq.codegen]]
|
||||
=== Code Generation
|
||||
|
||||
In order to use jOOQ type-safe queries, you need to generate Java classes from your database schema.
|
||||
You can follow the instructions in the {url-jooq-docs}/#jooq-in-7-steps-step3[jOOQ user manual].
|
||||
If you use the `jooq-codegen-maven` plugin and you also use the `spring-boot-starter-parent` "`parent POM`", you can safely omit the plugin's `<version>` tag.
|
||||
You can also use Spring Boot-defined version variables (such as `h2.version`) to declare the plugin's database dependency.
|
||||
The following listing shows an example:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<plugin>
|
||||
<groupId>org.jooq</groupId>
|
||||
<artifactId>jooq-codegen-maven</artifactId>
|
||||
<executions>
|
||||
...
|
||||
</executions>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<configuration>
|
||||
<jdbc>
|
||||
<driver>org.h2.Driver</driver>
|
||||
<url>jdbc:h2:~/yourdatabase</url>
|
||||
</jdbc>
|
||||
<generator>
|
||||
...
|
||||
</generator>
|
||||
</configuration>
|
||||
</plugin>
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[data.sql.jooq.dslcontext]]
|
||||
=== Using DSLContext
|
||||
|
||||
The fluent API offered by jOOQ is initiated through the `org.jooq.DSLContext` interface.
|
||||
Spring Boot auto-configures a `DSLContext` as a Spring Bean and connects it to your application `DataSource`.
|
||||
To use the `DSLContext`, you can inject it, as shown in the following example:
|
||||
|
||||
include-code::MyBean[tag=!method]
|
||||
|
||||
TIP: The jOOQ manual tends to use a variable named `create` to hold the `DSLContext`.
|
||||
|
||||
You can then use the `DSLContext` to construct your queries, as shown in the following example:
|
||||
|
||||
include-code::MyBean[tag=method]
|
||||
|
||||
|
||||
|
||||
[[data.sql.jooq.sqldialect]]
|
||||
=== jOOQ SQL Dialect
|
||||
|
||||
Unless the configprop:spring.jooq.sql-dialect[] property has been configured, Spring Boot determines the SQL dialect to use for your datasource.
|
||||
If Spring Boot could not detect the dialect, it uses `DEFAULT`.
|
||||
|
||||
NOTE: Spring Boot can only auto-configure dialects supported by the open source version of jOOQ.
|
||||
|
||||
|
||||
|
||||
[[data.sql.jooq.customizing]]
|
||||
=== 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]]
|
||||
== Using R2DBC
|
||||
|
||||
The Reactive Relational Database Connectivity (https://r2dbc.io[R2DBC]) 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.
|
||||
Connections are provided by using a `ConnectionFactory`, similar to a `DataSource` with jdbc.
|
||||
|
||||
`ConnectionFactory` configuration is controlled by external configuration properties in `+spring.r2dbc.*+`.
|
||||
For example, you might declare the following section in `application.properties`:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
r2dbc:
|
||||
url: "r2dbc:postgresql://localhost/test"
|
||||
username: "dbuser"
|
||||
password: "dbpass"
|
||||
----
|
||||
|
||||
TIP: You do not need to specify a driver class name, since Spring Boot obtains the driver from R2DBC's Connection Factory discovery.
|
||||
|
||||
NOTE: At least the url should be provided.
|
||||
Information specified in the URL takes precedence over individual properties, that is `name`, `username`, `password` and pooling options.
|
||||
|
||||
TIP: The "`How-to`" section includes a xref:how-to:data-initialization.adoc#howto.data-initialization.using-basic-sql-scripts[section on how to initialize a database].
|
||||
|
||||
To customize the connections created by a `ConnectionFactory`, that is, set specific parameters that you do not want (or cannot) configure in your central database configuration, you can use a `ConnectionFactoryOptionsBuilderCustomizer` `@Bean`.
|
||||
The following example shows how to manually override the database port while the rest of the options are taken from the application configuration:
|
||||
|
||||
include-code::MyR2dbcConfiguration[]
|
||||
|
||||
The following examples show how to set some PostgreSQL connection options:
|
||||
|
||||
include-code::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]]
|
||||
=== Embedded Database Support
|
||||
|
||||
Similarly to xref:data/sql.adoc#data.sql.datasource.embedded[the JDBC support], Spring Boot can automatically configure an embedded database for reactive usage.
|
||||
You need not provide any connection URLs.
|
||||
You need only include a build dependency to the embedded database that you want to use, as shown in the following example:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<dependency>
|
||||
<groupId>io.r2dbc</groupId>
|
||||
<artifactId>r2dbc-h2</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
----
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
If you are using this feature in your tests, you may notice that the same database is reused by your whole test suite regardless of the number of application contexts that you use.
|
||||
If you want to make sure that each context has a separate embedded database, you should set `spring.r2dbc.generate-unique-name` to `true`.
|
||||
====
|
||||
|
||||
|
||||
|
||||
[[data.sql.r2dbc.using-database-client]]
|
||||
=== Using DatabaseClient
|
||||
|
||||
A `DatabaseClient` bean is auto-configured, and you can `@Autowire` it directly into your own beans, as shown in the following example:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
|
||||
|
||||
[[data.sql.r2dbc.repositories]]
|
||||
=== Spring Data R2DBC Repositories
|
||||
|
||||
https://spring.io/projects/spring-data-r2dbc[Spring Data R2DBC] repositories are interfaces that you can define to access data.
|
||||
Queries are created automatically from your method names.
|
||||
For example, a `CityRepository` interface might declare a `findAllByState(String state)` method to find all the cities in a given state.
|
||||
|
||||
For more complex queries, you can annotate your method with Spring Data's {url-spring-data-r2dbc-javadoc}/org/springframework/data/r2dbc/repository/Query.html[`Query`] annotation.
|
||||
|
||||
Spring Data repositories usually extend from the {url-spring-data-commons-javadoc}/org/springframework/data/repository/Repository.html[`Repository`] or {url-spring-data-commons-javadoc}/org/springframework/data/repository/CrudRepository.html[`CrudRepository`] interfaces.
|
||||
If you use auto-configuration, the xref:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages] are searched for repositories.
|
||||
|
||||
The following example shows a typical Spring Data repository interface definition:
|
||||
|
||||
include-code::CityRepository[]
|
||||
|
||||
TIP: We have barely scratched the surface of Spring Data R2DBC. For complete details, see the {url-spring-data-r2dbc-docs}[Spring Data R2DBC reference documentation].
|
||||
@@ -0,0 +1,424 @@
|
||||
[[deployment.cloud]]
|
||||
= 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`".
|
||||
They manage application processes (not Java applications specifically), so they need an intermediary layer that adapts _your_ application to the _cloud's_ notion of a running process.
|
||||
|
||||
Two popular cloud providers, Heroku and Cloud Foundry, employ a "`buildpack`" approach.
|
||||
The buildpack wraps your deployed code in whatever is needed to _start_ your application.
|
||||
It might be a JDK and a call to `java`, an embedded web server, or a full-fledged application server.
|
||||
A buildpack is pluggable, but ideally you should be able to get by with as few customizations to it as possible.
|
||||
This reduces the footprint of functionality that is not under your control.
|
||||
It minimizes divergence between development and production environments.
|
||||
|
||||
Ideally, your application, like a Spring Boot executable jar, has everything that it needs to run packaged within it.
|
||||
|
||||
In this section, we look at what it takes to get the xref:tutorial:first-application/index.adoc[application that we developed] in the "`Getting Started`" section up and running in the Cloud.
|
||||
|
||||
|
||||
|
||||
[[deployment.cloud.cloud-foundry]]
|
||||
== Cloud Foundry
|
||||
|
||||
Cloud Foundry provides default buildpacks that come into play if no other buildpack is specified.
|
||||
The Cloud Foundry https://github.com/cloudfoundry/java-buildpack[Java buildpack] has excellent support for Spring applications, including Spring Boot.
|
||||
You can deploy stand-alone executable jar applications as well as traditional `.war` packaged applications.
|
||||
|
||||
Once you have built your application (by using, for example, `mvn clean package`) and have https://docs.cloudfoundry.org/cf-cli/install-go-cli.html[installed the `cf` command line tool], deploy your application by using the `cf push` command, substituting the path to your compiled `.jar`.
|
||||
Be sure to have https://docs.cloudfoundry.org/cf-cli/getting-started.html#login[logged in with your `cf` command line client] before pushing an application.
|
||||
The following line shows using the `cf push` command to deploy an application:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ cf push acloudyspringtime -p target/demo-0.0.1-SNAPSHOT.jar
|
||||
----
|
||||
|
||||
NOTE: In the preceding example, we substitute `acloudyspringtime` for whatever value you give `cf` as the name of your application.
|
||||
|
||||
See the https://docs.cloudfoundry.org/cf-cli/getting-started.html#push[`cf push` documentation] for more options.
|
||||
If there is a Cloud Foundry https://docs.cloudfoundry.org/devguide/deploy-apps/manifest.html[`manifest.yml`] file present in the same directory, it is considered.
|
||||
|
||||
At this point, `cf` starts uploading your application, producing output similar to the following example:
|
||||
|
||||
[source,subs="verbatim,quotes"]
|
||||
----
|
||||
Uploading acloudyspringtime... *OK*
|
||||
Preparing to start acloudyspringtime... *OK*
|
||||
-----> Downloaded app package (*8.9M*)
|
||||
-----> Java Buildpack Version: v3.12 (offline) | https://github.com/cloudfoundry/java-buildpack.git#6f25b7e
|
||||
-----> Downloading Open Jdk JRE
|
||||
Expanding Open Jdk JRE to .java-buildpack/open_jdk_jre (1.6s)
|
||||
-----> Downloading Open JDK Like Memory Calculator 2.0.2_RELEASE from https://java-buildpack.cloudfoundry.org/memory-calculator/trusty/x86_64/memory-calculator-2.0.2_RELEASE.tar.gz (found in cache)
|
||||
Memory Settings: -Xss349K -Xmx681574K -XX:MaxMetaspaceSize=104857K -Xms681574K -XX:MetaspaceSize=104857K
|
||||
-----> Downloading Container Certificate Trust Store 1.0.0_RELEASE from https://java-buildpack.cloudfoundry.org/container-certificate-trust-store/container-certificate-trust-store-1.0.0_RELEASE.jar (found in cache)
|
||||
Adding certificates to .java-buildpack/container_certificate_trust_store/truststore.jks (0.6s)
|
||||
-----> Downloading Spring Auto Reconfiguration 1.10.0_RELEASE from https://java-buildpack.cloudfoundry.org/auto-reconfiguration/auto-reconfiguration-1.10.0_RELEASE.jar (found in cache)
|
||||
Checking status of app 'acloudyspringtime'...
|
||||
0 of 1 instances running (1 starting)
|
||||
...
|
||||
0 of 1 instances running (1 starting)
|
||||
...
|
||||
0 of 1 instances running (1 starting)
|
||||
...
|
||||
1 of 1 instances running (1 running)
|
||||
|
||||
App started
|
||||
----
|
||||
|
||||
Congratulations! The application is now live!
|
||||
|
||||
Once your application is live, you can verify the status of the deployed application by using the `cf apps` command, as shown in the following example:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ cf apps
|
||||
Getting applications in ...
|
||||
OK
|
||||
|
||||
name requested state instances memory disk urls
|
||||
...
|
||||
acloudyspringtime started 1/1 512M 1G acloudyspringtime.cfapps.io
|
||||
...
|
||||
----
|
||||
|
||||
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]]
|
||||
=== 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.
|
||||
Process-scoped environment variables are language agnostic.
|
||||
|
||||
Environment variables do not always make for the easiest API, so Spring Boot automatically extracts them and flattens the data into properties that can be accessed through Spring's `Environment` abstraction, as shown in the following example:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
All Cloud Foundry properties are prefixed with `vcap`.
|
||||
You can use `vcap` properties to access application information (such as the public URL of the application) and service information (such as database credentials).
|
||||
See the xref:api:java/org/springframework/boot/cloud/CloudFoundryVcapEnvironmentPostProcessor.html[`CloudFoundryVcapEnvironmentPostProcessor`] Javadoc for complete details.
|
||||
|
||||
TIP: The https://github.com/pivotal-cf/java-cfenv/[Java CFEnv] project is a better fit for tasks such as configuring a DataSource.
|
||||
|
||||
|
||||
|
||||
[[deployment.cloud.kubernetes]]
|
||||
== 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 configprop:spring.main.cloud-platform[] configuration property.
|
||||
|
||||
Spring Boot helps you to xref:features/spring-application.adoc#features.spring-application.application-availability[manage the state of your application] and export it with xref:actuator/endpoints.adoc#actuator.endpoints.kubernetes-probes[HTTP Kubernetes Probes using Actuator].
|
||||
|
||||
|
||||
|
||||
[[deployment.cloud.kubernetes.container-lifecycle]]
|
||||
=== 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.
|
||||
|
||||
You can configure a sleep execution in a preStop handler to avoid requests being routed to a pod that has already begun shutting down.
|
||||
This sleep should be long enough for new requests to stop being routed to the pod and its duration will vary from deployment to deployment.
|
||||
The preStop handler can be configured by using the PodSpec in the pod's configuration file as follows:
|
||||
|
||||
[source,yaml]
|
||||
----
|
||||
spec:
|
||||
containers:
|
||||
- name: "example-container"
|
||||
image: "example-image"
|
||||
lifecycle:
|
||||
preStop:
|
||||
exec:
|
||||
command: ["sh", "-c", "sleep 10"]
|
||||
----
|
||||
|
||||
Once the pre-stop hook has completed, SIGTERM will be sent to the container and xref:web/graceful-shutdown.adoc[graceful shutdown] will begin, allowing any remaining in-flight requests to complete.
|
||||
|
||||
NOTE: 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 configprop: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]]
|
||||
== Heroku
|
||||
|
||||
Heroku is another popular PaaS platform.
|
||||
To customize Heroku builds, you provide a `Procfile`, which provides the incantation required to deploy an application.
|
||||
Heroku assigns a `port` for the Java application to use and then ensures that routing to the external URI works.
|
||||
|
||||
You must configure your application to listen on the correct port.
|
||||
The following example shows the `Procfile` for our starter REST application:
|
||||
|
||||
[source]
|
||||
----
|
||||
web: java -Dserver.port=$PORT -jar target/demo-0.0.1-SNAPSHOT.jar
|
||||
----
|
||||
|
||||
Spring Boot makes `-D` arguments available as properties accessible from a Spring `Environment` instance.
|
||||
The `server.port` configuration property is fed to the embedded Tomcat, Jetty, or Undertow instance, which then uses the port when it starts up.
|
||||
The `$PORT` environment variable is assigned to us by the Heroku PaaS.
|
||||
|
||||
This should be everything you need.
|
||||
The most common deployment workflow for Heroku deployments is to `git push` the code to production, as shown in the following example:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ git push heroku main
|
||||
----
|
||||
|
||||
Which will result in the following:
|
||||
|
||||
[source,subs="verbatim,quotes"]
|
||||
----
|
||||
Initializing repository, *done*.
|
||||
Counting objects: 95, *done*.
|
||||
Delta compression using up to 8 threads.
|
||||
Compressing objects: 100% (78/78), *done*.
|
||||
Writing objects: 100% (95/95), 8.66 MiB | 606.00 KiB/s, *done*.
|
||||
Total 95 (delta 31), reused 0 (delta 0)
|
||||
|
||||
-----> Java app detected
|
||||
-----> Installing OpenJDK... *done*
|
||||
-----> Installing Maven... *done*
|
||||
-----> Installing settings.xml... *done*
|
||||
-----> Executing: mvn -B -DskipTests=true clean install
|
||||
|
||||
[INFO] Scanning for projects...
|
||||
Downloading: https://repo.spring.io/...
|
||||
Downloaded: https://repo.spring.io/... (818 B at 1.8 KB/sec)
|
||||
....
|
||||
Downloaded: https://s3pository.heroku.com/jvm/... (152 KB at 595.3 KB/sec)
|
||||
[INFO] Installing /tmp/build_0c35a5d2-a067-4abc-a232-14b1fb7a8229/target/...
|
||||
[INFO] Installing /tmp/build_0c35a5d2-a067-4abc-a232-14b1fb7a8229/pom.xml ...
|
||||
[INFO] ------------------------------------------------------------------------
|
||||
[INFO] *BUILD SUCCESS*
|
||||
[INFO] ------------------------------------------------------------------------
|
||||
[INFO] Total time: 59.358s
|
||||
[INFO] Finished at: Fri Mar 07 07:28:25 UTC 2014
|
||||
[INFO] Final Memory: 20M/493M
|
||||
[INFO] ------------------------------------------------------------------------
|
||||
|
||||
-----> Discovering process types
|
||||
Procfile declares types -> *web*
|
||||
|
||||
-----> Compressing... *done*, 70.4MB
|
||||
-----> Launching... *done*, v6
|
||||
https://agile-sierra-1405.herokuapp.com/ *deployed to Heroku*
|
||||
|
||||
To git@heroku.com:agile-sierra-1405.git
|
||||
* [new branch] main -> main
|
||||
----
|
||||
|
||||
Your application should now be up and running on Heroku.
|
||||
For more details, see https://devcenter.heroku.com/articles/deploying-spring-boot-apps-to-heroku[Deploying Spring Boot Applications to Heroku].
|
||||
|
||||
|
||||
|
||||
[[deployment.cloud.openshift]]
|
||||
== OpenShift
|
||||
|
||||
https://www.openshift.com/[OpenShift] has many resources describing how to deploy Spring Boot applications, including:
|
||||
|
||||
* https://blog.openshift.com/using-openshift-enterprise-grade-spring-boot-deployments/[Using the S2I builder]
|
||||
* https://access.redhat.com/documentation/en-us/reference_architectures/2017/html-single/spring_boot_microservices_on_red_hat_openshift_container_platform_3/[Architecture guide]
|
||||
* https://blog.openshift.com/using-spring-boot-on-openshift/[Running as a traditional web application on Wildfly]
|
||||
* https://blog.openshift.com/openshift-commons-briefing-96-cloud-native-applications-spring-rhoar/[OpenShift Commons Briefing]
|
||||
|
||||
|
||||
|
||||
[[deployment.cloud.aws]]
|
||||
== 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:
|
||||
|
||||
* AWS Elastic Beanstalk
|
||||
* AWS Code Deploy
|
||||
* AWS OPS Works
|
||||
* AWS Cloud Formation
|
||||
* AWS Container Registry
|
||||
|
||||
Each has different features and pricing models.
|
||||
In this document, we describe to approach using AWS Elastic Beanstalk.
|
||||
|
||||
|
||||
|
||||
[[deployment.cloud.aws.beanstalk]]
|
||||
=== AWS Elastic Beanstalk
|
||||
|
||||
As described in the official https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_Java.html[Elastic Beanstalk Java guide], 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
|
||||
|
||||
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
|
||||
|
||||
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.
|
||||
To configure it, add the following line to your `application.properties` file:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
server:
|
||||
port: 5000
|
||||
----
|
||||
|
||||
|
||||
[TIP]
|
||||
.Upload binaries instead of sources
|
||||
====
|
||||
By default, Elastic Beanstalk uploads sources and compiles them in AWS.
|
||||
However, it is best to upload the binaries instead.
|
||||
To do so, add lines similar to the following to your `.elasticbeanstalk/config.yml` file:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
deploy:
|
||||
artifact: target/demo-0.0.1-SNAPSHOT.jar
|
||||
----
|
||||
====
|
||||
|
||||
[TIP]
|
||||
.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 https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environments-create-wizard.html#environments-create-wizard-capacity[the Amazon documentation].
|
||||
You can also create single instance environments by using the CLI and the following command:
|
||||
|
||||
[source]
|
||||
----
|
||||
eb create -s
|
||||
----
|
||||
====
|
||||
|
||||
|
||||
|
||||
[[deployment.cloud.aws.summary]]
|
||||
=== 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 https://exampledriven.wordpress.com/2017/01/09/spring-boot-aws-elastic-beanstalk-example/[blog post] covering these topics more in detail.
|
||||
|
||||
|
||||
|
||||
[[deployment.cloud.boxfuse]]
|
||||
== CloudCaptain and Amazon Web Services
|
||||
|
||||
https://cloudcaptain.sh/[CloudCaptain] 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.
|
||||
CloudCaptain leverages this information both for the images it produces as well as for all the resources it provisions (instances, security groups, elastic load balancers, and so on).
|
||||
|
||||
Once you have created a https://console.cloudcaptain.sh[CloudCaptain account], connected it to your AWS account, installed the latest version of the CloudCaptain Client, and ensured that the application has been built by Maven or Gradle (by using, for example, `mvn clean package`), you can deploy your Spring Boot application to AWS with a command similar to the following:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ boxfuse run myapp-1.0.jar -env=prod
|
||||
----
|
||||
|
||||
See the https://cloudcaptain.sh/docs/commandline/run.html[`boxfuse run` documentation] for more options.
|
||||
If there is a https://cloudcaptain.sh/docs/commandline/#configuration[`boxfuse.conf`] file present in the current directory, it is considered.
|
||||
|
||||
TIP: By default, CloudCaptain activates a Spring profile named `boxfuse` on startup.
|
||||
If your executable jar or war contains an https://cloudcaptain.sh/docs/payloads/springboot.html#configuration[`application-boxfuse.properties`] file, CloudCaptain bases its configuration on the properties it contains.
|
||||
|
||||
At this point, CloudCaptain creates an image for your application, uploads it, and configures and starts the necessary resources on AWS, resulting in output similar to the following example:
|
||||
|
||||
[source]
|
||||
----
|
||||
Fusing Image for myapp-1.0.jar ...
|
||||
Image fused in 00:06.838s (53937 K) -> axelfontaine/myapp:1.0
|
||||
Creating axelfontaine/myapp ...
|
||||
Pushing axelfontaine/myapp:1.0 ...
|
||||
Verifying axelfontaine/myapp:1.0 ...
|
||||
Creating Elastic IP ...
|
||||
Mapping myapp-axelfontaine.boxfuse.io to 52.28.233.167 ...
|
||||
Waiting for AWS to create an AMI for axelfontaine/myapp:1.0 in eu-central-1 (this may take up to 50 seconds) ...
|
||||
AMI created in 00:23.557s -> ami-d23f38cf
|
||||
Creating security group boxfuse-sg_axelfontaine/myapp:1.0 ...
|
||||
Launching t2.micro instance of axelfontaine/myapp:1.0 (ami-d23f38cf) in eu-central-1 ...
|
||||
Instance launched in 00:30.306s -> i-92ef9f53
|
||||
Waiting for AWS to boot Instance i-92ef9f53 and Payload to start at https://52.28.235.61/ ...
|
||||
Payload started in 00:29.266s -> https://52.28.235.61/
|
||||
Remapping Elastic IP 52.28.233.167 to i-92ef9f53 ...
|
||||
Waiting 15s for AWS to complete Elastic IP Zero Downtime transition ...
|
||||
Deployment completed successfully. axelfontaine/myapp:1.0 is up and running at https://myapp-axelfontaine.boxfuse.io/
|
||||
----
|
||||
|
||||
Your application should now be up and running on AWS.
|
||||
|
||||
See the blog post on https://cloudcaptain.sh/blog/spring-boot-ec2.html[deploying Spring Boot apps on EC2] as well as the https://cloudcaptain.sh/docs/payloads/springboot.html[documentation for the CloudCaptain Spring Boot integration] to get started with a Maven build to run the app.
|
||||
|
||||
|
||||
|
||||
[[deployment.cloud.azure]]
|
||||
== Azure
|
||||
|
||||
This https://spring.io/guides/gs/spring-boot-for-azure/[Getting Started guide] walks you through deploying your Spring Boot application to either https://azure.microsoft.com/en-us/services/spring-cloud/[Azure Spring Cloud] or https://docs.microsoft.com/en-us/azure/app-service/overview[Azure App Service].
|
||||
|
||||
|
||||
|
||||
[[deployment.cloud.google]]
|
||||
== 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.
|
||||
|
||||
To deploy your first app to App Engine standard environment, follow https://codelabs.developers.google.com/codelabs/cloud-app-engine-springboot#0[this tutorial].
|
||||
|
||||
Alternatively, App Engine Flex requires you to create an `app.yaml` file to describe the resources your app requires.
|
||||
Normally, you put this file in `src/main/appengine`, and it should resemble the following file:
|
||||
|
||||
[source,yaml]
|
||||
----
|
||||
service: "default"
|
||||
|
||||
runtime: "java17"
|
||||
env: "flex"
|
||||
|
||||
handlers:
|
||||
- url: "/.*"
|
||||
script: "this field is required, but ignored"
|
||||
|
||||
manual_scaling:
|
||||
instances: 1
|
||||
|
||||
health_check:
|
||||
enable_health_check: false
|
||||
|
||||
env_variables:
|
||||
ENCRYPT_KEY: "your_encryption_key_here"
|
||||
----
|
||||
|
||||
You can deploy the app (for example, with a Maven plugin) by adding the project ID to the build configuration, as shown in the following example:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<plugin>
|
||||
<groupId>com.google.cloud.tools</groupId>
|
||||
<artifactId>appengine-maven-plugin</artifactId>
|
||||
<version>2.4.4</version>
|
||||
<configuration>
|
||||
<project>myproject</project>
|
||||
</configuration>
|
||||
</plugin>
|
||||
----
|
||||
|
||||
Then deploy with `mvn appengine:deploy` (you need to authenticate first, otherwise the build fails).
|
||||
@@ -0,0 +1,87 @@
|
||||
[[deployment.efficient]]
|
||||
= Efficient deployments
|
||||
|
||||
|
||||
|
||||
[[deployment.efficient.unpacking]]
|
||||
== Unpacking the Executable 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.
|
||||
For example, Cloud Foundry operates this way.
|
||||
One way to run an unpacked archive is by starting the appropriate launcher, as follows:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ jar -xf myapp.jar
|
||||
$ java org.springframework.boot.loader.launch.JarLauncher
|
||||
----
|
||||
|
||||
This is actually slightly faster on startup (depending on the size of the jar) than running from an unexploded archive.
|
||||
After startup, you should not expect any differences.
|
||||
|
||||
Once you have unpacked the jar file, you can also get an extra boost to startup time by running the app with its "natural" main method instead of the `JarLauncher`. For example:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ jar -xf myapp.jar
|
||||
$ java -cp "BOOT-INF/classes:BOOT-INF/lib/*" com.example.MyApplication
|
||||
----
|
||||
|
||||
NOTE: 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.
|
||||
|
||||
|
||||
|
||||
[[deployment.efficient.aot]]
|
||||
== Using Ahead-of-time Processing With the JVM
|
||||
|
||||
It's beneficial for the startup time to run your application using the AOT generated initialization code.
|
||||
First, you need to ensure that the jar you are building includes AOT generated code.
|
||||
|
||||
For Maven, this means that you should build with `-Pnative` to activate the `native` profile:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ mvn -Pnative package
|
||||
----
|
||||
|
||||
For Gradle, you need to ensure that your build includes the `org.springframework.boot.aot` plugin.
|
||||
|
||||
When the JAR has been built, run it with `spring.aot.enabled` system property set to `true`. For example:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ java -Dspring.aot.enabled=true -jar myapplication.jar
|
||||
|
||||
........ Starting AOT-processed MyApplication ...
|
||||
----
|
||||
|
||||
Beware that using the ahead-of-time processing has drawbacks.
|
||||
It implies the following restrictions:
|
||||
|
||||
* The classpath is fixed and fully defined at build time
|
||||
* The beans defined in your application cannot change at runtime, meaning:
|
||||
- The Spring `@Profile` annotation and profile-specific configuration xref:how-to:aot.adoc#howto.aot.conditions[have limitations].
|
||||
- Properties that change if a bean is created are not supported (for example, `@ConditionalOnProperty` and `.enable` properties).
|
||||
|
||||
To learn more about ahead-of-time processing, please see the xref:native-image/introducing-graalvm-native-images.adoc#native-image.introducing-graalvm-native-images.understanding-aot-processing[Understanding Spring Ahead-of-Time Processing section].
|
||||
|
||||
|
||||
|
||||
[[deployment.efficient.checkpoint-restore]]
|
||||
== Checkpoint and Restore With the JVM
|
||||
|
||||
https://wiki.openjdk.org/display/crac/Main[Coordinated Restore at Checkpoint] (CRaC) is an OpenJDK project that defines a new Java API to allow you to checkpoint and restore an application on the HotSpot JVM.
|
||||
It is based on https://github.com/checkpoint-restore/criu[CRIU], a project that implements checkpoint/restore functionality on Linux.
|
||||
|
||||
The principle is the following: you start your application almost as usual but with a CRaC enabled version of the JDK like https://bell-sw.com/pages/downloads/?package=jdk-crac[BellSoft Liberica JDK with CRaC] or https://www.azul.com/downloads/?package=jdk-crac#zulu[Azul Zulu JDK with CRaC].
|
||||
Then at some point, potentially after some workloads that will warm up your JVM by executing all common code paths, you trigger a checkpoint using an API call, a `jcmd` command, an HTTP endpoint, or a different mechanism.
|
||||
|
||||
A memory representation of the running JVM, including its warmness, is then serialized to disk, allowing a fast restoration at a later point, potentially on another machine with a similar operating system and CPU architecture.
|
||||
The restored process retains all the capabilities of the HotSpot JVM, including further JIT optimizations at runtime.
|
||||
|
||||
Based on the foundations provided by Spring Framework, Spring Boot provides support for checkpointing and restoring your application, and manages out-of-the-box the lifecycle of resources such as socket, files and thread pools https://github.com/spring-projects/spring-lifecycle-smoke-tests/blob/main/STATUS.adoc[on a limited scope].
|
||||
Additional lifecycle management is expected for other dependencies and potentially for the application code dealing with such resources.
|
||||
|
||||
You can find more details about the two modes supported ("on demand checkpoint/restore of a running application" and "automatic checkpoint/restore at startup"), how to enable checkpoint and restore support and some guidelines in {url-spring-framework-docs}/integration/checkpoint-restore.html[the Spring Framework JVM Checkpoint Restore support documentation].
|
||||
@@ -0,0 +1,8 @@
|
||||
[[deployment]]
|
||||
= 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.
|
||||
|
||||
@@ -0,0 +1,389 @@
|
||||
[[deployment.installing]]
|
||||
= Installing Spring Boot Applications
|
||||
|
||||
In addition to running Spring Boot applications by using `java -jar` directly, it is also possible to run them as `systemd`, `init.d` or Windows services.
|
||||
|
||||
|
||||
|
||||
[[deployment.installing.system-d]]
|
||||
== 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.
|
||||
Spring Boot applications can be launched by using `systemd` '`service`' scripts.
|
||||
|
||||
Assuming that you have a Spring Boot application packaged as an uber jar in `/var/myapp`, to install it as a `systemd` service, create a script named `myapp.service` and place it in `/etc/systemd/system` directory.
|
||||
The following script offers an example:
|
||||
|
||||
[source]
|
||||
----
|
||||
[Unit]
|
||||
Description=myapp
|
||||
After=syslog.target network.target
|
||||
|
||||
[Service]
|
||||
User=myapp
|
||||
Group=myapp
|
||||
|
||||
Environment="JAVA_HOME=/path/to/java/home"
|
||||
|
||||
ExecStart=${JAVA_HOME}/bin/java -jar /var/myapp/myapp.jar
|
||||
ExecStop=/bin/kill -15 $MAINPID
|
||||
SuccessExitStatus=143
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
----
|
||||
|
||||
IMPORTANT: Remember to change the `Description`, `User`, `Group`, `Environment` and `ExecStart` fields for your application.
|
||||
|
||||
NOTE: The `ExecStart` field does not declare the script action command, which means that the `run` command is used by default.
|
||||
|
||||
The user that runs the application, the PID file, and the console log file are managed by `systemd` itself and therefore must be configured by using appropriate fields in the '`service`' script.
|
||||
Consult the https://www.freedesktop.org/software/systemd/man/systemd.service.html[service unit configuration man page] for more details.
|
||||
|
||||
To flag the application to start automatically on system boot, use the following command:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ systemctl enable myapp.service
|
||||
----
|
||||
|
||||
Run `man systemctl` for more details.
|
||||
|
||||
|
||||
|
||||
[[deployment.installing.init-d]]
|
||||
== Installation as an init.d Service (System V)
|
||||
|
||||
To use your application as `init.d` service, configure its build to produce a xref:deployment/installing.adoc[fully executable jar].
|
||||
|
||||
CAUTION: Fully executable jars work by embedding an extra script at the front of the file.
|
||||
Currently, some tools do not accept this format, so you may not always be able to use this technique.
|
||||
For example, `jar -xf` may silently fail to extract a jar or war that has been made fully executable.
|
||||
It is recommended that you make your jar or war fully executable only if you intend to execute it directly, rather than running it with `java -jar` or deploying it to a servlet container.
|
||||
|
||||
CAUTION: A zip64-format jar file cannot be made fully executable.
|
||||
Attempting to do so will result in a jar file that is reported as corrupt when executed directly or with `java -jar`.
|
||||
A standard-format jar file that contains one or more zip64-format nested jars can be fully executable.
|
||||
|
||||
To create a '`fully executable`' jar with Maven, use the following plugin configuration:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<executable>true</executable>
|
||||
</configuration>
|
||||
</plugin>
|
||||
----
|
||||
|
||||
The following example shows the equivalent Gradle configuration:
|
||||
|
||||
[source,gradle]
|
||||
----
|
||||
tasks.named('bootJar') {
|
||||
launchScript()
|
||||
}
|
||||
----
|
||||
|
||||
It can then be symlinked to `init.d` to support the standard `start`, `stop`, `restart`, and `status` commands.
|
||||
|
||||
The default launch script that is added to a fully executable jar 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 script.
|
||||
The default scripts supports the following features:
|
||||
|
||||
* Starts the services as the user that owns the jar file
|
||||
* Tracks the application's PID by using `/var/run/<appname>/<appname>.pid`
|
||||
* Writes console logs to `/var/log/<appname>.log`
|
||||
|
||||
Assuming that you have a Spring Boot application installed in `/var/myapp`, to install a Spring Boot application as an `init.d` service, create a symlink, as follows:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ sudo ln -s /var/myapp/myapp.jar /etc/init.d/myapp
|
||||
----
|
||||
|
||||
Once installed, you can start and stop the service in the usual way.
|
||||
For example, on a Debian-based system, you could start it with the following command:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ service myapp start
|
||||
----
|
||||
|
||||
TIP: If your application fails to start, check the log file written to `/var/log/<appname>.log` for errors.
|
||||
|
||||
You can also flag the application to start automatically by using your standard operating system tools.
|
||||
For example, on Debian, you could use the following command:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ update-rc.d myapp defaults <priority>
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[deployment.installing.init-d.securing]]
|
||||
=== Securing an init.d Service
|
||||
|
||||
NOTE: 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.
|
||||
|
||||
When executed as root, as is the case when root is being used to start an init.d service, the default executable script runs the application as the user specified in the `RUN_AS_USER` environment variable.
|
||||
When the environment variable is not set, the user who owns the jar file is used instead.
|
||||
You should never run a Spring Boot application as `root`, so `RUN_AS_USER` should never be root and your application's jar file should never be owned by root.
|
||||
Instead, create a specific user to run your application and set the `RUN_AS_USER` environment variable or use `chown` to make it the owner of the jar file, as shown in the following example:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ chown bootapp:bootapp your-app.jar
|
||||
----
|
||||
|
||||
In this case, the default executable script runs the application as the `bootapp` user.
|
||||
|
||||
TIP: To reduce the chances of the application's user account being compromised, you should consider preventing it from using a login shell.
|
||||
For example, you can set the account's shell to `/usr/sbin/nologin`.
|
||||
|
||||
You should also take steps to prevent the modification of your application's jar file.
|
||||
Firstly, configure its permissions so that it cannot be written and can only be read or executed by its owner, as shown in the following example:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ chmod 500 your-app.jar
|
||||
----
|
||||
|
||||
Second, you should also take steps to limit the damage if your application or the account that is running it is compromised.
|
||||
If an attacker does gain access, they could make the jar file writable and change its contents.
|
||||
One way to protect against this is to make it immutable by using `chattr`, as shown in the following example:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ sudo chattr +i your-app.jar
|
||||
----
|
||||
|
||||
This will prevent any user, including root, from modifying the jar.
|
||||
|
||||
If root is used to control the application's service and you xref:deployment/installing.adoc#deployment.installing.init-d.script-customization.when-running.conf-file[use a `.conf` file] to customize its startup, the `.conf` file is read and evaluated by the root user.
|
||||
It should be secured accordingly.
|
||||
Use `chmod` so that the file can only be read by the owner and use `chown` to make root the owner, as shown in the following example:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ chmod 400 your-app.conf
|
||||
$ sudo chown root:root your-app.conf
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[deployment.installing.init-d.script-customization]]
|
||||
=== 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.init-d.script-customization.when-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`".
|
||||
Since you know the description up front (and it need not change), you may as well provide it when the jar is generated.
|
||||
|
||||
To customize written elements, use the `embeddedLaunchScriptProperties` option of the Spring Boot Maven plugin or the xref:gradle-plugin:packaging.adoc#packaging-executable.configuring.launch-script[`properties` property of the Spring Boot Gradle plugin's `launchScript`].
|
||||
|
||||
The following property substitutions are supported with the default script:
|
||||
|
||||
[cols="1,3,3,3"]
|
||||
|===
|
||||
| Name | Description | Gradle default | Maven default
|
||||
|
||||
| `mode`
|
||||
| The script mode.
|
||||
| `auto`
|
||||
| `auto`
|
||||
|
||||
| `initInfoProvides`
|
||||
| The `Provides` section of "`INIT INFO`"
|
||||
| `${task.baseName}`
|
||||
| `${project.artifactId}`
|
||||
|
||||
| `initInfoRequiredStart`
|
||||
| `Required-Start` section of "`INIT INFO`".
|
||||
| `$remote_fs $syslog $network`
|
||||
| `$remote_fs $syslog $network`
|
||||
|
||||
| `initInfoRequiredStop`
|
||||
| `Required-Stop` section of "`INIT INFO`".
|
||||
| `$remote_fs $syslog $network`
|
||||
| `$remote_fs $syslog $network`
|
||||
|
||||
| `initInfoDefaultStart`
|
||||
| `Default-Start` section of "`INIT INFO`".
|
||||
| `2 3 4 5`
|
||||
| `2 3 4 5`
|
||||
|
||||
| `initInfoDefaultStop`
|
||||
| `Default-Stop` section of "`INIT INFO`".
|
||||
| `0 1 6`
|
||||
| `0 1 6`
|
||||
|
||||
| `initInfoShortDescription`
|
||||
| `Short-Description` section of "`INIT INFO`".
|
||||
| Single-line version of `${project.description}` (falling back to `${task.baseName}`)
|
||||
| `${project.name}`
|
||||
|
||||
| `initInfoDescription`
|
||||
| `Description` section of "`INIT INFO`".
|
||||
| `${project.description}` (falling back to `${task.baseName}`)
|
||||
| `${project.description}` (falling back to `${project.name}`)
|
||||
|
||||
| `initInfoChkconfig`
|
||||
| `chkconfig` section of "`INIT INFO`"
|
||||
| `2345 99 01`
|
||||
| `2345 99 01`
|
||||
|
||||
| `confFolder`
|
||||
| The default value for `CONF_FOLDER`
|
||||
| Folder containing the jar
|
||||
| Folder containing the jar
|
||||
|
||||
| `inlinedConfScript`
|
||||
| Reference to a file script that should be inlined in the default launch script.
|
||||
This can be used to set environmental variables such as `JAVA_OPTS` before any external config files are loaded
|
||||
|
|
||||
|
|
||||
|
||||
| `logFolder`
|
||||
| Default value for `LOG_FOLDER`.
|
||||
Only valid for an `init.d` service
|
||||
|
|
||||
|
|
||||
|
||||
| `logFilename`
|
||||
| Default value for `LOG_FILENAME`.
|
||||
Only valid for an `init.d` service
|
||||
|
|
||||
|
|
||||
|
||||
| `pidFolder`
|
||||
| Default value for `PID_FOLDER`.
|
||||
Only valid for an `init.d` service
|
||||
|
|
||||
|
|
||||
|
||||
| `pidFilename`
|
||||
| Default value for the name of the PID file in `PID_FOLDER`.
|
||||
Only valid for an `init.d` service
|
||||
|
|
||||
|
|
||||
|
||||
| `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.init-d.script-customization.when-running]]
|
||||
==== 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 xref:deployment/installing.adoc#deployment.installing.init-d.script-customization.when-running.conf-file[config file].
|
||||
|
||||
The following environment properties are supported with the default script:
|
||||
|
||||
[cols="1,6"]
|
||||
|===
|
||||
| Variable | Description
|
||||
|
||||
| `MODE`
|
||||
| The "`mode`" of operation.
|
||||
The default depends on the way the jar was built but is usually `auto` (meaning it tries to guess if it is an init script by checking if it is a symlink in a directory called `init.d`).
|
||||
You can explicitly set it to `service` so that the `stop\|start\|status\|restart` commands work or to `run` if you want to run the script in the foreground.
|
||||
|
||||
| `RUN_AS_USER`
|
||||
| The user that will be used to run the application.
|
||||
When not set, the user that owns the jar file will be used.
|
||||
|
||||
| `USE_START_STOP_DAEMON`
|
||||
| Whether the `start-stop-daemon` command, when it is available, should be used to control the process.
|
||||
Defaults to `true`.
|
||||
|
||||
| `PID_FOLDER`
|
||||
| The root name of the pid folder (`/var/run` by default).
|
||||
|
||||
| `LOG_FOLDER`
|
||||
| The name of the folder in which to put log files (`/var/log` by default).
|
||||
|
||||
| `CONF_FOLDER`
|
||||
| The name of the folder from which to read .conf files (same folder as jar-file by default).
|
||||
|
||||
| `LOG_FILENAME`
|
||||
| The name of the log file in the `LOG_FOLDER` (`<appname>.log` by default).
|
||||
|
||||
| `APP_NAME`
|
||||
| The name of the app.
|
||||
If the jar is run from a symlink, the script guesses the app name.
|
||||
If it is not a symlink or you want to explicitly set the app name, this can be useful.
|
||||
|
||||
| `RUN_ARGS`
|
||||
| The arguments to pass to the program (the Spring Boot app).
|
||||
|
||||
| `JAVA_HOME`
|
||||
| The location of the `java` executable is discovered by using the `PATH` by default, but you can set it explicitly if there is an executable file at `$JAVA_HOME/bin/java`.
|
||||
|
||||
| `JAVA_OPTS`
|
||||
| Options that are passed to the JVM when it is launched.
|
||||
|
||||
| `JARFILE`
|
||||
| The explicit location of the jar file, in case the script is being used to launch a jar that it is not actually embedded.
|
||||
|
||||
| `DEBUG`
|
||||
| If not empty, sets the `-x` flag on the shell process, allowing you to see the logic in the script.
|
||||
|
||||
| `STOP_WAIT_TIME`
|
||||
| The time in seconds to wait when stopping the application before forcing a shutdown (`60` by default).
|
||||
|===
|
||||
|
||||
NOTE: The `PID_FOLDER`, `LOG_FOLDER`, and `LOG_FILENAME` variables are only valid for an `init.d` service.
|
||||
For `systemd`, the equivalent customizations are made by using the '`service`' script.
|
||||
See the https://www.freedesktop.org/software/systemd/man/systemd.service.html[service unit configuration man page] for more details.
|
||||
|
||||
|
||||
|
||||
[[deployment.installing.init-d.script-customization.when-running.conf-file]]
|
||||
===== Using a Conf File
|
||||
|
||||
With the exception of `JARFILE` and `APP_NAME`, the settings listed in the preceding section can be configured by using a `.conf` file.
|
||||
The file is expected to be next to the jar file and have the same name but suffixed with `.conf` rather than `.jar`.
|
||||
For example, a jar named `/var/myapp/myapp.jar` uses the configuration file named `/var/myapp/myapp.conf`, as shown in the following example:
|
||||
|
||||
.myapp.conf
|
||||
[source,properties]
|
||||
----
|
||||
JAVA_OPTS=-Xmx1024M
|
||||
LOG_FOLDER=/custom/log/folder
|
||||
----
|
||||
|
||||
TIP: If you do not like having the config file next to the jar file, you can set a `CONF_FOLDER` environment variable to customize the location of the config file.
|
||||
|
||||
To learn about securing this file appropriately, see xref:deployment/installing.adoc#deployment.installing.init-d.securing[the guidelines for securing an init.d service].
|
||||
|
||||
|
||||
|
||||
[[deployment.installing.windows-services]]
|
||||
== Microsoft Windows Services
|
||||
|
||||
A Spring Boot application can be started as a Windows service by using https://github.com/kohsuke/winsw[`winsw`].
|
||||
|
||||
A (https://github.com/snicoll/spring-boot-daemon[separately maintained sample]) describes step-by-step how you can create a Windows service for your Spring Boot application.
|
||||
@@ -0,0 +1,10 @@
|
||||
[[features.aop]]
|
||||
= Aspect-Oriented Programming
|
||||
|
||||
Spring Boot provides auto-configuration for aspect-oriented programming (AOP).
|
||||
You can learn more about AOP with Spring in the {url-spring-framework-docs}/core/aop-api.html[Spring Framework reference documentation].
|
||||
|
||||
By default, Spring Boot's auto-configuration configures Spring AOP to use CGLib proxies.
|
||||
To use JDK proxies instead, set `configprop:spring.aop.proxy-target-class` to `false`.
|
||||
|
||||
If AspectJ is on the classpath, Spring Boot's auto-configuration will automatically enable AspectJ auto proxy such that `@EnableAspectJAutoProxy` is not required.
|
||||
@@ -0,0 +1,341 @@
|
||||
[[features.developing-auto-configuration]]
|
||||
= Creating Your Own Auto-configuration
|
||||
|
||||
If you work in a company that develops shared libraries, or if you work on an open-source or commercial library, you might want to develop your own auto-configuration.
|
||||
Auto-configuration classes can be bundled in external jars and still be picked up by Spring Boot.
|
||||
|
||||
Auto-configuration can be associated to a "`starter`" that provides the auto-configuration code as well as the typical libraries that you would use with it.
|
||||
We first cover what you need to know to build your own auto-configuration and then we move on to the xref:features/developing-auto-configuration.adoc#features.developing-auto-configuration.custom-starter[typical steps required to create a custom starter].
|
||||
|
||||
|
||||
|
||||
[[features.developing-auto-configuration.understanding-auto-configured-beans]]
|
||||
== Understanding Auto-configured Beans
|
||||
|
||||
Classes that implement auto-configuration are annotated with `@AutoConfiguration`.
|
||||
This annotation itself is meta-annotated with `@Configuration`, making auto-configurations standard `@Configuration` classes.
|
||||
Additional `@Conditional` annotations are used to constrain when the auto-configuration should apply.
|
||||
Usually, auto-configuration classes use `@ConditionalOnClass` and `@ConditionalOnMissingBean` annotations.
|
||||
This ensures that auto-configuration applies only when relevant classes are found and when you have not declared your own `@Configuration`.
|
||||
|
||||
You can browse the source code of {code-spring-boot-autoconfigure-src}[`spring-boot-autoconfigure`] to see the `@AutoConfiguration` classes that Spring provides (see the {code-spring-boot}/spring-boot-project/spring-boot-autoconfigure/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports[`META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`] file).
|
||||
|
||||
|
||||
|
||||
[[features.developing-auto-configuration.locating-auto-configuration-candidates]]
|
||||
== Locating Auto-configuration Candidates
|
||||
|
||||
Spring Boot checks for the presence of a `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports` file within your published jar.
|
||||
The file should list your configuration classes, with one class name per line, as shown in the following example:
|
||||
|
||||
[source]
|
||||
----
|
||||
com.mycorp.libx.autoconfigure.LibXAutoConfiguration
|
||||
com.mycorp.libx.autoconfigure.LibXWebAutoConfiguration
|
||||
----
|
||||
|
||||
TIP: You can add comments to the imports file using the `#` character.
|
||||
|
||||
NOTE: Auto-configurations must be loaded _only_ by being named in the imports file.
|
||||
Make sure that they are defined in a specific package space and that they are never the target of component scanning.
|
||||
Furthermore, auto-configuration classes should not enable component scanning to find additional components.
|
||||
Specific `@Import` annotations should be used instead.
|
||||
|
||||
If your configuration needs to be applied in a specific order, you can use the `before`, `beforeName`, `after` and `afterName` attributes on the {code-spring-boot-autoconfigure-src}/AutoConfiguration.java[`@AutoConfiguration`] annotation or the dedicated {code-spring-boot-autoconfigure-src}/AutoConfigureBefore.java[`@AutoConfigureBefore`] and {code-spring-boot-autoconfigure-src}/AutoConfigureAfter.java[`@AutoConfigureAfter`] annotations.
|
||||
For example, if you provide web-specific configuration, your class may need to be applied after `WebMvcAutoConfiguration`.
|
||||
|
||||
If you want to order certain auto-configurations that should not have any direct knowledge of each other, you can also use `@AutoConfigureOrder`.
|
||||
That annotation has the same semantic as the regular `@Order` annotation but provides a dedicated order for auto-configuration classes.
|
||||
|
||||
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]]
|
||||
== Condition Annotations
|
||||
|
||||
You almost always want to include one or more `@Conditional` annotations on your auto-configuration class.
|
||||
The `@ConditionalOnMissingBean` annotation is one common example that is used to allow developers to override auto-configuration if they are not happy with your defaults.
|
||||
|
||||
Spring Boot includes a number of `@Conditional` annotations that you can reuse in your own code by annotating `@Configuration` classes or individual `@Bean` methods.
|
||||
These annotations include:
|
||||
|
||||
* xref:features/developing-auto-configuration.adoc#features.developing-auto-configuration.condition-annotations.class-conditions[Class Conditions]
|
||||
* xref:features/developing-auto-configuration.adoc#features.developing-auto-configuration.condition-annotations.bean-conditions[Bean Conditions]
|
||||
* xref:features/developing-auto-configuration.adoc#features.developing-auto-configuration.condition-annotations.property-conditions[Property Conditions]
|
||||
* xref:features/developing-auto-configuration.adoc#features.developing-auto-configuration.condition-annotations.resource-conditions[Resource Conditions]
|
||||
* xref:features/developing-auto-configuration.adoc#features.developing-auto-configuration.condition-annotations.web-application-conditions[Web Application Conditions]
|
||||
* xref:features/developing-auto-configuration.adoc#features.developing-auto-configuration.condition-annotations.spel-conditions[SpEL Expression Conditions]
|
||||
|
||||
|
||||
|
||||
[[features.developing-auto-configuration.condition-annotations.class-conditions]]
|
||||
=== Class Conditions
|
||||
|
||||
The `@ConditionalOnClass` and `@ConditionalOnMissingClass` annotations let `@Configuration` classes be included based on the presence or absence of specific classes.
|
||||
Due to the fact that annotation metadata is parsed by using https://asm.ow2.io/[ASM], you can use the `value` attribute to refer to the real class, even though that class might not actually appear on the running application classpath.
|
||||
You can also use the `name` attribute if you prefer to specify the class name by using a `String` value.
|
||||
|
||||
This mechanism does not apply the same way to `@Bean` methods where typically the return type is the target of the condition: before the condition on the method applies, the JVM will have loaded the class and potentially processed method references which will fail if the class is not present.
|
||||
|
||||
To handle this scenario, a separate `@Configuration` class can be used to isolate the condition, as shown in the following example:
|
||||
|
||||
include-code::MyAutoConfiguration[]
|
||||
|
||||
TIP: If you use `@ConditionalOnClass` or `@ConditionalOnMissingClass` as a part of a meta-annotation to compose your own composed annotations, you must use `name` as referring to the class in such a case is not handled.
|
||||
|
||||
|
||||
|
||||
[[features.developing-auto-configuration.condition-annotations.bean-conditions]]
|
||||
=== Bean Conditions
|
||||
|
||||
The `@ConditionalOnBean` and `@ConditionalOnMissingBean` annotations let a bean be included based on the presence or absence of specific beans.
|
||||
You can use the `value` attribute to specify beans by type or `name` to specify beans by name.
|
||||
The `search` attribute lets you limit the `ApplicationContext` hierarchy that should be considered when searching for beans.
|
||||
|
||||
When placed on a `@Bean` method, the target type defaults to the return type of the method, as shown in the following example:
|
||||
|
||||
include-code::MyAutoConfiguration[]
|
||||
|
||||
In the preceding example, the `someService` bean is going to be created if no bean of type `SomeService` is already contained in the `ApplicationContext`.
|
||||
|
||||
TIP: You need to be very careful about the order in which bean definitions are added, as these conditions are evaluated based on what has been processed so far.
|
||||
For this reason, we recommend using only `@ConditionalOnBean` and `@ConditionalOnMissingBean` annotations on auto-configuration classes (since these are guaranteed to load after any user-defined bean definitions have been added).
|
||||
|
||||
NOTE: `@ConditionalOnBean` and `@ConditionalOnMissingBean` do not prevent `@Configuration` classes from being created.
|
||||
The only difference between using these conditions at the class level and marking each contained `@Bean` method with the annotation is that the former prevents registration of the `@Configuration` class as a bean if the condition does not match.
|
||||
|
||||
TIP: 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]]
|
||||
=== 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]]
|
||||
=== 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]]
|
||||
=== 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`.
|
||||
A reactive web application is any application that uses a `ReactiveWebApplicationContext`, or has a `ConfigurableReactiveWebEnvironment`.
|
||||
|
||||
The `@ConditionalOnWarDeployment` and `@ConditionalOnNotWarDeployment` annotations let configuration be included depending on whether the application is a traditional WAR application that is deployed to a servlet container.
|
||||
This condition will not match for applications that are run with an embedded web server.
|
||||
|
||||
|
||||
|
||||
[[features.developing-auto-configuration.condition-annotations.spel-conditions]]
|
||||
=== SpEL Expression Conditions
|
||||
|
||||
The `@ConditionalOnExpression` annotation lets configuration be included based on the result of a {url-spring-framework-docs}/core/expressions.html[SpEL expression].
|
||||
|
||||
NOTE: 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]]
|
||||
== 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.
|
||||
|
||||
WARNING: `ApplicationContextRunner` doesn't work when running the tests in a native image.
|
||||
|
||||
`ApplicationContextRunner` is usually defined as a field of the test class to gather the base, common configuration.
|
||||
The following example makes sure that `MyServiceAutoConfiguration` is always invoked:
|
||||
|
||||
include-code::MyServiceAutoConfigurationTests[tag=runner]
|
||||
|
||||
TIP: If multiple auto-configurations have to be defined, there is no need to order their declarations as they are invoked in the exact same order as when running the application.
|
||||
|
||||
Each test can use the runner to represent a particular use case.
|
||||
For instance, the sample below invokes a user configuration (`UserConfiguration`) and checks that the auto-configuration backs off properly.
|
||||
Invoking `run` provides a callback context that can be used with `AssertJ`.
|
||||
|
||||
include-code::MyServiceAutoConfigurationTests[tag=test-user-config]
|
||||
|
||||
It is also possible to easily customize the `Environment`, as shown in the following example:
|
||||
|
||||
include-code::MyServiceAutoConfigurationTests[tag=test-env]
|
||||
|
||||
The runner can also be used to display the `ConditionEvaluationReport`.
|
||||
The report can be printed at `INFO` or `DEBUG` level.
|
||||
The following example shows how to use the `ConditionEvaluationReportLoggingListener` to print the report in auto-configuration tests.
|
||||
|
||||
include-code::MyConditionEvaluationReportingTests[]
|
||||
|
||||
|
||||
|
||||
[[features.developing-auto-configuration.testing.simulating-a-web-context]]
|
||||
=== Simulating a Web Context
|
||||
|
||||
If you need to test an auto-configuration that only operates in a servlet or reactive web application context, use the `WebApplicationContextRunner` or `ReactiveWebApplicationContextRunner` respectively.
|
||||
|
||||
|
||||
|
||||
[[features.developing-auto-configuration.testing.overriding-classpath]]
|
||||
=== Overriding the Classpath
|
||||
|
||||
It is also possible to test what happens when a particular class and/or package is not present at runtime.
|
||||
Spring Boot ships with a `FilteredClassLoader` that can easily be used by the runner.
|
||||
In the following example, we assert that if `MyService` is not present, the auto-configuration is properly disabled:
|
||||
|
||||
include-code::../MyServiceAutoConfigurationTests[tag=test-classloader]
|
||||
|
||||
|
||||
|
||||
[[features.developing-auto-configuration.custom-starter]]
|
||||
== 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.
|
||||
Finally, a single "starter" dependency is provided to help users get started as easily as possible.
|
||||
|
||||
Concretely, a custom starter can contain the following:
|
||||
|
||||
* The `autoconfigure` module that contains the auto-configuration code for "acme".
|
||||
* The `starter` module that provides a dependency to the `autoconfigure` module as well as "acme" and any additional dependencies that are typically useful.
|
||||
In a nutshell, adding the starter should provide everything needed to start using that library.
|
||||
|
||||
This separation in two modules is in no way necessary.
|
||||
If "acme" has several flavors, options or optional features, then it is better to separate the auto-configuration as you can clearly express the fact some features are optional.
|
||||
Besides, you have the ability to craft a starter that provides an opinion about those optional dependencies.
|
||||
At the same time, others can rely only on the `autoconfigure` module and craft their own starter with different opinions.
|
||||
|
||||
If the auto-configuration is relatively straightforward and does not have optional features, merging the two modules in the starter is definitely an option.
|
||||
|
||||
|
||||
|
||||
[[features.developing-auto-configuration.custom-starter.naming]]
|
||||
=== Naming
|
||||
|
||||
You should make sure to provide a proper namespace for your starter.
|
||||
Do not start your module names with `spring-boot`, even if you use a different Maven `groupId`.
|
||||
We may offer official support for the thing you auto-configure in the future.
|
||||
|
||||
As a rule of thumb, you should name a combined module after the starter.
|
||||
For example, assume that you are creating a starter for "acme" and that you name the auto-configure module `acme-spring-boot` 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]]
|
||||
=== 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).
|
||||
If you use the same namespace, we may modify these namespaces in the future in ways that break your modules.
|
||||
As a rule of thumb, prefix all your keys with a namespace that you own (for example `acme`).
|
||||
|
||||
Make sure that configuration keys are documented by adding field javadoc for each property, as shown in the following example:
|
||||
|
||||
include-code::AcmeProperties[]
|
||||
|
||||
NOTE: You should only use plain text with `@ConfigurationProperties` field Javadoc, since they are not processed before being added to the JSON.
|
||||
|
||||
Here are some rules we follow internally to make sure descriptions are consistent:
|
||||
|
||||
* Do not start the description by "The" or "A".
|
||||
* For `boolean` types, start the description with "Whether" or "Enable".
|
||||
* For collection-based types, start the description with "Comma-separated list"
|
||||
* Use `java.time.Duration` rather than `long` and describe the default unit if it differs from milliseconds, such as "If a duration suffix is not specified, seconds will be used".
|
||||
* Do not provide the default value in the description unless it has to be determined at runtime.
|
||||
|
||||
Make sure to xref:specification:configuration-metadata/annotation-processor.adoc[trigger meta-data generation] so that IDE assistance is available for your keys as well.
|
||||
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]]
|
||||
=== 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.
|
||||
|
||||
TIP: You should mark the dependencies to the library as optional so that you can include the `autoconfigure` module in your projects more easily.
|
||||
If you do it that way, the library is not provided and, by default, Spring Boot backs off.
|
||||
|
||||
Spring Boot uses an annotation processor to collect the conditions on auto-configurations in a metadata file (`META-INF/spring-autoconfigure-metadata.properties`).
|
||||
If that file is present, it is used to eagerly filter auto-configurations that do not match, which will improve startup time.
|
||||
|
||||
When building with Maven, it is recommended to add the following dependency in a module that contains auto-configurations:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-autoconfigure-processor</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
----
|
||||
|
||||
If you have defined auto-configurations directly in your application, make sure to configure the `spring-boot-maven-plugin` to prevent the `repackage` goal from adding the dependency into the uber jar:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<project>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-autoconfigure-processor</artifactId>
|
||||
</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
----
|
||||
|
||||
With Gradle, the dependency should be declared in the `annotationProcessor` configuration, as shown in the following example:
|
||||
|
||||
[source,gradle]
|
||||
----
|
||||
dependencies {
|
||||
annotationProcessor "org.springframework.boot:spring-boot-autoconfigure-processor"
|
||||
}
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[features.developing-auto-configuration.custom-starter.starter-module]]
|
||||
=== Starter Module
|
||||
|
||||
The starter is really an empty jar.
|
||||
Its only purpose is to provide the necessary dependencies to work with the library.
|
||||
You can think of it as an opinionated view of what is required to get started.
|
||||
|
||||
Do not make assumptions about the project in which your starter is added.
|
||||
If the library you are auto-configuring typically requires other starters, mention them as well.
|
||||
Providing a proper set of _default_ dependencies may be hard if the number of optional dependencies is high, as you should avoid including dependencies that are unnecessary for a typical usage of the library.
|
||||
In other words, you should not include optional dependencies.
|
||||
|
||||
NOTE: Either way, your starter must reference the core Spring Boot starter (`spring-boot-starter`) directly or indirectly (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.
|
||||
@@ -0,0 +1,273 @@
|
||||
[[features.docker-compose]]
|
||||
= Docker Compose Support
|
||||
|
||||
Docker Compose is a popular technology that can be used to define and manage multiple containers for services that your application needs.
|
||||
A `compose.yml` file is typically created next to your application which defines and configures service containers.
|
||||
|
||||
A typical workflow with Docker Compose is to run `docker compose up`, work on your application with it connecting to started services, then run `docker compose down` when you are finished.
|
||||
|
||||
The `spring-boot-docker-compose` module can be included in a project to provide support for working with containers using Docker Compose.
|
||||
Add the module dependency to your build, as shown in the following listings for Maven and Gradle:
|
||||
|
||||
.Maven
|
||||
[source,xml]
|
||||
----
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-docker-compose</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
----
|
||||
|
||||
.Gradle
|
||||
[source,gradle]
|
||||
----
|
||||
dependencies {
|
||||
developmentOnly("org.springframework.boot:spring-boot-docker-compose")
|
||||
}
|
||||
----
|
||||
|
||||
When this module is included as a dependency Spring Boot will do the following:
|
||||
|
||||
* Search for a `compose.yml` and other common compose filenames in your application directory
|
||||
* Call `docker compose up` with the discovered `compose.yml`
|
||||
* Create service connection beans for each supported container
|
||||
* Call `docker compose stop` when the application is shutdown
|
||||
|
||||
If the Docker Compose services are already running when starting the application, Spring Boot will only create the service connection beans for each supported container.
|
||||
It will not call `docker compose up` again and it will not call `docker compose stop` when the application is shutdown.
|
||||
|
||||
NOTE: By default, Spring Boot's Docker Compose support is disabled when running tests.
|
||||
To enable it, set configprop:spring.docker.compose.skip.in-tests[] to `false`.
|
||||
|
||||
|
||||
|
||||
[[features.docker-compose.prerequisites]]
|
||||
== Prerequisites
|
||||
|
||||
You need to have the `docker` and `docker compose` (or `docker-compose`) CLI applications on your path.
|
||||
The minimum supported Docker Compose version is 2.2.0.
|
||||
|
||||
|
||||
|
||||
[[features.docker-compose.service-connections]]
|
||||
== Service Connections
|
||||
|
||||
A service connection is a connection to any remote service.
|
||||
Spring Boot’s auto-configuration can consume the details of a service connection and use them to establish a connection to a remote service.
|
||||
When doing so, the connection details take precedence over any connection-related configuration properties.
|
||||
|
||||
When using Spring Boot’s Docker Compose support, service connections are established to the port mapped by the container.
|
||||
|
||||
NOTE: Docker compose is usually used in such a way that the ports inside the container are mapped to ephemeral ports on your computer.
|
||||
For example, a Postgres server may run inside the container using port 5432 but be mapped to a totally different port locally.
|
||||
The service connection will always discover and use the locally mapped port.
|
||||
|
||||
Service connections are established by using the image name of the container.
|
||||
The following service connections are currently supported:
|
||||
|
||||
|
||||
|===
|
||||
| Connection Details | Matched on
|
||||
|
||||
| `ActiveMQConnectionDetails`
|
||||
| Containers named "symptoma/activemq" or "apache/activemq-classic"
|
||||
|
||||
| `ArtemisConnectionDetails`
|
||||
| Containers named "apache/activemq-artemis"
|
||||
|
||||
| `CassandraConnectionDetails`
|
||||
| Containers named "cassandra" or "bitnami/cassandra"
|
||||
|
||||
| `ElasticsearchConnectionDetails`
|
||||
| Containers named "elasticsearch" or "bitnami/elasticsearch"
|
||||
|
||||
| `JdbcConnectionDetails`
|
||||
| Containers named "gvenzl/oracle-free", "gvenzl/oracle-xe", "mariadb", "bitnami/mariadb", "mssql/server", "mysql", "bitnami/mysql", "postgres", or "bitnami/postgresql"
|
||||
|
||||
| `LdapConnectionDetails`
|
||||
| Containers named "osixia/openldap"
|
||||
|
||||
| `MongoConnectionDetails`
|
||||
| Containers named "mongo" or "bitnami/mongodb"
|
||||
|
||||
| `Neo4jConnectionDetails`
|
||||
| Containers named "neo4j" or "bitnami/neo4j"
|
||||
|
||||
| `OtlpMetricsConnectionDetails`
|
||||
| Containers named "otel/opentelemetry-collector-contrib"
|
||||
|
||||
| `OtlpTracingConnectionDetails`
|
||||
| Containers named "otel/opentelemetry-collector-contrib"
|
||||
|
||||
| `PulsarConnectionDetails`
|
||||
| Containers named "apachepulsar/pulsar"
|
||||
|
||||
| `R2dbcConnectionDetails`
|
||||
| Containers named "gvenzl/oracle-free", "gvenzl/oracle-xe", "mariadb", "bitnami/mariadb", "mssql/server", "mysql", "bitnami/mysql", "postgres", or "bitnami/postgresql"
|
||||
|
||||
| `RabbitConnectionDetails`
|
||||
| Containers named "rabbitmq" or "bitnami/rabbitmq"
|
||||
|
||||
| `RedisConnectionDetails`
|
||||
| Containers named "redis" or "bitnami/redis"
|
||||
|
||||
| `ZipkinConnectionDetails`
|
||||
| Containers named "openzipkin/zipkin".
|
||||
|===
|
||||
|
||||
|
||||
|
||||
[[features.docker-compose.custom-images]]
|
||||
== Custom Images
|
||||
|
||||
Sometimes you may need to use your own version of an image to provide a service.
|
||||
You can use any custom image as long as it behaves in the same way as the standard image.
|
||||
Specifically, any environment variables that the standard image supports must also be used in your custom image.
|
||||
|
||||
If your image uses a different name, you can use a label in your `compose.yml` file so that Spring Boot can provide a service connection.
|
||||
Use a label named `org.springframework.boot.service-connection` to provide the service name.
|
||||
|
||||
For example:
|
||||
|
||||
[source,yaml,]
|
||||
----
|
||||
services:
|
||||
redis:
|
||||
image: 'mycompany/mycustomredis:7.0'
|
||||
ports:
|
||||
- '6379'
|
||||
labels:
|
||||
org.springframework.boot.service-connection: redis
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[features.docker-compose.skipping]]
|
||||
== Skipping Specific Containers
|
||||
|
||||
If you have a container image defined in your `compose.yml` that you don’t want connected to your application you can use a label to ignore it.
|
||||
Any container with labeled with `org.springframework.boot.ignore` will be ignored by Spring Boot.
|
||||
|
||||
For example:
|
||||
|
||||
[source,yaml]
|
||||
----
|
||||
services:
|
||||
redis:
|
||||
image: 'redis:7.0'
|
||||
ports:
|
||||
- '6379'
|
||||
labels:
|
||||
org.springframework.boot.ignore: true
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[features.docker-compose.specific-file]]
|
||||
== Using a Specific Compose File
|
||||
|
||||
If your compose file is not in the same directory as your application, or if it’s named differently, you can use configprop:spring.docker.compose.file[] in your `application.properties` or `application.yaml` to point to a different file.
|
||||
Properties can be defined as an exact path or a path that’s relative to your application.
|
||||
|
||||
For example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
docker:
|
||||
compose:
|
||||
file: "../my-compose.yml"
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[features.docker-compose.readiness]]
|
||||
== Waiting for Container Readiness
|
||||
|
||||
Containers started by Docker Compose may take some time to become fully ready.
|
||||
The recommended way of checking for readiness is to add a `healthcheck` section under the service definition in your `compose.yml` file.
|
||||
|
||||
Since it's not uncommon for `healthcheck` configuration to be omitted from `compose.yml` files, Spring Boot also checks directly for service readiness.
|
||||
By default, a container is considered ready when a TCP/IP connection can be established to its mapped port.
|
||||
|
||||
You can disable this on a per-container basis by adding a `org.springframework.boot.readiness-check.tcp.disable` label in your `compose.yml` file.
|
||||
|
||||
For example:
|
||||
|
||||
[source,yaml]
|
||||
----
|
||||
services:
|
||||
redis:
|
||||
image: 'redis:7.0'
|
||||
ports:
|
||||
- '6379'
|
||||
labels:
|
||||
org.springframework.boot.readiness-check.tcp.disable: true
|
||||
----
|
||||
|
||||
You can also change timeout values in your `application.properties` or `application.yaml` file:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
docker:
|
||||
compose:
|
||||
readiness:
|
||||
tcp:
|
||||
connect-timeout: 10s
|
||||
read-timeout: 5s
|
||||
----
|
||||
|
||||
The overall timeout can be configured using configprop:spring.docker.compose.readiness.timeout[].
|
||||
|
||||
|
||||
|
||||
[[features.docker-compose.lifecycle]]
|
||||
== Controlling the Docker Compose Lifecycle
|
||||
|
||||
By default Spring Boot calls `docker compose up` when your application starts and `docker compose stop` when it's shut down.
|
||||
If you prefer to have different lifecycle management you can use the configprop:spring.docker.compose.lifecycle-management[] property.
|
||||
|
||||
The following values are supported:
|
||||
|
||||
* `none` - Do not start or stop Docker Compose
|
||||
* `start-only` - Start Docker Compose when the application starts and leave it running
|
||||
* `start-and-stop` - Start Docker Compose when the application starts and stop it when the JVM exits
|
||||
|
||||
In addition you can use the configprop:spring.docker.compose.start.command[] property to change whether `docker compose up` or `docker compose start` is used.
|
||||
The configprop:spring.docker.compose.stop.command[] allows you to configure if `docker compose down` or `docker compose stop` is used.
|
||||
|
||||
The following example shows how lifecycle management can be configured:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
docker:
|
||||
compose:
|
||||
lifecycle-management: start-and-stop
|
||||
start:
|
||||
command: start
|
||||
stop:
|
||||
command: down
|
||||
timeout: 1m
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[features.docker-compose.profiles]]
|
||||
== Activating Docker Compose Profiles
|
||||
|
||||
Docker Compose profiles are similar to Spring profiles in that they let you adjust your Docker Compose configuration for specific environments.
|
||||
If you want to activate a specific Docker Compose profile you can use the configprop:spring.docker.compose.profiles.active[] property in your `application.properties` or `application.yaml` file:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
docker:
|
||||
compose:
|
||||
profiles:
|
||||
active: "myprofile"
|
||||
----
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,7 @@
|
||||
[[features]]
|
||||
= 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 "xref:tutorial:index.adoc[Tutoral]" and "xref:using/index.adoc[Developing with Spring Boot]" sections, so that you have a good grounding of the basics.
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
[[features.internationalization]]
|
||||
= Internationalization
|
||||
|
||||
Spring Boot supports localized messages so that your application can cater to users of different language preferences.
|
||||
By default, Spring Boot looks for the presence of a `messages` resource bundle at the root of the classpath.
|
||||
|
||||
NOTE: The auto-configuration applies when the default properties file for the configured resource bundle is available (`messages.properties` by default).
|
||||
If your resource bundle contains only language-specific properties files, you are required to add the default.
|
||||
If no properties file is found that matches any of the configured base names, there will be no auto-configured `MessageSource`.
|
||||
|
||||
The basename of the resource bundle as well as several other attributes can be configured using the `spring.messages` namespace, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
messages:
|
||||
basename: "messages,config.i18n.messages"
|
||||
fallback-to-system-locale: false
|
||||
----
|
||||
|
||||
TIP: `spring.messages.basename` supports comma-separated list of locations, either a package qualifier or a resource resolved from the classpath root.
|
||||
|
||||
See {code-spring-boot-autoconfigure-src}/context/MessageSourceProperties.java[`MessageSourceProperties`] for more supported options.
|
||||
@@ -0,0 +1,70 @@
|
||||
[[features.json]]
|
||||
= JSON
|
||||
|
||||
Spring Boot provides integration with three JSON mapping libraries:
|
||||
|
||||
- Gson
|
||||
- Jackson
|
||||
- JSON-B
|
||||
|
||||
Jackson is the preferred and default library.
|
||||
|
||||
|
||||
|
||||
[[features.json.jackson]]
|
||||
== Jackson
|
||||
|
||||
Auto-configuration for Jackson is provided and Jackson is part of `spring-boot-starter-json`.
|
||||
When Jackson is on the classpath an `ObjectMapper` bean is automatically configured.
|
||||
Several configuration properties are provided for xref:how-to:spring-mvc.adoc#howto.spring-mvc.customize-jackson-objectmapper[customizing the configuration of the `ObjectMapper`].
|
||||
|
||||
|
||||
|
||||
[[features.json.jackson.custom-serializers-and-deserializers]]
|
||||
=== Custom Serializers and Deserializers
|
||||
|
||||
If you use Jackson to serialize and deserialize JSON data, you might want to write your own `JsonSerializer` and `JsonDeserializer` classes.
|
||||
Custom serializers are usually https://github.com/FasterXML/jackson-docs/wiki/JacksonHowToCustomSerializers[registered with Jackson through a module], but Spring Boot provides an alternative `@JsonComponent` annotation that makes it easier to directly register Spring Beans.
|
||||
|
||||
You can use the `@JsonComponent` annotation directly on `JsonSerializer`, `JsonDeserializer` or `KeyDeserializer` implementations.
|
||||
You can also use it on classes that contain serializers/deserializers as inner classes, as shown in the following example:
|
||||
|
||||
include-code::MyJsonComponent[]
|
||||
|
||||
All `@JsonComponent` beans in the `ApplicationContext` are automatically registered with Jackson.
|
||||
Because `@JsonComponent` is meta-annotated with `@Component`, the usual component-scanning rules apply.
|
||||
|
||||
Spring Boot also provides {code-spring-boot-src}/jackson/JsonObjectSerializer.java[`JsonObjectSerializer`] and {code-spring-boot-src}/jackson/JsonObjectDeserializer.java[`JsonObjectDeserializer`] base classes that provide useful alternatives to the standard Jackson versions when serializing objects.
|
||||
See xref:api:java/org/springframework/boot/jackson/JsonObjectSerializer.html[`JsonObjectSerializer`] and xref:api:java/org/springframework/boot/jackson/JsonObjectDeserializer.html[`JsonObjectDeserializer`] in the Javadoc for details.
|
||||
|
||||
The example above can be rewritten to use `JsonObjectSerializer`/`JsonObjectDeserializer` as follows:
|
||||
|
||||
include-code::object/MyJsonComponent[]
|
||||
|
||||
|
||||
|
||||
[[features.json.jackson.mixins]]
|
||||
=== Mixins
|
||||
|
||||
Jackson has support for mixins that can be used to mix additional annotations into those already declared on a target class.
|
||||
Spring Boot's Jackson auto-configuration will scan your application's packages for classes annotated with `@JsonMixin` and register them with the auto-configured `ObjectMapper`.
|
||||
The registration is performed by Spring Boot's `JsonMixinModule`.
|
||||
|
||||
|
||||
|
||||
[[features.json.gson]]
|
||||
== Gson
|
||||
|
||||
Auto-configuration for Gson is provided.
|
||||
When Gson is on the classpath a `Gson` bean is automatically configured.
|
||||
Several `+spring.gson.*+` configuration properties are provided for customizing the configuration.
|
||||
To take more control, one or more `GsonBuilderCustomizer` beans can be used.
|
||||
|
||||
|
||||
|
||||
[[features.json.json-b]]
|
||||
== JSON-B
|
||||
|
||||
Auto-configuration for JSON-B is provided.
|
||||
When the JSON-B API and an implementation are on the classpath a `Jsonb` bean will be automatically configured.
|
||||
The preferred JSON-B implementation is Eclipse Yasson for which dependency management is provided.
|
||||
@@ -0,0 +1,182 @@
|
||||
[[features.kotlin]]
|
||||
= Kotlin Support
|
||||
|
||||
https://kotlinlang.org[Kotlin] is a statically-typed language targeting the JVM (and other platforms) which allows writing concise and elegant code while providing {url-kotlin-docs}/java-interop.html[interoperability] with existing libraries written in Java.
|
||||
|
||||
Spring Boot provides Kotlin support by leveraging the support in other Spring projects such as Spring Framework, Spring Data, and Reactor.
|
||||
See the {url-spring-framework-docs}/languages/kotlin.html[Spring Framework Kotlin support documentation] for more information.
|
||||
|
||||
The easiest way to start with Spring Boot and Kotlin is to follow https://spring.io/guides/tutorials/spring-boot-kotlin/[this comprehensive tutorial].
|
||||
You can create new Kotlin projects by using https://start.spring.io/#!language=kotlin[start.spring.io].
|
||||
Feel free to join the #spring channel of https://slack.kotlinlang.org/[Kotlin Slack] or ask a question with the `spring` and `kotlin` tags on https://stackoverflow.com/questions/tagged/spring+kotlin[Stack Overflow] if you need support.
|
||||
|
||||
|
||||
|
||||
[[features.kotlin.requirements]]
|
||||
== Requirements
|
||||
|
||||
Spring Boot requires at least Kotlin 1.7.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.
|
||||
The `kotlin-stdlib` variants `kotlin-stdlib-jdk7` and `kotlin-stdlib-jdk8` can also be used.
|
||||
|
||||
Since https://discuss.kotlinlang.org/t/classes-final-by-default/166[Kotlin classes are final by default], you are likely to want to configure {url-kotlin-docs}/compiler-plugins.html#spring-support[kotlin-spring] plugin in order to automatically open Spring-annotated classes so that they can be proxied.
|
||||
|
||||
https://github.com/FasterXML/jackson-module-kotlin[Jackson's Kotlin module] is required for serializing / deserializing JSON data in Kotlin.
|
||||
It is automatically registered when found on the classpath.
|
||||
A warning message is logged if Jackson and Kotlin are present but the Jackson Kotlin module is not.
|
||||
|
||||
TIP: These dependencies and plugins are provided by default if one bootstraps a Kotlin project on https://start.spring.io/#!language=kotlin[start.spring.io].
|
||||
|
||||
|
||||
|
||||
[[features.kotlin.null-safety]]
|
||||
== Null-safety
|
||||
|
||||
One of Kotlin's key features is {url-kotlin-docs}/null-safety.html[null-safety].
|
||||
It deals with `null` values at compile time rather than deferring the problem to runtime and encountering a `NullPointerException`.
|
||||
This helps to eliminate a common source of bugs without paying the cost of wrappers like `Optional`.
|
||||
Kotlin also allows using functional constructs with nullable values as described in this https://www.baeldung.com/kotlin-null-safety[comprehensive guide to null-safety in Kotlin].
|
||||
|
||||
Although Java does not allow one to express null-safety in its type system, Spring Framework, Spring Data, and Reactor now provide null-safety of their API through tooling-friendly annotations.
|
||||
By default, types from Java APIs used in Kotlin are recognized as {url-kotlin-docs}/java-interop.html#null-safety-and-platform-types[platform types] for which null-checks are relaxed.
|
||||
{url-kotlin-docs}/java-interop.html#jsr-305-support[Kotlin's support for JSR 305 annotations] combined with nullability annotations provide null-safety for the related Spring API in Kotlin.
|
||||
|
||||
The JSR 305 checks can be configured by adding the `-Xjsr305` compiler flag with the following options: `-Xjsr305={strict|warn|ignore}`.
|
||||
The default behavior is the same as `-Xjsr305=warn`.
|
||||
The `strict` value is required to have null-safety taken in account in Kotlin types inferred from Spring API but should be used with the knowledge that Spring API nullability declaration could evolve even between minor releases and more checks may be added in the future).
|
||||
|
||||
WARNING: Generic type arguments, varargs and array elements nullability are not yet supported.
|
||||
See https://jira.spring.io/browse/SPR-15942[SPR-15942] for up-to-date information.
|
||||
Also be aware that Spring Boot's own API is {url-github-issues}/10712[not yet annotated].
|
||||
|
||||
|
||||
|
||||
[[features.kotlin.api]]
|
||||
== Kotlin API
|
||||
|
||||
|
||||
|
||||
[[features.kotlin.api.run-application]]
|
||||
=== runApplication
|
||||
|
||||
Spring Boot provides an idiomatic way to run an application with `runApplication<MyApplication>(*args)` as shown in the following example:
|
||||
|
||||
[source,kotlin]
|
||||
----
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication
|
||||
import org.springframework.boot.runApplication
|
||||
|
||||
@SpringBootApplication
|
||||
class MyApplication
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
runApplication<MyApplication>(*args)
|
||||
}
|
||||
----
|
||||
|
||||
This is a drop-in replacement for `SpringApplication.run(MyApplication::class.java, *args)`.
|
||||
It also allows customization of the application as shown in the following example:
|
||||
|
||||
[source,kotlin]
|
||||
----
|
||||
runApplication<MyApplication>(*args) {
|
||||
setBannerMode(OFF)
|
||||
}
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[features.kotlin.api.extensions]]
|
||||
=== Extensions
|
||||
|
||||
Kotlin {url-kotlin-docs}/extensions.html[extensions] provide the ability to extend existing classes with additional functionality.
|
||||
The Spring Boot Kotlin API makes use of these extensions to add new Kotlin specific conveniences to existing APIs.
|
||||
|
||||
`TestRestTemplate` extensions, similar to those provided by Spring Framework for `RestOperations` in Spring Framework, are provided.
|
||||
Among other things, the extensions make it possible to take advantage of Kotlin reified type parameters.
|
||||
|
||||
|
||||
|
||||
[[features.kotlin.dependency-management]]
|
||||
== Dependency management
|
||||
|
||||
In order to avoid mixing different versions of Kotlin dependencies on the classpath, Spring Boot imports the Kotlin BOM.
|
||||
|
||||
With Maven, the Kotlin version can be customized by setting the `kotlin.version` property and plugin management is provided for `kotlin-maven-plugin`.
|
||||
With Gradle, the Spring Boot plugin automatically aligns the `kotlin.version` with the version of the Kotlin plugin.
|
||||
|
||||
Spring Boot also manages the version of Coroutines dependencies by importing the Kotlin Coroutines BOM.
|
||||
The version can be customized by setting the `kotlin-coroutines.version` property.
|
||||
|
||||
TIP: `org.jetbrains.kotlinx:kotlinx-coroutines-reactor` dependency is provided by default if one bootstraps a Kotlin project with at least one reactive dependency on https://start.spring.io/#!language=kotlin[start.spring.io].
|
||||
|
||||
|
||||
|
||||
[[features.kotlin.configuration-properties]]
|
||||
== @ConfigurationProperties
|
||||
|
||||
`@ConfigurationProperties` when used in combination with xref:features/external-config.adoc#features.external-config.typesafe-configuration-properties.constructor-binding[constructor binding] supports classes with immutable `val` properties as shown in the following example:
|
||||
|
||||
[source,kotlin]
|
||||
----
|
||||
@ConfigurationProperties("example.kotlin")
|
||||
data class KotlinExampleProperties(
|
||||
val name: String,
|
||||
val description: String,
|
||||
val myService: MyService) {
|
||||
|
||||
data class MyService(
|
||||
val apiToken: String,
|
||||
val uri: URI
|
||||
)
|
||||
}
|
||||
----
|
||||
|
||||
TIP: To generate xref:specification:configuration-metadata/annotation-processor.adoc[your own metadata] using the annotation processor, {url-kotlin-docs}/kapt.html[`kapt` should be configured] 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]]
|
||||
== 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.
|
||||
This makes it possible to use `@BeforeAll` and `@AfterAll` annotations on non-static methods, which is a good fit for Kotlin.
|
||||
|
||||
To mock Kotlin classes, https://mockk.io/[MockK] is recommended.
|
||||
If you need the `MockK` equivalent of the Mockito specific xref:features/testing.adoc#features.testing.spring-boot-applications.mocking-beans[`@MockBean` and `@SpyBean` annotations], you can use https://github.com/Ninja-Squad/springmockk[SpringMockK] which provides similar `@MockkBean` and `@SpykBean` annotations.
|
||||
|
||||
|
||||
|
||||
[[features.kotlin.resources]]
|
||||
== Resources
|
||||
|
||||
|
||||
|
||||
[[features.kotlin.resources.further-reading]]
|
||||
=== Further reading
|
||||
|
||||
* {url-kotlin-docs}[Kotlin language reference]
|
||||
* https://kotlinlang.slack.com/[Kotlin Slack] (with a dedicated #spring channel)
|
||||
* https://stackoverflow.com/questions/tagged/spring+kotlin[Stack Overflow with `spring` and `kotlin` tags]
|
||||
* https://try.kotlinlang.org/[Try Kotlin in your browser]
|
||||
* https://blog.jetbrains.com/kotlin/[Kotlin blog]
|
||||
* https://kotlin.link/[Awesome Kotlin]
|
||||
* https://spring.io/guides/tutorials/spring-boot-kotlin/[Tutorial: building web applications with Spring Boot and Kotlin]
|
||||
* https://spring.io/blog/2016/02/15/developing-spring-boot-applications-with-kotlin[Developing Spring Boot applications with Kotlin]
|
||||
* https://spring.io/blog/2016/03/20/a-geospatial-messenger-with-kotlin-spring-boot-and-postgresql[A Geospatial Messenger with Kotlin, Spring Boot and PostgreSQL]
|
||||
* https://spring.io/blog/2017/01/04/introducing-kotlin-support-in-spring-framework-5-0[Introducing Kotlin support in Spring Framework 5.0]
|
||||
* https://spring.io/blog/2017/08/01/spring-framework-5-kotlin-apis-the-functional-way[Spring Framework 5 Kotlin APIs, the functional way]
|
||||
|
||||
|
||||
|
||||
[[features.kotlin.resources.examples]]
|
||||
=== Examples
|
||||
|
||||
* https://github.com/sdeleuze/spring-boot-kotlin-demo[spring-boot-kotlin-demo]: regular Spring Boot + Spring Data JPA project
|
||||
* https://github.com/mixitconf/mixit[mixit]: Spring Boot 2 + WebFlux + Reactive Spring Data MongoDB
|
||||
* https://github.com/sdeleuze/spring-kotlin-fullstack[spring-kotlin-fullstack]: WebFlux Kotlin fullstack example with Kotlin2js for frontend instead of JavaScript or TypeScript
|
||||
* https://github.com/spring-petclinic/spring-petclinic-kotlin[spring-petclinic-kotlin]: Kotlin version of the Spring PetClinic Sample Application
|
||||
* https://github.com/sdeleuze/spring-kotlin-deepdive[spring-kotlin-deepdive]: a step by step migration for Boot 1.0 + Java to Boot 2.0 + Kotlin
|
||||
* https://github.com/sdeleuze/spring-boot-coroutines-demo[spring-boot-coroutines-demo]: Coroutines sample project
|
||||
@@ -0,0 +1,572 @@
|
||||
[[features.logging]]
|
||||
= Logging
|
||||
|
||||
Spring Boot uses https://commons.apache.org/logging[Commons Logging] for all internal logging but leaves the underlying log implementation open.
|
||||
Default configurations are provided for {apiref-openjdk}/java.logging/java/util/logging/package-summary.html[Java Util Logging], https://logging.apache.org/log4j/2.x/[Log4j2], and https://logback.qos.ch/[Logback].
|
||||
In each case, loggers are pre-configured to use console output with optional file output also available.
|
||||
|
||||
By default, if you use the "`Starters`", Logback is used for logging.
|
||||
Appropriate Logback routing is also included to ensure that dependent libraries that use Java Util Logging, Commons Logging, Log4J, or SLF4J all work correctly.
|
||||
|
||||
TIP: There are a lot of logging frameworks available for Java.
|
||||
Do not worry if the above list seems confusing.
|
||||
Generally, you do not need to change your logging dependencies and the Spring Boot defaults work just fine.
|
||||
|
||||
TIP: 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]]
|
||||
== Log Format
|
||||
|
||||
The default log output from Spring Boot resembles the following example:
|
||||
|
||||
[source]
|
||||
----
|
||||
include::ROOT:partial$logging/logging-format.txt[]
|
||||
----
|
||||
|
||||
The following items are output:
|
||||
|
||||
* Date and Time: Millisecond precision and easily sortable.
|
||||
* Log Level: `ERROR`, `WARN`, `INFO`, `DEBUG`, or `TRACE`.
|
||||
* Process ID.
|
||||
* A `---` separator to distinguish the start of actual log messages.
|
||||
* Application name: Enclosed in square brackets (logged by default only if configprop:spring.application.name[] is set)
|
||||
* Thread name: Enclosed in square brackets (may be truncated for console output).
|
||||
* Correlation ID: If tracing is enabled (not shown in the sample above)
|
||||
* Logger name: This is usually the source class name (often abbreviated).
|
||||
* The log message.
|
||||
|
||||
NOTE: Logback does not have a `FATAL` level.
|
||||
It is mapped to `ERROR`.
|
||||
|
||||
TIP: If you have a configprop:spring.application.name[] property but don't want it logged you can set configprop:logging.include-application-name[] to `false`.
|
||||
|
||||
|
||||
|
||||
[[features.logging.console-output]]
|
||||
== Console Output
|
||||
|
||||
The default log configuration echoes messages to the console as they are written.
|
||||
By default, `ERROR`-level, `WARN`-level, and `INFO`-level messages are logged.
|
||||
You can also enable a "`debug`" mode by starting your application with a `--debug` flag.
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ java -jar myapp.jar --debug
|
||||
----
|
||||
|
||||
NOTE: You can also specify `debug=true` in your `application.properties`.
|
||||
|
||||
When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate, and Spring Boot) are configured to output more information.
|
||||
Enabling the debug mode does _not_ configure your application to log all messages with `DEBUG` level.
|
||||
|
||||
Alternatively, you can enable a "`trace`" mode by starting your application with a `--trace` flag (or `trace=true` in your `application.properties`).
|
||||
Doing so enables trace logging for a selection of core loggers (embedded container, Hibernate schema generation, and the whole Spring portfolio).
|
||||
|
||||
|
||||
|
||||
[[features.logging.console-output.color-coded]]
|
||||
=== Color-coded Output
|
||||
|
||||
If your terminal supports ANSI, color output is used to aid readability.
|
||||
You can set `spring.output.ansi.enabled` to a xref:api:java/org/springframework/boot/ansi/AnsiOutput.Enabled.html[supported value] to override the auto-detection.
|
||||
|
||||
Color coding is configured by using the `%clr` conversion word.
|
||||
In its simplest form, the converter colors the output according to the log level, as shown in the following example:
|
||||
|
||||
[source]
|
||||
----
|
||||
%clr(%5p)
|
||||
----
|
||||
|
||||
The following table describes the mapping of log levels to colors:
|
||||
|
||||
|===
|
||||
| Level | Color
|
||||
|
||||
| `FATAL`
|
||||
| Red
|
||||
|
||||
| `ERROR`
|
||||
| Red
|
||||
|
||||
| `WARN`
|
||||
| Yellow
|
||||
|
||||
| `INFO`
|
||||
| Green
|
||||
|
||||
| `DEBUG`
|
||||
| Green
|
||||
|
||||
| `TRACE`
|
||||
| Green
|
||||
|===
|
||||
|
||||
Alternatively, you can specify the color or style that should be used by providing it as an option to the conversion.
|
||||
For example, to make the text yellow, use the following setting:
|
||||
|
||||
[source]
|
||||
----
|
||||
%clr(%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}){yellow}
|
||||
----
|
||||
|
||||
The following colors and styles are supported:
|
||||
|
||||
* `blue`
|
||||
* `cyan`
|
||||
* `faint`
|
||||
* `green`
|
||||
* `magenta`
|
||||
* `red`
|
||||
* `yellow`
|
||||
|
||||
|
||||
|
||||
[[features.logging.file-output]]
|
||||
== File Output
|
||||
|
||||
By default, Spring Boot logs only to the console and does not write log files.
|
||||
If you want to write log files in addition to the console output, you need to set a configprop:logging.file.name[] or configprop:logging.file.path[] property (for example, in your `application.properties`).
|
||||
|
||||
The following table shows how the `logging.*` properties can be used together:
|
||||
|
||||
.Logging properties
|
||||
[cols="1,1,1,4"]
|
||||
|===
|
||||
| configprop:logging.file.name[] | configprop:logging.file.path[] | Example | Description
|
||||
|
||||
| _(none)_
|
||||
| _(none)_
|
||||
|
|
||||
| Console only logging.
|
||||
|
||||
| Specific file
|
||||
| _(none)_
|
||||
| `my.log`
|
||||
| Writes to the specified log file.
|
||||
Names can be an exact location or relative to the current directory.
|
||||
|
||||
| _(none)_
|
||||
| Specific directory
|
||||
| `/var/log`
|
||||
| Writes `spring.log` to the specified directory.
|
||||
Names can be an exact location or relative to the current directory.
|
||||
|===
|
||||
|
||||
Log files rotate when they reach 10 MB and, as with console output, `ERROR`-level, `WARN`-level, and `INFO`-level messages are logged by default.
|
||||
|
||||
TIP: Logging properties are independent of the actual logging infrastructure.
|
||||
As a result, specific configuration keys (such as `logback.configurationFile` for Logback) are not managed by spring Boot.
|
||||
|
||||
|
||||
|
||||
[[features.logging.file-rotation]]
|
||||
== 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).
|
||||
|
||||
The following rotation policy properties are supported:
|
||||
|
||||
|===
|
||||
| Name | Description
|
||||
|
||||
| configprop:logging.logback.rollingpolicy.file-name-pattern[]
|
||||
| The filename pattern used to create log archives.
|
||||
|
||||
| configprop:logging.logback.rollingpolicy.clean-history-on-start[]
|
||||
| If log archive cleanup should occur when the application starts.
|
||||
|
||||
| configprop:logging.logback.rollingpolicy.max-file-size[]
|
||||
| The maximum size of log file before it is archived.
|
||||
|
||||
| configprop:logging.logback.rollingpolicy.total-size-cap[]
|
||||
| The maximum amount of size log archives can take before being deleted.
|
||||
|
||||
| configprop:logging.logback.rollingpolicy.max-history[]
|
||||
| The maximum number of archive log files to keep (defaults to 7).
|
||||
|===
|
||||
|
||||
|
||||
|
||||
[[features.logging.log-levels]]
|
||||
== Log Levels
|
||||
|
||||
All the supported logging systems can have the logger levels set in the Spring `Environment` (for example, in `application.properties`) by using `+logging.level.<logger-name>=<level>+` where `level` is one of TRACE, DEBUG, INFO, WARN, ERROR, FATAL, or OFF.
|
||||
The `root` logger can be configured by using `logging.level.root`.
|
||||
|
||||
The following example shows potential logging settings in `application.properties`:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
logging:
|
||||
level:
|
||||
root: "warn"
|
||||
org.springframework.web: "debug"
|
||||
org.hibernate: "error"
|
||||
----
|
||||
|
||||
It is also possible to set logging levels using environment variables.
|
||||
For example, `LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_WEB=DEBUG` will set `org.springframework.web` to `DEBUG`.
|
||||
|
||||
NOTE: 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 xref:features/external-config.adoc#features.external-config.application-json[the `SPRING_APPLICATION_JSON`] variable.
|
||||
|
||||
|
||||
|
||||
[[features.logging.log-groups]]
|
||||
== 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.
|
||||
|
||||
To help with this, Spring Boot allows you to define logging groups in your Spring `Environment`.
|
||||
For example, here is how you could define a "`tomcat`" group by adding it to your `application.properties`:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
logging:
|
||||
group:
|
||||
tomcat: "org.apache.catalina,org.apache.coyote,org.apache.tomcat"
|
||||
----
|
||||
|
||||
Once defined, you can change the level for all the loggers in the group with a single line:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
logging:
|
||||
level:
|
||||
tomcat: "trace"
|
||||
----
|
||||
|
||||
Spring Boot includes the following pre-defined logging groups that can be used out-of-the-box:
|
||||
|
||||
[cols="1,4"]
|
||||
|===
|
||||
| Name | Loggers
|
||||
|
||||
| web
|
||||
| `org.springframework.core.codec`, `org.springframework.http`, `org.springframework.web`, `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]]
|
||||
== 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.
|
||||
If your application has complex context hierarchies the shutdown hook may not meet your needs.
|
||||
If it does not, disable the shutdown hook and investigate the options provided directly by the underlying logging system.
|
||||
For example, Logback offers https://logback.qos.ch/manual/loggingSeparation.html[context selectors] which allow each Logger to be created in its own context.
|
||||
You can use the configprop:logging.register-shutdown-hook[] property to disable the shutdown hook.
|
||||
Setting it to `false` will disable the registration.
|
||||
You can set the property in your `application.properties` or `application.yaml` file:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
logging:
|
||||
register-shutdown-hook: false
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[features.logging.custom-log-configuration]]
|
||||
== Custom Log Configuration
|
||||
|
||||
The various logging systems can be activated by including the appropriate libraries on the classpath and can be further customized by providing a suitable configuration file in the root of the classpath or in a location specified by the following Spring `Environment` property: configprop:logging.config[].
|
||||
|
||||
You can force Spring Boot to use a particular logging system by using the `org.springframework.boot.logging.LoggingSystem` system property.
|
||||
The value should be the fully qualified class name of a `LoggingSystem` implementation.
|
||||
You can also disable Spring Boot's logging configuration entirely by using a value of `none`.
|
||||
|
||||
NOTE: Since logging is initialized *before* the `ApplicationContext` is created, it is not possible to control logging from `@PropertySources` in Spring `@Configuration` files.
|
||||
The only way to change the logging system or disable it entirely is through System properties.
|
||||
|
||||
Depending on your logging system, the following files are loaded:
|
||||
|
||||
|===
|
||||
| Logging System | Customization
|
||||
|
||||
| Logback
|
||||
| `logback-spring.xml`, `logback-spring.groovy`, `logback.xml`, or `logback.groovy`
|
||||
|
||||
| Log4j2
|
||||
| `log4j2-spring.xml` or `log4j2.xml`
|
||||
|
||||
| JDK (Java Util Logging)
|
||||
| `logging.properties`
|
||||
|===
|
||||
|
||||
NOTE: When possible, we recommend that you use the `-spring` variants for your logging configuration (for example, `logback-spring.xml` rather than `logback.xml`).
|
||||
If you use standard configuration locations, Spring cannot completely control log initialization.
|
||||
|
||||
WARNING: There are known classloading issues with Java Util Logging that cause problems when running from an 'executable jar'.
|
||||
We recommend that you avoid it when running from an 'executable jar' if at all possible.
|
||||
|
||||
To help with the customization, some other properties are transferred from the Spring `Environment` to System properties.
|
||||
This allows the properties to be consumed by logging system configuration. For example, setting `logging.file.name` in `application.properties` or `LOGGING_FILE_NAME` as an environment variable will result in the `LOG_FILE` System property being set.
|
||||
The properties that are transferred are described in the following table:
|
||||
|
||||
|===
|
||||
| Spring Environment | System Property | Comments
|
||||
|
||||
| configprop:logging.exception-conversion-word[]
|
||||
| `LOG_EXCEPTION_CONVERSION_WORD`
|
||||
| The conversion word used when logging exceptions.
|
||||
|
||||
| configprop:logging.file.name[]
|
||||
| `LOG_FILE`
|
||||
| If defined, it is used in the default log configuration.
|
||||
|
||||
| configprop:logging.file.path[]
|
||||
| `LOG_PATH`
|
||||
| If defined, it is used in the default log configuration.
|
||||
|
||||
| configprop:logging.pattern.console[]
|
||||
| `CONSOLE_LOG_PATTERN`
|
||||
| The log pattern to use on the console (stdout).
|
||||
|
||||
| configprop:logging.pattern.dateformat[]
|
||||
| `LOG_DATEFORMAT_PATTERN`
|
||||
| Appender pattern for log date format.
|
||||
|
||||
| configprop:logging.charset.console[]
|
||||
| `CONSOLE_LOG_CHARSET`
|
||||
| The charset to use for console logging.
|
||||
|
||||
| configprop:logging.threshold.console[]
|
||||
| `CONSOLE_LOG_THRESHOLD`
|
||||
| The log level threshold to use for console logging.
|
||||
|
||||
| configprop:logging.pattern.file[]
|
||||
| `FILE_LOG_PATTERN`
|
||||
| The log pattern to use in a file (if `LOG_FILE` is enabled).
|
||||
|
||||
| configprop:logging.charset.file[]
|
||||
| `FILE_LOG_CHARSET`
|
||||
| The charset to use for file logging (if `LOG_FILE` is enabled).
|
||||
|
||||
| configprop:logging.threshold.file[]
|
||||
| `FILE_LOG_THRESHOLD`
|
||||
| The log level threshold to use for file logging.
|
||||
|
||||
| configprop:logging.pattern.level[]
|
||||
| `LOG_LEVEL_PATTERN`
|
||||
| The format to use when rendering the log level (default `%5p`).
|
||||
|
||||
| `PID`
|
||||
| `PID`
|
||||
| The current process ID (discovered if possible and when not already defined as an OS environment variable).
|
||||
|===
|
||||
|
||||
If you use Logback, the following properties are also transferred:
|
||||
|
||||
|===
|
||||
| Spring Environment | System Property | Comments
|
||||
|
||||
| configprop:logging.logback.rollingpolicy.file-name-pattern[]
|
||||
| `LOGBACK_ROLLINGPOLICY_FILE_NAME_PATTERN`
|
||||
| Pattern for rolled-over log file names (default `$\{LOG_FILE}.%d\{yyyy-MM-dd}.%i.gz`).
|
||||
|
||||
| configprop:logging.logback.rollingpolicy.clean-history-on-start[]
|
||||
| `LOGBACK_ROLLINGPOLICY_CLEAN_HISTORY_ON_START`
|
||||
| Whether to clean the archive log files on startup.
|
||||
|
||||
| configprop:logging.logback.rollingpolicy.max-file-size[]
|
||||
| `LOGBACK_ROLLINGPOLICY_MAX_FILE_SIZE`
|
||||
| Maximum log file size.
|
||||
|
||||
| configprop:logging.logback.rollingpolicy.total-size-cap[]
|
||||
| `LOGBACK_ROLLINGPOLICY_TOTAL_SIZE_CAP`
|
||||
| Total size of log backups to be kept.
|
||||
|
||||
| configprop:logging.logback.rollingpolicy.max-history[]
|
||||
| `LOGBACK_ROLLINGPOLICY_MAX_HISTORY`
|
||||
| Maximum number of archive log files to keep.
|
||||
|===
|
||||
|
||||
|
||||
All the supported logging systems can consult System properties when parsing their configuration files.
|
||||
See the default configurations in `spring-boot.jar` for examples:
|
||||
|
||||
* {code-spring-boot}/spring-boot-project/spring-boot/src/main/resources/org/springframework/boot/logging/logback/defaults.xml[Logback]
|
||||
* {code-spring-boot}/spring-boot-project/spring-boot/src/main/resources/org/springframework/boot/logging/log4j2/log4j2.xml[Log4j 2]
|
||||
* {code-spring-boot}/spring-boot-project/spring-boot/src/main/resources/org/springframework/boot/logging/java/logging-file.properties[Java Util logging]
|
||||
|
||||
[TIP]
|
||||
====
|
||||
If you want to use a placeholder in a logging property, you should use xref:features/external-config.adoc#features.external-config.files.property-placeholders[Spring Boot's syntax] and not the syntax of the underlying framework.
|
||||
Notably, if you use Logback, you should use `:` as the delimiter between a property name and its default value and not use `:-`.
|
||||
====
|
||||
|
||||
[TIP]
|
||||
====
|
||||
You can add MDC and other ad-hoc content to log lines by overriding only the `LOG_LEVEL_PATTERN` (or `logging.pattern.level` with Logback).
|
||||
For example, if you use `logging.pattern.level=user:%X\{user} %5p`, then the default log format contains an MDC entry for "user", if it exists, as shown in the following example.
|
||||
|
||||
[source]
|
||||
----
|
||||
2019-08-30 12:30:04.031 user:someone INFO 22174 --- [ nio-8080-exec-0] demo.Controller
|
||||
Handling authenticated request
|
||||
----
|
||||
====
|
||||
|
||||
|
||||
|
||||
[[features.logging.logback-extensions]]
|
||||
== Logback Extensions
|
||||
|
||||
Spring Boot includes a number of extensions to Logback that can help with advanced configuration.
|
||||
You can use these extensions in your `logback-spring.xml` configuration file.
|
||||
|
||||
NOTE: Because the standard `logback.xml` configuration file is loaded too early, you cannot use extensions in it.
|
||||
You need to either use `logback-spring.xml` or define a configprop:logging.config[] property.
|
||||
|
||||
WARNING: The extensions cannot be used with Logback's https://logback.qos.ch/manual/configuration.html#autoScan[configuration scanning].
|
||||
If you attempt to do so, making changes to the configuration file results in an error similar to one of the following being logged:
|
||||
|
||||
[source]
|
||||
----
|
||||
ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProperty], current ElementPath is [[configuration][springProperty]]
|
||||
ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProfile], current ElementPath is [[configuration][springProfile]]
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[features.logging.logback-extensions.profile-specific]]
|
||||
=== Profile-specific Configuration
|
||||
|
||||
The `<springProfile>` tag lets you optionally include or exclude sections of configuration based on the active Spring profiles.
|
||||
Profile sections are supported anywhere within the `<configuration>` element.
|
||||
Use the `name` attribute to specify which profile accepts the configuration.
|
||||
The `<springProfile>` tag can contain a profile name (for example `staging`) or a profile expression.
|
||||
A profile expression allows for more complicated profile logic to be expressed, for example `production & (eu-central | eu-west)`.
|
||||
Check the {url-spring-framework-docs}/core/beans/environment.html#beans-definition-profiles-java[Spring Framework reference guide] for more details.
|
||||
The following listing shows three sample profiles:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<springProfile name="staging">
|
||||
<!-- configuration to be enabled when the "staging" profile is active -->
|
||||
</springProfile>
|
||||
|
||||
<springProfile name="dev | staging">
|
||||
<!-- configuration to be enabled when the "dev" or "staging" profiles are active -->
|
||||
</springProfile>
|
||||
|
||||
<springProfile name="!production">
|
||||
<!-- configuration to be enabled when the "production" profile is not active -->
|
||||
</springProfile>
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[features.logging.logback-extensions.environment-properties]]
|
||||
=== Environment Properties
|
||||
|
||||
The `<springProperty>` tag lets you expose properties from the Spring `Environment` for use within Logback.
|
||||
Doing so can be useful if you want to access values from your `application.properties` file in your Logback configuration.
|
||||
The tag works in a similar way to Logback's standard `<property>` tag.
|
||||
However, rather than specifying a direct `value`, you specify the `source` of the property (from the `Environment`).
|
||||
If you need to store the property somewhere other than in `local` scope, you can use the `scope` attribute.
|
||||
If you need a fallback value (in case the property is not set in the `Environment`), you can use the `defaultValue` attribute.
|
||||
The following example shows how to expose properties for use within Logback:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<springProperty scope="context" name="fluentHost" source="myapp.fluentd.host"
|
||||
defaultValue="localhost"/>
|
||||
<appender name="FLUENT" class="ch.qos.logback.more.appenders.DataFluentAppender">
|
||||
<remoteHost>${fluentHost}</remoteHost>
|
||||
...
|
||||
</appender>
|
||||
----
|
||||
|
||||
NOTE: The `source` must be specified in kebab case (such as `my.property-name`).
|
||||
However, properties can be added to the `Environment` by using the relaxed rules.
|
||||
|
||||
|
||||
|
||||
[[features.logging.log4j2-extensions]]
|
||||
== Log4j2 Extensions
|
||||
|
||||
Spring Boot includes a number of extensions to Log4j2 that can help with advanced configuration.
|
||||
You can use these extensions in any `log4j2-spring.xml` configuration file.
|
||||
|
||||
NOTE: Because the standard `log4j2.xml` configuration file is loaded too early, you cannot use extensions in it.
|
||||
You need to either use `log4j2-spring.xml` or define a configprop:logging.config[] property.
|
||||
|
||||
NOTE: The extensions supersede the https://logging.apache.org/log4j/2.x/log4j-spring-boot/index.html[Spring Boot support] provided by Log4J.
|
||||
You should make sure not to include the `org.apache.logging.log4j:log4j-spring-boot` module in your build.
|
||||
|
||||
|
||||
|
||||
[[features.logging.log4j2-extensions.profile-specific]]
|
||||
=== Profile-specific Configuration
|
||||
|
||||
The `<SpringProfile>` tag lets you optionally include or exclude sections of configuration based on the active Spring profiles.
|
||||
Profile sections are supported anywhere within the `<Configuration>` element.
|
||||
Use the `name` attribute to specify which profile accepts the configuration.
|
||||
The `<SpringProfile>` tag can contain a profile name (for example `staging`) or a profile expression.
|
||||
A profile expression allows for more complicated profile logic to be expressed, for example `production & (eu-central | eu-west)`.
|
||||
Check the {url-spring-framework-docs}/core/beans/environment.html#beans-definition-profiles-java[Spring Framework reference guide] for more details.
|
||||
The following listing shows three sample profiles:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<SpringProfile name="staging">
|
||||
<!-- configuration to be enabled when the "staging" profile is active -->
|
||||
</SpringProfile>
|
||||
|
||||
<SpringProfile name="dev | staging">
|
||||
<!-- configuration to be enabled when the "dev" or "staging" profiles are active -->
|
||||
</SpringProfile>
|
||||
|
||||
<SpringProfile name="!production">
|
||||
<!-- configuration to be enabled when the "production" profile is not active -->
|
||||
</SpringProfile>
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[features.logging.log4j2-extensions.environment-properties-lookup]]
|
||||
=== Environment Properties Lookup
|
||||
|
||||
If you want to refer to properties from your Spring `Environment` within your Log4j2 configuration you can use `spring:` prefixed https://logging.apache.org/log4j/2.x/manual/lookups.html[lookups].
|
||||
Doing so can be useful if you want to access values from your `application.properties` file in your Log4j2 configuration.
|
||||
|
||||
The following example shows how to set a Log4j2 property named `applicationName` that reads `spring.application.name` from the Spring `Environment`:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<Properties>
|
||||
<Property name="applicationName">${spring:spring.application.name}</Property>
|
||||
</Properties>
|
||||
----
|
||||
|
||||
NOTE: The lookup key should be specified in kebab case (such as `my.property-name`).
|
||||
|
||||
|
||||
|
||||
[[features.logging.log4j2-extensions.environment-property-source]]
|
||||
=== Log4j2 System Properties
|
||||
|
||||
Log4j2 supports a number of https://logging.apache.org/log4j/2.x/manual/configuration.html#SystemProperties[System Properties] that can be used to configure various items.
|
||||
For example, the `log4j2.skipJansi` system property can be used to configure if the `ConsoleAppender` will try to use a https://github.com/fusesource/jansi[Jansi] output stream on Windows.
|
||||
|
||||
All system properties that are loaded after the Log4j2 initialization can be obtained from the Spring `Environment`.
|
||||
For example, you could add `log4j2.skipJansi=false` to your `application.properties` file to have the `ConsoleAppender` use Jansi on Windows.
|
||||
|
||||
NOTE: The Spring `Environment` is only considered when system properties and OS environment variables do not contain the value being loaded.
|
||||
|
||||
WARNING: System properties that are loaded during early Log4j2 initialization cannot reference the Spring `Environment`.
|
||||
For example, the property Log4j2 uses to allow the default Log4j2 implementation to be chosen is used before the Spring Environment is available.
|
||||
@@ -0,0 +1,124 @@
|
||||
[[features.profiles]]
|
||||
= Profiles
|
||||
|
||||
Spring Profiles provide a way to segregate parts of your application configuration and make it be available only in certain environments.
|
||||
Any `@Component`, `@Configuration` or `@ConfigurationProperties` can be marked with `@Profile` to limit when it is loaded, as shown in the following example:
|
||||
|
||||
include-code::ProductionConfiguration[]
|
||||
|
||||
NOTE: If `@ConfigurationProperties` beans are registered through `@EnableConfigurationProperties` instead of automatic scanning, the `@Profile` annotation needs to be specified on the `@Configuration` class that has the `@EnableConfigurationProperties` annotation.
|
||||
In the case where `@ConfigurationProperties` are scanned, `@Profile` can be specified on the `@ConfigurationProperties` class itself.
|
||||
|
||||
You can use a configprop:spring.profiles.active[] `Environment` property to specify which profiles are active.
|
||||
You can specify the property in any of the ways described earlier in this chapter.
|
||||
For example, you could include it in your `application.properties`, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
profiles:
|
||||
active: "dev,hsqldb"
|
||||
----
|
||||
|
||||
You could also specify it on the command line by using the following switch: `--spring.profiles.active=dev,hsqldb`.
|
||||
|
||||
If no profile is active, a default profile is enabled.
|
||||
The name of the default profile is `default` and it can be tuned using the configprop:spring.profiles.default[] `Environment` property, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
profiles:
|
||||
default: "none"
|
||||
----
|
||||
|
||||
`spring.profiles.active` and `spring.profiles.default` can only be used in non-profile specific documents.
|
||||
This means they cannot be included in xref:features/external-config.adoc#features.external-config.files.profile-specific[profile specific files] or xref:features/external-config.adoc#features.external-config.files.activation-properties[documents activated] by `spring.config.activate.on-profile`.
|
||||
|
||||
For example, the second document configuration is invalid:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
# this document is valid
|
||||
spring:
|
||||
profiles:
|
||||
active: "prod"
|
||||
---
|
||||
# this document is invalid
|
||||
spring:
|
||||
config:
|
||||
activate:
|
||||
on-profile: "prod"
|
||||
profiles:
|
||||
active: "metrics"
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[features.profiles.adding-active-profiles]]
|
||||
== Adding Active Profiles
|
||||
|
||||
The configprop:spring.profiles.active[] property follows the same ordering rules as other properties: The highest `PropertySource` wins.
|
||||
This means that you can specify active profiles in `application.properties` and then *replace* them by using the command line switch.
|
||||
|
||||
Sometimes, it is useful to have properties that *add* to the active profiles rather than replace them.
|
||||
The `spring.profiles.include` property can be used to add active profiles on top of those activated by the configprop:spring.profiles.active[] property.
|
||||
The `SpringApplication` entry point also has a Java API for setting additional profiles.
|
||||
See the `setAdditionalProfiles()` method in xref:api:java/org/springframework/boot/SpringApplication.html[SpringApplication].
|
||||
|
||||
For example, when an application with the following properties is run, the common and local profiles will be activated even when it runs using the `--spring.profiles.active` switch:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
profiles:
|
||||
include:
|
||||
- "common"
|
||||
- "local"
|
||||
----
|
||||
|
||||
WARNING: Similar to `spring.profiles.active`, `spring.profiles.include` can only be used in non-profile specific documents.
|
||||
This means it cannot be included in xref:features/external-config.adoc#features.external-config.files.profile-specific[profile specific files] or xref:features/external-config.adoc#features.external-config.files.activation-properties[documents activated] by `spring.config.activate.on-profile`.
|
||||
|
||||
Profile groups, which are described in the xref:features/profiles.adoc#features.profiles.groups[next section] can also be used to add active profiles if a given profile is active.
|
||||
|
||||
|
||||
|
||||
[[features.profiles.groups]]
|
||||
== 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.
|
||||
|
||||
To help with this, Spring Boot lets you define profile groups.
|
||||
A profile group allows you to define a logical name for a related group of profiles.
|
||||
|
||||
For example, we can create a `production` group that consists of our `proddb` and `prodmq` profiles.
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
profiles:
|
||||
group:
|
||||
production:
|
||||
- "proddb"
|
||||
- "prodmq"
|
||||
----
|
||||
|
||||
Our application can now be started using `--spring.profiles.active=production` to activate the `production`, `proddb` and `prodmq` profiles in one hit.
|
||||
|
||||
|
||||
|
||||
[[features.profiles.programmatically-setting-profiles]]
|
||||
== Programmatically Setting Profiles
|
||||
|
||||
You can programmatically set active profiles by calling `SpringApplication.setAdditionalProfiles(...)` before your application runs.
|
||||
It is also possible to activate profiles by using Spring's `ConfigurableEnvironment` interface.
|
||||
|
||||
|
||||
|
||||
[[features.profiles.profile-specific-configuration-files]]
|
||||
== Profile-specific Configuration Files
|
||||
|
||||
Profile-specific variants of both `application.properties` (or `application.yaml`) and files referenced through `@ConfigurationProperties` are considered as files and loaded.
|
||||
See "xref:features/external-config.adoc#features.external-config.files.profile-specific[Profile Specific Files]" for details.
|
||||
@@ -0,0 +1,414 @@
|
||||
[[features.spring-application]]
|
||||
= SpringApplication
|
||||
|
||||
The `SpringApplication` class provides a convenient way to bootstrap a Spring application that is started from a `main()` method.
|
||||
In many situations, you can delegate to the static `SpringApplication.run` method, as shown in the following example:
|
||||
|
||||
include-code::MyApplication[]
|
||||
|
||||
When your application starts, you should see something similar to the following output:
|
||||
|
||||
[source,subs="verbatim,attributes"]
|
||||
----
|
||||
include::ROOT:partial$application/spring-application.txt[]
|
||||
----
|
||||
|
||||
|
||||
|
||||
By default, `INFO` logging messages are shown, including some relevant startup details, such as the user that launched the application.
|
||||
If you need a log level other than `INFO`, you can set it, as described in xref:features/logging.adoc#features.logging.log-levels[Log Levels].
|
||||
The application version is determined using the implementation version from the main application class's package.
|
||||
Startup information logging can be turned off by setting `spring.main.log-startup-info` to `false`.
|
||||
This will also turn off logging of the application's active profiles.
|
||||
|
||||
TIP: To add additional logging during startup, you can override `logStartupInfo(boolean)` in a subclass of `SpringApplication`.
|
||||
|
||||
|
||||
|
||||
[[features.spring-application.startup-failure]]
|
||||
== Startup Failure
|
||||
|
||||
If your application fails to start, registered `FailureAnalyzers` get a chance to provide a dedicated error message and a concrete action to fix the problem.
|
||||
For instance, if you start a web application on port `8080` and that port is already in use, you should see something similar to the following message:
|
||||
|
||||
[source]
|
||||
----
|
||||
***************************
|
||||
APPLICATION FAILED TO START
|
||||
***************************
|
||||
|
||||
Description:
|
||||
|
||||
Embedded servlet container failed to start. Port 8080 was already in use.
|
||||
|
||||
Action:
|
||||
|
||||
Identify and stop the process that is listening on port 8080 or configure this application to listen on another port.
|
||||
----
|
||||
|
||||
NOTE: Spring Boot provides numerous `FailureAnalyzer` implementations, and you can xref:how-to:application.adoc#howto.application.failure-analyzer[add your own].
|
||||
|
||||
If no failure analyzers are able to handle the exception, you can still display the full conditions report to better understand what went wrong.
|
||||
To do so, you need to xref:features/external-config.adoc[enable the `debug` property] or xref:features/logging.adoc#features.logging.log-levels[enable `DEBUG` logging] for `org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener`.
|
||||
|
||||
For instance, if you are running your application by using `java -jar`, you can enable the `debug` property as follows:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ java -jar myproject-0.0.1-SNAPSHOT.jar --debug
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[features.spring-application.lazy-initialization]]
|
||||
== Lazy Initialization
|
||||
|
||||
`SpringApplication` allows an application to be initialized lazily.
|
||||
When lazy initialization is enabled, beans are created as they are needed rather than during application startup.
|
||||
As a result, enabling lazy initialization can reduce the time that it takes your application to start.
|
||||
In a web application, enabling lazy initialization will result in many web-related beans not being initialized until an HTTP request is received.
|
||||
|
||||
A downside of lazy initialization is that it can delay the discovery of a problem with the application.
|
||||
If a misconfigured bean is initialized lazily, a failure will no longer occur during startup and the problem will only become apparent when the bean is initialized.
|
||||
Care must also be taken to ensure that the JVM has sufficient memory to accommodate all of the application's beans and not just those that are initialized during startup.
|
||||
For these reasons, lazy initialization is not enabled by default and it is recommended that fine-tuning of the JVM's heap size is done before enabling lazy initialization.
|
||||
|
||||
Lazy initialization can be enabled programmatically using the `lazyInitialization` method on `SpringApplicationBuilder` or the `setLazyInitialization` method on `SpringApplication`.
|
||||
Alternatively, it can be enabled using the configprop:spring.main.lazy-initialization[] property as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
main:
|
||||
lazy-initialization: true
|
||||
----
|
||||
|
||||
TIP: If you want to disable lazy initialization for certain beans while using lazy initialization for the rest of the application, you can explicitly set their lazy attribute to false using the `@Lazy(false)` annotation.
|
||||
|
||||
|
||||
|
||||
[[features.spring-application.banner]]
|
||||
== Customizing the Banner
|
||||
|
||||
The banner that is printed on start up can be changed by adding a `banner.txt` file to your classpath or by setting the configprop: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`.
|
||||
|
||||
Inside your `banner.txt` file, you can use any key available in the `Environment` as well as any of the following placeholders:
|
||||
|
||||
.Banner variables
|
||||
|===
|
||||
| Variable | Description
|
||||
|
||||
| `${application.version}`
|
||||
| The version number of your application, as declared in `MANIFEST.MF`.
|
||||
For example, `Implementation-Version: 1.0` is printed as `1.0`.
|
||||
|
||||
| `${application.formatted-version}`
|
||||
| The version number of your application, as declared in `MANIFEST.MF` and formatted for display (surrounded with brackets and prefixed with `v`).
|
||||
For example `(v1.0)`.
|
||||
|
||||
| `${spring-boot.version}`
|
||||
| The Spring Boot version that you are using.
|
||||
For example `{version-spring-boot}`.
|
||||
|
||||
| `${spring-boot.formatted-version}`
|
||||
| The Spring Boot version that you are using, formatted for display (surrounded with brackets and prefixed with `v`).
|
||||
For example `(v{version-spring-boot})`.
|
||||
|
||||
| `${Ansi.NAME}` (or `${AnsiColor.NAME}`, `${AnsiBackground.NAME}`, `${AnsiStyle.NAME}`)
|
||||
| Where `NAME` is the name of an ANSI escape code.
|
||||
See {code-spring-boot-src}/ansi/AnsiPropertySource.java[`AnsiPropertySource`] for details.
|
||||
|
||||
| `${application.title}`
|
||||
| The title of your application, as declared in `MANIFEST.MF`.
|
||||
For example `Implementation-Title: MyApp` is printed as `MyApp`.
|
||||
|===
|
||||
|
||||
TIP: The `SpringApplication.setBanner(...)` method can be used if you want to generate a banner programmatically.
|
||||
Use the `org.springframework.boot.Banner` interface and implement your own `printBanner()` method.
|
||||
|
||||
You can also use the configprop:spring.main.banner-mode[] property to determine if the banner has to be printed on `System.out` (`console`), sent to the configured logger (`log`), or not produced at all (`off`).
|
||||
|
||||
The printed banner is registered as a singleton bean under the following name: `springBootBanner`.
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
The `application.title`, `application.version`, and `application.formatted-version` properties are only available if you are using `java -jar` or `java -cp` with Spring Boot launchers.
|
||||
The values will not be resolved if you are running an unpacked jar and starting it with `java -cp <classpath> <mainclass>`
|
||||
or running your application as a native image.
|
||||
|
||||
To use the `application.*` properties, launch your application as a packed jar using `java -jar` or as an unpacked jar using `java org.springframework.boot.loader.launch.JarLauncher`.
|
||||
This will initialize the `application.*` banner properties before building the classpath and launching your app.
|
||||
====
|
||||
|
||||
|
||||
|
||||
[[features.spring-application.customizing-spring-application]]
|
||||
== Customizing SpringApplication
|
||||
|
||||
If the `SpringApplication` defaults are not to your taste, you can instead create a local instance and customize it.
|
||||
For example, to turn off the banner, you could write:
|
||||
|
||||
include-code::MyApplication[]
|
||||
|
||||
NOTE: The constructor arguments passed to `SpringApplication` are configuration sources for Spring beans.
|
||||
In most cases, these are references to `@Configuration` classes, but they could also be direct references `@Component` classes.
|
||||
|
||||
It is also possible to configure the `SpringApplication` by using an `application.properties` file.
|
||||
See _xref:features/external-config.adoc[Externalized Configuration]_ for details.
|
||||
|
||||
For a complete list of the configuration options, see the xref:api:java/org/springframework/boot/SpringApplication.html[`SpringApplication` Javadoc].
|
||||
|
||||
|
||||
|
||||
[[features.spring-application.fluent-builder-api]]
|
||||
== Fluent Builder API
|
||||
|
||||
If you need to build an `ApplicationContext` hierarchy (multiple contexts with a parent/child relationship) or if you prefer using a "`fluent`" builder API, you can use the `SpringApplicationBuilder`.
|
||||
|
||||
The `SpringApplicationBuilder` lets you chain together multiple method calls and includes `parent` and `child` methods that let you create a hierarchy, as shown in the following example:
|
||||
|
||||
include-code::MyApplication[tag=*]
|
||||
|
||||
NOTE: There are some restrictions when creating an `ApplicationContext` hierarchy.
|
||||
For example, Web components *must* be contained within the child context, and the same `Environment` is used for both parent and child contexts.
|
||||
See the xref:api:java/org/springframework/boot/builder/SpringApplicationBuilder.html[`SpringApplicationBuilder` Javadoc] for full details.
|
||||
|
||||
|
||||
|
||||
[[features.spring-application.application-availability]]
|
||||
== Application Availability
|
||||
|
||||
When deployed on platforms, applications can provide information about their availability to the platform using infrastructure such as https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/[Kubernetes Probes].
|
||||
Spring Boot includes out-of-the box support for the commonly used "`liveness`" and "`readiness`" availability states.
|
||||
If you are using Spring Boot's "`actuator`" support then these states are exposed as health endpoint groups.
|
||||
|
||||
In addition, you can also obtain availability states by injecting the `ApplicationAvailability` interface into your own beans.
|
||||
|
||||
|
||||
|
||||
[[features.spring-application.application-availability.liveness]]
|
||||
=== 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.
|
||||
|
||||
NOTE: In general, the "Liveness" state should not be based on external checks, such as xref:actuator/endpoints.adoc#actuator.endpoints.health[Health checks].
|
||||
If it did, a failing external system (a database, a Web API, an external cache) would trigger massive restarts and cascading failures across the platform.
|
||||
|
||||
The internal state of Spring Boot applications is mostly represented by the Spring `ApplicationContext`.
|
||||
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 xref:features/spring-application.adoc#features.spring-application.application-events-and-listeners[Spring Boot application lifecycle and related Application Events].
|
||||
|
||||
|
||||
|
||||
[[features.spring-application.application-availability.readiness]]
|
||||
=== 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.
|
||||
This typically happens during startup, while `CommandLineRunner` and `ApplicationRunner` components are being processed, or at any time if the application decides that it is too busy for additional traffic.
|
||||
|
||||
An application is considered ready as soon as application and command-line runners have been called, see xref:features/spring-application.adoc#features.spring-application.application-events-and-listeners[Spring Boot application lifecycle and related Application Events].
|
||||
|
||||
TIP: 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]]
|
||||
=== 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.
|
||||
|
||||
For example, we can export the "Readiness" state of the application to a file so that a Kubernetes "exec Probe" can look at this file:
|
||||
|
||||
include-code::MyReadinessStateExporter[]
|
||||
|
||||
We can also update the state of the application, when the application breaks and cannot recover:
|
||||
|
||||
include-code::MyLocalCacheVerifier[]
|
||||
|
||||
Spring Boot provides xref:actuator/endpoints.adoc#actuator.endpoints.kubernetes-probes[Kubernetes HTTP probes for "Liveness" and "Readiness" with Actuator Health Endpoints].
|
||||
You can get more guidance about xref:deployment/cloud.adoc#deployment.cloud.kubernetes[deploying Spring Boot applications on Kubernetes in the dedicated section].
|
||||
|
||||
|
||||
|
||||
[[features.spring-application.application-events-and-listeners]]
|
||||
== Application Events and Listeners
|
||||
|
||||
In addition to the usual Spring Framework events, such as {url-spring-framework-javadoc}/org/springframework/context/event/ContextRefreshedEvent.html[`ContextRefreshedEvent`], a `SpringApplication` sends some additional application events.
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
Some events are actually triggered before the `ApplicationContext` is created, so you cannot register a listener on those as a `@Bean`.
|
||||
You can register them with the `SpringApplication.addListeners(...)` method or the `SpringApplicationBuilder.listeners(...)` method.
|
||||
|
||||
If you want those listeners to be registered automatically, regardless of the way the application is created, you can add a `META-INF/spring.factories` file to your project and reference your listener(s) by using the `org.springframework.context.ApplicationListener` key, as shown in the following example:
|
||||
|
||||
[source]
|
||||
----
|
||||
org.springframework.context.ApplicationListener=com.example.project.MyListener
|
||||
----
|
||||
|
||||
====
|
||||
|
||||
Application events are sent in the following order, as your application runs:
|
||||
|
||||
. An `ApplicationStartingEvent` is sent at the start of a run but before any processing, except for the registration of listeners and initializers.
|
||||
. An `ApplicationEnvironmentPreparedEvent` is sent when the `Environment` to be used in the context is known but before the context is created.
|
||||
. An `ApplicationContextInitializedEvent` is sent when the `ApplicationContext` is prepared and ApplicationContextInitializers have been called but before any bean definitions are loaded.
|
||||
. An `ApplicationPreparedEvent` is sent just before the refresh is started but after bean definitions have been loaded.
|
||||
. An `ApplicationStartedEvent` is sent after the context has been refreshed but before any application and command-line runners have been called.
|
||||
. An `AvailabilityChangeEvent` is sent right after with `LivenessState.CORRECT` to indicate that the application is considered as live.
|
||||
. An `ApplicationReadyEvent` is sent after any xref:features/spring-application.adoc#features.spring-application.command-line-runner[application and command-line runners] have been called.
|
||||
. An `AvailabilityChangeEvent` is sent right after with `ReadinessState.ACCEPTING_TRAFFIC` to indicate that the application is ready to service requests.
|
||||
. An `ApplicationFailedEvent` is sent if there is an exception on startup.
|
||||
|
||||
The above list only includes ``SpringApplicationEvent``s that are tied to a `SpringApplication`.
|
||||
In addition to these, the following events are also published after `ApplicationPreparedEvent` and before `ApplicationStartedEvent`:
|
||||
|
||||
- A `WebServerInitializedEvent` is sent after the `WebServer` is ready.
|
||||
`ServletWebServerInitializedEvent` and `ReactiveWebServerInitializedEvent` are the servlet and reactive variants respectively.
|
||||
- A `ContextRefreshedEvent` is sent when an `ApplicationContext` is refreshed.
|
||||
|
||||
TIP: You often need not use application events, but it can be handy to know that they exist.
|
||||
Internally, Spring Boot uses events to handle a variety of tasks.
|
||||
|
||||
NOTE: Event listeners should not run potentially lengthy tasks as they execute in the same thread by default.
|
||||
Consider using xref:features/spring-application.adoc#features.spring-application.command-line-runner[application and command-line runners] instead.
|
||||
|
||||
Application events are sent by using Spring Framework's event publishing mechanism.
|
||||
Part of this mechanism ensures that an event published to the listeners in a child context is also published to the listeners in any ancestor contexts.
|
||||
As a result of this, if your application uses a hierarchy of `SpringApplication` instances, a listener may receive multiple instances of the same type of application event.
|
||||
|
||||
To allow your listener to distinguish between an event for its context and an event for a descendant context, it should request that its application context is injected and then compare the injected context with the context of the event.
|
||||
The context can be injected by implementing `ApplicationContextAware` or, if the listener is a bean, by using `@Autowired`.
|
||||
|
||||
|
||||
|
||||
[[features.spring-application.web-environment]]
|
||||
== Web Environment
|
||||
|
||||
A `SpringApplication` attempts to create the right type of `ApplicationContext` on your behalf.
|
||||
The algorithm used to determine a `WebApplicationType` is the following:
|
||||
|
||||
* If Spring MVC is present, an `AnnotationConfigServletWebServerApplicationContext` is used
|
||||
* If Spring MVC is not present and Spring WebFlux is present, an `AnnotationConfigReactiveWebServerApplicationContext` is used
|
||||
* Otherwise, `AnnotationConfigApplicationContext` is used
|
||||
|
||||
This means that if you are using Spring MVC and the new `WebClient` from Spring WebFlux in the same application, Spring MVC will be used by default.
|
||||
You can override that easily by calling `setWebApplicationType(WebApplicationType)`.
|
||||
|
||||
It is also possible to take complete control of the `ApplicationContext` type that is used by calling `setApplicationContextFactory(...)`.
|
||||
|
||||
TIP: It is often desirable to call `setWebApplicationType(WebApplicationType.NONE)` when using `SpringApplication` within a JUnit test.
|
||||
|
||||
|
||||
|
||||
[[features.spring-application.application-arguments]]
|
||||
== Accessing Application Arguments
|
||||
|
||||
If you need to access the application arguments that were passed to `SpringApplication.run(...)`, you can inject a `org.springframework.boot.ApplicationArguments` bean.
|
||||
The `ApplicationArguments` interface provides access to both the raw `String[]` arguments as well as parsed `option` and `non-option` arguments, as shown in the following example:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
TIP: Spring Boot also registers a `CommandLinePropertySource` with the Spring `Environment`.
|
||||
This lets you also inject single application arguments by using the `@Value` annotation.
|
||||
|
||||
|
||||
|
||||
[[features.spring-application.command-line-runner]]
|
||||
== Using the ApplicationRunner or CommandLineRunner
|
||||
|
||||
If you need to run some specific code once the `SpringApplication` has started, you can implement the `ApplicationRunner` or `CommandLineRunner` interfaces.
|
||||
Both interfaces work in the same way and offer a single `run` method, which is called just before `SpringApplication.run(...)` completes.
|
||||
|
||||
NOTE: This contract is well suited for tasks that should run after application startup but before it starts accepting traffic.
|
||||
|
||||
|
||||
The `CommandLineRunner` interfaces provides access to application arguments as a string array, whereas the `ApplicationRunner` uses the `ApplicationArguments` interface discussed earlier.
|
||||
The following example shows a `CommandLineRunner` with a `run` method:
|
||||
|
||||
include-code::MyCommandLineRunner[]
|
||||
|
||||
If several `CommandLineRunner` or `ApplicationRunner` beans are defined that must be called in a specific order, you can additionally implement the `org.springframework.core.Ordered` interface or use the `org.springframework.core.annotation.Order` annotation.
|
||||
|
||||
|
||||
|
||||
[[features.spring-application.application-exit]]
|
||||
== Application Exit
|
||||
|
||||
Each `SpringApplication` registers a shutdown hook with the JVM to ensure that the `ApplicationContext` closes gracefully on exit.
|
||||
All the standard Spring lifecycle callbacks (such as the `DisposableBean` interface or the `@PreDestroy` annotation) can be used.
|
||||
|
||||
In addition, beans may implement the `org.springframework.boot.ExitCodeGenerator` interface if they wish to return a specific exit code when `SpringApplication.exit()` is called.
|
||||
This exit code can then be passed to `System.exit()` to return it as a status code, as shown in the following example:
|
||||
|
||||
include-code::MyApplication[]
|
||||
|
||||
Also, the `ExitCodeGenerator` interface may be implemented by exceptions.
|
||||
When such an exception is encountered, Spring Boot returns the exit code provided by the implemented `getExitCode()` method.
|
||||
|
||||
If there is more than one `ExitCodeGenerator`, the first non-zero exit code that is generated is used.
|
||||
To control the order in which the generators are called, additionally implement the `org.springframework.core.Ordered` interface or use the `org.springframework.core.annotation.Order` annotation.
|
||||
|
||||
|
||||
|
||||
[[features.spring-application.admin]]
|
||||
== Admin Features
|
||||
|
||||
It is possible to enable admin-related features for the application by specifying the configprop:spring.application.admin.enabled[] property.
|
||||
This exposes the {code-spring-boot-src}/admin/SpringApplicationAdminMXBean.java[`SpringApplicationAdminMXBean`] on the platform `MBeanServer`.
|
||||
You could use this feature to administer your Spring Boot application remotely.
|
||||
This feature could also be useful for any service wrapper implementation.
|
||||
|
||||
TIP: If you want to know on which HTTP port the application is running, get the property with a key of `local.server.port`.
|
||||
|
||||
|
||||
|
||||
[[features.spring-application.startup-tracking]]
|
||||
== 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.
|
||||
With {url-spring-framework-javadoc}/org/springframework/core/metrics/ApplicationStartup.html[`ApplicationStartup`], Spring Framework {url-spring-framework-docs}/core/beans/context-introduction.html#context-functionality-startup[allows you to track the application startup sequence with `StartupStep` objects].
|
||||
This data can be collected for profiling purposes, or just to have a better understanding of an application startup process.
|
||||
|
||||
You can choose an `ApplicationStartup` implementation when setting up the `SpringApplication` instance.
|
||||
For example, to use the `BufferingApplicationStartup`, you could write:
|
||||
|
||||
include-code::MyApplication[]
|
||||
|
||||
The first available implementation, `FlightRecorderApplicationStartup` is provided by Spring Framework.
|
||||
It adds Spring-specific startup events to a Java Flight Recorder session and is meant for profiling applications and correlating their Spring context lifecycle with JVM events (such as allocations, GCs, class loading...).
|
||||
Once configured, you can record data by running the application with the Flight Recorder enabled:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ java -XX:StartFlightRecording:filename=recording.jfr,duration=10s -jar demo.jar
|
||||
----
|
||||
|
||||
Spring Boot ships with the `BufferingApplicationStartup` variant; this implementation is meant for buffering the startup steps and draining them into an external metrics system.
|
||||
Applications can ask for the bean of type `BufferingApplicationStartup` in any component.
|
||||
|
||||
Spring Boot can also be configured to expose a xref:api:rest/actuator/startup.adoc[`startup` endpoint] that provides this information as a JSON document.
|
||||
|
||||
|
||||
|
||||
[[features.spring-application.virtual-threads]]
|
||||
== Virtual threads
|
||||
|
||||
If you're running on Java 21 or up, you can enable virtual threads by setting the property configprop:spring.threads.virtual.enabled[] to `true`.
|
||||
|
||||
Before turning on this option for your application, you should consider https://docs.oracle.com/en/java/javase/21/core/virtual-threads.html[reading the official Java virtual threads documentation].
|
||||
In some cases, applications can experience lower throughput because of "Pinned Virtual Threads"; this page also explains how to detect such cases with JDK Flight Recorder or the `jcmd` CLI.
|
||||
|
||||
WARNING: One side effect of virtual threads is that they are daemon threads.
|
||||
A JVM will exit if all of its threads are daemon threads.
|
||||
This behavior can be a problem when you rely on `@Scheduled` beans, for example, to keep your application alive.
|
||||
If you use virtual threads, the scheduler thread is a virtual thread and therefore a daemon thread and won't keep the JVM alive.
|
||||
This not only affects scheduling and can be the case with other technologies too.
|
||||
To keep the JVM running in all cases, it is recommended to set the property configprop:spring.main.keep-alive[] to `true`.
|
||||
This ensures that the JVM is kept alive, even if all threads are virtual threads.
|
||||
@@ -0,0 +1,170 @@
|
||||
[[features.ssl]]
|
||||
= SSL
|
||||
|
||||
Spring Boot provides the ability to configure SSL trust material that can be applied to several types of connections in order to support secure communications.
|
||||
Configuration properties with the prefix `spring.ssl.bundle` can be used to specify named sets of trust material and associated information.
|
||||
|
||||
|
||||
|
||||
[[features.ssl.jks]]
|
||||
== Configuring SSL With Java KeyStore Files
|
||||
|
||||
Configuration properties with the prefix `spring.ssl.bundle.jks` can be used to configure bundles of trust material created with the Java `keytool` utility and stored in Java KeyStore files in the JKS or PKCS12 format.
|
||||
Each bundle has a user-provided name that can be used to reference the bundle.
|
||||
|
||||
When used to secure an embedded web server, a `keystore` is typically configured with a Java KeyStore containing a certificate and private key as shown in this example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
ssl:
|
||||
bundle:
|
||||
jks:
|
||||
mybundle:
|
||||
key:
|
||||
alias: "application"
|
||||
keystore:
|
||||
location: "classpath:application.p12"
|
||||
password: "secret"
|
||||
type: "PKCS12"
|
||||
----
|
||||
|
||||
When used to secure a client-side connection, a `truststore` is typically configured with a Java KeyStore containing the server certificate as shown in this example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
ssl:
|
||||
bundle:
|
||||
jks:
|
||||
mybundle:
|
||||
truststore:
|
||||
location: "classpath:server.p12"
|
||||
password: "secret"
|
||||
----
|
||||
|
||||
See {code-spring-boot-autoconfigure-src}/ssl/JksSslBundleProperties.java[JksSslBundleProperties] for the full set of supported properties.
|
||||
|
||||
|
||||
|
||||
[[features.ssl.pem]]
|
||||
== Configuring SSL With PEM-encoded Certificates
|
||||
|
||||
Configuration properties with the prefix `spring.ssl.bundle.pem` can be used to configure bundles of trust material in the form of PEM-encoded text.
|
||||
Each bundle has a user-provided name that can be used to reference the bundle.
|
||||
|
||||
When used to secure an embedded web server, a `keystore` is typically configured with a certificate and private key as shown in this example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
ssl:
|
||||
bundle:
|
||||
pem:
|
||||
mybundle:
|
||||
keystore:
|
||||
certificate: "classpath:application.crt"
|
||||
private-key: "classpath:application.key"
|
||||
----
|
||||
|
||||
When used to secure a client-side connection, a `truststore` is typically configured with the server certificate as shown in this example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
ssl:
|
||||
bundle:
|
||||
pem:
|
||||
mybundle:
|
||||
truststore:
|
||||
certificate: "classpath:server.crt"
|
||||
----
|
||||
|
||||
[TIP]
|
||||
====
|
||||
PEM content can be used directly for both the `certificate` and `private-key` properties.
|
||||
If the property values contain `BEGIN` and `END` markers then they will be treated as PEM content rather than a resource location.
|
||||
|
||||
The following example shows how a truststore certificate can be defined:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
ssl:
|
||||
bundle:
|
||||
pem:
|
||||
mybundle:
|
||||
truststore:
|
||||
certificate: |
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIID1zCCAr+gAwIBAgIUNM5QQv8IzVQsgSmmdPQNaqyzWs4wDQYJKoZIhvcNAQEL
|
||||
BQAwezELMAkGA1UEBhMCWFgxEjAQBgNVBAgMCVN0YXRlTmFtZTERMA8GA1UEBwwI
|
||||
...
|
||||
V0IJjcmYjEZbTvpjFKznvaFiOUv+8L7jHQ1/Yf+9c3C8gSjdUfv88m17pqYXd+Ds
|
||||
HEmfmNNjht130UyjNCITmLVXyy5p35vWmdf95U3uEbJSnNVtXH8qRmN9oK9mUpDb
|
||||
ngX6JBJI7fw7tXoqWSLHNiBODM88fUlQSho8
|
||||
-----END CERTIFICATE-----
|
||||
----
|
||||
====
|
||||
|
||||
See {code-spring-boot-autoconfigure-src}/ssl/PemSslBundleProperties.java[PemSslBundleProperties] for the full set of supported properties.
|
||||
|
||||
|
||||
|
||||
[[features.ssl.applying]]
|
||||
== Applying SSL Bundles
|
||||
|
||||
Once configured using properties, SSL bundles can be referred to by name in configuration properties for various types of connections that are auto-configured by Spring Boot.
|
||||
See the sections on xref:how-to:webserver.adoc#howto.webserver.configure-ssl[embedded web servers], xref:data/index.adoc[data technologies], and xref:io/rest-client.adoc[REST clients] for further information.
|
||||
|
||||
|
||||
|
||||
[[features.ssl.bundles]]
|
||||
== Using SSL Bundles
|
||||
|
||||
Spring Boot auto-configures a bean of type `SslBundles` that provides access to each of the named bundles configured using the `spring.ssl.bundle` properties.
|
||||
|
||||
An `SslBundle` can be retrieved from the auto-configured `SslBundles` bean and used to create objects that are used to configure SSL connectivity in client libraries.
|
||||
The `SslBundle` provides a layered approach of obtaining these SSL objects:
|
||||
|
||||
- `getStores()` provides access to the key store and trust store `java.security.KeyStore` instances as well as any required key store password.
|
||||
- `getManagers()` provides access to the `java.net.ssl.KeyManagerFactory` and `java.net.ssl.TrustManagerFactory` instances as well as the `java.net.ssl.KeyManager` and `java.net.ssl.TrustManager` arrays that they create.
|
||||
- `createSslContext()` provides a convenient way to obtain a new `java.net.ssl.SSLContext` instance.
|
||||
|
||||
In addition, the `SslBundle` provides details about the key being used, the protocol to use and any option that should be applied to the SSL engine.
|
||||
|
||||
The following example shows retrieving an `SslBundle` and using it to create an `SSLContext`:
|
||||
|
||||
include-code::MyComponent[]
|
||||
|
||||
|
||||
|
||||
[[features.ssl.reloading]]
|
||||
== Reloading SSL bundles
|
||||
|
||||
SSL bundles can be reloaded when the key material changes.
|
||||
The component consuming the bundle has to be compatible with reloadable SSL bundles.
|
||||
Currently the following components are compatible:
|
||||
|
||||
* Tomcat web server
|
||||
* Netty web server
|
||||
|
||||
To enable reloading, you need to opt-in via a configuration property as shown in this example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
ssl:
|
||||
bundle:
|
||||
pem:
|
||||
mybundle:
|
||||
reload-on-update: true
|
||||
keystore:
|
||||
certificate: "file:/some/directory/application.crt"
|
||||
private-key: "file:/some/directory/application.key"
|
||||
----
|
||||
|
||||
A file watcher is then watching the files and if they change, the SSL bundle will be reloaded.
|
||||
This in turn triggers a reload in the consuming component, e.g. Tomcat rotates the certificates in the SSL enabled connectors.
|
||||
|
||||
You can configure the quiet period (to make sure that there are no more changes) of the file watcher with the configprop:spring.ssl.bundle.watch.file.quiet-period[] property.
|
||||
@@ -0,0 +1,59 @@
|
||||
[[features.task-execution-and-scheduling]]
|
||||
= Task Execution and Scheduling
|
||||
|
||||
In the absence of an `Executor` bean in the context, Spring Boot auto-configures an `AsyncTaskExecutor`.
|
||||
When virtual threads are enabled (using Java 21+ and configprop:spring.threads.virtual.enabled[] set to `true`) this will be a `SimpleAsyncTaskExecutor` that uses virtual threads.
|
||||
Otherwise, it will be a `ThreadPoolTaskExecutor` with sensible defaults.
|
||||
In either case, the auto-configured executor will be automatically used for:
|
||||
|
||||
- asynchronous task execution (`@EnableAsync`)
|
||||
- Spring for GraphQL's asynchronous handling of `Callable` return values from controller methods
|
||||
- Spring MVC's asynchronous request processing
|
||||
- Spring WebFlux's blocking execution support
|
||||
|
||||
[TIP]
|
||||
====
|
||||
If you have defined a custom `Executor` in the context, both regular task execution (that is `@EnableAsync`) and Spring for GraphQL will use it.
|
||||
However, the Spring MVC and Spring WebFlux support will only use it if it is an `AsyncTaskExecutor` implementation (named `applicationTaskExecutor`).
|
||||
Depending on your target arrangement, you could change your `Executor` into an `AsyncTaskExecutor` or define both an `AsyncTaskExecutor` and an `AsyncConfigurer` wrapping your custom `Executor`.
|
||||
|
||||
The auto-configured `ThreadPoolTaskExecutorBuilder` allows you to easily create instances that reproduce what the auto-configuration does by default.
|
||||
====
|
||||
|
||||
When a `ThreadPoolTaskExecutor` is auto-configured, the thread pool uses 8 core threads that can grow and shrink according to the load.
|
||||
Those default settings can be fine-tuned using the `spring.task.execution` namespace, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
task:
|
||||
execution:
|
||||
pool:
|
||||
max-size: 16
|
||||
queue-capacity: 100
|
||||
keep-alive: "10s"
|
||||
----
|
||||
|
||||
This changes the thread pool to use a bounded queue so that when the queue is full (100 tasks), the thread pool increases to maximum 16 threads.
|
||||
Shrinking of the pool is more aggressive as threads are reclaimed when they are idle for 10 seconds (rather than 60 seconds by default).
|
||||
|
||||
A scheduler can also be auto-configured if it needs to be associated with scheduled task execution (using `@EnableScheduling` for instance).
|
||||
|
||||
If virtual threads are enabled (using Java 21+ and configprop:spring.threads.virtual.enabled[] set to `true`) this will be a `SimpleAsyncTaskScheduler` that uses virtual threads.
|
||||
This `SimpleAsyncTaskScheduler` will ignore any pooling related properties.
|
||||
|
||||
If virtual threads are not enabled, it will be a `ThreadPoolTaskScheduler` with sensible defaults.
|
||||
The `ThreadPoolTaskScheduler` uses one thread by default and its settings can be fine-tuned using the `spring.task.scheduling` namespace, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
task:
|
||||
scheduling:
|
||||
thread-name-prefix: "scheduling-"
|
||||
pool:
|
||||
size: 2
|
||||
----
|
||||
|
||||
A `ThreadPoolTaskExecutorBuilder` bean, a `SimpleAsyncTaskExecutorBuilder` bean, a `ThreadPoolTaskSchedulerBuilder` bean and a `SimpleAsyncTaskSchedulerBuilder` are made available in the context if a custom executor or scheduler needs to be created.
|
||||
The `SimpleAsyncTaskExecutorBuilder` and `SimpleAsyncTaskSchedulerBuilder` beans are auto-configured to use virtual threads if they are enabled (using Java 21+ and configprop:spring.threads.virtual.enabled[] set to `true`).
|
||||
@@ -0,0 +1,98 @@
|
||||
[[features.testcontainers]]
|
||||
= Testcontainers Support
|
||||
|
||||
As well as xref:features/testing.adoc#features.testing.testcontainers[using Testcontainers for integration testing], it's also possible to use them at development time.
|
||||
The next sections will provide more details about that.
|
||||
|
||||
|
||||
|
||||
[[features.testcontainers.at-development-time]]
|
||||
== Using Testcontainers at Development Time
|
||||
|
||||
This approach allows developers to quickly start containers for the services that the application depends on, removing the need to manually provision things like database servers.
|
||||
Using Testcontainers in this way provides functionality similar to Docker Compose, except that your container configuration is in Java rather than YAML.
|
||||
|
||||
To use Testcontainers at development time you need to launch your application using your "`test`" classpath rather than "`main`".
|
||||
This will allow you to access all declared test dependencies and give you a natural place to write your test configuration.
|
||||
|
||||
To create a test launchable version of your application you should create an "`Application`" class in the `src/test` directory.
|
||||
For example, if your main application is in `src/main/java/com/example/MyApplication.java`, you should create `src/test/java/com/example/TestMyApplication.java`
|
||||
|
||||
The `TestMyApplication` class can use the `SpringApplication.from(...)` method to launch the real application:
|
||||
|
||||
include-code::launch/TestMyApplication[]
|
||||
|
||||
You'll also need to define the `Container` instances that you want to start along with your application.
|
||||
To do this, you need to make sure that the `spring-boot-testcontainers` module has been added as a `test` dependency.
|
||||
Once that has been done, you can create a `@TestConfiguration` class that declares `@Bean` methods for the containers you want to start.
|
||||
|
||||
You can also annotate your `@Bean` methods with `@ServiceConnection` in order to create `ConnectionDetails` beans.
|
||||
See xref:features/testing.adoc#features.testing.testcontainers.service-connections[the service connections] section for details of the supported technologies.
|
||||
|
||||
A typical Testcontainers configuration would look like this:
|
||||
|
||||
include-code::test/MyContainersConfiguration[]
|
||||
|
||||
NOTE: The lifecycle of `Container` beans is automatically managed by Spring Boot.
|
||||
Containers will be started and stopped automatically.
|
||||
|
||||
TIP: You can use the configprop:spring.testcontainers.beans.startup[] property to change how containers are started.
|
||||
By default `sequential` startup is used, but you may also choose `parallel` if you wish to start multiple containers in parallel.
|
||||
|
||||
Once you have defined your test configuration, you can use the `with(...)` method to attach it to your test launcher:
|
||||
|
||||
include-code::test/TestMyApplication[]
|
||||
|
||||
You can now launch `TestMyApplication` as you would any regular Java `main` method application to start your application and the containers that it needs to run.
|
||||
|
||||
TIP: You can use the Maven goal `spring-boot:test-run` or the Gradle task `bootTestRun` to do this from the command line.
|
||||
|
||||
|
||||
|
||||
[[features.testcontainers.at-development-time.dynamic-properties]]
|
||||
=== Contributing Dynamic Properties at Development Time
|
||||
|
||||
If you want to contribute dynamic properties at development time from your `Container` `@Bean` methods, you can do so by injecting a `DynamicPropertyRegistry`.
|
||||
This works in a similar way to the xref:features/testing.adoc#features.testing.testcontainers.dynamic-properties[`@DynamicPropertySource` annotation] that you can use in your tests.
|
||||
It allows you to add properties that will become available once your container has started.
|
||||
|
||||
A typical configuration would look like this:
|
||||
|
||||
include-code::MyContainersConfiguration[]
|
||||
|
||||
NOTE: Using a `@ServiceConnection` is recommended whenever possible, however, dynamic properties can be a useful fallback for technologies that don't yet have `@ServiceConnection` support.
|
||||
|
||||
|
||||
|
||||
[[features.testcontainers.at-development-time.importing-container-declarations]]
|
||||
=== Importing Testcontainer Declaration Classes
|
||||
|
||||
A common pattern when using Testcontainers is to declare `Container` instances as static fields.
|
||||
Often these fields are defined directly on the test class.
|
||||
They can also be declared on a parent class or on an interface that the test implements.
|
||||
|
||||
For example, the following `MyContainers` interface declares `mongo` and `neo4j` containers:
|
||||
|
||||
include-code::MyContainers[]
|
||||
|
||||
If you already have containers defined in this way, or you just prefer this style, you can import these declaration classes rather than defining you containers as `@Bean` methods.
|
||||
To do so, add the `@ImportTestcontainers` annotation to your test configuration class:
|
||||
|
||||
include-code::MyContainersConfiguration[]
|
||||
|
||||
TIP: If you don't intend to use the xref:features/testing.adoc#features.testing.testcontainers.service-connections[service connections feature] but want to use xref:features/testing.adoc#features.testing.testcontainers.dynamic-properties[`@DynamicPropertySource`] instead, remove the `@ServiceConnection` annotation from the `Container` fields.
|
||||
You can also add `@DynamicPropertySource` annotated methods to your declaration class.
|
||||
|
||||
|
||||
|
||||
[[features.testcontainers.at-development-time.devtools]]
|
||||
=== Using DevTools with Testcontainers at Development Time
|
||||
|
||||
When using devtools, you can annotate beans and bean methods with `@RestartScope`.
|
||||
Such beans won't be recreated when the devtools restart the application.
|
||||
This is especially useful for Testcontainer `Container` beans, as they keep their state despite the application restart.
|
||||
|
||||
include-code::MyContainersConfiguration[]
|
||||
|
||||
WARNING: If you're using Gradle and want to use this feature, you need to change the configuration of the `spring-boot-devtools` dependency from `developmentOnly` to `testAndDevelopmentOnly`.
|
||||
With the default scope of `developmentOnly`, the `bootTestRun` task will not pick up changes in your code, as the devtools are not active.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,279 @@
|
||||
[[io.caching]]
|
||||
= Caching
|
||||
|
||||
The Spring Framework provides support for transparently adding caching to an application.
|
||||
At its core, the abstraction applies caching to methods, thus reducing the number of executions based on the information available in the cache.
|
||||
The caching logic is applied transparently, without any interference to the invoker.
|
||||
Spring Boot auto-configures the cache infrastructure as long as caching support is enabled by using the `@EnableCaching` annotation.
|
||||
|
||||
NOTE: Check the {url-spring-framework-docs}/integration/cache.html[relevant section] of the Spring Framework reference for more details.
|
||||
|
||||
In a nutshell, to add caching to an operation of your service add the relevant annotation to its method, as shown in the following example:
|
||||
|
||||
include-code::MyMathService[]
|
||||
|
||||
This example demonstrates the use of caching on a potentially costly operation.
|
||||
Before invoking `computePiDecimal`, the abstraction looks for an entry in the `piDecimals` cache that matches the `i` argument.
|
||||
If an entry is found, the content in the cache is immediately returned to the caller, and the method is not invoked.
|
||||
Otherwise, the method is invoked, and the cache is updated before returning the value.
|
||||
|
||||
CAUTION: You can also use the standard JSR-107 (JCache) annotations (such as `@CacheResult`) transparently.
|
||||
However, we strongly advise you to not mix and match the Spring Cache and JCache annotations.
|
||||
|
||||
If you do not add any specific cache library, Spring Boot auto-configures a xref:io/caching.adoc#io.caching.provider.simple[simple provider] that uses concurrent maps in memory.
|
||||
When a cache is required (such as `piDecimals` in the preceding example), this provider creates it for you.
|
||||
The simple provider is not really recommended for production usage, but it is great for getting started and making sure that you understand the features.
|
||||
When you have made up your mind about the cache provider to use, please make sure to read its documentation to figure out how to configure the caches that your application uses.
|
||||
Nearly all providers require you to explicitly configure every cache that you use in the application.
|
||||
Some offer a way to customize the default caches defined by the configprop:spring.cache.cache-names[] property.
|
||||
|
||||
TIP: It is also possible to transparently {url-spring-framework-docs}/integration/cache/annotations.html#cache-annotations-put[update] or {url-spring-framework-docs}/integration/cache/annotations.html#cache-annotations-evict[evict] data from the cache.
|
||||
|
||||
|
||||
|
||||
[[io.caching.provider]]
|
||||
== Supported Cache Providers
|
||||
|
||||
The cache abstraction does not provide an actual store and relies on abstraction materialized by the `org.springframework.cache.Cache` and `org.springframework.cache.CacheManager` interfaces.
|
||||
|
||||
If you have not defined a bean of type `CacheManager` or a `CacheResolver` named `cacheResolver` (see {url-spring-framework-javadoc}/org/springframework/cache/annotation/CachingConfigurer.html[`CachingConfigurer`]), Spring Boot tries to detect the following providers (in the indicated order):
|
||||
|
||||
. xref:io/caching.adoc#io.caching.provider.generic[Generic]
|
||||
. xref:io/caching.adoc#io.caching.provider.jcache[JCache (JSR-107)] (EhCache 3, Hazelcast, Infinispan, and others)
|
||||
. xref:io/caching.adoc#io.caching.provider.hazelcast[Hazelcast]
|
||||
. xref:io/caching.adoc#io.caching.provider.infinispan[Infinispan]
|
||||
. xref:io/caching.adoc#io.caching.provider.couchbase[Couchbase]
|
||||
. xref:io/caching.adoc#io.caching.provider.redis[Redis]
|
||||
. xref:io/caching.adoc#io.caching.provider.caffeine[Caffeine]
|
||||
. xref:io/caching.adoc#io.caching.provider.cache2k[Cache2k]
|
||||
. xref:io/caching.adoc#io.caching.provider.simple[Simple]
|
||||
|
||||
Additionally, {url-spring-boot-for-apache-geode-site}[Spring Boot for Apache Geode] provides {url-spring-boot-for-apache-geode-docs}#geode-caching-provider[auto-configuration for using Apache Geode as a cache provider].
|
||||
|
||||
TIP: If the `CacheManager` is auto-configured by Spring Boot, it is possible to _force_ a particular cache provider by setting the configprop:spring.cache.type[] property.
|
||||
Use this property if you need to xref:io/caching.adoc#io.caching.provider.none[use no-op caches] in certain environments (such as tests).
|
||||
|
||||
TIP: Use the `spring-boot-starter-cache` "`Starter`" to quickly add basic caching dependencies.
|
||||
The starter brings in `spring-context-support`.
|
||||
If you add dependencies manually, you must include `spring-context-support` in order to use the JCache or Caffeine support.
|
||||
|
||||
If the `CacheManager` is auto-configured by Spring Boot, you can further tune its configuration before it is fully initialized by exposing a bean that implements the `CacheManagerCustomizer` interface.
|
||||
The following example sets a flag to say that `null` values should not be passed down to the underlying map:
|
||||
|
||||
include-code::MyCacheManagerConfiguration[]
|
||||
|
||||
NOTE: In the preceding example, an auto-configured `ConcurrentMapCacheManager` is expected.
|
||||
If that is not the case (either you provided your own config or a different cache provider was auto-configured), the customizer is not invoked at all.
|
||||
You can have as many customizers as you want, and you can also order them by using `@Order` or `Ordered`.
|
||||
|
||||
|
||||
|
||||
[[io.caching.provider.generic]]
|
||||
=== Generic
|
||||
|
||||
Generic caching is used if the context defines _at least_ one `org.springframework.cache.Cache` bean.
|
||||
A `CacheManager` wrapping all beans of that type is created.
|
||||
|
||||
|
||||
|
||||
[[io.caching.provider.jcache]]
|
||||
=== JCache (JSR-107)
|
||||
|
||||
https://jcp.org/en/jsr/detail?id=107[JCache] is bootstrapped through the presence of a `javax.cache.spi.CachingProvider` on the classpath (that is, a JSR-107 compliant caching library exists on the classpath), and the `JCacheCacheManager` is provided by the `spring-boot-starter-cache` "`Starter`".
|
||||
Various compliant libraries are available, and Spring Boot provides dependency management for Ehcache 3, Hazelcast, and Infinispan.
|
||||
Any other compliant library can be added as well.
|
||||
|
||||
It might happen that more than one provider is present, in which case the provider must be explicitly specified.
|
||||
Even if the JSR-107 standard does not enforce a standardized way to define the location of the configuration file, Spring Boot does its best to accommodate setting a cache with implementation details, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
# Only necessary if more than one provider is present
|
||||
spring:
|
||||
cache:
|
||||
jcache:
|
||||
provider: "com.example.MyCachingProvider"
|
||||
config: "classpath:example.xml"
|
||||
----
|
||||
|
||||
NOTE: When a cache library offers both a native implementation and JSR-107 support, Spring Boot prefers the JSR-107 support, so that the same features are available if you switch to a different JSR-107 implementation.
|
||||
|
||||
TIP: Spring Boot has xref:io/hazelcast.adoc[general support for Hazelcast].
|
||||
If a single `HazelcastInstance` is available, it is automatically reused for the `CacheManager` as well, unless the configprop:spring.cache.jcache.config[] property is specified.
|
||||
|
||||
There are two ways to customize the underlying `javax.cache.cacheManager`:
|
||||
|
||||
* Caches can be created on startup by setting the configprop:spring.cache.cache-names[] property.
|
||||
If a custom `javax.cache.configuration.Configuration` bean is defined, it is used to customize them.
|
||||
* `org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer` beans are invoked with the reference of the `CacheManager` for full customization.
|
||||
|
||||
TIP: If a standard `javax.cache.CacheManager` bean is defined, it is wrapped automatically in an `org.springframework.cache.CacheManager` implementation that the abstraction expects.
|
||||
No further customization is applied to it.
|
||||
|
||||
|
||||
|
||||
[[io.caching.provider.hazelcast]]
|
||||
=== Hazelcast
|
||||
|
||||
Spring Boot has xref:io/hazelcast.adoc[general support for Hazelcast].
|
||||
If a `HazelcastInstance` has been auto-configured and `com.hazelcast:hazelcast-spring` is on the classpath, it is automatically wrapped in a `CacheManager`.
|
||||
|
||||
NOTE: Hazelcast can be used as a JCache compliant cache or as a Spring `CacheManager` compliant cache.
|
||||
When setting configprop:spring.cache.type[] to `hazelcast`, Spring Boot will use the `CacheManager` based implementation.
|
||||
If you want to use Hazelcast as a JCache compliant cache, set configprop:spring.cache.type[] to `jcache`.
|
||||
If you have multiple JCache compliant cache providers and want to force the use of Hazelcast, you have to xref:io/caching.adoc#io.caching.provider.jcache[explicitly set the JCache provider].
|
||||
|
||||
|
||||
|
||||
[[io.caching.provider.infinispan]]
|
||||
=== Infinispan
|
||||
|
||||
https://infinispan.org/[Infinispan] has no default configuration file location, so it must be specified explicitly.
|
||||
Otherwise, the default bootstrap is used.
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
cache:
|
||||
infinispan:
|
||||
config: "infinispan.xml"
|
||||
----
|
||||
|
||||
Caches can be created on startup by setting the configprop:spring.cache.cache-names[] property.
|
||||
If a custom `ConfigurationBuilder` bean is defined, it is used to customize the caches.
|
||||
|
||||
To be compatible with Spring Boot's Jakarta EE 9 baseline, Infinispan's `-jakarta` modules must be used.
|
||||
For every module with a `-jakarta` variant, the variant must be used in place of the standard module.
|
||||
For example, `infinispan-core-jakarta` and `infinispan-commons-jakarta` must be used in place of `infinispan-core` and `infinispan-commons` respectively.
|
||||
|
||||
|
||||
|
||||
[[io.caching.provider.couchbase]]
|
||||
=== Couchbase
|
||||
|
||||
If Spring Data Couchbase is available and Couchbase is xref:data/nosql.adoc#data.nosql.couchbase[configured], a `CouchbaseCacheManager` is auto-configured.
|
||||
It is possible to create additional caches on startup by setting the configprop:spring.cache.cache-names[] property and cache defaults can be configured by using `spring.cache.couchbase.*` properties.
|
||||
For instance, the following configuration creates `cache1` and `cache2` caches with an entry _expiration_ of 10 minutes:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
cache:
|
||||
cache-names: "cache1,cache2"
|
||||
couchbase:
|
||||
expiration: "10m"
|
||||
----
|
||||
|
||||
If you need more control over the configuration, consider registering a `CouchbaseCacheManagerBuilderCustomizer` bean.
|
||||
The following example shows a customizer that configures a specific entry expiration for `cache1` and `cache2`:
|
||||
|
||||
include-code::MyCouchbaseCacheManagerConfiguration[]
|
||||
|
||||
|
||||
|
||||
[[io.caching.provider.redis]]
|
||||
=== Redis
|
||||
|
||||
If https://redis.io/[Redis] is available and configured, a `RedisCacheManager` is auto-configured.
|
||||
It is possible to create additional caches on startup by setting the configprop:spring.cache.cache-names[] property and cache defaults can be configured by using `spring.cache.redis.*` properties.
|
||||
For instance, the following configuration creates `cache1` and `cache2` caches with a _time to live_ of 10 minutes:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
cache:
|
||||
cache-names: "cache1,cache2"
|
||||
redis:
|
||||
time-to-live: "10m"
|
||||
----
|
||||
|
||||
NOTE: By default, a key prefix is added so that, if two separate caches use the same key, Redis does not have overlapping keys and cannot return invalid values.
|
||||
We strongly recommend keeping this setting enabled if you create your own `RedisCacheManager`.
|
||||
|
||||
TIP: You can take full control of the default configuration by adding a `RedisCacheConfiguration` `@Bean` of your own.
|
||||
This can be useful if you need to customize the default serialization strategy.
|
||||
|
||||
If you need more control over the configuration, consider registering a `RedisCacheManagerBuilderCustomizer` bean.
|
||||
The following example shows a customizer that configures a specific time to live for `cache1` and `cache2`:
|
||||
|
||||
include-code::MyRedisCacheManagerConfiguration[]
|
||||
|
||||
|
||||
|
||||
[[io.caching.provider.caffeine]]
|
||||
=== Caffeine
|
||||
|
||||
https://github.com/ben-manes/caffeine[Caffeine] is a Java 8 rewrite of Guava's cache that supersedes support for Guava.
|
||||
If Caffeine is present, a `CaffeineCacheManager` (provided by the `spring-boot-starter-cache` "`Starter`") is auto-configured.
|
||||
Caches can be created on startup by setting the configprop:spring.cache.cache-names[] property and can be customized by one of the following (in the indicated order):
|
||||
|
||||
. A cache spec defined by `spring.cache.caffeine.spec`
|
||||
. A `com.github.benmanes.caffeine.cache.CaffeineSpec` bean is defined
|
||||
. A `com.github.benmanes.caffeine.cache.Caffeine` bean is defined
|
||||
|
||||
For instance, the following configuration creates `cache1` and `cache2` caches with a maximum size of 500 and a _time to live_ of 10 minutes
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
cache:
|
||||
cache-names: "cache1,cache2"
|
||||
caffeine:
|
||||
spec: "maximumSize=500,expireAfterAccess=600s"
|
||||
----
|
||||
|
||||
If a `com.github.benmanes.caffeine.cache.CacheLoader` bean is defined, it is automatically associated to the `CaffeineCacheManager`.
|
||||
Since the `CacheLoader` is going to be associated with _all_ caches managed by the cache manager, it must be defined as `CacheLoader<Object, Object>`.
|
||||
The auto-configuration ignores any other generic type.
|
||||
|
||||
|
||||
|
||||
[[io.caching.provider.cache2k]]
|
||||
=== Cache2k
|
||||
|
||||
https://cache2k.org/[Cache2k] is an in-memory cache.
|
||||
If the Cache2k spring integration is present, a `SpringCache2kCacheManager` is auto-configured.
|
||||
|
||||
Caches can be created on startup by setting the configprop:spring.cache.cache-names[] property.
|
||||
Cache defaults can be customized using a `Cache2kBuilderCustomizer` bean.
|
||||
The following example shows a customizer that configures the capacity of the cache to 200 entries, with an expiration of 5 minutes:
|
||||
|
||||
include-code::MyCache2kDefaultsConfiguration[]
|
||||
|
||||
|
||||
|
||||
[[io.caching.provider.simple]]
|
||||
=== Simple
|
||||
|
||||
If none of the other providers can be found, a simple implementation using a `ConcurrentHashMap` as the cache store is configured.
|
||||
This is the default if no caching library is present in your application.
|
||||
By default, caches are created as needed, but you can restrict the list of available caches by setting the `cache-names` property.
|
||||
For instance, if you want only `cache1` and `cache2` caches, set the `cache-names` property as follows:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
cache:
|
||||
cache-names: "cache1,cache2"
|
||||
----
|
||||
|
||||
If you do so and your application uses a cache not listed, then it fails at runtime when the cache is needed, but not on startup.
|
||||
This is similar to the way the "real" cache providers behave if you use an undeclared cache.
|
||||
|
||||
|
||||
|
||||
[[io.caching.provider.none]]
|
||||
=== None
|
||||
|
||||
When `@EnableCaching` is present in your configuration, a suitable cache configuration is expected as well.
|
||||
If you have a custom `CacheManager`, consider defining it in a separate `@Configuration` class so that you can override it if necessary.
|
||||
None uses a no-op implementation that is useful in tests, and slice tests use that by default via `@AutoConfigureCache`.
|
||||
|
||||
If you need to use a no-op cache rather than the auto-configured cache manager in a certain environment, set the cache type to `none`, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
cache:
|
||||
type: "none"
|
||||
----
|
||||
@@ -0,0 +1,33 @@
|
||||
[[io.email]]
|
||||
= 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.
|
||||
|
||||
TIP: See the {url-spring-framework-docs}/integration/email.html[reference documentation] for a detailed explanation of how you can use `JavaMailSender`.
|
||||
|
||||
If `spring.mail.host` and the relevant libraries (as defined by `spring-boot-starter-mail`) are available, a default `JavaMailSender` is created if none exists.
|
||||
The sender can be further customized by configuration items from the `spring.mail` namespace.
|
||||
See {code-spring-boot-autoconfigure-src}/mail/MailProperties.java[`MailProperties`] for more details.
|
||||
|
||||
In particular, certain default timeout values are infinite, and you may want to change that to avoid having a thread blocked by an unresponsive mail server, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
mail:
|
||||
properties:
|
||||
"[mail.smtp.connectiontimeout]": 5000
|
||||
"[mail.smtp.timeout]": 3000
|
||||
"[mail.smtp.writetimeout]": 5000
|
||||
----
|
||||
|
||||
It is also possible to configure a `JavaMailSender` with an existing `Session` from JNDI:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
mail:
|
||||
jndi-name: "mail/Session"
|
||||
----
|
||||
|
||||
When a `jndi-name` is set, it takes precedence over all other Session-related settings.
|
||||
@@ -0,0 +1,35 @@
|
||||
[[io.hazelcast]]
|
||||
= Hazelcast
|
||||
|
||||
If https://hazelcast.com/[Hazelcast] is on the classpath and a suitable configuration is found, Spring Boot auto-configures a `HazelcastInstance` that you can inject in your application.
|
||||
|
||||
Spring Boot first attempts to create a client by checking the following configuration options:
|
||||
|
||||
* The presence of a `com.hazelcast.client.config.ClientConfig` bean.
|
||||
* A configuration file defined by the configprop:spring.hazelcast.config[] property.
|
||||
* The presence of the `hazelcast.client.config` system property.
|
||||
* A `hazelcast-client.xml` in the working directory or at the root of the classpath.
|
||||
* A `hazelcast-client.yaml` (or `hazelcast-client.yml`) in the working directory or at the root of the classpath.
|
||||
|
||||
If a client can not be created, Spring Boot attempts to configure an embedded server.
|
||||
If you define a `com.hazelcast.config.Config` bean, Spring Boot uses that.
|
||||
If your configuration defines an instance name, Spring Boot tries to locate an existing instance rather than creating a new one.
|
||||
|
||||
You could also specify the Hazelcast configuration file to use through configuration, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
hazelcast:
|
||||
config: "classpath:config/my-hazelcast.xml"
|
||||
----
|
||||
|
||||
Otherwise, Spring Boot tries to find the Hazelcast configuration from the default locations: `hazelcast.xml` in the working directory or at the root of the classpath, or a YAML counterpart in the same locations.
|
||||
We also check if the `hazelcast.config` system property is set.
|
||||
See the https://docs.hazelcast.org/docs/latest/manual/html-single/[Hazelcast documentation] for more details.
|
||||
|
||||
TIP: By default, `@SpringAware` on Hazelcast components is supported.
|
||||
The `ManagementContext` can be overridden by declaring a `HazelcastConfigCustomizer` bean with an `@Order` higher than zero.
|
||||
|
||||
NOTE: Spring Boot also has xref:io/caching.adoc#io.caching.provider.hazelcast[explicit caching support for Hazelcast].
|
||||
If caching is enabled, the `HazelcastInstance` is automatically wrapped in a `CacheManager` implementation.
|
||||
@@ -0,0 +1,8 @@
|
||||
[[io]]
|
||||
= 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.
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
[[io.jta]]
|
||||
= Distributed Transactions With JTA
|
||||
|
||||
Spring Boot supports distributed JTA transactions across multiple XA resources by using a transaction manager retrieved from JNDI.
|
||||
|
||||
When a JTA environment is detected, Spring's `JtaTransactionManager` is used to manage transactions.
|
||||
Auto-configured JMS, DataSource, and JPA beans are upgraded to support XA transactions.
|
||||
You can use standard Spring idioms, such as `@Transactional`, to participate in a distributed transaction.
|
||||
If you are within a JTA environment and still want to use local transactions, you can set the configprop:spring.jta.enabled[] property to `false` to disable the JTA auto-configuration.
|
||||
|
||||
|
||||
|
||||
[[io.jta.jakartaee]]
|
||||
== Using a Jakarta EE Managed Transaction Manager
|
||||
|
||||
If you package your Spring Boot application as a `war` or `ear` file and deploy it to a Jakarta 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).
|
||||
When using 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 xref:data/sql.adoc#data.sql.datasource.jndi[configprop:spring.datasource.jndi-name[] property] to configure your `DataSource`.
|
||||
|
||||
|
||||
|
||||
[[io.jta.mixing-xa-and-non-xa-connections]]
|
||||
== 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`:
|
||||
|
||||
include-code::primary/MyBean[tag=*]
|
||||
|
||||
In some situations, you might want to process certain JMS messages by using a non-XA `ConnectionFactory`.
|
||||
For example, your JMS processing logic might take longer than the XA timeout.
|
||||
|
||||
If you want to use a non-XA `ConnectionFactory`, you can the `nonXaJmsConnectionFactory` bean:
|
||||
|
||||
include-code::nonxa/MyBean[tag=*]
|
||||
|
||||
For consistency, the `jmsConnectionFactory` bean is also provided by using the bean alias `xaJmsConnectionFactory`:
|
||||
|
||||
include-code::xa/MyBean[tag=*]
|
||||
|
||||
|
||||
|
||||
[[io.jta.supporting-embedded-transaction-manager]]
|
||||
== Supporting an Embedded Transaction Manager
|
||||
|
||||
The {code-spring-boot-src}/jms/XAConnectionFactoryWrapper.java[`XAConnectionFactoryWrapper`] and {code-spring-boot-src}/jdbc/XADataSourceWrapper.java[`XADataSourceWrapper`] interfaces can be used to support embedded transaction managers.
|
||||
The interfaces are responsible for wrapping `XAConnectionFactory` and `XADataSource` beans and exposing them as regular `ConnectionFactory` and `DataSource` beans, which transparently enroll in the distributed transaction.
|
||||
DataSource and JMS auto-configuration use JTA variants, provided you have a `JtaTransactionManager` bean and appropriate XA wrapper beans registered within your `ApplicationContext`.
|
||||
@@ -0,0 +1,54 @@
|
||||
[[io.quartz]]
|
||||
= Quartz Scheduler
|
||||
|
||||
Spring Boot offers several conveniences for working with the https://www.quartz-scheduler.org/[Quartz scheduler], including the `spring-boot-starter-quartz` "`Starter`".
|
||||
If Quartz is available, a `Scheduler` is auto-configured (through the `SchedulerFactoryBean` abstraction).
|
||||
|
||||
Beans of the following types are automatically picked up and associated with the `Scheduler`:
|
||||
|
||||
* `JobDetail`: defines a particular Job.
|
||||
`JobDetail` instances can be built with the `JobBuilder` API.
|
||||
* `Calendar`.
|
||||
* `Trigger`: defines when a particular job is triggered.
|
||||
|
||||
By default, an in-memory `JobStore` is used.
|
||||
However, it is possible to configure a JDBC-based store if a `DataSource` bean is available in your application and if the configprop:spring.quartz.job-store-type[] property is configured accordingly, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
quartz:
|
||||
job-store-type: "jdbc"
|
||||
----
|
||||
|
||||
When the JDBC store is used, the schema can be initialized on startup, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
quartz:
|
||||
jdbc:
|
||||
initialize-schema: "always"
|
||||
----
|
||||
|
||||
WARNING: By default, the database is detected and initialized by using the standard scripts provided with the Quartz library.
|
||||
These scripts drop existing tables, deleting all triggers on every restart.
|
||||
It is also possible to provide a custom script by setting the configprop:spring.quartz.jdbc.schema[] property.
|
||||
|
||||
To have Quartz use a `DataSource` other than the application's main `DataSource`, declare a `DataSource` bean, annotating its `@Bean` method with `@QuartzDataSource`.
|
||||
Doing so ensures that the Quartz-specific `DataSource` is used by both the `SchedulerFactoryBean` and for schema initialization.
|
||||
Similarly, to have Quartz use a `TransactionManager` other than the application's main `TransactionManager` declare a `TransactionManager` bean, annotating its `@Bean` method with `@QuartzTransactionManager`.
|
||||
|
||||
By default, jobs created by configuration will not overwrite already registered jobs that have been read from a persistent job store.
|
||||
To enable overwriting existing job definitions set the configprop:spring.quartz.overwrite-existing-jobs[] property.
|
||||
|
||||
Quartz Scheduler configuration can be customized using `spring.quartz` properties and `SchedulerFactoryBeanCustomizer` beans, which allow programmatic `SchedulerFactoryBean` customization.
|
||||
Advanced Quartz configuration properties can be customized using `spring.quartz.properties.*`.
|
||||
|
||||
NOTE: In particular, an `Executor` bean is not associated with the scheduler as Quartz offers a way to configure the scheduler through `spring.quartz.properties`.
|
||||
If you need to customize the task executor, consider implementing `SchedulerFactoryBeanCustomizer`.
|
||||
|
||||
Jobs can define setters to inject data map properties.
|
||||
Regular beans can also be injected in a similar manner, as shown in the following example:
|
||||
|
||||
include-code::MySampleJob[]
|
||||
@@ -0,0 +1,200 @@
|
||||
[[io.rest-client]]
|
||||
= Calling REST Services
|
||||
|
||||
Spring Boot provides various convenient ways to call remote REST services.
|
||||
If you are developing a non-blocking reactive application and you're using Spring WebFlux, then you can use `WebClient`.
|
||||
If you prefer blocking APIs then you can use `RestClient` or `RestTemplate`.
|
||||
|
||||
|
||||
|
||||
[[io.rest-client.webclient]]
|
||||
== WebClient
|
||||
|
||||
If you have Spring WebFlux on your classpath we recommend that you use `WebClient` to call remote REST services.
|
||||
The `WebClient` interface provides a functional style API and is fully reactive.
|
||||
You can learn more about the `WebClient` in the dedicated {url-spring-framework-docs}/web/webflux-webclient.html[section in the Spring Framework docs].
|
||||
|
||||
TIP: If you are not writing a reactive Spring WebFlux application you can use the xref:io/rest-client.adoc#io.rest-client.restclient[`RestClient`] instead of a `WebClient`.
|
||||
This provides a similar functional API, but is blocking rather than reactive.
|
||||
|
||||
Spring Boot creates and pre-configures a prototype `WebClient.Builder` bean for you.
|
||||
It is strongly advised to inject it in your components and use it to create `WebClient` instances.
|
||||
Spring Boot is configuring that builder to share HTTP resources and reflect codecs setup in the same fashion as the server ones (see xref:web/reactive.adoc#web.reactive.webflux.httpcodecs[WebFlux HTTP codecs auto-configuration]), and more.
|
||||
|
||||
The following code shows a typical example:
|
||||
|
||||
include-code::MyService[]
|
||||
|
||||
|
||||
|
||||
[[io.rest-client.webclient.runtime]]
|
||||
=== WebClient Runtime
|
||||
|
||||
Spring Boot will auto-detect which `ClientHttpConnector` to use to drive `WebClient` depending on the libraries available on the application classpath.
|
||||
In order of preference, the following clients are supported:
|
||||
|
||||
. Reactor Netty
|
||||
. Jetty RS client
|
||||
. Apache HttpClient
|
||||
. JDK HttpClient
|
||||
|
||||
If multiple clients are available on the classpath, the most preferred client will be used.
|
||||
|
||||
The `spring-boot-starter-webflux` starter depends on `io.projectreactor.netty:reactor-netty` by default, which brings both server and client implementations.
|
||||
If you choose to use Jetty as a reactive server instead, you should add a dependency on the Jetty Reactive HTTP client library, `org.eclipse.jetty:jetty-reactive-httpclient`.
|
||||
Using the same technology for server and client has its advantages, as it will automatically share HTTP resources between client and server.
|
||||
|
||||
Developers can override the resource configuration for Jetty and Reactor Netty by providing a custom `ReactorResourceFactory` or `JettyResourceFactory` bean - this will be applied to both clients and servers.
|
||||
|
||||
If you wish to override that choice for the client, you can define your own `ClientHttpConnector` bean and have full control over the client configuration.
|
||||
|
||||
You can learn more about the {url-spring-framework-docs}/web/webflux-webclient/client-builder.html[`WebClient` configuration options in the Spring Framework reference documentation].
|
||||
|
||||
|
||||
|
||||
[[io.rest-client.webclient.customization]]
|
||||
=== WebClient Customization
|
||||
|
||||
There are three main approaches to `WebClient` customization, depending on how broadly you want the customizations to apply.
|
||||
|
||||
To make the scope of any customizations as narrow as possible, inject the auto-configured `WebClient.Builder` and then call its methods as required.
|
||||
`WebClient.Builder` instances are stateful: Any change on the builder is reflected in all clients subsequently created with it.
|
||||
If you want to create several clients with the same builder, you can also consider cloning the builder with `WebClient.Builder other = builder.clone();`.
|
||||
|
||||
To make an application-wide, additive customization to all `WebClient.Builder` instances, you can declare `WebClientCustomizer` beans and change the `WebClient.Builder` locally at the point of injection.
|
||||
|
||||
Finally, you can fall back to the original API and use `WebClient.create()`.
|
||||
In that case, no auto-configuration or `WebClientCustomizer` is applied.
|
||||
|
||||
|
||||
|
||||
[[io.rest-client.webclient.ssl]]
|
||||
=== WebClient SSL Support
|
||||
|
||||
If you need custom SSL configuration on the `ClientHttpConnector` used by the `WebClient`, you can inject a `WebClientSsl` instance that can be used with the builder's `apply` method.
|
||||
|
||||
The `WebClientSsl` interface provides access to any xref:features/ssl.adoc#features.ssl.bundles[SSL bundles] that you have defined in your `application.properties` or `application.yaml` file.
|
||||
|
||||
The following code shows a typical example:
|
||||
|
||||
include-code::MyService[]
|
||||
|
||||
|
||||
|
||||
[[io.rest-client.restclient]]
|
||||
== RestClient
|
||||
|
||||
If you are not using Spring WebFlux or Project Reactor in your application we recommend that you use `RestClient` to call remote REST services.
|
||||
|
||||
The `RestClient` interface provides a functional style blocking API.
|
||||
|
||||
Spring Boot creates and pre-configures a prototype `RestClient.Builder` bean for you.
|
||||
It is strongly advised to inject it in your components and use it to create `RestClient` instances.
|
||||
Spring Boot is configuring that builder with `HttpMessageConverters` and an appropriate `ClientHttpRequestFactory`.
|
||||
|
||||
The following code shows a typical example:
|
||||
|
||||
include-code::MyService[]
|
||||
|
||||
|
||||
|
||||
[[io.rest-client.restclient.customization]]
|
||||
=== RestClient Customization
|
||||
|
||||
There are three main approaches to `RestClient` customization, depending on how broadly you want the customizations to apply.
|
||||
|
||||
To make the scope of any customizations as narrow as possible, inject the auto-configured `RestClient.Builder` and then call its methods as required.
|
||||
`RestClient.Builder` instances are stateful: Any change on the builder is reflected in all clients subsequently created with it.
|
||||
If you want to create several clients with the same builder, you can also consider cloning the builder with `RestClient.Builder other = builder.clone();`.
|
||||
|
||||
To make an application-wide, additive customization to all `RestClient.Builder` instances, you can declare `RestClientCustomizer` beans and change the `RestClient.Builder` locally at the point of injection.
|
||||
|
||||
Finally, you can fall back to the original API and use `RestClient.create()`.
|
||||
In that case, no auto-configuration or `RestClientCustomizer` is applied.
|
||||
|
||||
|
||||
|
||||
[[io.rest-client.restclient.ssl]]
|
||||
=== RestClient SSL Support
|
||||
|
||||
If you need custom SSL configuration on the `ClientHttpRequestFactory` used by the `RestClient`, you can inject a `RestClientSsl` instance that can be used with the builder's `apply` method.
|
||||
|
||||
The `RestClientSsl` interface provides access to any xref:features/ssl.adoc#features.ssl.bundles[SSL bundles] that you have defined in your `application.properties` or `application.yaml` file.
|
||||
|
||||
The following code shows a typical example:
|
||||
|
||||
include-code::MyService[]
|
||||
|
||||
If you need to apply other customization in addition to an SSL bundle, you can use the `ClientHttpRequestFactorySettings` class with `ClientHttpRequestFactories`:
|
||||
|
||||
include-code::settings/MyService[]
|
||||
|
||||
|
||||
|
||||
[[io.rest-client.resttemplate]]
|
||||
== RestTemplate
|
||||
|
||||
Spring Framework's {url-spring-framework-javadoc}/org/springframework/web/client/RestTemplate.html[`RestTemplate`] class predates `RestClient` and is the classic way that many applications use to call remote REST services.
|
||||
You might choose to use `RestTemplate` when you have existing code that you don't want to migrate to `RestClient`, or because you're already familiar with the `RestTemplate` API.
|
||||
|
||||
Since `RestTemplate` instances often need to be customized before being used, Spring Boot does not provide any single auto-configured `RestTemplate` bean.
|
||||
It does, however, auto-configure a `RestTemplateBuilder`, which can be used to create `RestTemplate` instances when needed.
|
||||
The auto-configured `RestTemplateBuilder` ensures that sensible `HttpMessageConverters` and an appropriate `ClientHttpRequestFactory` are applied to `RestTemplate` instances.
|
||||
|
||||
The following code shows a typical example:
|
||||
|
||||
include-code::MyService[]
|
||||
|
||||
`RestTemplateBuilder` includes a number of useful methods that can be used to quickly configure a `RestTemplate`.
|
||||
For example, to add BASIC authentication support, you can use `builder.basicAuthentication("user", "password").build()`.
|
||||
|
||||
|
||||
|
||||
[[io.rest-client.resttemplate.customization]]
|
||||
=== RestTemplate Customization
|
||||
|
||||
There are three main approaches to `RestTemplate` customization, depending on how broadly you want the customizations to apply.
|
||||
|
||||
To make the scope of any customizations as narrow as possible, inject the auto-configured `RestTemplateBuilder` and then call its methods as required.
|
||||
Each method call returns a new `RestTemplateBuilder` instance, so the customizations only affect this use of the builder.
|
||||
|
||||
To make an application-wide, additive customization, use a `RestTemplateCustomizer` bean.
|
||||
All such beans are automatically registered with the auto-configured `RestTemplateBuilder` and are applied to any templates that are built with it.
|
||||
|
||||
The following example shows a customizer that configures the use of a proxy for all hosts except `192.168.0.5`:
|
||||
|
||||
include-code::MyRestTemplateCustomizer[]
|
||||
|
||||
Finally, you can define your own `RestTemplateBuilder` bean.
|
||||
Doing so will replace the auto-configured builder.
|
||||
If you want any `RestTemplateCustomizer` beans to be applied to your custom builder, as the auto-configuration would have done, configure it using a `RestTemplateBuilderConfigurer`.
|
||||
The following example exposes a `RestTemplateBuilder` that matches what Spring Boot's auto-configuration would have done, except that custom connect and read timeouts are also specified:
|
||||
|
||||
include-code::MyRestTemplateBuilderConfiguration[]
|
||||
|
||||
The most extreme (and rarely used) option is to create your own `RestTemplateBuilder` bean without using a configurer.
|
||||
In addition to replacing the auto-configured builder, this also prevents any `RestTemplateCustomizer` beans from being used.
|
||||
|
||||
|
||||
|
||||
[[io.rest-client.resttemplate.ssl]]
|
||||
=== RestTemplate SSL Support
|
||||
|
||||
If you need custom SSL configuration on the `RestTemplate`, you can apply an xref:features/ssl.adoc#features.ssl.bundles[SSL bundle] to the `RestTemplateBuilder` as shown in this example:
|
||||
|
||||
include-code::MyService[]
|
||||
|
||||
|
||||
|
||||
[[io.rest-client.clienthttprequestfactory]]
|
||||
== HTTP Client Detection for RestClient and RestTemplate
|
||||
|
||||
Spring Boot will auto-detect which HTTP client to use with `RestClient` and `RestTemplate` depending on the libraries available on the application classpath.
|
||||
In order of preference, the following clients are supported:
|
||||
|
||||
. Apache HttpClient
|
||||
. Jetty HttpClient
|
||||
. OkHttp (deprecated)
|
||||
. Simple JDK client (`HttpURLConnection`)
|
||||
|
||||
If multiple clients are available on the classpath, the most preferred client will be used.
|
||||
@@ -0,0 +1,17 @@
|
||||
[[io.validation]]
|
||||
= Validation
|
||||
|
||||
The method validation feature supported by Bean Validation 1.1 is automatically enabled as long as a JSR-303 implementation (such as Hibernate validator) is on the classpath.
|
||||
This lets bean methods be annotated with `jakarta.validation` constraints on their parameters and/or on their return value.
|
||||
Target classes with such annotated methods need to be annotated with the `@Validated` annotation at the type level for their methods to be searched for inline constraint annotations.
|
||||
|
||||
For instance, the following service triggers the validation of the first argument, making sure its size is between 8 and 10:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
The application's `MessageSource` is used when resolving `+{parameters}+` in constraint messages.
|
||||
This allows you to use xref:features/internationalization.adoc[your application's `messages.properties` files] for Bean Validation messages.
|
||||
Once the parameters have been resolved, message interpolation is completed using Bean Validation's default interpolator.
|
||||
|
||||
To customize the `Configuration` used to build the `ValidatorFactory`, define a `ValidationConfigurationCustomizer` bean.
|
||||
When multiple customizer beans are defined, they are called in order based on their `@Order` annotation or `Ordered` implementation.
|
||||
@@ -0,0 +1,35 @@
|
||||
[[io.webservices]]
|
||||
= Web Services
|
||||
|
||||
Spring Boot provides Web Services auto-configuration so that all you must do is define your `Endpoints`.
|
||||
|
||||
The {url-spring-webservices-docs}[Spring Web Services features] can be easily accessed with the `spring-boot-starter-webservices` module.
|
||||
|
||||
`SimpleWsdl11Definition` and `SimpleXsdSchema` beans can be automatically created for your WSDLs and XSDs respectively.
|
||||
To do so, configure their location, as shown in the following example:
|
||||
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
webservices:
|
||||
wsdl-locations: "classpath:/wsdl"
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[io.webservices.template]]
|
||||
== Calling Web Services with WebServiceTemplate
|
||||
|
||||
If you need to call remote Web services from your application, you can use the {url-spring-webservices-docs}#client-web-service-template[`WebServiceTemplate`] class.
|
||||
Since `WebServiceTemplate` instances often need to be customized before being used, Spring Boot does not provide any single auto-configured `WebServiceTemplate` bean.
|
||||
It does, however, auto-configure a `WebServiceTemplateBuilder`, which can be used to create `WebServiceTemplate` instances when needed.
|
||||
|
||||
The following code shows a typical example:
|
||||
|
||||
include-code::MyService[]
|
||||
|
||||
By default, `WebServiceTemplateBuilder` detects a suitable HTTP-based `WebServiceMessageSender` using the available HTTP client libraries on the classpath.
|
||||
You can also customize read and connection timeouts as follows:
|
||||
|
||||
include-code::MyWebServiceTemplateConfiguration[]
|
||||
@@ -0,0 +1,136 @@
|
||||
[[messaging.amqp]]
|
||||
= AMQP
|
||||
|
||||
The Advanced Message Queuing Protocol (AMQP) is a platform-neutral, wire-level protocol for message-oriented middleware.
|
||||
The Spring AMQP project applies core Spring concepts to the development of AMQP-based messaging solutions.
|
||||
Spring Boot offers several conveniences for working with AMQP through RabbitMQ, including the `spring-boot-starter-amqp` "`Starter`".
|
||||
|
||||
|
||||
|
||||
[[messaging.amqp.rabbitmq]]
|
||||
== RabbitMQ Support
|
||||
|
||||
https://www.rabbitmq.com/[RabbitMQ] is a lightweight, reliable, scalable, and portable message broker based on the AMQP protocol.
|
||||
Spring uses RabbitMQ to communicate through the AMQP protocol.
|
||||
|
||||
RabbitMQ configuration is controlled by external configuration properties in `+spring.rabbitmq.*+`.
|
||||
For example, you might declare the following section in `application.properties`:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
rabbitmq:
|
||||
host: "localhost"
|
||||
port: 5672
|
||||
username: "admin"
|
||||
password: "secret"
|
||||
----
|
||||
|
||||
Alternatively, you could configure the same connection using the `addresses` attribute:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
rabbitmq:
|
||||
addresses: "amqp://admin:secret@localhost"
|
||||
----
|
||||
|
||||
NOTE: When specifying addresses that way, the `host` and `port` properties are ignored.
|
||||
If the address uses the `amqps` protocol, SSL support is enabled automatically.
|
||||
|
||||
See {code-spring-boot-autoconfigure-src}/amqp/RabbitProperties.java[`RabbitProperties`] for more of the supported property-based configuration options.
|
||||
To configure lower-level details of the RabbitMQ `ConnectionFactory` that is used by Spring AMQP, define a `ConnectionFactoryCustomizer` bean.
|
||||
|
||||
If a `ConnectionNameStrategy` bean exists in the context, it will be automatically used to name connections created by the auto-configured `CachingConnectionFactory`.
|
||||
|
||||
To make an application-wide, additive customization to the `RabbitTemplate`, use a `RabbitTemplateCustomizer` bean.
|
||||
|
||||
TIP: See https://spring.io/blog/2010/06/14/understanding-amqp-the-protocol-used-by-rabbitmq/[Understanding AMQP, the protocol used by RabbitMQ] for more details.
|
||||
|
||||
|
||||
|
||||
[[messaging.amqp.sending]]
|
||||
== Sending a Message
|
||||
|
||||
Spring's `AmqpTemplate` and `AmqpAdmin` are auto-configured, and you can autowire them directly into your own beans, as shown in the following example:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
NOTE: {url-spring-amqp-javadoc}/rabbit/core/RabbitMessagingTemplate.html[`RabbitMessagingTemplate`] can be injected in a similar manner.
|
||||
If a `MessageConverter` bean is defined, it is associated automatically to the auto-configured `AmqpTemplate`.
|
||||
|
||||
If necessary, any `org.springframework.amqp.core.Queue` that is defined as a bean is automatically used to declare a corresponding queue on the RabbitMQ instance.
|
||||
|
||||
To retry operations, you can enable retries on the `AmqpTemplate` (for example, in the event that the broker connection is lost):
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
rabbitmq:
|
||||
template:
|
||||
retry:
|
||||
enabled: true
|
||||
initial-interval: "2s"
|
||||
----
|
||||
|
||||
Retries are disabled by default.
|
||||
You can also customize the `RetryTemplate` programmatically by declaring a `RabbitRetryTemplateCustomizer` bean.
|
||||
|
||||
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.sending-stream]]
|
||||
== Sending a Message To A Stream
|
||||
|
||||
To send a message to a particular stream, specify the name of the stream, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
rabbitmq:
|
||||
stream:
|
||||
name: "my-stream"
|
||||
----
|
||||
|
||||
If a `MessageConverter`, `StreamMessageConverter`, or `ProducerCustomizer` bean is defined, it is associated automatically to the auto-configured `RabbitStreamTemplate`.
|
||||
|
||||
If you need to create more `RabbitStreamTemplate` instances or if you want to override the default, Spring Boot provides a `RabbitStreamTemplateConfigurer` bean that you can use to initialize a `RabbitStreamTemplate` with the same settings as the factories used by the auto-configuration.
|
||||
|
||||
|
||||
|
||||
[[messaging.amqp.receiving]]
|
||||
== Receiving a Message
|
||||
|
||||
When the Rabbit infrastructure is present, any bean can be annotated with `@RabbitListener` to create a listener endpoint.
|
||||
If no `RabbitListenerContainerFactory` has been defined, a default `SimpleRabbitListenerContainerFactory` is automatically configured and you can switch to a direct container using the configprop:spring.rabbitmq.listener.type[] property.
|
||||
If a `MessageConverter` or a `MessageRecoverer` bean is defined, it is automatically associated with the default factory.
|
||||
|
||||
The following sample component creates a listener endpoint on the `someQueue` queue:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
TIP: See {url-spring-amqp-javadoc}/rabbit/annotation/EnableRabbit.html[the Javadoc of `@EnableRabbit`] for more details.
|
||||
|
||||
If you need to create more `RabbitListenerContainerFactory` instances or if you want to override the default, Spring Boot provides a `SimpleRabbitListenerContainerFactoryConfigurer` and a `DirectRabbitListenerContainerFactoryConfigurer` that you can use to initialize a `SimpleRabbitListenerContainerFactory` and a `DirectRabbitListenerContainerFactory` with the same settings as the factories used by the auto-configuration.
|
||||
|
||||
TIP: It does not matter which container type you chose.
|
||||
Those two beans are exposed by the auto-configuration.
|
||||
|
||||
For instance, the following configuration class exposes another factory that uses a specific `MessageConverter`:
|
||||
|
||||
include-code::custom/MyRabbitConfiguration[]
|
||||
|
||||
Then you can use the factory in any `@RabbitListener`-annotated method, as follows:
|
||||
|
||||
include-code::custom/MyBean[]
|
||||
|
||||
You can enable retries to handle situations where your listener throws an exception.
|
||||
By default, `RejectAndDontRequeueRecoverer` is used, but you can define a `MessageRecoverer` of your own.
|
||||
When retries are exhausted, the message is rejected and either dropped or routed to a dead-letter exchange if the broker is configured to do so.
|
||||
By default, retries are disabled.
|
||||
You can also customize the `RetryTemplate` programmatically by declaring a `RabbitRetryTemplateCustomizer` bean.
|
||||
|
||||
IMPORTANT: By default, if retries are disabled and the listener throws an exception, the delivery is retried indefinitely.
|
||||
You can modify this behavior in two ways: Set the `defaultRequeueRejected` property to `false` so that zero re-deliveries are attempted or throw an `AmqpRejectAndDontRequeueException` to signal the message should be rejected.
|
||||
The latter is the mechanism used when retries are enabled and the maximum number of delivery attempts is reached.
|
||||
@@ -0,0 +1,8 @@
|
||||
[[messaging]]
|
||||
= Messaging
|
||||
|
||||
The Spring Framework provides extensive support for integrating with messaging systems, from simplified use of the JMS API using `JmsTemplate` to a complete infrastructure to receive messages asynchronously.
|
||||
Spring AMQP provides a similar feature set for the Advanced Message Queuing Protocol.
|
||||
Spring Boot also provides auto-configuration options for `RabbitTemplate` and RabbitMQ.
|
||||
Spring WebSocket natively includes support for STOMP messaging, and Spring Boot has support for that through starters and a small amount of auto-configuration.
|
||||
Spring Boot also has support for Apache Kafka and Apache Pulsar.
|
||||
@@ -0,0 +1,168 @@
|
||||
[[messaging.jms]]
|
||||
= JMS
|
||||
|
||||
The `jakarta.jms.ConnectionFactory` interface provides a standard method of creating a `jakarta.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 {url-spring-framework-docs}/integration/jms.html[relevant section] of the Spring Framework reference documentation for details.)
|
||||
Spring Boot also auto-configures the necessary infrastructure to send and receive messages.
|
||||
|
||||
|
||||
|
||||
[[messaging.jms.activemq]]
|
||||
== ActiveMQ "Classic" Support
|
||||
|
||||
When https://activemq.apache.org/components/classic[ActiveMQ "Classic"] is available on the classpath, Spring Boot can configure a `ConnectionFactory`.
|
||||
|
||||
NOTE: If you use `spring-boot-starter-activemq`, the necessary dependencies to connect to an ActiveMQ "Classic" instance are provided, as is the Spring infrastructure to integrate with JMS.
|
||||
|
||||
ActiveMQ "Classic" configuration is controlled by external configuration properties in `+spring.activemq.*+`.
|
||||
By default, ActiveMQ "Classic" is auto-configured to use the https://activemq.apache.org/tcp-transport-reference[TCP transport], connecting by default to `tcp://localhost:61616`. The following example shows how to change the default broker URL:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
activemq:
|
||||
broker-url: "tcp://192.168.1.210:9876"
|
||||
user: "admin"
|
||||
password: "secret"
|
||||
----
|
||||
|
||||
By default, a `CachingConnectionFactory` wraps the native `ConnectionFactory` with sensible settings that you can control by external configuration properties in `+spring.jms.*+`:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
jms:
|
||||
cache:
|
||||
session-cache-size: 5
|
||||
----
|
||||
|
||||
If you'd rather use native pooling, you can do so by adding a dependency to `org.messaginghub:pooled-jms` and configuring the `JmsPoolConnectionFactory` accordingly, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
activemq:
|
||||
pool:
|
||||
enabled: true
|
||||
max-connections: 50
|
||||
----
|
||||
|
||||
TIP: See {code-spring-boot-autoconfigure-src}/jms/activemq/ActiveMQProperties.java[`ActiveMQProperties`] for more of the supported options.
|
||||
You can also register an arbitrary number of beans that implement `ActiveMQConnectionFactoryCustomizer` for more advanced customizations.
|
||||
|
||||
By default, ActiveMQ "Classic" creates a destination if it does not yet exist so that destinations are resolved against their provided names.
|
||||
|
||||
|
||||
|
||||
[[messaging.jms.artemis]]
|
||||
== ActiveMQ Artemis Support
|
||||
|
||||
Spring Boot can auto-configure a `ConnectionFactory` when it detects that https://activemq.apache.org/components/artemis/[ActiveMQ Artemis] is available on the classpath.
|
||||
If the broker is present, an embedded broker is automatically started and configured (unless the mode property has been explicitly set).
|
||||
The supported modes are `embedded` (to make explicit that an embedded broker is required and that an error should occur if the broker is not available on the classpath) and `native` (to connect to a broker using the `netty` transport protocol).
|
||||
When the latter is configured, Spring Boot configures a `ConnectionFactory` that connects to a broker running on the local machine with the default settings.
|
||||
|
||||
NOTE: If you use `spring-boot-starter-artemis`, the necessary dependencies to connect to an existing ActiveMQ Artemis instance are provided, as well as the Spring infrastructure to integrate with JMS.
|
||||
Adding `org.apache.activemq:artemis-jakarta-server` to your application lets you use embedded mode.
|
||||
|
||||
ActiveMQ Artemis configuration is controlled by external configuration properties in `+spring.artemis.*+`.
|
||||
For example, you might declare the following section in `application.properties`:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
artemis:
|
||||
mode: native
|
||||
broker-url: "tcp://192.168.1.210:9876"
|
||||
user: "admin"
|
||||
password: "secret"
|
||||
----
|
||||
|
||||
When embedding the broker, you can choose if you want to enable persistence and list the destinations that should be made available.
|
||||
These can be specified as a comma-separated list to create them with the default options, or you can define bean(s) of type `org.apache.activemq.artemis.jms.server.config.JMSQueueConfiguration` or `org.apache.activemq.artemis.jms.server.config.TopicConfiguration`, for advanced queue and topic configurations, respectively.
|
||||
|
||||
By default, a `CachingConnectionFactory` wraps the native `ConnectionFactory` with sensible settings that you can control by external configuration properties in `+spring.jms.*+`:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
jms:
|
||||
cache:
|
||||
session-cache-size: 5
|
||||
----
|
||||
|
||||
If you'd rather use native pooling, you can do so by adding a dependency on `org.messaginghub:pooled-jms` and configuring the `JmsPoolConnectionFactory` accordingly, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
artemis:
|
||||
pool:
|
||||
enabled: true
|
||||
max-connections: 50
|
||||
----
|
||||
|
||||
See {code-spring-boot-autoconfigure-src}/jms/artemis/ArtemisProperties.java[`ArtemisProperties`] for more supported options.
|
||||
|
||||
No JNDI lookup is involved, and destinations are resolved against their names, using either the `name` attribute in the ActiveMQ Artemis configuration or the names provided through configuration.
|
||||
|
||||
|
||||
|
||||
[[messaging.jms.jndi]]
|
||||
== Using a JNDI ConnectionFactory
|
||||
|
||||
If you are running your application in an application server, Spring Boot tries to locate a JMS `ConnectionFactory` by using JNDI.
|
||||
By default, the `java:/JmsXA` and `java:/XAConnectionFactory` location are checked.
|
||||
You can use the configprop:spring.jms.jndi-name[] property if you need to specify an alternative location, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
jms:
|
||||
jndi-name: "java:/MyConnectionFactory"
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[messaging.jms.sending]]
|
||||
== Sending a Message
|
||||
|
||||
Spring's `JmsTemplate` is auto-configured, and you can autowire it directly into your own beans, as shown in the following example:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
NOTE: {url-spring-framework-javadoc}/org/springframework/jms/core/JmsMessagingTemplate.html[`JmsMessagingTemplate`] can be injected in a similar manner.
|
||||
If a `DestinationResolver` or a `MessageConverter` bean is defined, it is associated automatically to the auto-configured `JmsTemplate`.
|
||||
|
||||
|
||||
|
||||
[[messaging.jms.receiving]]
|
||||
== Receiving a Message
|
||||
|
||||
When the JMS infrastructure is present, any bean can be annotated with `@JmsListener` to create a listener endpoint.
|
||||
If no `JmsListenerContainerFactory` has been defined, a default one is configured automatically.
|
||||
If a `DestinationResolver`, a `MessageConverter`, or a `jakarta.jms.ExceptionListener` beans are defined, they are associated automatically with the default factory.
|
||||
|
||||
By default, the default factory is transactional.
|
||||
If you run in an infrastructure where a `JtaTransactionManager` is present, it is associated to the listener container by default.
|
||||
If not, the `sessionTransacted` flag is enabled.
|
||||
In that latter scenario, you can associate your local data store transaction to the processing of an incoming message by adding `@Transactional` on your listener method (or a delegate thereof).
|
||||
This ensures that the incoming message is acknowledged, once the local transaction has completed.
|
||||
This also includes sending response messages that have been performed on the same JMS session.
|
||||
|
||||
The following component creates a listener endpoint on the `someQueue` destination:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
TIP: See {url-spring-framework-javadoc}/org/springframework/jms/annotation/EnableJms.html[the Javadoc of `@EnableJms`] for more details.
|
||||
|
||||
If you need to create more `JmsListenerContainerFactory` instances or if you want to override the default, Spring Boot provides a `DefaultJmsListenerContainerFactoryConfigurer` that you can use to initialize a `DefaultJmsListenerContainerFactory` with the same settings as the one that is auto-configured.
|
||||
|
||||
For instance, the following example exposes another factory that uses a specific `MessageConverter`:
|
||||
|
||||
include-code::custom/MyJmsConfiguration[]
|
||||
|
||||
Then you can use the factory in any `@JmsListener`-annotated method as follows:
|
||||
|
||||
include-code::custom/MyBean[]
|
||||
@@ -0,0 +1,171 @@
|
||||
[[messaging.kafka]]
|
||||
= Apache Kafka Support
|
||||
|
||||
https://kafka.apache.org/[Apache Kafka] is supported by providing auto-configuration of the `spring-kafka` project.
|
||||
|
||||
Kafka configuration is controlled by external configuration properties in `spring.kafka.*`.
|
||||
For example, you might declare the following section in `application.properties`:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
kafka:
|
||||
bootstrap-servers: "localhost:9092"
|
||||
consumer:
|
||||
group-id: "myGroup"
|
||||
----
|
||||
|
||||
TIP: To create a topic on startup, add a bean of type `NewTopic`.
|
||||
If the topic already exists, the bean is ignored.
|
||||
|
||||
See {code-spring-boot-autoconfigure-src}/kafka/KafkaProperties.java[`KafkaProperties`] for more supported options.
|
||||
|
||||
|
||||
|
||||
[[messaging.kafka.sending]]
|
||||
== 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:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
NOTE: If the property configprop:spring.kafka.producer.transaction-id-prefix[] is defined, a `KafkaTransactionManager` is automatically configured.
|
||||
Also, if a `RecordMessageConverter` bean is defined, it is automatically associated to the auto-configured `KafkaTemplate`.
|
||||
|
||||
|
||||
|
||||
[[messaging.kafka.receiving]]
|
||||
== Receiving a Message
|
||||
|
||||
When the Apache Kafka infrastructure is present, any bean can be annotated with `@KafkaListener` to create a listener endpoint.
|
||||
If no `KafkaListenerContainerFactory` has been defined, a default one is automatically configured with keys defined in `spring.kafka.listener.*`.
|
||||
|
||||
The following component creates a listener endpoint on the `someTopic` topic:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
If a `KafkaTransactionManager` bean is defined, it is automatically associated to the container factory.
|
||||
Similarly, if a `RecordFilterStrategy`, `CommonErrorHandler`, `AfterRollbackProcessor` or `ConsumerAwareRebalanceListener` bean is defined, it is automatically associated to the default factory.
|
||||
|
||||
Depending on the listener type, a `RecordMessageConverter` or `BatchMessageConverter` bean is associated to the default factory.
|
||||
If only a `RecordMessageConverter` bean is present for a batch listener, it is wrapped in a `BatchMessageConverter`.
|
||||
|
||||
TIP: A custom `ChainedKafkaTransactionManager` must be marked `@Primary` as it usually references the auto-configured `KafkaTransactionManager` bean.
|
||||
|
||||
|
||||
|
||||
[[messaging.kafka.streams]]
|
||||
== Kafka Streams
|
||||
|
||||
Spring for Apache Kafka provides a factory bean to create a `StreamsBuilder` object and manage the lifecycle of its streams.
|
||||
Spring Boot auto-configures the required `KafkaStreamsConfiguration` bean as long as `kafka-streams` is on the classpath and Kafka Streams is enabled by the `@EnableKafkaStreams` annotation.
|
||||
|
||||
Enabling Kafka Streams means that the application id and bootstrap servers must be set.
|
||||
The former can be configured using `spring.kafka.streams.application-id`, defaulting to `spring.application.name` if not set.
|
||||
The latter can be set globally or specifically overridden only for streams.
|
||||
|
||||
Several additional properties are available using dedicated properties; other arbitrary Kafka properties can be set using the `spring.kafka.streams.properties` namespace.
|
||||
See also xref:messaging/kafka.adoc#messaging.kafka.additional-properties[Additional Kafka Properties] for more information.
|
||||
|
||||
To use the factory bean, wire `StreamsBuilder` into your `@Bean` as shown in the following example:
|
||||
|
||||
include-code::MyKafkaStreamsConfiguration[]
|
||||
|
||||
By default, the streams managed by the `StreamBuilder` object are started automatically.
|
||||
You can customize this behavior using the configprop:spring.kafka.streams.auto-startup[] property.
|
||||
|
||||
|
||||
|
||||
[[messaging.kafka.additional-properties]]
|
||||
== Additional Kafka Properties
|
||||
|
||||
The properties supported by auto configuration are shown in the xref:appendix:application-properties/index.adoc#appendix.application-properties.integration["`Integration Properties`"] section of the Appendix.
|
||||
Note that, for the most part, these properties (hyphenated or camelCase) map directly to the Apache Kafka dotted properties.
|
||||
See the Apache Kafka documentation for details.
|
||||
|
||||
Properties that don't include a client type (`producer`, `consumer`, `admin`, or `streams`) in their name are considered to be common and apply to all clients.
|
||||
Most of these common properties can be overridden for one or more of the client types, if needed.
|
||||
|
||||
Apache Kafka designates properties with an importance of HIGH, MEDIUM, or LOW.
|
||||
Spring Boot auto-configuration supports all HIGH importance properties, some selected MEDIUM and LOW properties, and any properties that do not have a default value.
|
||||
|
||||
Only a subset of the properties supported by Kafka are available directly through the `KafkaProperties` class.
|
||||
If you wish to configure the individual client types with additional properties that are not directly supported, use the following properties:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
kafka:
|
||||
properties:
|
||||
"[prop.one]": "first"
|
||||
admin:
|
||||
properties:
|
||||
"[prop.two]": "second"
|
||||
consumer:
|
||||
properties:
|
||||
"[prop.three]": "third"
|
||||
producer:
|
||||
properties:
|
||||
"[prop.four]": "fourth"
|
||||
streams:
|
||||
properties:
|
||||
"[prop.five]": "fifth"
|
||||
----
|
||||
|
||||
This sets the common `prop.one` Kafka property to `first` (applies to producers, consumers, admins, and streams), the `prop.two` admin property to `second`, the `prop.three` consumer property to `third`, the `prop.four` producer property to `fourth` and the `prop.five` streams property to `fifth`.
|
||||
|
||||
You can also configure the Spring Kafka `JsonDeserializer` as follows:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
kafka:
|
||||
consumer:
|
||||
value-deserializer: "org.springframework.kafka.support.serializer.JsonDeserializer"
|
||||
properties:
|
||||
"[spring.json.value.default.type]": "com.example.Invoice"
|
||||
"[spring.json.trusted.packages]": "com.example.main,com.example.another"
|
||||
----
|
||||
|
||||
Similarly, you can disable the `JsonSerializer` default behavior of sending type information in headers:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
kafka:
|
||||
producer:
|
||||
value-serializer: "org.springframework.kafka.support.serializer.JsonSerializer"
|
||||
properties:
|
||||
"[spring.json.add.type.headers]": false
|
||||
----
|
||||
|
||||
IMPORTANT: Properties set in this way override any configuration item that Spring Boot explicitly supports.
|
||||
|
||||
|
||||
|
||||
[[messaging.kafka.embedded]]
|
||||
== 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.
|
||||
For more information, please see the Spring for Apache Kafka {url-spring-kafka-docs}/testing.html#ekb[reference manual].
|
||||
|
||||
To make Spring Boot auto-configuration work with the aforementioned embedded Apache Kafka broker, you need to remap a system property for embedded broker addresses (populated by the `EmbeddedKafkaBroker`) into the Spring Boot configuration property for Apache Kafka.
|
||||
There are several ways to do that:
|
||||
|
||||
* Provide a system property to map embedded broker addresses into configprop:spring.kafka.bootstrap-servers[] in the test class:
|
||||
|
||||
include-code::property/MyTest[tag=*]
|
||||
|
||||
* Configure a property name on the `@EmbeddedKafka` annotation:
|
||||
|
||||
include-code::annotation/MyTest[]
|
||||
|
||||
* Use a placeholder in configuration properties:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
kafka:
|
||||
bootstrap-servers: "${spring.embedded.kafka.brokers}"
|
||||
----
|
||||
@@ -0,0 +1,226 @@
|
||||
[[messaging.pulsar]]
|
||||
= Apache Pulsar Support
|
||||
|
||||
https://pulsar.apache.org/[Apache Pulsar] is supported by providing auto-configuration of the {url-spring-pulsar-site}[Spring for Apache Pulsar] project.
|
||||
|
||||
Spring Boot will auto-configure and register the classic (imperative) Spring for Apache Pulsar components when `org.springframework.pulsar:spring-pulsar` is on the classpath.
|
||||
It will do the same for the reactive components when `org.springframework.pulsar:spring-pulsar-reactive` is on the classpath.
|
||||
|
||||
There are `spring-boot-starter-pulsar` and `spring-boot-starter-pulsar-reactive` "`Starters`" for conveniently collecting the dependencies for imperative and reactive use, respectively.
|
||||
|
||||
|
||||
|
||||
[[messaging.pulsar.connecting]]
|
||||
== Connecting to Pulsar
|
||||
|
||||
When you use the Pulsar starter, Spring Boot will auto-configure and register a `PulsarClient` bean.
|
||||
|
||||
By default, the application tries to connect to a local Pulsar instance at `pulsar://localhost:6650`.
|
||||
This can be adjusted by setting the configprop:spring.pulsar.client.service-url[] property to a different value.
|
||||
|
||||
NOTE: The value must be a valid https://pulsar.apache.org/docs/client-libraries-java/#connection-urls[Pulsar Protocol] URL
|
||||
|
||||
You can configure the client by specifying any of the `spring.pulsar.client.*` prefixed application properties.
|
||||
|
||||
If you need more control over the configuration, consider registering one or more `PulsarClientBuilderCustomizer` beans.
|
||||
|
||||
|
||||
|
||||
[[messaging.pulsar.connecting.auth]]
|
||||
=== Authentication
|
||||
|
||||
To connect to a Pulsar cluster that requires authentication, you need to specify which authentication plugin to use by setting the `pluginClassName` and any parameters required by the plugin.
|
||||
You can set the parameters as a map of parameter names to parameter values.
|
||||
The following example shows how to configure the `AuthenticationOAuth2` plugin.
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
pulsar:
|
||||
client:
|
||||
authentication:
|
||||
plugin-class-name: org.apache.pulsar.client.impl.auth.oauth2.AuthenticationOAuth2
|
||||
param:
|
||||
issuerUrl: https://auth.server.cloud/
|
||||
privateKey: file:///Users/some-key.json
|
||||
audience: urn:sn:acme:dev:my-instance
|
||||
----
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
You need to ensure that names defined under `+spring.pulsar.client.authentication.param.*+` exactly match those expected by your auth plugin (which is typically camel cased).
|
||||
Spring Boot will not attempt any kind of relaxed binding for these entries.
|
||||
|
||||
For example, if you want to configure the issuer url for the `AuthenticationOAuth2` auth plugin you must use `+spring.pulsar.client.authentication.param.issuerUrl+`.
|
||||
If you use other forms, such as `issuerurl` or `issuer-url`, the setting will not be applied to the plugin.
|
||||
|
||||
This lack of relaxed binding also makes using environment variables for authentication parameters problematic because the case sensitivity is lost during translation.
|
||||
If you use environment variables for the parameters then you will need to follow {url-spring-pulsar-docs}/reference/pulsar.html#client-authentication-env-vars[these steps] in the Spring for Apache Pulsar reference documentation for it to work properly.
|
||||
====
|
||||
|
||||
|
||||
|
||||
[[messaging.pulsar.connecting.ssl]]
|
||||
=== SSL
|
||||
|
||||
By default, Pulsar clients communicate with Pulsar services in plain text.
|
||||
You can follow {url-spring-pulsar-docs}reference/pulsar.html#tls-encryption[these steps] in the Spring for Apache Pulsar reference documentation to enable TLS encryption.
|
||||
|
||||
For complete details on the client and authentication see the Spring for Apache Pulsar {url-spring-pulsar-docs}reference/pulsar.html#pulsar-client[reference documentation].
|
||||
|
||||
|
||||
|
||||
[[messaging.pulsar.connecting-reactive]]
|
||||
== Connecting to Pulsar Reactively
|
||||
|
||||
When the Reactive auto-configuration is activated, Spring Boot will auto-configure and register a `ReactivePulsarClient` bean.
|
||||
|
||||
The `ReactivePulsarClient` adapts an instance of the previously described `PulsarClient`.
|
||||
Therefore, follow the previous section to configure the `PulsarClient` used by the `ReactivePulsarClient`.
|
||||
|
||||
|
||||
|
||||
[[messaging.pulsar.admin]]
|
||||
== Connecting to Pulsar Administration
|
||||
|
||||
Spring for Apache Pulsar's `PulsarAdministration` client is also auto-configured.
|
||||
|
||||
By default, the application tries to connect to a local Pulsar instance at `\http://localhost:8080`.
|
||||
This can be adjusted by setting the configprop:spring.pulsar.admin.service-url[] property to a different value in the form `(http|https)://<host>:<port>`.
|
||||
|
||||
If you need more control over the configuration, consider registering one or more `PulsarAdminBuilderCustomizer` beans.
|
||||
|
||||
|
||||
|
||||
[[messaging.pulsar.admin.auth]]
|
||||
=== Authentication
|
||||
|
||||
When accessing a Pulsar cluster that requires authentication, the admin client requires the same security configuration as the regular Pulsar client.
|
||||
You can use the aforementioned xref:messaging/pulsar.adoc#messaging.pulsar.connecting.auth[authentication configuration] by replacing `spring.pulsar.client.authentication` with `spring.pulsar.admin.authentication`.
|
||||
|
||||
TIP: To create a topic on startup, add a bean of type `PulsarTopic`.
|
||||
If the topic already exists, the bean is ignored.
|
||||
|
||||
|
||||
|
||||
[[messaging.pulsar.sending]]
|
||||
== Sending a Message
|
||||
|
||||
Spring's `PulsarTemplate` is auto-configured, and you can use it to send messages, as shown in the following example:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
The `PulsarTemplate` relies on a `PulsarProducerFactory` to create the underlying Pulsar producer.
|
||||
Spring Boot auto-configuration also provides this producer factory, which by default, caches the producers that it creates.
|
||||
You can configure the producer factory and cache settings by specifying any of the `spring.pulsar.producer.\*` and `spring.pulsar.producer.cache.*` prefixed application properties.
|
||||
|
||||
If you need more control over the producer factory configuration, consider registering one or more `ProducerBuilderCustomizer` beans.
|
||||
These customizers are applied to all created producers.
|
||||
You can also pass in a `ProducerBuilderCustomizer` when sending a message to only affect the current producer.
|
||||
|
||||
If you need more control over the message being sent, you can pass in a `TypedMessageBuilderCustomizer` when sending a message.
|
||||
|
||||
|
||||
|
||||
[[messaging.pulsar.sending-reactive]]
|
||||
== Sending a Message Reactively
|
||||
|
||||
When the Reactive auto-configuration is activated, Spring's `ReactivePulsarTemplate` is auto-configured, and you can use it to send messages, as shown in the following example:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
The `ReactivePulsarTemplate` relies on a `ReactivePulsarSenderFactory` to actually create the underlying sender.
|
||||
Spring Boot auto-configuration also provides this sender factory, which by default, caches the producers that it creates.
|
||||
You can configure the sender factory and cache settings by specifying any of the `spring.pulsar.producer.\*` and `spring.pulsar.producer.cache.*` prefixed application properties.
|
||||
|
||||
If you need more control over the sender factory configuration, consider registering one or more `ReactiveMessageSenderBuilderCustomizer` beans.
|
||||
These customizers are applied to all created senders.
|
||||
You can also pass in a `ReactiveMessageSenderBuilderCustomizer` when sending a message to only affect the current sender.
|
||||
|
||||
If you need more control over the message being sent, you can pass in a `MessageSpecBuilderCustomizer` when sending a message.
|
||||
|
||||
|
||||
|
||||
[[messaging.pulsar.receiving]]
|
||||
== Receiving a Message
|
||||
|
||||
When the Apache Pulsar infrastructure is present, any bean can be annotated with `@PulsarListener` to create a listener endpoint.
|
||||
The following component creates a listener endpoint on the `someTopic` topic:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
Spring Boot auto-configuration provides all the components necessary for `PulsarListener`, such as the `PulsarListenerContainerFactory` and the consumer factory it uses to construct the underlying Pulsar consumers.
|
||||
You can configure these components by specifying any of the `spring.pulsar.listener.\*` and `spring.pulsar.consumer.*` prefixed application properties.
|
||||
|
||||
If you need more control over the consumer factory configuration, consider registering one or more `ConsumerBuilderCustomizer` beans.
|
||||
These customizers are applied to all consumers created by the factory, and therefore all `@PulsarListener` instances.
|
||||
You can also customize a single listener by setting the `consumerCustomizer` attribute of the `@PulsarListener` annotation.
|
||||
|
||||
|
||||
|
||||
[[messaging.pulsar.receiving-reactive]]
|
||||
== Receiving a Message Reactively
|
||||
|
||||
When the Apache Pulsar infrastructure is present and the Reactive auto-configuration is activated, any bean can be annotated with `@ReactivePulsarListener` to create a reactive listener endpoint.
|
||||
The following component creates a reactive listener endpoint on the `someTopic` topic:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
Spring Boot auto-configuration provides all the components necessary for `ReactivePulsarListener`, such as the `ReactivePulsarListenerContainerFactory` and the consumer factory it uses to construct the underlying reactive Pulsar consumers.
|
||||
You can configure these components by specifying any of the `spring.pulsar.listener.*` and `spring.pulsar.consumer.*` prefixed application properties.
|
||||
|
||||
If you need more control over the consumer factory configuration, consider registering one or more `ReactiveMessageConsumerBuilderCustomizer` beans.
|
||||
These customizers are applied to all consumers created by the factory, and therefore all `@ReactivePulsarListener` instances.
|
||||
You can also customize a single listener by setting the `consumerCustomizer` attribute of the `@ReactivePulsarListener` annotation.
|
||||
|
||||
|
||||
|
||||
[[messaging.pulsar.reading]]
|
||||
== Reading a Message
|
||||
|
||||
The Pulsar reader interface enables applications to manually manage cursors.
|
||||
When you use a reader to connect to a topic you need to specify which message the reader begins reading from when it connects to a topic.
|
||||
|
||||
When the Apache Pulsar infrastructure is present, any bean can be annotated with `@PulsarReader` to consume messages using a reader.
|
||||
The following component creates a reader endpoint that starts reading messages from the beginning of the `someTopic` topic:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
The `@PulsarReader` relies on a `PulsarReaderFactory` to create the underlying Pulsar reader.
|
||||
Spring Boot auto-configuration provides this reader factory which can be customized by setting any of the `spring.pulsar.reader.*` prefixed application properties.
|
||||
|
||||
If you need more control over the reader factory configuration, consider registering one or more `ReaderBuilderCustomizer` beans.
|
||||
These customizers are applied to all readers created by the factory, and therefore all `@PulsarReader` instances.
|
||||
You can also customize a single listener by setting the `readerCustomizer` attribute of the `@PulsarReader` annotation.
|
||||
|
||||
|
||||
|
||||
[[messaging.pulsar.reading-reactive]]
|
||||
== Reading a Message Reactively
|
||||
|
||||
When the Apache Pulsar infrastructure is present and the Reactive auto-configuration is activated, Spring's `ReactivePulsarReaderFactory` is provided, and you can use it to create a reader in order to read messages in a reactive fashion.
|
||||
The following component creates a reader using the provided factory and reads a single message from 5 minutes ago from the `someTopic` topic:
|
||||
|
||||
include-code::MyBean[]
|
||||
|
||||
Spring Boot auto-configuration provides this reader factory which can be customized by setting any of the `spring.pulsar.reader.*` prefixed application properties.
|
||||
|
||||
If you need more control over the reader factory configuration, consider passing in one or more `ReactiveMessageReaderBuilderCustomizer` instances when using the factory to create a reader.
|
||||
|
||||
If you need more control over the reader factory configuration, consider registering one or more `ReactiveMessageReaderBuilderCustomizer` beans.
|
||||
These customizers are applied to all created readers.
|
||||
You can also pass one or more `ReactiveMessageReaderBuilderCustomizer` when creating a reader to only apply the customizations to the created reader.
|
||||
|
||||
TIP: For more details on any of the above components and to discover other available features, see the Spring for Apache Pulsar {url-spring-pulsar-docs}[reference documentation].
|
||||
|
||||
|
||||
|
||||
[[messaging.pulsar.additional-properties]]
|
||||
== Additional Pulsar Properties
|
||||
|
||||
The properties supported by auto-configuration are shown in the xref:appendix:application-properties/index.adoc#appendix.application-properties.integration["`Integration Properties`"] section of the Appendix.
|
||||
Note that, for the most part, these properties (hyphenated or camelCase) map directly to the Apache Pulsar configuration properties.
|
||||
See the Apache Pulsar documentation for details.
|
||||
|
||||
Only a subset of the properties supported by Pulsar are available directly through the `PulsarProperties` class.
|
||||
If you wish to tune the auto-configured components with additional properties that are not directly supported, you can use the customizer supported by each aforementioned component.
|
||||
@@ -0,0 +1,88 @@
|
||||
[[messaging.rsocket]]
|
||||
= RSocket
|
||||
|
||||
https://rsocket.io[RSocket] is a binary protocol for use on byte stream transports.
|
||||
It enables symmetric interaction models through async message passing over a single connection.
|
||||
|
||||
|
||||
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 {url-spring-framework-docs}/rsocket.html#rsocket-spring[RSocket section] of the Spring Framework reference for more details, including an overview of the RSocket protocol.
|
||||
|
||||
|
||||
|
||||
[[messaging.rsocket.strategies-auto-configuration]]
|
||||
== RSocket Strategies Auto-configuration
|
||||
|
||||
Spring Boot auto-configures an `RSocketStrategies` bean that provides all the required infrastructure for encoding and decoding RSocket payloads.
|
||||
By default, the auto-configuration will try to configure the following (in order):
|
||||
|
||||
. https://cbor.io/[CBOR] codecs with Jackson
|
||||
. JSON codecs with Jackson
|
||||
|
||||
The `spring-boot-starter-rsocket` starter provides both dependencies.
|
||||
See the xref:features/json.adoc#features.json.jackson[Jackson support section] to know more about customization possibilities.
|
||||
|
||||
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]]
|
||||
== RSocket server Auto-configuration
|
||||
|
||||
Spring Boot provides RSocket server auto-configuration.
|
||||
The required dependencies are provided by the `spring-boot-starter-rsocket`.
|
||||
|
||||
Spring Boot allows exposing RSocket over WebSocket from a WebFlux server, or standing up an independent RSocket server.
|
||||
This depends on the type of application and its configuration.
|
||||
|
||||
For WebFlux application (that is of type `WebApplicationType.REACTIVE`), the RSocket server will be plugged into the Web Server only if the following properties match:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
rsocket:
|
||||
server:
|
||||
mapping-path: "/rsocket"
|
||||
transport: "websocket"
|
||||
----
|
||||
|
||||
WARNING: Plugging RSocket into a web server is only supported with Reactor Netty, as RSocket itself is built with that library.
|
||||
|
||||
Alternatively, an RSocket TCP or websocket server is started as an independent, embedded server.
|
||||
Besides the dependency requirements, the only required configuration is to define a port for that server:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
rsocket:
|
||||
server:
|
||||
port: 9898
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[messaging.rsocket.messaging]]
|
||||
== 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]]
|
||||
== Calling RSocket Services with RSocketRequester
|
||||
|
||||
Once the `RSocket` channel is established between server and client, any party can send or receive requests to the other.
|
||||
|
||||
As a server, you can get injected with an `RSocketRequester` instance on any handler method of an RSocket `@Controller`.
|
||||
As a client, you need to configure and establish an RSocket connection first.
|
||||
Spring Boot auto-configures an `RSocketRequester.Builder` for such cases with the expected codecs and applies any `RSocketConnectorConfigurer` bean.
|
||||
|
||||
The `RSocketRequester.Builder` instance is a prototype bean, meaning each injection point will provide you with a new instance .
|
||||
This is done on purpose since this builder is stateful and you should not create requesters with different setups using the same instance.
|
||||
|
||||
The following code shows a typical example:
|
||||
|
||||
include-code::MyService[]
|
||||
@@ -0,0 +1,49 @@
|
||||
[[messaging.spring-integration]]
|
||||
= Spring Integration
|
||||
|
||||
Spring Boot offers several conveniences for working with {url-spring-integration-site}[Spring Integration], including the `spring-boot-starter-integration` "`Starter`".
|
||||
Spring Integration provides abstractions over messaging and also other transports such as HTTP, TCP, and others.
|
||||
If Spring Integration is available on your classpath, it is initialized through the `@EnableIntegration` annotation.
|
||||
|
||||
Spring Integration polling logic relies xref:features/task-execution-and-scheduling.adoc[on the auto-configured `TaskScheduler`].
|
||||
The default `PollerMetadata` (poll unbounded number of messages every second) can be customized with `spring.integration.poller.*` configuration properties.
|
||||
|
||||
Spring Boot also configures some features that are triggered by the presence of additional Spring Integration modules.
|
||||
If `spring-integration-jmx` is also on the classpath, message processing statistics are published over JMX.
|
||||
If `spring-integration-jdbc` is available, the default database schema can be created on startup, as shown in the following line:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
integration:
|
||||
jdbc:
|
||||
initialize-schema: "always"
|
||||
----
|
||||
|
||||
If `spring-integration-rsocket` is available, developers can configure an RSocket server using `"spring.rsocket.server.*"` properties and let it use `IntegrationRSocketEndpoint` or `RSocketOutboundGateway` components to handle incoming RSocket messages.
|
||||
This infrastructure can handle Spring Integration RSocket channel adapters and `@MessageMapping` handlers (given `"spring.integration.rsocket.server.message-mapping-enabled"` is configured).
|
||||
|
||||
Spring Boot can also auto-configure an `ClientRSocketConnector` using configuration properties:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
# Connecting to a RSocket server over TCP
|
||||
spring:
|
||||
integration:
|
||||
rsocket:
|
||||
client:
|
||||
host: "example.org"
|
||||
port: 9898
|
||||
----
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
# Connecting to a RSocket Server over WebSocket
|
||||
spring:
|
||||
integration:
|
||||
rsocket:
|
||||
client:
|
||||
uri: "ws://example.org"
|
||||
----
|
||||
|
||||
See the {code-spring-boot-autoconfigure-src}/integration/IntegrationAutoConfiguration.java[`IntegrationAutoConfiguration`] and {code-spring-boot-autoconfigure-src}/integration/IntegrationProperties.java[`IntegrationProperties`] classes for more details.
|
||||
@@ -0,0 +1,17 @@
|
||||
[[messaging.websockets]]
|
||||
= WebSockets
|
||||
|
||||
Spring Boot provides WebSockets auto-configuration for embedded Tomcat, Jetty, and Undertow.
|
||||
If you deploy a war file to a standalone container, Spring Boot assumes that the container is responsible for the configuration of its WebSocket support.
|
||||
|
||||
Spring Framework provides {url-spring-framework-docs}/web/websocket.html[rich WebSocket support] for MVC web applications that can be easily accessed through the `spring-boot-starter-websocket` module.
|
||||
|
||||
WebSocket support is also available for {url-spring-framework-docs}/web/webflux-websocket.html[reactive web applications] and requires to include the WebSocket API alongside `spring-boot-starter-webflux`:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<dependency>
|
||||
<groupId>jakarta.websocket</groupId>
|
||||
<artifactId>jakarta.websocket-api</artifactId>
|
||||
</dependency>
|
||||
----
|
||||
@@ -0,0 +1,195 @@
|
||||
[[native-image.advanced]]
|
||||
= Advanced Native Images Topics
|
||||
|
||||
|
||||
|
||||
[[native-image.advanced.nested-configuration-properties]]
|
||||
== Nested Configuration Properties
|
||||
|
||||
Reflection hints are automatically created for configuration properties by the Spring ahead-of-time engine.
|
||||
Nested configuration properties which are not inner classes, however, *must* be annotated with `@NestedConfigurationProperty`, otherwise they won't be detected and will not be bindable.
|
||||
|
||||
include-code::MyProperties[]
|
||||
|
||||
where `Nested` is:
|
||||
|
||||
include-code::Nested[]
|
||||
|
||||
The example above produces configuration properties for `my.properties.name` and `my.properties.nested.number`.
|
||||
Without the `@NestedConfigurationProperty` annotation on the `nested` field, the `my.properties.nested.number` property would not be bindable in a native image.
|
||||
|
||||
When using constructor binding, you have to annotate the field with `@NestedConfigurationProperty`:
|
||||
|
||||
include-code::MyPropertiesCtor[]
|
||||
|
||||
When using records, you have to annotate the parameter with `@NestedConfigurationProperty`:
|
||||
|
||||
include-code::MyPropertiesRecord[]
|
||||
|
||||
When using Kotlin, you need to annotate the parameter of a data class with `@NestedConfigurationProperty`:
|
||||
|
||||
include-code::MyPropertiesKotlin[]
|
||||
|
||||
NOTE: Please use public getters and setters in all cases, otherwise the properties will not be bindable.
|
||||
|
||||
|
||||
|
||||
[[native-image.advanced.converting-executable-jars]]
|
||||
== Converting a Spring Boot Executable Jar
|
||||
|
||||
It is possible to convert a Spring Boot xref:specification:executable-jar/index.adoc[executable jar] into a native image as long as the jar contains the AOT generated assets.
|
||||
This can be useful for a number of reasons, including:
|
||||
|
||||
* You can keep your regular JVM pipeline and turn the JVM application into a native image on your CI/CD platform.
|
||||
* As `native-image` https://github.com/oracle/graal/issues/407[does not support cross-compilation], you can keep an OS neutral deployment artifact which you convert later to different OS architectures.
|
||||
|
||||
You can convert a Spring Boot executable jar into a native image using Cloud Native Buildpacks, or using the `native-image` tool that is shipped with GraalVM.
|
||||
|
||||
NOTE: Your executable jar must include AOT generated assets such as generated classes and JSON hint files.
|
||||
|
||||
|
||||
|
||||
[[native-image.advanced.converting-executable-jars.buildpacks]]
|
||||
=== Using Buildpacks
|
||||
|
||||
Spring Boot applications usually use Cloud Native Buildpacks through the Maven (`mvn spring-boot:build-image`) or Gradle (`gradle bootBuildImage`) integrations.
|
||||
You can, however, also use https://buildpacks.io//docs/tools/pack/[`pack`] to turn an AOT processed Spring Boot executable jar into a native container image.
|
||||
|
||||
|
||||
First, make sure that a Docker daemon is available (see https://docs.docker.com/installation/#installation[Get Docker] for more details).
|
||||
https://docs.docker.com/engine/install/linux-postinstall/#manage-docker-as-a-non-root-user[Configure it to allow non-root user] if you are on Linux.
|
||||
|
||||
You also need to install `pack` by following https://buildpacks.io//docs/tools/pack/#install[the installation guide on buildpacks.io].
|
||||
|
||||
Assuming an AOT processed Spring Boot executable jar built as `myproject-0.0.1-SNAPSHOT.jar` is in the `target` directory, run:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ pack build --builder paketobuildpacks/builder-jammy-tiny \
|
||||
--path target/myproject-0.0.1-SNAPSHOT.jar \
|
||||
--env 'BP_NATIVE_IMAGE=true' \
|
||||
my-application:0.0.1-SNAPSHOT
|
||||
----
|
||||
|
||||
NOTE: You do not need to have a local GraalVM installation to generate an image in this way.
|
||||
|
||||
Once `pack` has finished, you can launch the application using `docker run`:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ docker run --rm -p 8080:8080 docker.io/library/myproject:0.0.1-SNAPSHOT
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[native-image.advanced.converting-executable-jars.native-image]]
|
||||
=== Using GraalVM native-image
|
||||
|
||||
Another option to turn an AOT processed Spring Boot executable jar into a native executable is to use the GraalVM `native-image` tool.
|
||||
For this to work, you'll need a GraalVM distribution on your machine.
|
||||
You can either download it manually on the {url-download-liberica-nik}[Liberica Native Image Kit page] or you can use a download manager like SDKMAN!.
|
||||
|
||||
Assuming an AOT processed Spring Boot executable jar built as `myproject-0.0.1-SNAPSHOT.jar` is in the `target` directory, run:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ rm -rf target/native
|
||||
$ mkdir -p target/native
|
||||
$ cd target/native
|
||||
$ jar -xvf ../myproject-0.0.1-SNAPSHOT.jar
|
||||
$ native-image -H:Name=myproject @META-INF/native-image/argfile -cp .:BOOT-INF/classes:`find BOOT-INF/lib | tr '\n' ':'`
|
||||
$ mv myproject ../
|
||||
----
|
||||
|
||||
NOTE: These commands work on Linux or macOS machines, but you will need to adapt them for Windows.
|
||||
|
||||
TIP: The `@META-INF/native-image/argfile` might not be packaged in your jar.
|
||||
It is only included when reachability metadata overrides are needed.
|
||||
|
||||
WARNING: The `native-image` `-cp` flag does not accept wildcards.
|
||||
You need to ensure that all jars are listed (the command above uses `find` and `tr` to do this).
|
||||
|
||||
|
||||
|
||||
[[native-image.advanced.using-the-tracing-agent]]
|
||||
== Using the Tracing Agent
|
||||
|
||||
The GraalVM native image {url-graal-docs-native-image}/metadata/AutomaticMetadataCollection[tracing agent] allows you to intercept reflection, resources or proxy usage on the JVM in order to generate the related hints.
|
||||
Spring should generate most of these hints automatically, but the tracing agent can be used to quickly identify the missing entries.
|
||||
|
||||
When using the agent to generate hints for a native image, there are a couple of approaches:
|
||||
|
||||
* Launch the application directly and exercise it.
|
||||
* Run application tests to exercise the application.
|
||||
|
||||
The first option is interesting for identifying the missing hints when a library or a pattern is not recognized by Spring.
|
||||
|
||||
The second option sounds more appealing for a repeatable setup, but by default the generated hints will include anything required by the test infrastructure.
|
||||
Some of these will be unnecessary when the application runs for real.
|
||||
To address this problem the agent supports an access-filter file that will cause certain data to be excluded from the generated output.
|
||||
|
||||
|
||||
|
||||
[[native-image.advanced.using-the-tracing-agent.launch]]
|
||||
=== Launch the Application Directly
|
||||
|
||||
Use the following command to launch the application with the native image tracing agent attached:
|
||||
|
||||
[source,shell,subs="verbatim,attributes"]
|
||||
----
|
||||
$ java -Dspring.aot.enabled=true \
|
||||
-agentlib:native-image-agent=config-output-dir=/path/to/config-dir/ \
|
||||
-jar target/myproject-0.0.1-SNAPSHOT.jar
|
||||
----
|
||||
|
||||
Now you can exercise the code paths you want to have hints for and then stop the application with `ctrl-c`.
|
||||
|
||||
On application shutdown the native image tracing agent will write the hint files to the given config output directory.
|
||||
You can either manually inspect these files, or use them as input to the native image build process.
|
||||
To use them as input, copy them into the `src/main/resources/META-INF/native-image/` directory.
|
||||
The next time you build the native image, GraalVM will take these files into consideration.
|
||||
|
||||
There are more advanced options which can be set on the native image tracing agent, for example filtering the recorded hints by caller classes, etc.
|
||||
For further reading, please see {url-graal-docs-native-image}/metadata/AutomaticMetadataCollection[the official documentation].
|
||||
|
||||
|
||||
|
||||
[[native-image.advanced.custom-hints]]
|
||||
== Custom Hints
|
||||
|
||||
If you need to provide your own hints for reflection, resources, serialization, proxy usage etc. you can use the `RuntimeHintsRegistrar` API.
|
||||
Create a class that implements the `RuntimeHintsRegistrar` interface, and then make appropriate calls to the provided `RuntimeHints` instance:
|
||||
|
||||
include-code::MyRuntimeHints[]
|
||||
|
||||
You can then use `@ImportRuntimeHints` on any `@Configuration` class (for example your `@SpringBootApplication` annotated application class) to activate those hints.
|
||||
|
||||
If you have classes which need binding (mostly needed when serializing or deserializing JSON), you can use {url-spring-framework-docs}/core/aot.html#aot.hints.register-reflection-for-binding[`@RegisterReflectionForBinding`] on any bean.
|
||||
Most of the hints are automatically inferred, for example when accepting or returning data from a `@RestController` method.
|
||||
But when you work with `WebClient`, `RestClient` or `RestTemplate` directly, you might need to use `@RegisterReflectionForBinding`.
|
||||
|
||||
|
||||
|
||||
[[native-image.advanced.custom-hints.testing]]
|
||||
=== Testing custom hints
|
||||
|
||||
The `RuntimeHintsPredicates` API can be used to test your hints.
|
||||
The API provides methods that build a `Predicate` that can be used to test a `RuntimeHints` instance.
|
||||
|
||||
If you're using AssertJ, your test would look like this:
|
||||
|
||||
include-code::MyRuntimeHintsTests[]
|
||||
|
||||
|
||||
|
||||
[[native-image.advanced.known-limitations]]
|
||||
== Known Limitations
|
||||
|
||||
GraalVM native images are an evolving technology and not all libraries provide support.
|
||||
The GraalVM community is helping by providing https://github.com/oracle/graalvm-reachability-metadata[reachability metadata] for projects that don't yet ship their own.
|
||||
Spring itself doesn't contain hints for 3rd party libraries and instead relies on the reachability metadata project.
|
||||
|
||||
If you encounter problems when generating native images for Spring Boot applications, please check the {url-github-wiki}/Spring-Boot-with-GraalVM[Spring Boot with GraalVM] page of the Spring Boot wiki.
|
||||
You can also contribute issues to the https://github.com/spring-projects/spring-aot-smoke-tests[spring-aot-smoke-tests] project on GitHub which is used to confirm that common application types are working as expected.
|
||||
|
||||
If you find a library which doesn't work with GraalVM, please raise an issue on the https://github.com/oracle/graalvm-reachability-metadata[reachability metadata project].
|
||||
@@ -0,0 +1,281 @@
|
||||
[[native-image.developing-your-first-application]]
|
||||
= Developing Your First GraalVM Native Application
|
||||
|
||||
Now that we have a good overview of GraalVM Native Images and how the Spring ahead-of-time engine works, we can look at how to create an application.
|
||||
|
||||
There are two main ways to build a Spring Boot native image application:
|
||||
|
||||
* Using Spring Boot support for Cloud Native Buildpacks to generate a lightweight container containing a native executable.
|
||||
* Using GraalVM Native Build Tools to generate a native executable.
|
||||
|
||||
TIP: The easiest way to start a new native Spring Boot project is to go to https://start.spring.io[start.spring.io], add the "`GraalVM Native Support`" dependency and generate the project.
|
||||
The included `HELP.md` file will provide getting started hints.
|
||||
|
||||
|
||||
|
||||
[[native-image.developing-your-first-application.sample-application]]
|
||||
== Sample Application
|
||||
|
||||
We need an example application that we can use to create our native image.
|
||||
For our purposes, the simple "`Hello World!`" web application that's covered in the "`xref:tutorial:first-application/index.adoc[Developing Your First Spring Boot Application]`" section will suffice.
|
||||
|
||||
To recap, our main application code looks like this:
|
||||
|
||||
include-code::MyApplication[]
|
||||
|
||||
This application uses Spring MVC and embedded Tomcat, both of which have been tested and verified to work with GraalVM native images.
|
||||
|
||||
|
||||
|
||||
[[native-image.developing-your-first-application.buildpacks]]
|
||||
== Building a Native Image Using Buildpacks
|
||||
|
||||
Spring Boot includes buildpack support for native images directly for both Maven and Gradle.
|
||||
This means you can just type a single command and quickly get a sensible image into your locally running Docker daemon.
|
||||
The resulting image doesn't contain a JVM, instead the native image is compiled statically.
|
||||
This leads to smaller images.
|
||||
|
||||
NOTE: The builder used for the images is `paketobuildpacks/builder-jammy-tiny:latest`.
|
||||
It has small footprint and reduced attack surface, but you can also use `paketobuildpacks/builder-jammy-base:latest` or `paketobuildpacks/builder-jammy-full:latest` to have more tools available in the image if required.
|
||||
|
||||
|
||||
|
||||
[[native-image.developing-your-first-application.buildpacks.system-requirements]]
|
||||
=== System Requirements
|
||||
|
||||
Docker should be installed. See https://docs.docker.com/installation/#installation[Get Docker] for more details.
|
||||
https://docs.docker.com/engine/install/linux-postinstall/#manage-docker-as-a-non-root-user[Configure it to allow non-root user] if you are on Linux.
|
||||
|
||||
NOTE: You can run `docker run hello-world` (without `sudo`) to check the Docker daemon is reachable as expected.
|
||||
Check the xref:maven-plugin:build-image.adoc#build-image.docker-daemon[Maven] or xref:gradle-plugin:packaging-oci-image.adoc#build-image.docker-daemon[Gradle] Spring Boot plugin documentation for more details.
|
||||
|
||||
TIP: On macOS, it is recommended to increase the memory allocated to Docker to at least `8GB`, and potentially add more CPUs as well.
|
||||
See this https://stackoverflow.com/questions/44533319/how-to-assign-more-memory-to-docker-container/44533437#44533437[Stack Overflow answer] for more details.
|
||||
On Microsoft Windows, make sure to enable the https://docs.docker.com/docker-for-windows/wsl/[Docker WSL 2 backend] for better performance.
|
||||
|
||||
|
||||
|
||||
[[native-image.developing-your-first-application.buildpacks.maven]]
|
||||
=== Using Maven
|
||||
|
||||
To build a native image container using Maven you should ensure that your `pom.xml` file uses the `spring-boot-starter-parent` and the `org.graalvm.buildtools:native-maven-plugin`.
|
||||
You should have a `<parent>` section that looks like this:
|
||||
|
||||
[source,xml,subs="verbatim,attributes"]
|
||||
----
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>{version-spring-boot}</version>
|
||||
</parent>
|
||||
----
|
||||
|
||||
You additionally should have this in the `<build> <plugins>` section:
|
||||
|
||||
[source,xml,subs="verbatim,attributes"]
|
||||
----
|
||||
<plugin>
|
||||
<groupId>org.graalvm.buildtools</groupId>
|
||||
<artifactId>native-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
----
|
||||
|
||||
The `spring-boot-starter-parent` declares a `native` profile that configures the executions that need to run in order to create a native image.
|
||||
You can activate profiles using the `-P` flag on the command line.
|
||||
|
||||
TIP: If you don't want to use `spring-boot-starter-parent` you'll need to configure executions for the `process-aot` goal from Spring Boot's plugin and the `add-reachability-metadata` goal from the Native Build Tools plugin.
|
||||
|
||||
To build the image, you can run the `spring-boot:build-image` goal with the `native` profile active:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ mvn -Pnative spring-boot:build-image
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[native-image.developing-your-first-application.buildpacks.gradle]]
|
||||
=== Using Gradle
|
||||
|
||||
The Spring Boot Gradle plugin automatically configures AOT tasks when the GraalVM Native Image plugin is applied.
|
||||
You should check that your Gradle build contains a `plugins` block that includes `org.graalvm.buildtools.native`.
|
||||
|
||||
As long as the `org.graalvm.buildtools.native` plugin is applied, the `bootBuildImage` task will generate a native image rather than a JVM one.
|
||||
You can run the task using:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ gradle bootBuildImage
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[native-image.developing-your-first-application.buildpacks.running]]
|
||||
=== Running the example
|
||||
|
||||
Once you have run the appropriate build command, a Docker image should be available.
|
||||
You can start your application using `docker run`:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ docker run --rm -p 8080:8080 docker.io/library/myproject:0.0.1-SNAPSHOT
|
||||
----
|
||||
|
||||
You should see output similar to the following:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
. ____ _ __ _ _
|
||||
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
|
||||
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
|
||||
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
|
||||
' |____| .__|_| |_|_| |_\__, | / / / /
|
||||
=========|_|==============|___/=/_/_/_/
|
||||
:: Spring Boot :: (v{version-spring-boot})
|
||||
....... . . .
|
||||
....... . . . (log output here)
|
||||
....... . . .
|
||||
........ Started MyApplication in 0.08 seconds (process running for 0.095)
|
||||
----
|
||||
|
||||
NOTE: The startup time differs from machine to machine, but it should be much faster than a Spring Boot application running on a JVM.
|
||||
|
||||
If you open a web browser to `http://localhost:8080`, you should see the following output:
|
||||
|
||||
[source]
|
||||
----
|
||||
Hello World!
|
||||
----
|
||||
|
||||
To gracefully exit the application, press `ctrl-c`.
|
||||
|
||||
|
||||
|
||||
[[native-image.developing-your-first-application.native-build-tools]]
|
||||
== Building a Native Image using Native Build Tools
|
||||
|
||||
If you want to generate a native executable directly without using Docker, you can use GraalVM Native Build Tools.
|
||||
Native Build Tools are plugins shipped by GraalVM for both Maven and Gradle.
|
||||
You can use them to perform a variety of GraalVM tasks, including generating a native image.
|
||||
|
||||
|
||||
|
||||
[[native-image.developing-your-first-application.native-build-tools.prerequisites]]
|
||||
=== Prerequisites
|
||||
|
||||
To build a native image using the Native Build Tools, you'll need a GraalVM distribution on your machine.
|
||||
You can either download it manually on the {url-download-liberica-nik}[Liberica Native Image Kit page], or you can use a download manager like SDKMAN!.
|
||||
|
||||
|
||||
|
||||
[[native-image.developing-your-first-application.native-build-tools.prerequisites.linux-macos]]
|
||||
==== Linux and macOS
|
||||
|
||||
To install the native image compiler on macOS or Linux, we recommend using SDKMAN!.
|
||||
Get SDKMAN! from https://sdkman.io and install the Liberica GraalVM distribution by using the following commands:
|
||||
|
||||
[source,shell,subs="verbatim,attributes"]
|
||||
----
|
||||
$ sdk install java {version-graal}.r17-nik
|
||||
$ sdk use java {version-graal}.r17-nik
|
||||
----
|
||||
|
||||
Verify that the correct version has been configured by checking the output of `java -version`:
|
||||
|
||||
[source,shell,subs="verbatim,attributes"]
|
||||
----
|
||||
$ java -version
|
||||
openjdk version "17.0.5" 2022-10-18 LTS
|
||||
OpenJDK Runtime Environment GraalVM 22.3.0 (build 17.0.5+8-LTS)
|
||||
OpenJDK 64-Bit Server VM GraalVM 22.3.0 (build 17.0.5+8-LTS, mixed mode)
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[native-image.developing-your-first-application.native-build-tools.prerequisites.windows]]
|
||||
==== Windows
|
||||
|
||||
On Windows, follow https://medium.com/graalvm/using-graalvm-and-native-image-on-windows-10-9954dc071311[these instructions] to install either https://www.graalvm.org/downloads/[GraalVM] or {url-download-liberica-nik}[Liberica Native Image Kit] in version {version-graal}, the Visual Studio Build Tools and the Windows SDK.
|
||||
Due to the https://docs.microsoft.com/en-US/troubleshoot/windows-client/shell-experience/command-line-string-limitation[Windows related command-line maximum length], make sure to use x64 Native Tools Command Prompt instead of the regular Windows command line to run Maven or Gradle plugins.
|
||||
|
||||
|
||||
|
||||
[[native-image.developing-your-first-application.native-build-tools.maven]]
|
||||
=== Using Maven
|
||||
|
||||
As with the xref:native-image/developing-your-first-application.adoc#native-image.developing-your-first-application.buildpacks.maven[buildpack support], you need to make sure that you're using `spring-boot-starter-parent` in order to inherit the `native` profile and that the `org.graalvm.buildtools:native-maven-plugin` plugin is used.
|
||||
|
||||
With the `native` profile active, you can invoke the `native:compile` goal to trigger `native-image` compilation:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ mvn -Pnative native:compile
|
||||
----
|
||||
|
||||
The native image executable can be found in the `target` directory.
|
||||
|
||||
|
||||
|
||||
[[native-image.developing-your-first-application.native-build-tools.gradle]]
|
||||
=== Using Gradle
|
||||
|
||||
When the Native Build Tools Gradle plugin is applied to your project, the Spring Boot Gradle plugin will automatically trigger the Spring AOT engine.
|
||||
Task dependencies are automatically configured, so you can just run the standard `nativeCompile` task to generate a native image:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ gradle nativeCompile
|
||||
----
|
||||
|
||||
The native image executable can be found in the `build/native/nativeCompile` directory.
|
||||
|
||||
|
||||
|
||||
[[native-image.developing-your-first-application.native-build-tools.running]]
|
||||
=== Running the Example
|
||||
|
||||
At this point, your application should work. You can now start the application by running it directly:
|
||||
|
||||
[tabs]
|
||||
======
|
||||
Maven::
|
||||
+
|
||||
[source,shell]
|
||||
----
|
||||
$ target/myproject
|
||||
----
|
||||
Gradle::
|
||||
+
|
||||
[source,shell]
|
||||
----
|
||||
$ build/native/nativeCompile/myproject
|
||||
----
|
||||
======
|
||||
|
||||
You should see output similar to the following:
|
||||
|
||||
[source,shell,subs="verbatim,attributes"]
|
||||
----
|
||||
. ____ _ __ _ _
|
||||
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
|
||||
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
|
||||
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
|
||||
' |____| .__|_| |_|_| |_\__, | / / / /
|
||||
=========|_|==============|___/=/_/_/_/
|
||||
:: Spring Boot :: (v{version-spring-boot})
|
||||
....... . . .
|
||||
....... . . . (log output here)
|
||||
....... . . .
|
||||
........ Started MyApplication in 0.08 seconds (process running for 0.095)
|
||||
----
|
||||
|
||||
NOTE: The startup time differs from machine to machine, but it should be much faster than a Spring Boot application running on a JVM.
|
||||
|
||||
If you open a web browser to `http://localhost:8080`, you should see the following output:
|
||||
|
||||
[source]
|
||||
----
|
||||
Hello World!
|
||||
----
|
||||
|
||||
To gracefully exit the application, press `ctrl-c`.
|
||||
@@ -0,0 +1,6 @@
|
||||
[[native-image]]
|
||||
= GraalVM Native Image Support
|
||||
|
||||
https://www.graalvm.org/native-image/[GraalVM Native Images] are standalone executables that can be generated by processing compiled Java applications ahead-of-time.
|
||||
Native Images generally have a smaller memory footprint and start faster than their JVM counterparts.
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
[[native-image.introducing-graalvm-native-images]]
|
||||
= Introducing GraalVM Native Images
|
||||
|
||||
GraalVM Native Images provide a new way to deploy and run Java applications.
|
||||
Compared to the Java Virtual Machine, native images can run with a smaller memory footprint and with much faster startup times.
|
||||
|
||||
They are well suited to applications that are deployed using container images and are especially interesting when combined with "Function as a service" (FaaS) platforms.
|
||||
|
||||
Unlike traditional applications written for the JVM, GraalVM Native Image applications require ahead-of-time processing in order to create an executable.
|
||||
This ahead-of-time processing involves statically analyzing your application code from its main entry point.
|
||||
|
||||
A GraalVM Native Image is a complete, platform-specific executable.
|
||||
You do not need to ship a Java Virtual Machine in order to run a native image.
|
||||
|
||||
TIP: If you just want to get started and experiment with GraalVM you can skip ahead to the "`xref:native-image/developing-your-first-application.adoc[Developing Your First GraalVM Native Application]`" section and return to this section later.
|
||||
|
||||
|
||||
|
||||
[[native-image.introducing-graalvm-native-images.key-differences-with-jvm-deployments]]
|
||||
== Key Differences with JVM Deployments
|
||||
|
||||
The fact that GraalVM Native Images are produced ahead-of-time means that there are some key differences between native and JVM based applications.
|
||||
The main differences are:
|
||||
|
||||
* Static analysis of your application is performed at build-time from the `main` entry point.
|
||||
* Code that cannot be reached when the native image is created will be removed and won't be part of the executable.
|
||||
* GraalVM is not directly aware of dynamic elements of your code and must be told about reflection, resources, serialization, and dynamic proxies.
|
||||
* The application classpath is fixed at build time and cannot change.
|
||||
* There is no lazy class loading, everything shipped in the executables will be loaded in memory on startup.
|
||||
* There are some limitations around some aspects of Java applications that are not fully supported.
|
||||
|
||||
On top of those differences, Spring uses a process called xref:native-image/introducing-graalvm-native-images.adoc#native-image.introducing-graalvm-native-images.understanding-aot-processing[Spring Ahead-of-Time processing], which imposes further limitations.
|
||||
Please make sure to read at least the beginning of the next section to learn about those.
|
||||
|
||||
TIP: The {url-graal-docs-native-image}/metadata/Compatibility/[Native Image Compatibility Guide] section of the GraalVM reference documentation provides more details about GraalVM limitations.
|
||||
|
||||
|
||||
|
||||
[[native-image.introducing-graalvm-native-images.understanding-aot-processing]]
|
||||
== Understanding Spring Ahead-of-Time Processing
|
||||
|
||||
Typical Spring Boot applications are quite dynamic and configuration is performed at runtime.
|
||||
In fact, the concept of Spring Boot auto-configuration depends heavily on reacting to the state of the runtime in order to configure things correctly.
|
||||
|
||||
Although it would be possible to tell GraalVM about these dynamic aspects of the application, doing so would undo most of the benefit of static analysis.
|
||||
So instead, when using Spring Boot to create native images, a closed-world is assumed and the dynamic aspects of the application are restricted.
|
||||
|
||||
A closed-world assumption implies, besides xref:native-image/introducing-graalvm-native-images.adoc#native-image.introducing-graalvm-native-images.key-differences-with-jvm-deployments[the limitations created by GraalVM itself], the following restrictions:
|
||||
|
||||
* The beans defined in your application cannot change at runtime, meaning:
|
||||
- The Spring `@Profile` annotation and profile-specific configuration xref:how-to:aot.adoc#howto.aot.conditions[have limitations].
|
||||
- Properties that change if a bean is created are not supported (for example, `@ConditionalOnProperty` and `.enable` properties).
|
||||
|
||||
When these restrictions are in place, it becomes possible for Spring to perform ahead-of-time processing during build-time and generate additional assets that GraalVM can use.
|
||||
A Spring AOT processed application will typically generate:
|
||||
|
||||
* Java source code
|
||||
* Bytecode (for dynamic proxies etc)
|
||||
* GraalVM JSON hint files:
|
||||
- Resource hints (`resource-config.json`)
|
||||
- Reflection hints (`reflect-config.json`)
|
||||
- Serialization hints (`serialization-config.json`)
|
||||
- Java Proxy Hints (`proxy-config.json`)
|
||||
- JNI Hints (`jni-config.json`)
|
||||
|
||||
|
||||
|
||||
[[native-image.introducing-graalvm-native-images.understanding-aot-processing.source-code-generation]]
|
||||
=== Source Code Generation
|
||||
|
||||
Spring applications are composed of Spring Beans.
|
||||
Internally, Spring Framework uses two distinct concepts to manage beans.
|
||||
There are bean instances, which are the actual instances that have been created and can be injected into other beans.
|
||||
There are also bean definitions which are used to define attributes of a bean and how its instance should be created.
|
||||
|
||||
If we take a typical `@Configuration` class:
|
||||
|
||||
include-code::MyConfiguration[]
|
||||
|
||||
The bean definition is created by parsing the `@Configuration` class and finding the `@Bean` methods.
|
||||
In the above example, we're defining a `BeanDefinition` for a singleton bean named `myBean`.
|
||||
We're also creating a `BeanDefinition` for the `MyConfiguration` class itself.
|
||||
|
||||
When the `myBean` instance is required, Spring knows that it must invoke the `myBean()` method and use the result.
|
||||
When running on the JVM, `@Configuration` class parsing happens when your application starts and `@Bean` methods are invoked using reflection.
|
||||
|
||||
When creating a native image, Spring operates in a different way.
|
||||
Rather than parsing `@Configuration` classes and generating bean definitions at runtime, it does it at build-time.
|
||||
Once the bean definitions have been discovered, they are processed and converted into source code that can be analyzed by the GraalVM compiler.
|
||||
|
||||
The Spring AOT process would convert the configuration class above to code like this:
|
||||
|
||||
include-code::MyConfiguration__BeanDefinitions[]
|
||||
|
||||
NOTE: The exact code generated may differ depending on the nature of your bean definitions.
|
||||
|
||||
You can see above that the generated code creates equivalent bean definitions to the `@Configuration` class, but in a direct way that can be understood by GraalVM.
|
||||
|
||||
There is a bean definition for the `myConfiguration` bean, and one for `myBean`.
|
||||
When a `myBean` instance is required, a `BeanInstanceSupplier` is called.
|
||||
This supplier will invoke the `myBean()` method on the `myConfiguration` bean.
|
||||
|
||||
NOTE: During Spring AOT processing your application is started up to the point that bean definitions are available.
|
||||
Bean instances are not created during the AOT processing phase.
|
||||
|
||||
Spring AOT will generate code like this for all your bean definitions.
|
||||
It will also generate code when bean post-processing is required (for example, to call `@Autowired` methods).
|
||||
An `ApplicationContextInitializer` will also be generated which will be used by Spring Boot to initialize the `ApplicationContext` when an AOT processed application is actually run.
|
||||
|
||||
TIP: Although AOT generated source code can be verbose, it is quite readable and can be helpful when debugging an application.
|
||||
Generated source files can be found in `target/spring-aot/main/sources` when using Maven and `build/generated/aotSources` with Gradle.
|
||||
|
||||
|
||||
|
||||
[[native-image.introducing-graalvm-native-images.understanding-aot-processing.hint-file-generation]]
|
||||
=== Hint File Generation
|
||||
|
||||
In addition to generating source files, the Spring AOT engine will also generate hint files that are used by GraalVM.
|
||||
Hint files contain JSON data that describes how GraalVM should deal with things that it can't understand by directly inspecting the code.
|
||||
|
||||
For example, you might be using a Spring annotation on a private method.
|
||||
Spring will need to use reflection in order to invoke private methods, even on GraalVM.
|
||||
When such situations arise, Spring can write a reflection hint so that GraalVM knows that even though the private method isn't called directly, it still needs to be available in the native image.
|
||||
|
||||
Hint files are generated under `META-INF/native-image` where they are automatically picked up by GraalVM.
|
||||
|
||||
TIP: Generated hint files can be found in `target/spring-aot/main/resources` when using Maven and `build/generated/aotResources` with Gradle.
|
||||
|
||||
|
||||
|
||||
[[native-image.introducing-graalvm-native-images.understanding-aot-processing.proxy-class-generation]]
|
||||
=== Proxy Class Generation
|
||||
|
||||
Spring sometimes needs to generate proxy classes to enhance the code you've written with additional features.
|
||||
To do this, it uses the cglib library which directly generates bytecode.
|
||||
|
||||
When an application is running on the JVM, proxy classes are generated dynamically as the application runs.
|
||||
When creating a native image, these proxies need to be created at build-time so that they can be included by GraalVM.
|
||||
|
||||
NOTE: Unlike source code generation, generated bytecode isn't particularly helpful when debugging an application.
|
||||
However, if you need to inspect the contents of the `.class` files using a tool such as `javap` you can find them in `target/spring-aot/main/classes` for Maven and `build/generated/aotClasses` for Gradle.
|
||||
@@ -0,0 +1,114 @@
|
||||
[[native-image.testing]]
|
||||
= Testing GraalVM Native Images
|
||||
|
||||
When writing native image applications, we recommend that you continue to use the JVM whenever possible to develop the majority of your unit and integration tests.
|
||||
This will help keep developer build times down and allow you to use existing IDE integrations.
|
||||
With broad test coverage on the JVM, you can then focus native image testing on the areas that are likely to be different.
|
||||
|
||||
For native image testing, you're generally looking to ensure that the following aspects work:
|
||||
|
||||
* The Spring AOT engine is able to process your application, and it will run in an AOT-processed mode.
|
||||
* GraalVM has enough hints to ensure that a valid native image can be produced.
|
||||
|
||||
|
||||
|
||||
|
||||
[[native-image.testing.with-the-jvm]]
|
||||
== Testing Ahead-of-time Processing With the JVM
|
||||
|
||||
When a Spring Boot application runs, it attempts to detect if it is running as a native image.
|
||||
If it is running as a native image, it will initialize the application using the code that was generated during at build-time by the Spring AOT engine.
|
||||
|
||||
If the application is running on a regular JVM, then any AOT generated code is ignored.
|
||||
|
||||
Since the `native-image` compilation phase can take a while to complete, it's sometimes useful to run your application on the JVM but have it use the AOT generated initialization code.
|
||||
Doing so helps you to quickly validate that there are no errors in the AOT generated code and nothing is missing when your application is eventually converted to a native image.
|
||||
|
||||
To run a Spring Boot application on the JVM and have it use AOT generated code you can set the `spring.aot.enabled` system property to `true`.
|
||||
|
||||
For example:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ java -Dspring.aot.enabled=true -jar myapplication.jar
|
||||
----
|
||||
|
||||
NOTE: You need to ensure that the jar you are testing includes AOT generated code.
|
||||
For Maven, this means that you should build with `-Pnative` to activate the `native` profile.
|
||||
For Gradle, you need to ensure that your build includes the `org.graalvm.buildtools.native` plugin.
|
||||
|
||||
If your application starts with the `spring.aot.enabled` property set to `true`, then you have higher confidence that it will work when converted to a native image.
|
||||
|
||||
You can also consider running integration tests against the running application.
|
||||
For example, you could use the Spring `WebClient` to call your application REST endpoints.
|
||||
Or you might consider using a project like Selenium to check your application's HTML responses.
|
||||
|
||||
|
||||
|
||||
[[native-image.testing.with-native-build-tools]]
|
||||
== Testing With Native Build Tools
|
||||
|
||||
GraalVM Native Build Tools includes the ability to run tests inside a native image.
|
||||
This can be helpful when you want to deeply test that the internals of your application work in a GraalVM native image.
|
||||
|
||||
Generating the native image that contains the tests to run can be a time-consuming operation, so most developers will probably prefer to use the JVM locally.
|
||||
They can, however, be very useful as part of a CI pipeline.
|
||||
For example, you might choose to run native tests once a day.
|
||||
|
||||
Spring Framework includes ahead-of-time support for running tests.
|
||||
All the usual Spring testing features work with native image tests.
|
||||
For example, you can continue to use the `@SpringBootTest` annotation.
|
||||
You can also use Spring Boot xref:features/testing.adoc#features.testing.spring-boot-applications.autoconfigured-tests[test slices] to test only specific parts of your application.
|
||||
|
||||
Spring Framework's native testing support works in the following way:
|
||||
|
||||
* Tests are analyzed in order to discover any `ApplicationContext` instances that will be required.
|
||||
* Ahead-of-time processing is applied to each of these application contexts and assets are generated.
|
||||
* A native image is created, with the generated assets being processed by GraalVM.
|
||||
* The native image also includes the JUnit `TestEngine` configured with a list of the discovered tests.
|
||||
* The native image is started, triggering the engine which will run each test and report results.
|
||||
|
||||
|
||||
|
||||
[[native-image.testing.with-native-build-tools.maven]]
|
||||
=== Using Maven
|
||||
|
||||
To run native tests using Maven, ensure that your `pom.xml` file uses the `spring-boot-starter-parent`.
|
||||
You should have a `<parent>` section that looks like this:
|
||||
|
||||
[source,xml,subs="verbatim,attributes"]
|
||||
----
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>{version-spring-boot}</version>
|
||||
</parent>
|
||||
----
|
||||
|
||||
The `spring-boot-starter-parent` declares a `nativeTest` profile that configures the executions that are needed to run the native tests.
|
||||
You can activate profiles using the `-P` flag on the command line.
|
||||
|
||||
TIP: If you don't want to use `spring-boot-starter-parent` you'll need to configure executions for the `process-test-aot` goal from the Spring Boot plugin and the `test` goal from the Native Build Tools plugin.
|
||||
|
||||
To build the image and run the tests, use the `test` goal with the `nativeTest` profile active:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ mvn -PnativeTest test
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[native-image.testing.with-native-build-tools.gradle]]
|
||||
=== Using Gradle
|
||||
|
||||
The Spring Boot Gradle plugin automatically configures AOT test tasks when the GraalVM Native Image plugin is applied.
|
||||
You should check that your Gradle build contains a `plugins` block that includes `org.graalvm.buildtools.native`.
|
||||
|
||||
To run native tests using Gradle you can use the `nativeTest` task:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ gradle nativeTest
|
||||
----
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
[[using.auto-configuration]]
|
||||
= Auto-configuration
|
||||
|
||||
Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added.
|
||||
For example, if `HSQLDB` is on your classpath, and you have not manually configured any database connection beans, then Spring Boot auto-configures an in-memory database.
|
||||
|
||||
You need to opt-in to auto-configuration by adding the `@EnableAutoConfiguration` or `@SpringBootApplication` annotations to one of your `@Configuration` classes.
|
||||
|
||||
TIP: You should only ever add one `@SpringBootApplication` or `@EnableAutoConfiguration` annotation.
|
||||
We generally recommend that you add one or the other to your primary `@Configuration` class only.
|
||||
|
||||
|
||||
|
||||
[[using.auto-configuration.replacing]]
|
||||
== Gradually Replacing Auto-configuration
|
||||
|
||||
Auto-configuration is non-invasive.
|
||||
At any point, you can start to define your own configuration to replace specific parts of the auto-configuration.
|
||||
For example, if you add your own `DataSource` bean, the default embedded database support backs away.
|
||||
|
||||
If you need to find out what auto-configuration is currently being applied, and why, start your application with the `--debug` switch.
|
||||
Doing so enables debug logs for a selection of core loggers and logs a conditions report to the console.
|
||||
|
||||
|
||||
|
||||
[[using.auto-configuration.disabling-specific]]
|
||||
== 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:
|
||||
|
||||
include-code::MyApplication[]
|
||||
|
||||
If the class is not on the classpath, you can use the `excludeName` attribute of the annotation and specify the fully qualified name instead.
|
||||
If you prefer to use `@EnableAutoConfiguration` rather than `@SpringBootApplication`, `exclude` and `excludeName` are also available.
|
||||
Finally, you can also control the list of auto-configuration classes to exclude by using the configprop:spring.autoconfigure.exclude[] property.
|
||||
|
||||
TIP: You can define exclusions both at the annotation level and by using the property.
|
||||
|
||||
NOTE: 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.auto-configuration.packages]]
|
||||
== Auto-configuration Packages
|
||||
|
||||
Auto-configuration packages are the packages that various auto-configured features look in by default when scanning for things such as entities and Spring Data repositories.
|
||||
The `@EnableAutoConfiguration` annotation (either directly or through its presence on `@SpringBootApplication`) determines the default auto-configuration package.
|
||||
Additional packages can be configured using the `@AutoConfigurationPackage` annotation.
|
||||
@@ -0,0 +1,151 @@
|
||||
[[using.build-systems]]
|
||||
= Build Systems
|
||||
|
||||
It is strongly recommended that you choose a build system that supports xref:using/build-systems.adoc#using.build-systems.dependency-management[_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]]
|
||||
== Dependency Management
|
||||
|
||||
Each release of Spring Boot provides a curated list of dependencies that it supports.
|
||||
In practice, you do not need to provide a version for any of these dependencies in your build configuration, as Spring Boot manages that for you.
|
||||
When you upgrade Spring Boot itself, these dependencies are upgraded as well in a consistent way.
|
||||
|
||||
NOTE: You can still specify a version and override Spring Boot's recommendations if you need to do so.
|
||||
|
||||
The curated list contains all the Spring modules that you can use with Spring Boot as well as a refined list of third party libraries.
|
||||
The list is available as a standard Bills of Materials (`spring-boot-dependencies`) that can be used with both xref:using/build-systems.adoc#using.build-systems.maven[Maven] and xref:using/build-systems.adoc#using.build-systems.gradle[Gradle].
|
||||
|
||||
WARNING: Each release of Spring Boot is associated with a base version of the Spring Framework.
|
||||
We **highly** recommend that you do not specify its version.
|
||||
|
||||
|
||||
|
||||
[[using.build-systems.maven]]
|
||||
== Maven
|
||||
|
||||
To learn about using Spring Boot with Maven, see the documentation for Spring Boot's Maven plugin:
|
||||
|
||||
* xref:maven-plugin:index.adoc[Reference]
|
||||
* xref:maven-plugin:api/java/index.html[API]
|
||||
|
||||
|
||||
|
||||
[[using.build-systems.gradle]]
|
||||
== Gradle
|
||||
|
||||
To learn about using Spring Boot with Gradle, see the documentation for Spring Boot's Gradle plugin:
|
||||
|
||||
* xref:gradle-plugin:index.adoc[Reference]
|
||||
* xref:gradle-plugin:api/java/index.html[API]
|
||||
|
||||
|
||||
|
||||
[[using.build-systems.ant]]
|
||||
== Ant
|
||||
|
||||
It is possible to build a Spring Boot project using Apache Ant+Ivy.
|
||||
The `spring-boot-antlib` "`AntLib`" module is also available to help Ant create executable jars.
|
||||
|
||||
To declare dependencies, a typical `ivy.xml` file looks something like the following example:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<ivy-module version="2.0">
|
||||
<info organisation="org.springframework.boot" module="spring-boot-sample-ant" />
|
||||
<configurations>
|
||||
<conf name="compile" description="everything needed to compile this module" />
|
||||
<conf name="runtime" extends="compile" description="everything needed to run this module" />
|
||||
</configurations>
|
||||
<dependencies>
|
||||
<dependency org="org.springframework.boot" name="spring-boot-starter"
|
||||
rev="${spring-boot.version}" conf="compile" />
|
||||
</dependencies>
|
||||
</ivy-module>
|
||||
----
|
||||
|
||||
A typical `build.xml` looks like the following example:
|
||||
|
||||
[source,xml,subs="verbatim,attributes"]
|
||||
----
|
||||
<project
|
||||
xmlns:ivy="antlib:org.apache.ivy.ant"
|
||||
xmlns:spring-boot="antlib:org.springframework.boot.ant"
|
||||
name="myapp" default="build">
|
||||
|
||||
<property name="spring-boot.version" value="{version-spring-boot}" />
|
||||
|
||||
<target name="resolve" description="--> retrieve dependencies with ivy">
|
||||
<ivy:retrieve pattern="lib/[conf]/[artifact]-[type]-[revision].[ext]" />
|
||||
</target>
|
||||
|
||||
<target name="classpaths" depends="resolve">
|
||||
<path id="compile.classpath">
|
||||
<fileset dir="lib/compile" includes="*.jar" />
|
||||
</path>
|
||||
</target>
|
||||
|
||||
<target name="init" depends="classpaths">
|
||||
<mkdir dir="build/classes" />
|
||||
</target>
|
||||
|
||||
<target name="compile" depends="init" description="compile">
|
||||
<javac srcdir="src/main/java" destdir="build/classes" classpathref="compile.classpath" />
|
||||
</target>
|
||||
|
||||
<target name="build" depends="compile">
|
||||
<spring-boot:exejar destfile="build/myapp.jar" classes="build/classes">
|
||||
<spring-boot:lib>
|
||||
<fileset dir="lib/runtime" />
|
||||
</spring-boot:lib>
|
||||
</spring-boot:exejar>
|
||||
</target>
|
||||
</project>
|
||||
----
|
||||
|
||||
TIP: If you do not want to use the `spring-boot-antlib` module, see the _xref:how-to:build.adoc#howto.build.build-an-executable-archive-with-ant-without-using-spring-boot-antlib[Build an Executable Archive From Ant without Using spring-boot-antlib]_ "`How-to`" .
|
||||
|
||||
|
||||
|
||||
[[using.build-systems.starters]]
|
||||
== Starters
|
||||
|
||||
Starters are a set of convenient dependency descriptors that you can include in your application.
|
||||
You get a one-stop shop for all the Spring and related technologies that you need without having to hunt through sample code and copy-paste loads of dependency descriptors.
|
||||
For example, if you want to get started using Spring and JPA for database access, include the `spring-boot-starter-data-jpa` dependency in your project.
|
||||
|
||||
The starters contain a lot of the dependencies that you need to get a project up and running quickly and with a consistent, supported set of managed transitive dependencies.
|
||||
|
||||
.What is in a name
|
||||
****
|
||||
All **official** starters follow a similar naming pattern; `+spring-boot-starter-*+`, where `+*+` is a particular type of application.
|
||||
This naming structure is intended to help when you need to find a starter.
|
||||
The Maven integration in many IDEs lets you search dependencies by name.
|
||||
For example, with the appropriate Eclipse or Spring Tools plugin installed, you can press `ctrl-space` in the POM editor and type "`spring-boot-starter`" for a complete list.
|
||||
|
||||
As explained in the "`xref:features/developing-auto-configuration.adoc#features.developing-auto-configuration.custom-starter[Creating Your Own Starter]`" section, third party starters should not start with `spring-boot`, as it is reserved for official Spring Boot artifacts.
|
||||
Rather, a third-party starter typically starts with the name of the project.
|
||||
For example, a third-party starter project called `thirdpartyproject` would typically be named `thirdpartyproject-spring-boot-starter`.
|
||||
****
|
||||
|
||||
The following application starters are provided by Spring Boot under the `org.springframework.boot` group:
|
||||
|
||||
.Spring Boot application starters
|
||||
include::ROOT:partial$starters/application-starters.adoc[]
|
||||
|
||||
In addition to the application starters, the following starters can be used to add _xref:how-to:actuator.adoc[production ready]_ features:
|
||||
|
||||
.Spring Boot production starters
|
||||
include::ROOT:partial$starters/production-starters.adoc[]
|
||||
|
||||
Finally, Spring Boot also includes the following starters that can be used if you want to exclude or swap specific technical facets:
|
||||
|
||||
.Spring Boot technical starters
|
||||
include::ROOT:partial$starters/technical-starters.adoc[]
|
||||
|
||||
To learn how to swap technical facets, please see the how-to documentation for xref:how-to:webserver.adoc#howto.webserver.use-another[swapping web server] and xref:how-to:logging.adoc#howto.logging.log4j[logging system].
|
||||
|
||||
TIP: For a list of additional community contributed starters, see the {code-spring-boot-latest}/spring-boot-project/spring-boot-starters/README.adoc[README file] in the `spring-boot-starters` module on GitHub.
|
||||
@@ -0,0 +1,27 @@
|
||||
[[using.configuration-classes]]
|
||||
= Configuration Classes
|
||||
|
||||
Spring Boot favors Java-based configuration.
|
||||
Although it is possible to use `SpringApplication` with XML sources, we generally recommend that your primary source be a single `@Configuration` class.
|
||||
Usually the class that defines the `main` method is a good candidate as the primary `@Configuration`.
|
||||
|
||||
TIP: Many Spring configuration examples have been published on the Internet that use XML configuration.
|
||||
If possible, always try to use the equivalent Java-based configuration.
|
||||
Searching for `+Enable*+` annotations can be a good starting point.
|
||||
|
||||
|
||||
|
||||
[[using.configuration-classes.importing-additional-configuration]]
|
||||
== Importing Additional Configuration Classes
|
||||
|
||||
You need not put all your `@Configuration` into a single class.
|
||||
The `@Import` annotation can be used to import additional configuration classes.
|
||||
Alternatively, you can use `@ComponentScan` to automatically pick up all Spring components, including `@Configuration` classes.
|
||||
|
||||
|
||||
|
||||
[[using.configuration-classes.importing-xml-configuration]]
|
||||
== Importing XML Configuration
|
||||
|
||||
If you absolutely must use XML based configuration, we recommend that you still start with a `@Configuration` class.
|
||||
You can then use an `@ImportResource` annotation to load XML configuration files.
|
||||
@@ -0,0 +1,440 @@
|
||||
[[using.devtools]]
|
||||
= Developer Tools
|
||||
|
||||
Spring Boot includes an additional set of tools that can make the application development experience a little more pleasant.
|
||||
The `spring-boot-devtools` module can be included in any project to provide additional development-time features.
|
||||
To include devtools support, add the module dependency to your build, as shown in the following listings for Maven and Gradle:
|
||||
|
||||
.Maven
|
||||
[source,xml]
|
||||
----
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-devtools</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
----
|
||||
|
||||
.Gradle
|
||||
[source,gradle]
|
||||
----
|
||||
dependencies {
|
||||
developmentOnly("org.springframework.boot:spring-boot-devtools")
|
||||
}
|
||||
----
|
||||
|
||||
CAUTION: Devtools might cause classloading issues, in particular in multi-module projects.
|
||||
xref:using/devtools.adoc#using.devtools.diagnosing-classloading-issues[Diagnosing Classloading Issues] explains how to diagnose and solve them.
|
||||
|
||||
NOTE: Developer tools are automatically disabled when running a fully packaged application.
|
||||
If your application is launched from `java -jar` or if it is started from a special classloader, then it is considered a "`production application`".
|
||||
You can control this behavior by using the `spring.devtools.restart.enabled` system property.
|
||||
To enable devtools, irrespective of the classloader used to launch your application, set the `-Dspring.devtools.restart.enabled=true` system property.
|
||||
This must not be done in a production environment where running devtools is a security risk.
|
||||
To disable devtools, exclude the dependency or set the `-Dspring.devtools.restart.enabled=false` system property.
|
||||
|
||||
TIP: Flagging the dependency as optional in Maven or using the `developmentOnly` configuration in Gradle (as shown above) prevents devtools from being transitively applied to other modules that use your project.
|
||||
|
||||
TIP: Repackaged archives do not contain devtools by default.
|
||||
If you want to use a xref:using/devtools.adoc#using.devtools.remote-applications[certain remote devtools feature], you need to include it.
|
||||
When using the Maven plugin, set the `excludeDevtools` property to `false`.
|
||||
When using the Gradle plugin, xref:gradle-plugin:packaging.adoc#packaging-executable.configuring.including-development-only-dependencies[configure the task's classpath to include the `developmentOnly` configuration].
|
||||
|
||||
|
||||
|
||||
[[using.devtools.diagnosing-classloading-issues]]
|
||||
== Diagnosing Classloading Issues
|
||||
|
||||
As described in the xref:#using.devtools.restart.restart-vs-reload[] section, restart functionality is implemented by using two classloaders.
|
||||
For most applications, this approach works well.
|
||||
However, it can sometimes cause classloading issues, in particular in multi-module projects.
|
||||
|
||||
To diagnose whether the classloading issues are indeed caused by devtools and its two classloaders, xref:using/devtools.adoc#using.devtools.restart.disable[try disabling restart].
|
||||
If this solves your problems, xref:using/devtools.adoc#using.devtools.restart.customizing-the-classload[customize the restart classloader] to include your entire project.
|
||||
|
||||
|
||||
|
||||
[[using.devtools.property-defaults]]
|
||||
== Property Defaults
|
||||
|
||||
Several of the libraries supported by Spring Boot use caches to improve performance.
|
||||
For example, xref:web/servlet.adoc#web.servlet.spring-mvc.template-engines[template engines] cache compiled templates to avoid repeatedly parsing template files.
|
||||
Also, Spring MVC can add HTTP caching headers to responses when serving static resources.
|
||||
|
||||
While caching is very beneficial in production, it can be counter-productive during development, preventing you from seeing the changes you just made in your application.
|
||||
For this reason, spring-boot-devtools disables the caching options by default.
|
||||
|
||||
Cache options are usually configured by settings in your `application.properties` file.
|
||||
For example, Thymeleaf offers the configprop:spring.thymeleaf.cache[] property.
|
||||
Rather than needing to set these properties manually, the `spring-boot-devtools` module automatically applies sensible development-time configuration.
|
||||
|
||||
The following table lists all the properties that are applied:
|
||||
|
||||
include::ROOT:partial$propertydefaults/devtools-property-defaults.adoc[]
|
||||
|
||||
NOTE: If you do not want property defaults to be applied you can set configprop:spring.devtools.add-properties[] to `false` in your `application.properties`.
|
||||
|
||||
Because you need more information about web requests while developing Spring MVC and Spring WebFlux applications, developer tools suggests you to enable `DEBUG` logging for the `web` logging group.
|
||||
This will give you information about the incoming request, which handler is processing it, the response outcome, and other details.
|
||||
If you wish to log all request details (including potentially sensitive information), you can turn on the configprop:spring.mvc.log-request-details[] or configprop:spring.codec.log-request-details[] configuration properties.
|
||||
|
||||
|
||||
|
||||
[[using.devtools.restart]]
|
||||
== Automatic Restart
|
||||
|
||||
Applications that use `spring-boot-devtools` automatically restart whenever files on the classpath change.
|
||||
This can be a useful feature when working in an IDE, as it gives a very fast feedback loop for code changes.
|
||||
By default, any entry on the classpath that points to a directory is monitored for changes.
|
||||
Note that certain resources, such as static assets and view templates, xref:using/devtools.adoc#using.devtools.restart.excluding-resources[do not need to restart the application].
|
||||
|
||||
.Triggering a restart
|
||||
****
|
||||
As DevTools monitors classpath resources, the only way to trigger a restart is to update the classpath.
|
||||
Whether you're using an IDE or one of the build plugins, the modified files have to be recompiled to trigger a restart.
|
||||
The way in which you cause the classpath to be updated depends on the tool that you are using:
|
||||
|
||||
* In Eclipse, saving a modified file causes the classpath to be updated and triggers a restart.
|
||||
* In IntelliJ IDEA, building the project (`Build +->+ Build Project`) has the same effect.
|
||||
* If using a build plugin, running `mvn compile` for Maven or `gradle build` for Gradle will trigger a restart.
|
||||
****
|
||||
|
||||
NOTE: If you are restarting with Maven or Gradle using the build plugin you must leave the `forking` set to `enabled`.
|
||||
If you disable forking, the isolated application classloader used by devtools will not be created and restarts will not operate properly.
|
||||
|
||||
TIP: Automatic restart works very well when used with LiveReload.
|
||||
xref:using/devtools.adoc#using.devtools.livereload[See the LiveReload section] for details.
|
||||
If you use JRebel, automatic restarts are disabled in favor of dynamic class reloading.
|
||||
Other devtools features (such as LiveReload and property overrides) can still be used.
|
||||
|
||||
NOTE: DevTools relies on the application context's shutdown hook to close it during a restart.
|
||||
It does not work correctly if you have disabled the shutdown hook (`SpringApplication.setRegisterShutdownHook(false)`).
|
||||
|
||||
NOTE: DevTools needs to customize the `ResourceLoader` used by the `ApplicationContext`.
|
||||
If your application provides one already, it is going to be wrapped.
|
||||
Direct override of the `getResource` method on the `ApplicationContext` is not supported.
|
||||
|
||||
CAUTION: Automatic restart is not supported when using AspectJ weaving.
|
||||
|
||||
[[using.devtools.restart.restart-vs-reload]]
|
||||
.Restart vs Reload
|
||||
****
|
||||
The restart technology provided by Spring Boot works by using two classloaders.
|
||||
Classes that do not change (for example, those from third-party jars) are loaded into a _base_ classloader.
|
||||
Classes that you are actively developing are loaded into a _restart_ classloader.
|
||||
When the application is restarted, the _restart_ classloader is thrown away and a new one is created.
|
||||
This approach means that application restarts are typically much faster than "`cold starts`", since the _base_ classloader is already available and populated.
|
||||
|
||||
If you find that restarts are not quick enough for your applications or you encounter classloading issues, you could consider reloading technologies such as https://jrebel.com/software/jrebel/[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]]
|
||||
=== Logging Changes in Condition Evaluation
|
||||
|
||||
By default, each time your application restarts, a report showing the condition evaluation delta is logged.
|
||||
The report shows the changes to your application's auto-configuration as you make changes such as adding or removing beans and setting configuration properties.
|
||||
|
||||
To disable the logging of the report, set the following property:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
devtools:
|
||||
restart:
|
||||
log-condition-evaluation-delta: false
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[using.devtools.restart.excluding-resources]]
|
||||
=== Excluding Resources
|
||||
|
||||
Certain resources do not necessarily need to trigger a restart when they are changed.
|
||||
For example, Thymeleaf templates can be edited in-place.
|
||||
By default, changing resources in `/META-INF/maven`, `/META-INF/resources`, `/resources`, `/static`, `/public`, or `/templates` does not trigger a restart but does trigger a xref:using/devtools.adoc#using.devtools.livereload[live reload].
|
||||
If you want to customize these exclusions, you can use the configprop:spring.devtools.restart.exclude[] property.
|
||||
For example, to exclude only `/static` and `/public` you would set the following property:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
devtools:
|
||||
restart:
|
||||
exclude: "static/**,public/**"
|
||||
----
|
||||
|
||||
TIP: If you want to keep those defaults and _add_ additional exclusions, use the configprop:spring.devtools.restart.additional-exclude[] property instead.
|
||||
|
||||
|
||||
|
||||
[[using.devtools.restart.watching-additional-paths]]
|
||||
=== Watching Additional Paths
|
||||
|
||||
You may want your application to be restarted or reloaded when you make changes to files that are not on the classpath.
|
||||
To do so, use the configprop:spring.devtools.restart.additional-paths[] property to configure additional paths to watch for changes.
|
||||
You can use the configprop:spring.devtools.restart.exclude[] property xref:using/devtools.adoc#using.devtools.restart.excluding-resources[described earlier] to control whether changes beneath the additional paths trigger a full restart or a xref:using/devtools.adoc#using.devtools.livereload[live reload].
|
||||
|
||||
|
||||
|
||||
[[using.devtools.restart.disable]]
|
||||
=== Disabling Restart
|
||||
|
||||
If you do not want to use the restart feature, you can disable it by using the configprop:spring.devtools.restart.enabled[] property.
|
||||
In most cases, you can set this property in your `application.properties` (doing so still initializes the restart classloader, but it does not watch for file changes).
|
||||
|
||||
If you need to _completely_ disable restart support (for example, because it does not work with a specific library), you need to set the configprop:spring.devtools.restart.enabled[] `System` property to `false` before calling `SpringApplication.run(...)`, as shown in the following example:
|
||||
|
||||
include-code::MyApplication[]
|
||||
|
||||
|
||||
|
||||
[[using.devtools.restart.triggerfile]]
|
||||
=== Using a Trigger File
|
||||
|
||||
If you work with an IDE that continuously compiles changed files, you might prefer to trigger restarts only at specific times.
|
||||
To do so, you can use a "`trigger file`", which is a special file that must be modified when you want to actually trigger a restart check.
|
||||
|
||||
NOTE: Any update to the file will trigger a check, but restart only actually occurs if Devtools has detected it has something to do.
|
||||
|
||||
To use a trigger file, set the configprop:spring.devtools.restart.trigger-file[] property to the name (excluding any path) of your trigger file.
|
||||
The trigger file must appear somewhere on your classpath.
|
||||
|
||||
For example, if you have a project with the following structure:
|
||||
|
||||
[source]
|
||||
----
|
||||
src
|
||||
+- main
|
||||
+- resources
|
||||
+- .reloadtrigger
|
||||
----
|
||||
|
||||
Then your `trigger-file` property would be:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
devtools:
|
||||
restart:
|
||||
trigger-file: ".reloadtrigger"
|
||||
----
|
||||
|
||||
Restarts will now only happen when the `src/main/resources/.reloadtrigger` is updated.
|
||||
|
||||
TIP: You might want to set `spring.devtools.restart.trigger-file` as a xref:using/devtools.adoc#using.devtools.globalsettings[global setting], so that all your projects behave in the same way.
|
||||
|
||||
Some IDEs have features that save you from needing to update your trigger file manually.
|
||||
https://spring.io/tools[Spring Tools for Eclipse] and https://www.jetbrains.com/idea/[IntelliJ IDEA (Ultimate Edition)] both have such support.
|
||||
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 https://www.jetbrains.com/help/idea/spring-boot.html#application-update-policies[instructions in their documentation].
|
||||
|
||||
|
||||
|
||||
[[using.devtools.restart.customizing-the-classload]]
|
||||
=== Customizing the Restart Classloader
|
||||
|
||||
As described earlier in the xref:#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.
|
||||
|
||||
By default, any open project in your IDE is loaded with the "`restart`" classloader, and any regular `.jar` file is loaded with the "`base`" classloader.
|
||||
The same is true if you use `mvn spring-boot:run` or `gradle bootRun`: the project containing your `@SpringBootApplication` is loaded with the "`restart`" classloader, and everything else with the "`base`" classloader.
|
||||
|
||||
You can instruct Spring Boot to load parts of your project with a different classloader by creating a `META-INF/spring-devtools.properties` file.
|
||||
The `spring-devtools.properties` file can contain properties prefixed with `restart.exclude` and `restart.include`.
|
||||
The `include` elements are items that should be pulled up into the "`restart`" classloader, and the `exclude` elements are items that should be pushed down into the "`base`" classloader.
|
||||
The value of the property is a regex pattern that is applied to the classpath, as shown in the following example:
|
||||
|
||||
[source,properties]
|
||||
----
|
||||
restart:
|
||||
exclude:
|
||||
companycommonlibs: "/mycorp-common-[\\w\\d-\\.]+\\.jar"
|
||||
include:
|
||||
projectcommon: "/mycorp-myproj-[\\w\\d-\\.]+\\.jar"
|
||||
----
|
||||
|
||||
NOTE: All property keys must be unique.
|
||||
As long as a property starts with `restart.include.` or `restart.exclude.` it is considered.
|
||||
|
||||
TIP: All `META-INF/spring-devtools.properties` from the classpath are loaded.
|
||||
You can package files inside your project, or in the libraries that the project consumes.
|
||||
|
||||
|
||||
|
||||
[[using.devtools.restart.limitations]]
|
||||
=== Known Limitations
|
||||
|
||||
Restart functionality does not work well with objects that are deserialized by using a standard `ObjectInputStream`.
|
||||
If you need to deserialize data, you may need to use Spring's `ConfigurableObjectInputStream` in combination with `Thread.currentThread().getContextClassLoader()`.
|
||||
|
||||
Unfortunately, several third-party libraries deserialize without considering the context classloader.
|
||||
If you find such a problem, you need to request a fix with the original authors.
|
||||
|
||||
|
||||
|
||||
[[using.devtools.livereload]]
|
||||
== LiveReload
|
||||
|
||||
The `spring-boot-devtools` module includes an embedded LiveReload server that can be used to trigger a browser refresh when a resource is changed.
|
||||
LiveReload browser extensions are freely available for Chrome, Firefox and Safari.
|
||||
You can find these extensions by searching 'LiveReload' in the marketplace or store of your chosen browser.
|
||||
|
||||
If you do not want to start the LiveReload server when your application runs, you can set the configprop:spring.devtools.livereload.enabled[] property to `false`.
|
||||
|
||||
NOTE: You can only run one LiveReload server at a time.
|
||||
Before starting your application, ensure that no other LiveReload servers are running.
|
||||
If you start multiple applications from your IDE, only the first has LiveReload support.
|
||||
|
||||
WARNING: To trigger LiveReload when a file changes, xref:using/devtools.adoc#using.devtools.restart[Automatic Restart] must be enabled.
|
||||
|
||||
|
||||
|
||||
[[using.devtools.globalsettings]]
|
||||
== Global Settings
|
||||
|
||||
You can configure global devtools settings by adding any of the following files to the `$HOME/.config/spring-boot` directory:
|
||||
|
||||
. `spring-boot-devtools.properties`
|
||||
. `spring-boot-devtools.yaml`
|
||||
. `spring-boot-devtools.yml`
|
||||
|
||||
Any properties added to these files apply to _all_ Spring Boot applications on your machine that use devtools.
|
||||
For example, to configure restart to always use a xref:using/devtools.adoc#using.devtools.restart.triggerfile[trigger file], you would add the following property to your `spring-boot-devtools` file:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
devtools:
|
||||
restart:
|
||||
trigger-file: ".reloadtrigger"
|
||||
----
|
||||
|
||||
By default, `$HOME` is the user's home directory.
|
||||
To customize this location, set the `SPRING_DEVTOOLS_HOME` environment variable or the `spring.devtools.home` system property.
|
||||
|
||||
NOTE: If devtools configuration files are not found in `$HOME/.config/spring-boot`, the root of the `$HOME` directory is searched for the presence of a `.spring-boot-devtools.properties` file.
|
||||
This allows you to share the devtools global configuration with applications that are on an older version of Spring Boot that does not support the `$HOME/.config/spring-boot` location.
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
Profiles are not supported in devtools properties/yaml files.
|
||||
|
||||
Any profiles activated in `.spring-boot-devtools.properties` will not affect the loading of xref:features/external-config.adoc#features.external-config.files.profile-specific[profile-specific configuration files].
|
||||
Profile specific filenames (of the form `spring-boot-devtools-<profile>.properties`) and `spring.config.activate.on-profile` documents in both YAML and Properties files are not supported.
|
||||
====
|
||||
|
||||
|
||||
|
||||
[[using.devtools.globalsettings.configuring-file-system-watcher]]
|
||||
=== Configuring File System Watcher
|
||||
|
||||
{code-spring-boot-devtools-src}/filewatch/FileSystemWatcher.java[FileSystemWatcher] 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.
|
||||
If you observe such problems constantly, try increasing the `spring.devtools.restart.poll-interval` and `spring.devtools.restart.quiet-period` parameters to the values that fit your development environment:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
devtools:
|
||||
restart:
|
||||
poll-interval: "2s"
|
||||
quiet-period: "1s"
|
||||
----
|
||||
|
||||
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]]
|
||||
== Remote Applications
|
||||
|
||||
The Spring Boot developer tools are not limited to local development.
|
||||
You can also use several features when running applications remotely.
|
||||
Remote support is opt-in as enabling it can be a security risk.
|
||||
It should only be enabled when running on a trusted network or when secured with SSL.
|
||||
If neither of these options is available to you, you should not use DevTools' remote support.
|
||||
You should never enable support on a production deployment.
|
||||
|
||||
To enable it, you need to make sure that `devtools` is included in the repackaged archive, as shown in the following listing:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludeDevtools>false</excludeDevtools>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
----
|
||||
|
||||
Then you need to set the configprop:spring.devtools.remote.secret[] property.
|
||||
Like any important password or secret, the value should be unique and strong such that it cannot be guessed or brute-forced.
|
||||
|
||||
Remote devtools support is provided in two parts: a server-side endpoint that accepts connections and a client application that you run in your IDE.
|
||||
The server component is automatically enabled when the configprop:spring.devtools.remote.secret[] property is set.
|
||||
The client component must be launched manually.
|
||||
|
||||
NOTE: Remote devtools is not supported for Spring WebFlux applications.
|
||||
|
||||
|
||||
|
||||
[[using.devtools.remote-applications.client]]
|
||||
=== Running the Remote Client Application
|
||||
|
||||
The remote client application is designed to be run from within your IDE.
|
||||
You need to run `org.springframework.boot.devtools.RemoteSpringApplication` with the same classpath as the remote project that you connect to.
|
||||
The application's single required argument is the remote URL to which it connects.
|
||||
|
||||
For example, if you are using Eclipse or Spring Tools and you have a project named `my-app` that you have deployed to Cloud Foundry, you would do the following:
|
||||
|
||||
* Select `Run Configurations...` from the `Run` menu.
|
||||
* Create a new `Java Application` "`launch configuration`".
|
||||
* Browse for the `my-app` project.
|
||||
* Use `org.springframework.boot.devtools.RemoteSpringApplication` as the main class.
|
||||
* Add `+++https://myapp.cfapps.io+++` to the `Program arguments` (or whatever your remote URL is).
|
||||
|
||||
A running remote client might resemble the following listing:
|
||||
|
||||
[source,subs="verbatim,attributes"]
|
||||
----
|
||||
include::ROOT:example$remote-spring-application.txt[]
|
||||
----
|
||||
|
||||
NOTE: Because the remote client is using the same classpath as the real application it can directly read application properties.
|
||||
This is how the configprop:spring.devtools.remote.secret[] property is read and passed to the server for authentication.
|
||||
|
||||
TIP: It is always advisable to use `https://` as the connection protocol, so that traffic is encrypted and passwords cannot be intercepted.
|
||||
|
||||
TIP: If you need to use a proxy to access the remote application, configure the `spring.devtools.remote.proxy.host` and `spring.devtools.remote.proxy.port` properties.
|
||||
|
||||
|
||||
|
||||
[[using.devtools.remote-applications.update]]
|
||||
=== Remote Update
|
||||
|
||||
The remote client monitors your application classpath for changes in the same way as the xref:using/devtools.adoc#using.devtools.restart[local restart].
|
||||
Any updated resource is pushed to the remote application and (_if required_) triggers a restart.
|
||||
This can be helpful if you iterate on a feature that uses a cloud service that you do not have locally.
|
||||
Generally, remote updates and restarts are much quicker than a full rebuild and deploy cycle.
|
||||
|
||||
On a slower development environment, it may happen that the quiet period is not enough, and the changes in the classes may be split into batches.
|
||||
The server is restarted after the first batch of class changes is uploaded.
|
||||
The next batch can’t be sent to the application, since the server is restarting.
|
||||
|
||||
This is typically manifested by a warning in the `RemoteSpringApplication` logs about failing to upload some of the classes, and a consequent retry.
|
||||
But it may also lead to application code inconsistency and failure to restart after the first batch of changes is uploaded.
|
||||
If you observe such problems constantly, try increasing the `spring.devtools.restart.poll-interval` and `spring.devtools.restart.quiet-period` parameters to the values that fit your development environment.
|
||||
See the xref:using/devtools.adoc#using.devtools.globalsettings.configuring-file-system-watcher[Configuring File System Watcher] section for configuring these properties.
|
||||
|
||||
NOTE: Files are only monitored when the remote client is running.
|
||||
If you change a file before starting the remote client, it is not pushed to the remote server.
|
||||
@@ -0,0 +1,10 @@
|
||||
[[using]]
|
||||
= 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.
|
||||
We also cover some Spring Boot best practices.
|
||||
Although there is nothing particularly special about Spring Boot (it is just another library that you can consume), there are a few recommendations that, when followed, make your development process a little easier.
|
||||
|
||||
If you are starting out with Spring Boot, you should probably read the xref:tutorial:first-application/index.adoc[_Developing your first Spring Boot application_] tutorial before diving into this section.
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
[[using.packaging-for-production]]
|
||||
= Packaging Your Application for Production
|
||||
|
||||
Executable jars can be used for production deployment.
|
||||
As they are self-contained, they are also ideally suited for cloud-based deployment.
|
||||
|
||||
For additional "`production ready`" features, such as health, auditing, and metric REST or JMX end-points, consider adding `spring-boot-actuator`.
|
||||
See _xref:how-to:actuator.adoc[Actuator]_ for details.
|
||||
@@ -0,0 +1,101 @@
|
||||
[[using.running-your-application]]
|
||||
= Running Your Application
|
||||
|
||||
One of the biggest advantages of packaging your application as a jar and using an embedded HTTP server is that you can run your application as you would any other.
|
||||
The sample applies to debugging Spring Boot applications.
|
||||
You do not need any special IDE plugins or extensions.
|
||||
|
||||
NOTE: This section only covers jar-based packaging.
|
||||
If you choose to package your application as a war file, see your server and IDE documentation.
|
||||
|
||||
|
||||
|
||||
[[using.running-your-application.from-an-ide]]
|
||||
== 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.
|
||||
Import steps vary depending on your IDE and build system.
|
||||
Most IDEs can import Maven projects directly.
|
||||
For example, Eclipse users can select `Import...` -> `Existing Maven Projects` from the `File` menu.
|
||||
|
||||
If you cannot directly import your project into your IDE, you may be able to generate IDE metadata by using a build plugin.
|
||||
Maven includes plugins for https://maven.apache.org/plugins/maven-eclipse-plugin/[Eclipse] and https://maven.apache.org/plugins/maven-idea-plugin/[IDEA].
|
||||
Gradle offers plugins for {url-gradle-docs}/userguide.html[various IDEs].
|
||||
|
||||
TIP: 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]]
|
||||
== 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:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ java -jar target/myapplication-0.0.1-SNAPSHOT.jar
|
||||
----
|
||||
|
||||
It is also possible to run a packaged application with remote debugging support enabled.
|
||||
Doing so lets you attach a debugger to your packaged application, as shown in the following example:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ java -agentlib:jdwp=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]]
|
||||
== Using the Maven Plugin
|
||||
|
||||
The Spring Boot Maven plugin includes a `run` goal that can be used to quickly compile and run your application.
|
||||
Applications run in an exploded form, as they do in your IDE.
|
||||
The following example shows a typical Maven command to run a Spring Boot application:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ mvn spring-boot:run
|
||||
----
|
||||
|
||||
You might also want to use the `MAVEN_OPTS` operating system environment variable, as shown in the following example:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ export MAVEN_OPTS=-Xmx1024m
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[using.running-your-application.with-the-gradle-plugin]]
|
||||
== Using the Gradle Plugin
|
||||
|
||||
The Spring Boot Gradle plugin also includes a `bootRun` task that can be used to run your application in an exploded form.
|
||||
The `bootRun` task is added whenever you apply the `org.springframework.boot` and `java` plugins and is shown in the following example:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ gradle bootRun
|
||||
----
|
||||
|
||||
You might also want to use the `JAVA_OPTS` operating system environment variable, as shown in the following example:
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
$ export JAVA_OPTS=-Xmx1024m
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[using.running-your-application.hot-swapping]]
|
||||
== 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.
|
||||
For a more complete solution, https://www.jrebel.com/products/jrebel[JRebel] can be used.
|
||||
|
||||
The `spring-boot-devtools` module also includes support for quick application restarts.
|
||||
See the xref:how-to:hotswapping.adoc[Hot swapping "`How-to`"] for details.
|
||||
@@ -0,0 +1,18 @@
|
||||
[[using.spring-beans-and-dependency-injection]]
|
||||
= Spring Beans and Dependency Injection
|
||||
|
||||
You are free to use any of the standard Spring Framework techniques to define your beans and their injected dependencies.
|
||||
We generally recommend using constructor injection to wire up dependencies and `@ComponentScan` to find beans.
|
||||
|
||||
If you structure your code as suggested above (locating your application class in a top package), you can add `@ComponentScan` without any arguments or use the `@SpringBootApplication` annotation which implicitly includes it.
|
||||
All of your application components (`@Component`, `@Service`, `@Repository`, `@Controller`, and others) are automatically registered as Spring Beans.
|
||||
|
||||
The following example shows a `@Service` Bean that uses constructor injection to obtain a required `RiskAssessor` bean:
|
||||
|
||||
include-code::singleconstructor/MyAccountService[]
|
||||
|
||||
If a bean has more than one constructor, you will need to mark the one you want Spring to use with `@Autowired`:
|
||||
|
||||
include-code::multipleconstructors/MyAccountService[]
|
||||
|
||||
TIP: Notice how using constructor injection lets the `riskAssessor` field be marked as `final`, indicating that it cannot be subsequently changed.
|
||||
@@ -0,0 +1,56 @@
|
||||
[[using.structuring-your-code]]
|
||||
= Structuring Your Code
|
||||
|
||||
Spring Boot does not require any specific code layout to work.
|
||||
However, there are some best practices that help.
|
||||
|
||||
TIP: If you wish to enforce a structure based on domains, take a look at https://spring.io/projects/spring-modulith#overview[Spring Modulith].
|
||||
|
||||
|
||||
|
||||
[[using.structuring-your-code.using-the-default-package]]
|
||||
== Using the "`default`" Package
|
||||
|
||||
When a class does not include a `package` declaration, it is considered to be in the "`default package`".
|
||||
The use of the "`default package`" is generally discouraged and should be avoided.
|
||||
It can cause particular problems for Spring Boot applications that use the `@ComponentScan`, `@ConfigurationPropertiesScan`, `@EntityScan`, or `@SpringBootApplication` annotations, since every class from every jar is read.
|
||||
|
||||
TIP: We recommend that you follow Java's recommended package naming conventions and use a reversed domain name (for example, `com.example.project`).
|
||||
|
||||
|
||||
|
||||
[[using.structuring-your-code.locating-the-main-class]]
|
||||
== Locating the Main Application Class
|
||||
|
||||
We generally recommend that you locate your main application class in a root package above other classes.
|
||||
The xref:using/using-the-springbootapplication-annotation.adoc[`@SpringBootApplication` annotation] is often placed on your main class, and it implicitly defines a base "`search package`" for certain items.
|
||||
For example, if you are writing a JPA application, the package of the `@SpringBootApplication` annotated class is used to search for `@Entity` items.
|
||||
Using a root package also allows component scan to apply only on your project.
|
||||
|
||||
TIP: If you do not want to use `@SpringBootApplication`, the `@EnableAutoConfiguration` and `@ComponentScan` annotations that it imports defines that behavior so you can also use those instead.
|
||||
|
||||
The following listing shows a typical layout:
|
||||
|
||||
[source]
|
||||
----
|
||||
com
|
||||
+- example
|
||||
+- myapplication
|
||||
+- MyApplication.java
|
||||
|
|
||||
+- customer
|
||||
| +- Customer.java
|
||||
| +- CustomerController.java
|
||||
| +- CustomerService.java
|
||||
| +- CustomerRepository.java
|
||||
|
|
||||
+- order
|
||||
+- Order.java
|
||||
+- OrderController.java
|
||||
+- OrderService.java
|
||||
+- OrderRepository.java
|
||||
----
|
||||
|
||||
The `MyApplication.java` file would declare the `main` method, along with the basic `@SpringBootApplication`, as follows:
|
||||
|
||||
include-code::MyApplication[]
|
||||
@@ -0,0 +1,24 @@
|
||||
[[using.using-the-springbootapplication-annotation]]
|
||||
= Using the @SpringBootApplication Annotation
|
||||
|
||||
Many Spring Boot developers like their apps to use auto-configuration, component scan and be able to define extra configuration on their "application class".
|
||||
A single `@SpringBootApplication` annotation can be used to enable those three features, that is:
|
||||
|
||||
* `@EnableAutoConfiguration`: enable xref:using/auto-configuration.adoc[Spring Boot's auto-configuration mechanism]
|
||||
* `@ComponentScan`: enable `@Component` scan on the package where the application is located (see xref:using/structuring-your-code.adoc[the best practices])
|
||||
* `@SpringBootConfiguration`: enable registration of extra beans in the context or the import of additional configuration classes.
|
||||
An alternative to Spring's standard `@Configuration` that aids xref:features/testing.adoc#features.testing.spring-boot-applications.detecting-configuration[configuration detection] in your integration tests.
|
||||
|
||||
include-code::springapplication/MyApplication[]
|
||||
|
||||
NOTE: `@SpringBootApplication` also provides aliases to customize the attributes of `@EnableAutoConfiguration` and `@ComponentScan`.
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
None of these features are mandatory and you may choose to replace this single annotation by any of the features that it enables.
|
||||
For instance, you may not want to use component scan or configuration properties scan in your application:
|
||||
|
||||
include-code::individualannotations/MyApplication[]
|
||||
|
||||
In this example, `MyApplication` is just like any other Spring Boot application except that `@Component`-annotated classes and `@ConfigurationProperties`-annotated classes are not detected automatically and the user-defined beans are imported explicitly (see `@Import`).
|
||||
====
|
||||
@@ -0,0 +1,31 @@
|
||||
[[web.graceful-shutdown]]
|
||||
= 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.
|
||||
This stop processing uses a timeout which provides a grace period during which existing requests will be allowed to complete but no new requests will be permitted.
|
||||
The exact way in which new requests are not permitted varies depending on the web server that is being used.
|
||||
Jetty, Reactor Netty, and Tomcat will stop accepting requests at the network layer.
|
||||
Undertow will accept requests but respond immediately with a service unavailable (503) response.
|
||||
|
||||
NOTE: Graceful shutdown with Tomcat requires Tomcat 9.0.33 or later.
|
||||
|
||||
To enable graceful shutdown, configure the configprop:server.shutdown[] property, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
server:
|
||||
shutdown: "graceful"
|
||||
----
|
||||
|
||||
To configure the timeout period, configure the configprop:spring.lifecycle.timeout-per-shutdown-phase[] property, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
lifecycle:
|
||||
timeout-per-shutdown-phase: "20s"
|
||||
----
|
||||
|
||||
IMPORTANT: 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.
|
||||
@@ -0,0 +1,9 @@
|
||||
[[web]]
|
||||
= 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.
|
||||
Most web applications use the `spring-boot-starter-web` module to get up and running quickly.
|
||||
You can also choose to build reactive web applications by using the `spring-boot-starter-webflux` module.
|
||||
|
||||
If you have not yet developed a Spring Boot web application, you can follow the "Hello World!" example in the _xref:tutorial:first-application/index.adoc[Getting started]_ section.
|
||||
@@ -0,0 +1,344 @@
|
||||
[[web.reactive]]
|
||||
= Reactive Web Applications
|
||||
|
||||
Spring Boot simplifies development of reactive web applications by providing auto-configuration for Spring Webflux.
|
||||
|
||||
|
||||
|
||||
[[web.reactive.webflux]]
|
||||
== The "`Spring WebFlux Framework`"
|
||||
|
||||
Spring WebFlux is the new reactive web framework introduced in Spring Framework 5.0.
|
||||
Unlike Spring MVC, it does not require the servlet API, is fully asynchronous and non-blocking, and implements the https://www.reactive-streams.org/[Reactive Streams] specification through https://projectreactor.io/[the Reactor project].
|
||||
|
||||
Spring WebFlux comes in two flavors: functional and annotation-based.
|
||||
The annotation-based one is quite close to the Spring MVC model, as shown in the following example:
|
||||
|
||||
include-code::MyRestController[]
|
||||
|
||||
WebFlux is part of the Spring Framework and detailed information is available in its {url-spring-framework-docs}/web/webflux.html[reference documentation].
|
||||
|
||||
"`WebFlux.fn`", the functional variant, separates the routing configuration from the actual handling of the requests, as shown in the following example:
|
||||
|
||||
include-code::MyRoutingConfiguration[]
|
||||
|
||||
include-code::MyUserHandler[]
|
||||
|
||||
"`WebFlux.fn`" is part of the Spring Framework and detailed information is available in its {url-spring-framework-docs}/web/webflux-functional.html[reference documentation].
|
||||
|
||||
TIP: You can define as many `RouterFunction` beans as you like to modularize the definition of the router.
|
||||
Beans can be ordered if you need to apply a precedence.
|
||||
|
||||
To get started, add the `spring-boot-starter-webflux` module to your application.
|
||||
|
||||
NOTE: Adding both `spring-boot-starter-web` and `spring-boot-starter-webflux` modules in your application results in Spring Boot auto-configuring Spring MVC, not WebFlux.
|
||||
This behavior has been chosen because many Spring developers add `spring-boot-starter-webflux` to their Spring MVC application to use the reactive `WebClient`.
|
||||
You can still enforce your choice by setting the chosen application type to `SpringApplication.setWebApplicationType(WebApplicationType.REACTIVE)`.
|
||||
|
||||
|
||||
|
||||
[[web.reactive.webflux.auto-configuration]]
|
||||
=== Spring WebFlux Auto-configuration
|
||||
|
||||
Spring Boot provides auto-configuration for Spring WebFlux that works well with most applications.
|
||||
|
||||
The auto-configuration adds the following features on top of Spring's defaults:
|
||||
|
||||
* Configuring codecs for `HttpMessageReader` and `HttpMessageWriter` instances (described xref:web/reactive.adoc#web.reactive.webflux.httpcodecs[later in this document]).
|
||||
* Support for serving static resources, including support for WebJars (described xref:web/servlet.adoc#web.servlet.spring-mvc.static-content[later in this document]).
|
||||
|
||||
If you want to keep Spring Boot WebFlux features and you want to add additional {url-spring-framework-docs}/web/webflux/config.html[WebFlux configuration], you can add your own `@Configuration` class of type `WebFluxConfigurer` but *without* `@EnableWebFlux`.
|
||||
|
||||
If you want to add additional customization to the auto-configured `HttpHandler`, you can define beans of type `WebHttpHandlerBuilderCustomizer` and use them to modify the `WebHttpHandlerBuilder`.
|
||||
|
||||
If you want to take complete control of Spring WebFlux, you can add your own `@Configuration` annotated with `@EnableWebFlux`.
|
||||
|
||||
|
||||
|
||||
[[web.reactive.webflux.conversion-service]]
|
||||
=== Spring WebFlux Conversion Service
|
||||
|
||||
If you want to customize the `ConversionService` used by Spring WebFlux, you can provide a `WebFluxConfigurer` bean with an `addFormatters` method.
|
||||
|
||||
Conversion can also be customized using the `spring.webflux.format.*` configuration properties.
|
||||
When not configured, the following defaults are used:
|
||||
|
||||
|===
|
||||
|Property |`DateTimeFormatter`
|
||||
|
||||
|configprop:spring.webflux.format.date[]
|
||||
|`ofLocalizedDate(FormatStyle.SHORT)`
|
||||
|
||||
|configprop:spring.webflux.format.time[]
|
||||
|`ofLocalizedTime(FormatStyle.SHORT)`
|
||||
|
||||
|configprop:spring.webflux.format.date-time[]
|
||||
|`ofLocalizedDateTime(FormatStyle.SHORT)`
|
||||
|===
|
||||
|
||||
|
||||
|
||||
[[web.reactive.webflux.httpcodecs]]
|
||||
=== HTTP Codecs with HttpMessageReaders and HttpMessageWriters
|
||||
|
||||
Spring WebFlux uses the `HttpMessageReader` and `HttpMessageWriter` interfaces to convert HTTP requests and responses.
|
||||
They are configured with `CodecConfigurer` to have sensible defaults by looking at the libraries available in your classpath.
|
||||
|
||||
Spring Boot provides dedicated configuration properties for codecs, `+spring.codec.*+`.
|
||||
It also applies further customization by using `CodecCustomizer` instances.
|
||||
For example, `+spring.jackson.*+` configuration keys are applied to the Jackson codec.
|
||||
|
||||
If you need to add or customize codecs, you can create a custom `CodecCustomizer` component, as shown in the following example:
|
||||
|
||||
include-code::MyCodecsConfiguration[]
|
||||
|
||||
You can also leverage xref:features/json.adoc#features.json.jackson.custom-serializers-and-deserializers[Boot's custom JSON serializers and deserializers].
|
||||
|
||||
|
||||
|
||||
[[web.reactive.webflux.static-content]]
|
||||
=== Static Content
|
||||
|
||||
By default, Spring Boot serves static content from a directory called `/static` (or `/public` or `/resources` or `/META-INF/resources`) in the classpath.
|
||||
It uses the `ResourceWebHandler` from Spring WebFlux so that you can modify that behavior by adding your own `WebFluxConfigurer` and overriding the `addResourceHandlers` method.
|
||||
|
||||
By default, resources are mapped on `+/**+`, but you can tune that by setting the configprop:spring.webflux.static-path-pattern[] property.
|
||||
For instance, relocating all resources to `/resources/**` can be achieved as follows:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
webflux:
|
||||
static-path-pattern: "/resources/**"
|
||||
----
|
||||
|
||||
You can also customize the static resource locations by using `spring.web.resources.static-locations`.
|
||||
Doing so replaces the default values with a list of directory locations.
|
||||
If you do so, the default welcome page detection switches to your custom locations.
|
||||
So, if there is an `index.html` in any of your locations on startup, it is the home page of the application.
|
||||
|
||||
In addition to the "`standard`" static resource locations listed earlier, a special case is made for https://www.webjars.org/[Webjars content].
|
||||
By default, any resources with a path in `+/webjars/**+` are served from jar files if they are packaged in the Webjars format.
|
||||
The path can be customized with the configprop:spring.webflux.webjars-path-pattern[] property.
|
||||
|
||||
TIP: Spring WebFlux applications do not strictly depend on the servlet API, so they cannot be deployed as war files and do not use the `src/main/webapp` directory.
|
||||
|
||||
|
||||
|
||||
[[web.reactive.webflux.welcome-page]]
|
||||
=== Welcome Page
|
||||
|
||||
Spring Boot supports both static and templated welcome pages.
|
||||
It first looks for an `index.html` file in the configured static content locations.
|
||||
If one is not found, it then looks for an `index` template.
|
||||
If either is found, it is automatically used as the welcome page of the application.
|
||||
|
||||
This only acts as a fallback for actual index routes defined by the application.
|
||||
The ordering is defined by the order of `HandlerMapping` beans which is by default the following:
|
||||
|
||||
[cols="1,1"]
|
||||
|===
|
||||
|`RouterFunctionMapping`
|
||||
|Endpoints declared with `RouterFunction` beans
|
||||
|
||||
|`RequestMappingHandlerMapping`
|
||||
|Endpoints declared in `@Controller` beans
|
||||
|
||||
|`RouterFunctionMapping` for the Welcome Page
|
||||
|The welcome page support
|
||||
|===
|
||||
|
||||
|
||||
|
||||
[[web.reactive.webflux.template-engines]]
|
||||
=== Template Engines
|
||||
|
||||
As well as REST web services, you can also use Spring WebFlux to serve dynamic HTML content.
|
||||
Spring WebFlux supports a variety of templating technologies, including Thymeleaf, FreeMarker, and Mustache.
|
||||
|
||||
Spring Boot includes auto-configuration support for the following templating engines:
|
||||
|
||||
* https://freemarker.apache.org/docs/[FreeMarker]
|
||||
* https://www.thymeleaf.org[Thymeleaf]
|
||||
* https://mustache.github.io/[Mustache]
|
||||
|
||||
When you use one of these templating engines with the default configuration, your templates are picked up automatically from `src/main/resources/templates`.
|
||||
|
||||
|
||||
|
||||
[[web.reactive.webflux.error-handling]]
|
||||
=== Error Handling
|
||||
|
||||
Spring Boot provides a `WebExceptionHandler` that handles all errors in a sensible way.
|
||||
Its position in the processing order is immediately before the handlers provided by WebFlux, which are considered last.
|
||||
For machine clients, it produces a JSON response with details of the error, the HTTP status, and the exception message.
|
||||
For browser clients, there is a "`whitelabel`" error handler that renders the same data in HTML format.
|
||||
You can also provide your own HTML templates to display errors (see the xref:web/reactive.adoc#web.reactive.webflux.error-handling.error-pages[next section]).
|
||||
|
||||
Before customizing error handling in Spring Boot directly, you can leverage the {url-spring-framework-docs}/web/webflux/ann-rest-exceptions.html[RFC 7807 Problem Details] support in Spring WebFlux.
|
||||
Spring WebFlux can produce custom error messages with the `application/problem+json` media type, like:
|
||||
|
||||
[source,json]
|
||||
----
|
||||
{
|
||||
"type": "https://example.org/problems/unknown-project",
|
||||
"title": "Unknown project",
|
||||
"status": 404,
|
||||
"detail": "No project found for id 'spring-unknown'",
|
||||
"instance": "/projects/spring-unknown"
|
||||
}
|
||||
----
|
||||
|
||||
This support can be enabled by setting configprop:spring.webflux.problemdetails.enabled[] to `true`.
|
||||
|
||||
|
||||
The first step to customizing this feature often involves using the existing mechanism but replacing or augmenting the error contents.
|
||||
For that, you can add a bean of type `ErrorAttributes`.
|
||||
|
||||
To change the error handling behavior, you can implement `ErrorWebExceptionHandler` and register a bean definition of that type.
|
||||
Because an `ErrorWebExceptionHandler` is quite low-level, Spring Boot also provides a convenient `AbstractErrorWebExceptionHandler` to let you handle errors in a WebFlux functional way, as shown in the following example:
|
||||
|
||||
include-code::MyErrorWebExceptionHandler[]
|
||||
|
||||
For a more complete picture, you can also subclass `DefaultErrorWebExceptionHandler` directly and override specific methods.
|
||||
|
||||
In some cases, errors handled at the controller level are not recorded by web observations or the xref:actuator/metrics.adoc#actuator.metrics.supported.spring-webflux[metrics infrastructure].
|
||||
Applications can ensure that such exceptions are recorded with the observations by {url-spring-framework-docs}/integration/observability.html#observability.http-server.reactive[setting the handled exception on the observation context].
|
||||
|
||||
|
||||
|
||||
[[web.reactive.webflux.error-handling.error-pages]]
|
||||
==== Custom Error Pages
|
||||
|
||||
If you want to display a custom HTML error page for a given status code, you can add views that resolve from `error/*`, for example by adding files to a `/error` directory.
|
||||
Error pages can either be static HTML (that is, added under any of the static resource directories) or built with templates.
|
||||
The name of the file should be the exact status code, a status code series mask, or `error` for a default if nothing else matches.
|
||||
Note that the path to the default error view is `error/error`, whereas with Spring MVC the default error view is `error`.
|
||||
|
||||
For example, to map `404` to a static HTML file, your directory structure would be as follows:
|
||||
|
||||
[source]
|
||||
----
|
||||
src/
|
||||
+- main/
|
||||
+- java/
|
||||
| + <source code>
|
||||
+- resources/
|
||||
+- public/
|
||||
+- error/
|
||||
| +- 404.html
|
||||
+- <other public assets>
|
||||
----
|
||||
|
||||
To map all `5xx` errors by using a Mustache template, your directory structure would be as follows:
|
||||
|
||||
[source]
|
||||
----
|
||||
src/
|
||||
+- main/
|
||||
+- java/
|
||||
| + <source code>
|
||||
+- resources/
|
||||
+- templates/
|
||||
+- error/
|
||||
| +- 5xx.mustache
|
||||
+- <other templates>
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[web.reactive.webflux.web-filters]]
|
||||
=== Web Filters
|
||||
|
||||
Spring WebFlux provides a `WebFilter` interface that can be implemented to filter HTTP request-response exchanges.
|
||||
`WebFilter` beans found in the application context will be automatically used to filter each exchange.
|
||||
|
||||
Where the order of the filters is important they can implement `Ordered` or be annotated with `@Order`.
|
||||
Spring Boot auto-configuration may configure web filters for you.
|
||||
When it does so, the orders shown in the following table will be used:
|
||||
|
||||
|===
|
||||
| Web Filter | Order
|
||||
|
||||
| `WebFilterChainProxy` (Spring Security)
|
||||
| `-100`
|
||||
|
||||
| `HttpExchangesWebFilter`
|
||||
| `Ordered.LOWEST_PRECEDENCE - 10`
|
||||
|===
|
||||
|
||||
|
||||
|
||||
[[web.reactive.reactive-server]]
|
||||
== Embedded Reactive Server Support
|
||||
|
||||
Spring Boot includes support for the following embedded reactive web servers: Reactor Netty, Tomcat, Jetty, and Undertow.
|
||||
Most developers use the appropriate “Starter” to obtain a fully configured instance.
|
||||
By default, the embedded server listens for HTTP requests on port 8080.
|
||||
|
||||
|
||||
|
||||
[[web.reactive.reactive-server.customizing]]
|
||||
=== Customizing Reactive Servers
|
||||
|
||||
Common reactive web server settings can be configured by using Spring `Environment` properties.
|
||||
Usually, you would define the properties in your `application.properties` or `application.yaml` file.
|
||||
|
||||
Common server settings include:
|
||||
|
||||
* Network settings: Listen port for incoming HTTP requests (`server.port`), interface address to bind to (`server.address`), and so on.
|
||||
* Error management: Location of the error page (`server.error.path`) and so on.
|
||||
* xref:how-to:webserver.adoc#howto.webserver.configure-ssl[SSL]
|
||||
* xref:how-to:webserver.adoc#howto.webserver.enable-response-compression[HTTP compression]
|
||||
|
||||
Spring Boot tries as much as possible to expose common settings, but this is not always possible.
|
||||
For those cases, dedicated namespaces such as `server.netty.*` offer server-specific customizations.
|
||||
|
||||
TIP: See the {code-spring-boot-autoconfigure-src}/web/ServerProperties.java[`ServerProperties`] class for a complete list.
|
||||
|
||||
|
||||
|
||||
[[web.reactive.reactive-server.customizing.programmatic]]
|
||||
==== Programmatic Customization
|
||||
|
||||
If you need to programmatically configure your reactive web server, you can register a Spring bean that implements the `WebServerFactoryCustomizer` interface.
|
||||
`WebServerFactoryCustomizer` provides access to the `ConfigurableReactiveWebServerFactory`, which includes numerous customization setter methods.
|
||||
The following example shows programmatically setting the port:
|
||||
|
||||
include-code::MyWebServerFactoryCustomizer[]
|
||||
|
||||
`JettyReactiveWebServerFactory`, `NettyReactiveWebServerFactory`, `TomcatReactiveWebServerFactory`, and `UndertowReactiveWebServerFactory` are dedicated variants of `ConfigurableReactiveWebServerFactory` that have additional customization setter methods for Jetty, Reactor Netty, Tomcat, and Undertow respectively.
|
||||
The following example shows how to customize `NettyReactiveWebServerFactory` that provides access to Reactor Netty-specific configuration options:
|
||||
|
||||
include-code::MyNettyWebServerFactoryCustomizer[]
|
||||
|
||||
|
||||
|
||||
[[web.reactive.reactive-server.customizing.direct]]
|
||||
==== Customizing ConfigurableReactiveWebServerFactory Directly
|
||||
|
||||
For more advanced use cases that require you to extend from `ReactiveWebServerFactory`, you can expose a bean of such type yourself.
|
||||
|
||||
Setters are provided for many configuration options.
|
||||
Several protected method "`hooks`" are also provided should you need to do something more exotic.
|
||||
See the xref:api:java/org/springframework/boot/web/reactive/server/ConfigurableReactiveWebServerFactory.html[source code documentation] for details.
|
||||
|
||||
NOTE: Auto-configured customizers are still applied on your custom factory, so use that option carefully.
|
||||
|
||||
|
||||
|
||||
[[web.reactive.reactive-server-resources-configuration]]
|
||||
== Reactive Server Resources Configuration
|
||||
|
||||
When auto-configuring a Reactor Netty or Jetty server, Spring Boot will create specific beans that will provide HTTP resources to the server instance: `ReactorResourceFactory` or `JettyResourceFactory`.
|
||||
|
||||
By default, those resources will be also shared with the Reactor Netty and Jetty clients for optimal performances, given:
|
||||
|
||||
* the same technology is used for server and client
|
||||
* the client instance is built using the `WebClient.Builder` bean auto-configured by Spring Boot
|
||||
|
||||
Developers can override the resource configuration for Jetty and Reactor Netty by providing a custom `ReactorResourceFactory` or `JettyResourceFactory` bean - this will be applied to both clients and servers.
|
||||
|
||||
You can learn more about the resource configuration on the client side in the xref:io/rest-client.adoc#io.rest-client.webclient.runtime[WebClient Runtime section].
|
||||
|
||||
|
||||
@@ -0,0 +1,702 @@
|
||||
[[web.servlet]]
|
||||
= 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]]
|
||||
== The "`Spring Web MVC Framework`"
|
||||
|
||||
The {url-spring-framework-docs}/web/webmvc.html[Spring Web MVC framework] (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.
|
||||
Methods in your controller are mapped to HTTP by using `@RequestMapping` annotations.
|
||||
|
||||
The following code shows a typical `@RestController` that serves JSON data:
|
||||
|
||||
include-code::MyRestController[]
|
||||
|
||||
"`WebMvc.fn`", the functional variant, separates the routing configuration from the actual handling of the requests, as shown in the following example:
|
||||
|
||||
include-code::MyRoutingConfiguration[]
|
||||
|
||||
include-code::MyUserHandler[]
|
||||
|
||||
Spring MVC is part of the core Spring Framework, and detailed information is available in the {url-spring-framework-docs}/web/webmvc.html[reference documentation].
|
||||
There are also several guides that cover Spring MVC available at https://spring.io/guides.
|
||||
|
||||
TIP: You can define as many `RouterFunction` beans as you like to modularize the definition of the router.
|
||||
Beans can be ordered if you need to apply a precedence.
|
||||
|
||||
|
||||
|
||||
[[web.servlet.spring-mvc.auto-configuration]]
|
||||
=== Spring MVC Auto-configuration
|
||||
|
||||
Spring Boot provides auto-configuration for Spring MVC that works well with most applications.
|
||||
It replaces the need for `@EnableWebMvc` and the two cannot be used together.
|
||||
In addition to Spring MVC's defaults, the auto-configuration provides the following features:
|
||||
|
||||
* Inclusion of `ContentNegotiatingViewResolver` and `BeanNameViewResolver` beans.
|
||||
* Support for serving static resources, including support for WebJars (covered xref:web/servlet.adoc#web.servlet.spring-mvc.static-content[later in this document]).
|
||||
* Automatic registration of `Converter`, `GenericConverter`, and `Formatter` beans.
|
||||
* Support for `HttpMessageConverters` (covered xref:web/servlet.adoc#web.servlet.spring-mvc.message-converters[later in this document]).
|
||||
* Automatic registration of `MessageCodesResolver` (covered xref:web/servlet.adoc#web.servlet.spring-mvc.message-codes[later in this document]).
|
||||
* Static `index.html` support.
|
||||
* Automatic use of a `ConfigurableWebBindingInitializer` bean (covered xref:web/servlet.adoc#web.servlet.spring-mvc.binding-initializer[later in this document]).
|
||||
|
||||
If you want to keep those Spring Boot MVC customizations and make more {url-spring-framework-docs}/web/webmvc.html[MVC customizations] (interceptors, formatters, view controllers, and other features), you can add your own `@Configuration` class of type `WebMvcConfigurer` but *without* `@EnableWebMvc`.
|
||||
|
||||
If you want to provide custom instances of `RequestMappingHandlerMapping`, `RequestMappingHandlerAdapter`, or `ExceptionHandlerExceptionResolver`, and still keep the Spring Boot MVC customizations, you can declare a bean of type `WebMvcRegistrations` and use it to provide custom instances of those components.
|
||||
The custom instances will be subject to further initialization and configuration by Spring MVC.
|
||||
To participate in, and if desired, override that subsequent processing, a `WebMvcConfigurer` should be used.
|
||||
|
||||
If you do not want to use the auto-configuration and want to take complete control of Spring MVC, add your own `@Configuration` annotated with `@EnableWebMvc`.
|
||||
Alternatively, add your own `@Configuration`-annotated `DelegatingWebMvcConfiguration` as described in the Javadoc of `@EnableWebMvc`.
|
||||
|
||||
|
||||
|
||||
[[web.servlet.spring-mvc.conversion-service]]
|
||||
=== Spring MVC Conversion Service
|
||||
|
||||
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`.
|
||||
|
||||
Conversion can also be customized using the `spring.mvc.format.*` configuration properties.
|
||||
When not configured, the following defaults are used:
|
||||
|
||||
|===
|
||||
|Property |`DateTimeFormatter`
|
||||
|
||||
|configprop:spring.mvc.format.date[]
|
||||
|`ofLocalizedDate(FormatStyle.SHORT)`
|
||||
|
||||
|configprop:spring.mvc.format.time[]
|
||||
|`ofLocalizedTime(FormatStyle.SHORT)`
|
||||
|
||||
|configprop:spring.mvc.format.date-time[]
|
||||
|`ofLocalizedDateTime(FormatStyle.SHORT)`
|
||||
|===
|
||||
|
||||
|
||||
|
||||
[[web.servlet.spring-mvc.message-converters]]
|
||||
=== HttpMessageConverters
|
||||
|
||||
Spring MVC uses the `HttpMessageConverter` interface to convert HTTP requests and responses.
|
||||
Sensible defaults are included out of the box.
|
||||
For example, objects can be automatically converted to JSON (by using the Jackson library) or XML (by using the Jackson XML extension, if available, or by using JAXB if the Jackson XML extension is not available).
|
||||
By default, strings are encoded in `UTF-8`.
|
||||
|
||||
If you need to add or customize converters, you can use Spring Boot's `HttpMessageConverters` class, as shown in the following listing:
|
||||
|
||||
include-code::MyHttpMessageConvertersConfiguration[]
|
||||
|
||||
Any `HttpMessageConverter` bean that is present in the context is added to the list of converters.
|
||||
You can also override default converters in the same way.
|
||||
|
||||
|
||||
|
||||
[[web.servlet.spring-mvc.message-codes]]
|
||||
=== MessageCodesResolver
|
||||
|
||||
Spring MVC has a strategy for generating error codes for rendering error messages from binding errors: `MessageCodesResolver`.
|
||||
If you set the configprop:spring.mvc.message-codes-resolver-format[] property `PREFIX_ERROR_CODE` or `POSTFIX_ERROR_CODE`, Spring Boot creates one for you (see the enumeration in {url-spring-framework-javadoc}/org/springframework/validation/DefaultMessageCodesResolver.Format.html[`DefaultMessageCodesResolver.Format`]).
|
||||
|
||||
|
||||
|
||||
[[web.servlet.spring-mvc.static-content]]
|
||||
=== Static Content
|
||||
|
||||
By default, Spring Boot serves static content from a directory called `/static` (or `/public` or `/resources` or `/META-INF/resources`) in the classpath or from the root of the `ServletContext`.
|
||||
It uses the `ResourceHttpRequestHandler` from Spring MVC so that you can modify that behavior by adding your own `WebMvcConfigurer` and overriding the `addResourceHandlers` method.
|
||||
|
||||
In a stand-alone web application, the default servlet from the container is not enabled.
|
||||
It can be enabled using the configprop:server.servlet.register-default-servlet[] property.
|
||||
|
||||
The default servlet acts as a fallback, serving content from the root of the `ServletContext` if Spring decides not to handle it.
|
||||
Most of the time, this does not happen (unless you modify the default MVC configuration), because Spring can always handle requests through the `DispatcherServlet`.
|
||||
|
||||
By default, resources are mapped on `+/**+`, but you can tune that with the configprop:spring.mvc.static-path-pattern[] property.
|
||||
For instance, relocating all resources to `/resources/**` can be achieved as follows:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
mvc:
|
||||
static-path-pattern: "/resources/**"
|
||||
----
|
||||
|
||||
You can also customize the static resource locations by using the configprop:spring.web.resources.static-locations[] property (replacing the default values with a list of directory locations).
|
||||
The root servlet context path, `"/"`, is automatically added as a location as well.
|
||||
|
||||
In addition to the "`standard`" static resource locations mentioned earlier, a special case is made for https://www.webjars.org/[Webjars content].
|
||||
By default, any resources with a path in `+/webjars/**+` are served from jar files if they are packaged in the Webjars format.
|
||||
The path can be customized with the configprop:spring.mvc.webjars-path-pattern[] property.
|
||||
|
||||
TIP: Do not use the `src/main/webapp` directory if your application is packaged as a jar.
|
||||
Although this directory is a common standard, it works *only* with war packaging, and it is silently ignored by most build tools if you generate a jar.
|
||||
|
||||
Spring Boot also supports the advanced resource handling features provided by Spring MVC, allowing use cases such as cache-busting static resources or using version agnostic URLs for Webjars.
|
||||
|
||||
To use version agnostic URLs for Webjars, add the `webjars-locator-core` dependency.
|
||||
Then declare your Webjar.
|
||||
Using jQuery as an example, adding `"/webjars/jquery/jquery.min.js"` results in `"/webjars/jquery/x.y.z/jquery.min.js"` where `x.y.z` is the Webjar version.
|
||||
|
||||
NOTE: If you use JBoss, you need to declare the `webjars-locator-jboss-vfs` dependency instead of the `webjars-locator-core`.
|
||||
Otherwise, all Webjars resolve as a `404`.
|
||||
|
||||
To use cache busting, the following configuration configures a cache busting solution for all static resources, effectively adding a content hash, such as `<link href="/css/spring-2a2d595e6ed9a0b24f027f2b63b134d6.css"/>`, in URLs:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
web:
|
||||
resources:
|
||||
chain:
|
||||
strategy:
|
||||
content:
|
||||
enabled: true
|
||||
paths: "/**"
|
||||
----
|
||||
|
||||
NOTE: Links to resources are rewritten in templates at runtime, thanks to a `ResourceUrlEncodingFilter` that is auto-configured for Thymeleaf and FreeMarker.
|
||||
You should manually declare this filter when using JSPs.
|
||||
Other template engines are currently not automatically supported but can be with custom template macros/helpers and the use of the {url-spring-framework-javadoc}/org/springframework/web/servlet/resource/ResourceUrlProvider.html[`ResourceUrlProvider`].
|
||||
|
||||
When loading resources dynamically with, for example, a JavaScript module loader, renaming files is not an option.
|
||||
That is why other strategies are also supported and can be combined.
|
||||
A "fixed" strategy adds a static version string in the URL without changing the file name, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
web:
|
||||
resources:
|
||||
chain:
|
||||
strategy:
|
||||
content:
|
||||
enabled: true
|
||||
paths: "/**"
|
||||
fixed:
|
||||
enabled: true
|
||||
paths: "/js/lib/"
|
||||
version: "v12"
|
||||
----
|
||||
|
||||
With this configuration, JavaScript modules located under `"/js/lib/"` use a fixed versioning strategy (`"/v12/js/lib/mymodule.js"`), while other resources still use the content one (`<link href="/css/spring-2a2d595e6ed9a0b24f027f2b63b134d6.css"/>`).
|
||||
|
||||
See {code-spring-boot-autoconfigure-src}/web/WebProperties.java[`WebProperties.Resources`] for more supported options.
|
||||
|
||||
[TIP]
|
||||
====
|
||||
This feature has been thoroughly described in a dedicated https://spring.io/blog/2014/07/24/spring-framework-4-1-handling-static-web-resources[blog post] and in Spring Framework's {url-spring-framework-docs}/web/webmvc/mvc-config/static-resources.html[reference documentation].
|
||||
====
|
||||
|
||||
|
||||
|
||||
[[web.servlet.spring-mvc.welcome-page]]
|
||||
=== Welcome Page
|
||||
|
||||
Spring Boot supports both static and templated welcome pages.
|
||||
It first looks for an `index.html` file in the configured static content locations.
|
||||
If one is not found, it then looks for an `index` template.
|
||||
If either is found, it is automatically used as the welcome page of the application.
|
||||
|
||||
This only acts as a fallback for actual index routes defined by the application.
|
||||
The ordering is defined by the order of `HandlerMapping` beans which is by default the following:
|
||||
|
||||
[cols="1,1"]
|
||||
|===
|
||||
|`RouterFunctionMapping`
|
||||
|Endpoints declared with `RouterFunction` beans
|
||||
|
||||
|`RequestMappingHandlerMapping`
|
||||
|Endpoints declared in `@Controller` beans
|
||||
|
||||
|`WelcomePageHandlerMapping`
|
||||
|The welcome page support
|
||||
|===
|
||||
|
||||
|
||||
|
||||
[[web.servlet.spring-mvc.favicon]]
|
||||
=== Custom Favicon
|
||||
|
||||
As with other static resources, Spring Boot checks for a `favicon.ico` in the configured static content locations.
|
||||
If such a file is present, it is automatically used as the favicon of the application.
|
||||
|
||||
|
||||
|
||||
[[web.servlet.spring-mvc.content-negotiation]]
|
||||
=== Path Matching and Content Negotiation
|
||||
|
||||
Spring MVC can map incoming HTTP requests to handlers by looking at the request path and matching it to the mappings defined in your application (for example, `@GetMapping` annotations on Controller methods).
|
||||
|
||||
Spring Boot chooses to disable suffix pattern matching by default, which means that requests like `"GET /projects/spring-boot.json"` will not be matched to `@GetMapping("/projects/spring-boot")` mappings.
|
||||
This is considered as a {url-spring-framework-docs}/web/webmvc/mvc-controller/ann-requestmapping.html#mvc-ann-requestmapping-suffix-pattern-match[best practice for Spring MVC applications].
|
||||
This feature was mainly useful in the past for HTTP clients which did not send proper "Accept" request headers; we needed to make sure to send the correct Content Type to the client.
|
||||
Nowadays, Content Negotiation is much more reliable.
|
||||
|
||||
There are other ways to deal with HTTP clients that do not consistently send proper "Accept" request headers.
|
||||
Instead of using suffix matching, we can use a query parameter to ensure that requests like `"GET /projects/spring-boot?format=json"` will be mapped to `@GetMapping("/projects/spring-boot")`:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
mvc:
|
||||
contentnegotiation:
|
||||
favor-parameter: true
|
||||
----
|
||||
|
||||
Or if you prefer to use a different parameter name:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
mvc:
|
||||
contentnegotiation:
|
||||
favor-parameter: true
|
||||
parameter-name: "myparam"
|
||||
----
|
||||
|
||||
Most standard media types are supported out-of-the-box, but you can also define new ones:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
mvc:
|
||||
contentnegotiation:
|
||||
media-types:
|
||||
markdown: "text/markdown"
|
||||
----
|
||||
|
||||
As of Spring Framework 5.3, Spring MVC supports two strategies for matching request paths to controllers.
|
||||
By default, Spring Boot uses the `PathPatternParser` strategy.
|
||||
`PathPatternParser` is an https://spring.io/blog/2020/06/30/url-matching-with-pathpattern-in-spring-mvc[optimized implementation] but comes with some restrictions compared to the `AntPathMatcher` strategy.
|
||||
`PathPatternParser` restricts usage of {url-spring-framework-docs}/web/webmvc/mvc-controller/ann-requestmapping.html#mvc-ann-requestmapping-uri-templates[some path pattern variants].
|
||||
It is also incompatible with configuring the `DispatcherServlet` with a path prefix (configprop:spring.mvc.servlet.path[]).
|
||||
|
||||
The strategy can be configured using the configprop:spring.mvc.pathmatch.matching-strategy[] configuration property, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
mvc:
|
||||
pathmatch:
|
||||
matching-strategy: "ant-path-matcher"
|
||||
----
|
||||
|
||||
By default, Spring MVC will send a 404 Not Found error response if a handler is not found for a request.
|
||||
To have a `NoHandlerFoundException` thrown instead, set configprop:spring.mvc.throw-exception-if-no-handler-found to `true`.
|
||||
Note that, by default, the xref:web/servlet.adoc#web.servlet.spring-mvc.static-content[serving of static content] is mapped to `+/**+` and will, therefore, provide a handler for all requests.
|
||||
For a `NoHandlerFoundException` to be thrown, you must also set configprop:spring.mvc.static-path-pattern[] to a more specific value such as `/resources/**` or set configprop:spring.web.resources.add-mappings[] to `false` to disable serving of static content entirely.
|
||||
|
||||
|
||||
|
||||
[[web.servlet.spring-mvc.binding-initializer]]
|
||||
=== ConfigurableWebBindingInitializer
|
||||
|
||||
Spring MVC uses a `WebBindingInitializer` to initialize a `WebDataBinder` for a particular request.
|
||||
If you create your own `ConfigurableWebBindingInitializer` `@Bean`, Spring Boot automatically configures Spring MVC to use it.
|
||||
|
||||
|
||||
|
||||
[[web.servlet.spring-mvc.template-engines]]
|
||||
=== Template Engines
|
||||
|
||||
As well as REST web services, you can also use Spring MVC to serve dynamic HTML content.
|
||||
Spring MVC supports a variety of templating technologies, including Thymeleaf, FreeMarker, and JSPs.
|
||||
Also, many other templating engines include their own Spring MVC integrations.
|
||||
|
||||
Spring Boot includes auto-configuration support for the following templating engines:
|
||||
|
||||
* https://freemarker.apache.org/docs/[FreeMarker]
|
||||
* https://docs.groovy-lang.org/docs/next/html/documentation/template-engines.html#_the_markuptemplateengine[Groovy]
|
||||
* https://www.thymeleaf.org[Thymeleaf]
|
||||
* https://mustache.github.io/[Mustache]
|
||||
|
||||
TIP: If possible, JSPs should be avoided.
|
||||
There are several xref:web/servlet.adoc#web.servlet.embedded-container.jsp-limitations[known limitations] when using them with embedded servlet containers.
|
||||
|
||||
When you use one of these templating engines with the default configuration, your templates are picked up automatically from `src/main/resources/templates`.
|
||||
|
||||
TIP: Depending on how you run your application, 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]]
|
||||
=== Error Handling
|
||||
|
||||
By default, Spring Boot provides an `/error` mapping that handles all errors in a sensible way, and it is registered as a "`global`" error page in the servlet container.
|
||||
For machine clients, it produces a JSON response with details of the error, the HTTP status, and the exception message.
|
||||
For browser clients, there is a "`whitelabel`" error view that renders the same data in HTML format (to customize it, add a `View` that resolves to `error`).
|
||||
|
||||
There are a number of `server.error` properties that can be set if you want to customize the default error handling behavior.
|
||||
See the xref:appendix:application-properties/index.adoc#appendix.application-properties.server["`Server Properties`"] section of the Appendix.
|
||||
|
||||
To replace the default behavior completely, you can implement `ErrorController` and register a bean definition of that type or add a bean of type `ErrorAttributes` to use the existing mechanism but replace the contents.
|
||||
|
||||
TIP: The `BasicErrorController` can be used as a base class for a custom `ErrorController`.
|
||||
This is particularly useful if you want to add a handler for a new content type (the default is to handle `text/html` specifically and provide a fallback for everything else).
|
||||
To do so, extend `BasicErrorController`, add a public method with a `@RequestMapping` that has a `produces` attribute, and create a bean of your new type.
|
||||
|
||||
As of Spring Framework 6.0, {url-spring-framework-docs}/web/webmvc/mvc-ann-rest-exceptions.html[RFC 7807 Problem Details] is supported.
|
||||
Spring MVC can produce custom error messages with the `application/problem+json` media type, like:
|
||||
|
||||
[source,json]
|
||||
----
|
||||
{
|
||||
"type": "https://example.org/problems/unknown-project",
|
||||
"title": "Unknown project",
|
||||
"status": 404,
|
||||
"detail": "No project found for id 'spring-unknown'",
|
||||
"instance": "/projects/spring-unknown"
|
||||
}
|
||||
----
|
||||
|
||||
This support can be enabled by setting configprop:spring.mvc.problemdetails.enabled[] to `true`.
|
||||
|
||||
You can also define a class annotated with `@ControllerAdvice` to customize the JSON document to return for a particular controller and/or exception type, as shown in the following example:
|
||||
|
||||
include-code::MyControllerAdvice[]
|
||||
|
||||
In the preceding example, if `MyException` is thrown by a controller defined in the same package as `SomeController`, a JSON representation of the `MyErrorBody` POJO is used instead of the `ErrorAttributes` representation.
|
||||
|
||||
In some cases, errors handled at the controller level are not recorded by web observations or the xref:actuator/metrics.adoc#actuator.metrics.supported.spring-mvc[metrics infrastructure].
|
||||
Applications can ensure that such exceptions are recorded with the observations by {url-spring-framework-docs}/integration/observability.html#observability.http-server.servlet[setting the handled exception on the observation context].
|
||||
|
||||
|
||||
|
||||
[[web.servlet.spring-mvc.error-handling.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.
|
||||
The name of the file should be the exact status code or a series mask.
|
||||
|
||||
For example, to map `404` to a static HTML file, your directory structure would be as follows:
|
||||
|
||||
[source]
|
||||
----
|
||||
src/
|
||||
+- main/
|
||||
+- java/
|
||||
| + <source code>
|
||||
+- resources/
|
||||
+- public/
|
||||
+- error/
|
||||
| +- 404.html
|
||||
+- <other public assets>
|
||||
----
|
||||
|
||||
To map all `5xx` errors by using a FreeMarker template, your directory structure would be as follows:
|
||||
|
||||
[source]
|
||||
----
|
||||
src/
|
||||
+- main/
|
||||
+- java/
|
||||
| + <source code>
|
||||
+- resources/
|
||||
+- templates/
|
||||
+- error/
|
||||
| +- 5xx.ftlh
|
||||
+- <other templates>
|
||||
----
|
||||
|
||||
For more complex mappings, you can also add beans that implement the `ErrorViewResolver` interface, as shown in the following example:
|
||||
|
||||
include-code::MyErrorViewResolver[]
|
||||
|
||||
You can also use regular Spring MVC features such as {url-spring-framework-docs}/web/webmvc/mvc-servlet/exceptionhandlers.html[`@ExceptionHandler` methods] and {url-spring-framework-docs}/web/webmvc/mvc-controller/ann-advice.html[`@ControllerAdvice`].
|
||||
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
|
||||
|
||||
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`.
|
||||
|
||||
include-code::MyErrorPagesConfiguration[]
|
||||
|
||||
NOTE: If you register an `ErrorPage` with a path that ends up being handled by a `Filter` (as is common with some non-Spring web frameworks, like Jersey and Wicket), then the `Filter` has to be explicitly registered as an `ERROR` dispatcher, as shown in the following example:
|
||||
|
||||
include-code::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
|
||||
|
||||
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.
|
||||
Depending on the container that you are deploying your war file to and the technologies that your application uses, some additional configuration may be required.
|
||||
|
||||
The error page filter can only forward the request to the correct error page if the response has not already been committed.
|
||||
By default, WebSphere Application Server 8.0 and later commits the response upon successful completion of a servlet's service method.
|
||||
You should disable this behavior by setting `com.ibm.ws.webcontainer.invokeFlushAfterService` to `false`.
|
||||
|
||||
|
||||
|
||||
[[web.servlet.spring-mvc.cors]]
|
||||
=== CORS Support
|
||||
|
||||
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing[Cross-origin resource sharing] (CORS) is a https://www.w3.org/TR/cors/[W3C specification] implemented by https://caniuse.com/#feat=cors[most browsers] that lets you specify in a flexible way what kind of cross-domain requests are authorized, instead of using some less secure and less powerful approaches such as IFRAME or JSONP.
|
||||
|
||||
As of version 4.2, Spring MVC {url-spring-framework-docs}/web/webmvc-cors.html[supports CORS].
|
||||
Using {url-spring-framework-docs}/web/webmvc-cors.html#mvc-cors-controller[controller method CORS configuration] with {url-spring-framework-javadoc}/org/springframework/web/bind/annotation/CrossOrigin.html[`@CrossOrigin`] annotations in your Spring Boot application does not require any specific configuration.
|
||||
{url-spring-framework-docs}/web/webmvc-cors.html#mvc-cors-global[Global CORS configuration] can be defined by registering a `WebMvcConfigurer` bean with a customized `addCorsMappings(CorsRegistry)` method, as shown in the following example:
|
||||
|
||||
include-code::MyCorsConfiguration[]
|
||||
|
||||
|
||||
|
||||
[[web.servlet.jersey]]
|
||||
== JAX-RS and Jersey
|
||||
|
||||
If you prefer the JAX-RS programming model for REST endpoints, you can use one of the available implementations instead of Spring MVC.
|
||||
https://jersey.github.io/[Jersey] and https://cxf.apache.org/[Apache CXF] work quite well out of the box.
|
||||
CXF requires you to register its `Servlet` or `Filter` as a `@Bean` in your application context.
|
||||
Jersey has some native Spring support, so we also provide auto-configuration support for it in Spring Boot, together with a starter.
|
||||
|
||||
To get started with Jersey, include the `spring-boot-starter-jersey` as a dependency and then you need one `@Bean` of type `ResourceConfig` in which you register all the endpoints, as shown in the following example:
|
||||
|
||||
include-code::MyJerseyConfig[]
|
||||
|
||||
WARNING: Jersey's support for scanning executable archives is rather limited.
|
||||
For example, it cannot scan for endpoints in a package found in a xref:deployment/installing.adoc[fully executable jar file] or in `WEB-INF/classes` when running an executable war file.
|
||||
To avoid this limitation, the `packages` method should not be used, and endpoints should be registered individually by using the `register` method, as shown in the preceding example.
|
||||
|
||||
For more advanced customizations, you can also register an arbitrary number of beans that implement `ResourceConfigCustomizer`.
|
||||
|
||||
All the registered endpoints should be `@Components` with HTTP resource annotations (`@GET` and others), as shown in the following example:
|
||||
|
||||
include-code::MyEndpoint[]
|
||||
|
||||
Since the `Endpoint` is a Spring `@Component`, its lifecycle is managed by Spring and you can use the `@Autowired` annotation to inject dependencies and use the `@Value` annotation to inject external configuration.
|
||||
By default, the Jersey servlet is registered and mapped to `/*`.
|
||||
You can change the mapping by adding `@ApplicationPath` to your `ResourceConfig`.
|
||||
|
||||
By default, Jersey is set up as a servlet in a `@Bean` of type `ServletRegistrationBean` named `jerseyServletRegistration`.
|
||||
By default, the servlet is initialized lazily, but you can customize that behavior by setting `spring.jersey.servlet.load-on-startup`.
|
||||
You can disable or override that bean by creating one of your own with the same name.
|
||||
You can also use a filter instead of a servlet by setting `spring.jersey.type=filter` (in which case, the `@Bean` to replace or override is `jerseyFilterRegistration`).
|
||||
The filter has an `@Order`, which you can set with `spring.jersey.filter.order`.
|
||||
When using Jersey as a filter, a servlet that will handle any requests that are not intercepted by Jersey must be present.
|
||||
If your application does not contain such a servlet, you may want to enable the default servlet by setting configprop: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]]
|
||||
== Embedded Servlet Container Support
|
||||
|
||||
For servlet application, Spring Boot includes support for embedded https://tomcat.apache.org/[Tomcat], https://www.eclipse.org/jetty/[Jetty], and https://github.com/undertow-io/undertow[Undertow] servers.
|
||||
Most developers use the appropriate "`Starter`" to obtain a fully configured instance.
|
||||
By default, the embedded server listens for HTTP requests on port `8080`.
|
||||
|
||||
|
||||
|
||||
[[web.servlet.embedded-container.servlets-filters-listeners]]
|
||||
=== Servlets, Filters, and Listeners
|
||||
|
||||
When using an embedded servlet container, you can register servlets, filters, and all the listeners (such as `HttpSessionListener`) from the servlet spec, either by using Spring beans or by scanning for servlet components.
|
||||
|
||||
|
||||
|
||||
[[web.servlet.embedded-container.servlets-filters-listeners.beans]]
|
||||
==== Registering Servlets, Filters, and Listeners as Spring Beans
|
||||
|
||||
Any `Servlet`, `Filter`, or servlet `*Listener` instance that is a Spring bean is registered with the embedded container.
|
||||
This can be particularly convenient if you want to refer to a value from your `application.properties` during configuration.
|
||||
|
||||
By default, if the context contains only a single Servlet, it is mapped to `/`.
|
||||
In the case of multiple servlet beans, the bean name is used as a path prefix.
|
||||
Filters map to `+/*+`.
|
||||
|
||||
If convention-based mapping is not flexible enough, you can use the `ServletRegistrationBean`, `FilterRegistrationBean`, and `ServletListenerRegistrationBean` classes for complete control.
|
||||
|
||||
It is usually safe to leave filter beans unordered.
|
||||
If a specific order is required, you should annotate the `Filter` with `@Order` or make it implement `Ordered`.
|
||||
You cannot configure the order of a `Filter` by annotating its bean method with `@Order`.
|
||||
If you cannot change the `Filter` class to add `@Order` or implement `Ordered`, you must define a `FilterRegistrationBean` for the `Filter` and set the registration bean's order using the `setOrder(int)` method.
|
||||
Avoid configuring a filter that reads the request body at `Ordered.HIGHEST_PRECEDENCE`, since it might go against the character encoding configuration of your application.
|
||||
If a servlet filter wraps the request, it should be configured with an order that is less than or equal to `OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER`.
|
||||
|
||||
TIP: To see the order of every `Filter` in your application, enable debug level logging for the `web` xref:features/logging.adoc#features.logging.log-groups[logging group] (`logging.level.web=debug`).
|
||||
Details of the registered filters, including their order and URL patterns, will then be logged at startup.
|
||||
|
||||
WARNING: 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 xref:api:java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBean.html[`DelegatingFilterProxyRegistrationBean`] instead.
|
||||
|
||||
|
||||
|
||||
[[web.servlet.embedded-container.context-initializer]]
|
||||
=== Servlet Context Initialization
|
||||
|
||||
Embedded servlet containers do not directly execute the `jakarta.servlet.ServletContainerInitializer` interface or Spring's `org.springframework.web.WebApplicationInitializer` interface.
|
||||
This is an intentional design decision intended to reduce the risk that third party libraries designed to run inside a war may break Spring Boot applications.
|
||||
|
||||
If you need to perform servlet context initialization in a Spring Boot application, you should register a bean that implements the `org.springframework.boot.web.servlet.ServletContextInitializer` interface.
|
||||
The single `onStartup` method provides access to the `ServletContext` and, if necessary, can easily be used as an adapter to an existing `WebApplicationInitializer`.
|
||||
|
||||
|
||||
|
||||
[[web.servlet.embedded-container.context-initializer.scanning]]
|
||||
==== Scanning for Servlets, Filters, and listeners
|
||||
|
||||
When using an embedded container, automatic registration of classes annotated with `@WebServlet`, `@WebFilter`, and `@WebListener` can be enabled by using `@ServletComponentScan`.
|
||||
|
||||
TIP: `@ServletComponentScan` has no effect in a standalone container, where the container's built-in discovery mechanisms are used instead.
|
||||
|
||||
|
||||
|
||||
[[web.servlet.embedded-container.application-context]]
|
||||
=== The ServletWebServerApplicationContext
|
||||
|
||||
Under the hood, Spring Boot uses a different type of `ApplicationContext` for embedded servlet container support.
|
||||
The `ServletWebServerApplicationContext` is a special type of `WebApplicationContext` that bootstraps itself by searching for a single `ServletWebServerFactory` bean.
|
||||
Usually a `TomcatServletWebServerFactory`, `JettyServletWebServerFactory`, or `UndertowServletWebServerFactory` has been auto-configured.
|
||||
|
||||
NOTE: You usually do not need to be aware of these implementation classes.
|
||||
Most applications are auto-configured, and the appropriate `ApplicationContext` and `ServletWebServerFactory` are created on your behalf.
|
||||
|
||||
In an embedded container setup, the `ServletContext` is set as part of server startup which happens during application context initialization.
|
||||
Because of this beans in the `ApplicationContext` cannot be reliably initialized with a `ServletContext`.
|
||||
One way to get around this is to inject `ApplicationContext` as a dependency of the bean and access the `ServletContext` only when it is needed.
|
||||
Another way is to use a callback once the server has started.
|
||||
This can be done using an `ApplicationListener` which listens for the `ApplicationStartedEvent` as follows:
|
||||
|
||||
include-code::MyDemoBean[]
|
||||
|
||||
|
||||
|
||||
[[web.servlet.embedded-container.customizing]]
|
||||
=== 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.
|
||||
|
||||
Common server settings include:
|
||||
|
||||
* Network settings: Listen port for incoming HTTP requests (`server.port`), interface address to bind to (`server.address`), and so on.
|
||||
* Session settings: Whether the session is persistent (`server.servlet.session.persistent`), session timeout (`server.servlet.session.timeout`), location of session data (`server.servlet.session.store-dir`), and session-cookie configuration (`server.servlet.session.cookie.*`).
|
||||
* Error management: Location of the error page (`server.error.path`) and so on.
|
||||
* xref:how-to:webserver.adoc#howto.webserver.configure-ssl[SSL]
|
||||
* xref:how-to:webserver.adoc#howto.webserver.enable-response-compression[HTTP compression]
|
||||
|
||||
Spring Boot tries as much as possible to expose common settings, but this is not always possible.
|
||||
For those cases, dedicated namespaces offer server-specific customizations (see `server.tomcat` and `server.undertow`).
|
||||
For instance, xref:how-to:webserver.adoc#howto.webserver.configure-access-logs[access logs] can be configured with specific features of the embedded servlet container.
|
||||
|
||||
TIP: See the {code-spring-boot-autoconfigure-src}/web/ServerProperties.java[`ServerProperties`] class for a complete list.
|
||||
|
||||
|
||||
|
||||
[[web.servlet.embedded-container.customizing.samesite]]
|
||||
==== 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.
|
||||
|
||||
If you want to change the `SameSite` attribute of your session cookie, you can use the configprop:server.servlet.session.cookie.same-site[] property.
|
||||
This property is supported by auto-configured Tomcat, Jetty and Undertow servers.
|
||||
It is also used to configure Spring Session servlet based `SessionRepository` beans.
|
||||
|
||||
For example, if you want your session cookie to have a `SameSite` attribute of `None`, you can add the following to your `application.properties` or `application.yaml` file:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
server:
|
||||
servlet:
|
||||
session:
|
||||
cookie:
|
||||
same-site: "none"
|
||||
----
|
||||
|
||||
If you want to change the `SameSite` attribute on other cookies added to your `HttpServletResponse`, you can use a `CookieSameSiteSupplier`.
|
||||
The `CookieSameSiteSupplier` is passed a `Cookie` and may return a `SameSite` value, or `null`.
|
||||
|
||||
There are a number of convenience factory and filter methods that you can use to quickly match specific cookies.
|
||||
For example, adding the following bean will automatically apply a `SameSite` of `Lax` for all cookies with a name that matches the regular expression `myapp.*`.
|
||||
|
||||
include-code::MySameSiteConfiguration[]
|
||||
|
||||
|
||||
|
||||
[[web.servlet.embedded-container.customizing.encoding]]
|
||||
==== Character Encoding
|
||||
|
||||
The character encoding behavior of the embedded servlet container for request and response handling can be configured using the `server.servlet.encoding.*` configuration properties.
|
||||
|
||||
When a request's `Accept-Language` header indicates a locale for the request it will be automatically mapped to a charset by the servlet container.
|
||||
Each container provides default locale to charset mappings and you should verify that they meet your application's needs.
|
||||
When they do not, use the configprop:server.servlet.encoding.mapping[] configuration property to customize the mappings, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
server:
|
||||
servlet:
|
||||
encoding:
|
||||
mapping:
|
||||
ko: "UTF-8"
|
||||
----
|
||||
|
||||
In the preceding example, the `ko` (Korean) locale has been mapped to `UTF-8`.
|
||||
This is equivalent to a `<locale-encoding-mapping-list>` entry in a `web.xml` file of a traditional war deployment.
|
||||
|
||||
|
||||
|
||||
[[web.servlet.embedded-container.customizing.programmatic]]
|
||||
==== 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:
|
||||
|
||||
include-code::MyWebServerFactoryCustomizer[]
|
||||
|
||||
`TomcatServletWebServerFactory`, `JettyServletWebServerFactory` and `UndertowServletWebServerFactory` are dedicated variants of `ConfigurableServletWebServerFactory` that have additional customization setter methods for Tomcat, Jetty and Undertow respectively.
|
||||
The following example shows how to customize `TomcatServletWebServerFactory` that provides access to Tomcat-specific configuration options:
|
||||
|
||||
include-code::MyTomcatWebServerFactoryCustomizer[]
|
||||
|
||||
|
||||
|
||||
[[web.servlet.embedded-container.customizing.direct]]
|
||||
==== Customizing ConfigurableServletWebServerFactory Directly
|
||||
|
||||
For more advanced use cases that require you to extend from `ServletWebServerFactory`, you can expose a bean of such type yourself.
|
||||
|
||||
Setters are provided for many configuration options.
|
||||
Several protected method "`hooks`" are also provided should you need to do something more exotic.
|
||||
See the xref:api:java/org/springframework/boot/web/servlet/server/ConfigurableServletWebServerFactory.html[source code documentation] for details.
|
||||
|
||||
NOTE: Auto-configured customizers are still applied on your custom factory, so use that option carefully.
|
||||
|
||||
|
||||
|
||||
[[web.servlet.embedded-container.jsp-limitations]]
|
||||
=== JSP Limitations
|
||||
|
||||
When running a Spring Boot application that uses an embedded servlet container (and is packaged as an executable archive), there are some limitations in the JSP support.
|
||||
|
||||
* With Jetty and Tomcat, it should work if you use war packaging.
|
||||
An executable war will work when launched with `java -jar`, and will also be deployable to any standard container.
|
||||
JSPs are not supported when using an executable jar.
|
||||
|
||||
* Undertow does not support JSPs.
|
||||
|
||||
* Creating a custom `error.jsp` page does not override the default view for xref:web/servlet.adoc#web.servlet.spring-mvc.error-handling[error handling].
|
||||
xref:web/servlet.adoc#web.servlet.spring-mvc.error-handling.error-pages[Custom error pages] should be used instead.
|
||||
@@ -0,0 +1,165 @@
|
||||
[[web.graphql]]
|
||||
= Spring for GraphQL
|
||||
|
||||
If you want to build GraphQL applications, you can take advantage of Spring Boot's auto-configuration for {url-spring-graphql-site}[Spring for GraphQL].
|
||||
The Spring for GraphQL project is based on https://github.com/graphql-java/graphql-java[GraphQL Java].
|
||||
You'll need the `spring-boot-starter-graphql` starter at a minimum.
|
||||
Because GraphQL is transport-agnostic, you'll also need to have one or more additional starters in your application to expose your GraphQL API over the web:
|
||||
|
||||
|
||||
[cols="1,1,1"]
|
||||
|===
|
||||
| Starter | Transport | Implementation
|
||||
|
||||
| `spring-boot-starter-web`
|
||||
| HTTP
|
||||
| Spring MVC
|
||||
|
||||
| `spring-boot-starter-websocket`
|
||||
| WebSocket
|
||||
| WebSocket for Servlet apps
|
||||
|
||||
| `spring-boot-starter-webflux`
|
||||
| HTTP, WebSocket
|
||||
| Spring WebFlux
|
||||
|
||||
| `spring-boot-starter-rsocket`
|
||||
| TCP, WebSocket
|
||||
| Spring WebFlux on Reactor Netty
|
||||
|===
|
||||
|
||||
|
||||
|
||||
[[web.graphql.schema]]
|
||||
== GraphQL Schema
|
||||
|
||||
A Spring GraphQL application requires a defined schema at startup.
|
||||
By default, you can write ".graphqls" or ".gqls" schema files under `src/main/resources/graphql/**` and Spring Boot will pick them up automatically.
|
||||
You can customize the locations with configprop:spring.graphql.schema.locations[] and the file extensions with configprop:spring.graphql.schema.file-extensions[].
|
||||
|
||||
NOTE: If you want Spring Boot to detect schema files in all your application modules and dependencies for that location,
|
||||
you can set configprop:spring.graphql.schema.locations[] to `+"classpath*:graphql/**/"+` (note the `classpath*:` prefix).
|
||||
|
||||
In the following sections, we'll consider this sample GraphQL schema, defining two types and two queries:
|
||||
|
||||
[source,json,subs="verbatim,quotes"]
|
||||
----
|
||||
include::ROOT:example$resources/graphql/schema.graphqls[]
|
||||
----
|
||||
|
||||
NOTE: By default, https://spec.graphql.org/draft/#sec-Introspection[field introspection] will be allowed on the schema as it is required for tools such as GraphiQL.
|
||||
If you wish to not expose information about the schema, you can disable introspection by setting configprop:spring.graphql.schema.introspection.enabled[] to `false`.
|
||||
|
||||
|
||||
|
||||
[[web.graphql.runtimewiring]]
|
||||
== GraphQL RuntimeWiring
|
||||
|
||||
The GraphQL Java `RuntimeWiring.Builder` can be used to register custom scalar types, directives, type resolvers, `DataFetcher`, and more.
|
||||
You can declare `RuntimeWiringConfigurer` beans in your Spring config to get access to the `RuntimeWiring.Builder`.
|
||||
Spring Boot detects such beans and adds them to the {url-spring-graphql-docs}/#execution-graphqlsource[GraphQlSource builder].
|
||||
|
||||
Typically, however, applications will not implement `DataFetcher` directly and will instead create {url-spring-graphql-docs}/#controllers[annotated controllers].
|
||||
Spring Boot will automatically detect `@Controller` classes with annotated handler methods and register those as ``DataFetcher``s.
|
||||
Here's a sample implementation for our greeting query with a `@Controller` class:
|
||||
|
||||
include-code::GreetingController[]
|
||||
|
||||
|
||||
|
||||
[[web.graphql.data-query]]
|
||||
== Querydsl and QueryByExample Repositories Support
|
||||
|
||||
Spring Data offers support for both Querydsl and QueryByExample repositories.
|
||||
Spring GraphQL can {url-spring-graphql-docs}/#data[configure Querydsl and QueryByExample repositories as `DataFetcher`].
|
||||
|
||||
Spring Data repositories annotated with `@GraphQlRepository` and extending one of:
|
||||
|
||||
* `QuerydslPredicateExecutor`
|
||||
* `ReactiveQuerydslPredicateExecutor`
|
||||
* `QueryByExampleExecutor`
|
||||
* `ReactiveQueryByExampleExecutor`
|
||||
|
||||
are detected by Spring Boot and considered as candidates for `DataFetcher` for matching top-level queries.
|
||||
|
||||
|
||||
|
||||
[[web.graphql.transports]]
|
||||
== Transports
|
||||
|
||||
|
||||
|
||||
[[web.graphql.transports.http-websocket]]
|
||||
=== HTTP and WebSocket
|
||||
|
||||
The GraphQL HTTP endpoint is at HTTP POST `/graphql` by default.
|
||||
It also supports the `"text/event-stream"` media type over Server Sent Events for subscriptions only.
|
||||
The path can be customized with configprop:spring.graphql.path[].
|
||||
|
||||
TIP: The HTTP endpoint for both Spring MVC and Spring WebFlux is provided by a `RouterFunction` bean with an `@Order` of `0`.
|
||||
If you define your own `RouterFunction` beans, you may want to add appropriate `@Order` annotations to ensure that they are sorted correctly.
|
||||
|
||||
The GraphQL WebSocket endpoint is off by default. To enable it:
|
||||
|
||||
* For a Servlet application, add the WebSocket starter `spring-boot-starter-websocket`
|
||||
* For a WebFlux application, no additional dependency is required
|
||||
* For both, the configprop:spring.graphql.websocket.path[] application property must be set
|
||||
|
||||
Spring GraphQL provides a {url-spring-graphql-docs}/#web-interception[Web Interception] model.
|
||||
This is quite useful for retrieving information from an HTTP request header and set it in the GraphQL context or fetching information from the same context and writing it to a response header.
|
||||
With Spring Boot, you can declare a `WebInterceptor` bean to have it registered with the web transport.
|
||||
|
||||
|
||||
{url-spring-framework-docs}/web/webmvc-cors.html[Spring MVC] and {url-spring-framework-docs}/web/webflux-cors.html[Spring WebFlux] support CORS (Cross-Origin Resource Sharing) requests.
|
||||
CORS is a critical part of the web config for GraphQL applications that are accessed from browsers using different domains.
|
||||
|
||||
Spring Boot supports many configuration properties under the `spring.graphql.cors.*` namespace; here's a short configuration sample:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
graphql:
|
||||
cors:
|
||||
allowed-origins: "https://example.org"
|
||||
allowed-methods: GET,POST
|
||||
max-age: 1800s
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[web.graphql.transports.rsocket]]
|
||||
=== RSocket
|
||||
|
||||
RSocket is also supported as a transport, on top of WebSocket or TCP.
|
||||
Once the xref:messaging/rsocket.adoc#messaging.rsocket.server-auto-configuration[RSocket server is configured], we can configure our GraphQL handler on a particular route using configprop:spring.graphql.rsocket.mapping[].
|
||||
For example, configuring that mapping as `"graphql"` means we can use that as a route when sending requests with the `RSocketGraphQlClient`.
|
||||
|
||||
Spring Boot auto-configures a `RSocketGraphQlClient.Builder<?>` bean that you can inject in your components:
|
||||
|
||||
include-code::RSocketGraphQlClientExample[tag=builder]
|
||||
|
||||
And then send a request:
|
||||
include-code::RSocketGraphQlClientExample[tag=request]
|
||||
|
||||
|
||||
|
||||
[[web.graphql.exception-handling]]
|
||||
== Exception Handling
|
||||
|
||||
Spring GraphQL enables applications to register one or more Spring `DataFetcherExceptionResolver` components that are invoked sequentially.
|
||||
The Exception must be resolved to a list of `graphql.GraphQLError` objects, see {url-spring-graphql-docs}/#execution-exceptions[Spring GraphQL exception handling documentation].
|
||||
Spring Boot will automatically detect `DataFetcherExceptionResolver` beans and register them with the `GraphQlSource.Builder`.
|
||||
|
||||
|
||||
|
||||
[[web.graphql.graphiql]]
|
||||
== GraphiQL and Schema printer
|
||||
|
||||
Spring GraphQL offers infrastructure for helping developers when consuming or developing a GraphQL API.
|
||||
|
||||
Spring GraphQL ships with a default https://github.com/graphql/graphiql[GraphiQL] page that is exposed at `"/graphiql"` by default.
|
||||
This page is disabled by default and can be turned on with the configprop:spring.graphql.graphiql.enabled[] property.
|
||||
Many applications exposing such a page will prefer a custom build.
|
||||
A default implementation is very useful during development, this is why it is exposed automatically with xref:using/devtools.adoc[`spring-boot-devtools`] during development.
|
||||
|
||||
You can also choose to expose the GraphQL schema in text format at `/graphql/schema` when the configprop:spring.graphql.schema.printer.enabled[] property is enabled.
|
||||
@@ -0,0 +1,15 @@
|
||||
[[web.spring-hateoas]]
|
||||
= Spring HATEOAS
|
||||
|
||||
If you develop a RESTful API that makes use of hypermedia, Spring Boot provides auto-configuration for Spring HATEOAS that works well with most applications.
|
||||
The auto-configuration replaces the need to use `@EnableHypermediaSupport` and registers a number of beans to ease building hypermedia-based applications, including a `LinkDiscoverers` (for client side support) and an `ObjectMapper` configured to correctly marshal responses into the desired representation.
|
||||
The `ObjectMapper` is customized by setting the various `spring.jackson.*` properties or, if one exists, by a `Jackson2ObjectMapperBuilder` bean.
|
||||
|
||||
You can take control of Spring HATEOAS's configuration by using `@EnableHypermediaSupport`.
|
||||
Note that doing so disables the `ObjectMapper` customization described earlier.
|
||||
|
||||
WARNING: `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`.
|
||||
|
||||
By default, requests that accept `application/json` will receive an `application/hal+json` response.
|
||||
To disable this behavior set configprop:spring.hateoas.use-hal-as-default-json-media-type[] to `false` and define a `HypermediaMappingInformation` or `HalConfiguration` to configure Spring HATEOAS to meet the needs of your application and its clients.
|
||||
@@ -0,0 +1,408 @@
|
||||
[[web.security]]
|
||||
= Spring Security
|
||||
|
||||
If {url-spring-security-site}[Spring Security] is on the classpath, then web applications are secured by default.
|
||||
Spring Boot relies on Spring Security’s content-negotiation strategy to determine whether to use `httpBasic` or `formLogin`.
|
||||
To add method-level security to a web application, you can also add `@EnableGlobalMethodSecurity` with your desired settings.
|
||||
Additional information can be found in the {url-spring-security-docs}/servlet/authorization/method-security.html[Spring Security Reference Guide].
|
||||
|
||||
The default `UserDetailsService` has a single user.
|
||||
The user name is `user`, and the password is random and is printed at WARN level when the application starts, as shown in the following example:
|
||||
|
||||
[source]
|
||||
----
|
||||
Using generated security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35
|
||||
|
||||
This generated password is for development use only. Your security configuration must be updated before running your application in production.
|
||||
----
|
||||
|
||||
NOTE: If you fine-tune your logging configuration, ensure that the `org.springframework.boot.autoconfigure.security` category is set to log `WARN`-level messages.
|
||||
Otherwise, the default password is not printed.
|
||||
|
||||
You can change the username and password by providing a `spring.security.user.name` and `spring.security.user.password`.
|
||||
|
||||
The basic features you get by default in a web application are:
|
||||
|
||||
* A `UserDetailsService` (or `ReactiveUserDetailsService` in case of a WebFlux application) bean with in-memory store and a single user with a generated password (see xref:api:java/org/springframework/boot/autoconfigure/security/SecurityProperties.User.html[`SecurityProperties.User`] for the properties of the user).
|
||||
* Form-based login or HTTP Basic security (depending on the `Accept` header in the request) for the entire application (including actuator endpoints if actuator is on the classpath).
|
||||
* A `DefaultAuthenticationEventPublisher` for publishing authentication events.
|
||||
|
||||
You can provide a different `AuthenticationEventPublisher` by adding a bean for it.
|
||||
|
||||
|
||||
|
||||
[[web.security.spring-mvc]]
|
||||
== MVC Security
|
||||
|
||||
The default security configuration is implemented in `SecurityAutoConfiguration` and `UserDetailsServiceAutoConfiguration`.
|
||||
`SecurityAutoConfiguration` imports `SpringBootWebSecurityConfiguration` for web security and `UserDetailsServiceAutoConfiguration` configures authentication, which is also relevant in non-web applications.
|
||||
|
||||
To switch off the default web application security configuration completely 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).
|
||||
To also switch off the `UserDetailsService` configuration, you can add a bean of type `UserDetailsService`, `AuthenticationProvider`, or `AuthenticationManager`.
|
||||
|
||||
The auto-configuration of a `UserDetailsService` will also back off any of the following Spring Security modules is on the classpath:
|
||||
|
||||
- `spring-security-oauth2-client`
|
||||
- `spring-security-oauth2-resource-server`
|
||||
- `spring-security-saml2-service-provider`
|
||||
|
||||
To use `UserDetailsService` in addition to one or more of these dependencies, define your own `InMemoryUserDetailsManager` bean.
|
||||
|
||||
Access rules can be overridden by adding a custom `SecurityFilterChain` 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 configprop:management.endpoints.web.base-path[] property.
|
||||
`PathRequest` can be used to create a `RequestMatcher` for resources in commonly used locations.
|
||||
|
||||
|
||||
|
||||
[[web.security.spring-webflux]]
|
||||
== WebFlux Security
|
||||
|
||||
Similar to Spring MVC applications, you can secure your WebFlux applications by adding the `spring-boot-starter-security` dependency.
|
||||
The default security configuration is implemented in `ReactiveSecurityAutoConfiguration` and `UserDetailsServiceAutoConfiguration`.
|
||||
`ReactiveSecurityAutoConfiguration` imports `WebFluxSecurityConfiguration` for web security and `UserDetailsServiceAutoConfiguration` configures authentication, which is also relevant in non-web applications.
|
||||
|
||||
To switch off the default web application security configuration completely, you can add a bean of type `WebFilterChainProxy` (doing so does not disable the `UserDetailsService` configuration or Actuator's security).
|
||||
To also switch off the `UserDetailsService` configuration, you can add a bean of type `ReactiveUserDetailsService` or `ReactiveAuthenticationManager`.
|
||||
|
||||
The auto-configuration will also back off when any of the following Spring Security modules is on the classpath:
|
||||
|
||||
- `spring-security-oauth2-client`
|
||||
- `spring-security-oauth2-resource-server`
|
||||
|
||||
To use `ReactiveUserDetailsService` in addition to one or more of these dependencies, define your own `MapReactiveUserDetailsService` bean.
|
||||
|
||||
Access rules and the use of multiple Spring Security components such as OAuth 2 Client and Resource Server can be configured by adding a custom `SecurityWebFilterChain` 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 `ServerWebExchangeMatcher` that is based on the configprop:management.endpoints.web.base-path[] property.
|
||||
|
||||
`PathRequest` can be used to create a `ServerWebExchangeMatcher` for resources in commonly used locations.
|
||||
|
||||
For example, you can customize your security configuration by adding something like:
|
||||
|
||||
include-code::MyWebFluxSecurityConfiguration[]
|
||||
|
||||
|
||||
|
||||
[[web.security.oauth2]]
|
||||
== OAuth2
|
||||
|
||||
https://oauth.net/2/[OAuth2] is a widely used authorization framework that is supported by Spring.
|
||||
|
||||
|
||||
|
||||
[[web.security.oauth2.client]]
|
||||
=== Client
|
||||
|
||||
If you have `spring-security-oauth2-client` on your classpath, you can take advantage of some auto-configuration to set up OAuth2/Open ID Connect clients.
|
||||
This configuration makes use of the properties under `OAuth2ClientProperties`.
|
||||
The same properties are applicable to both servlet and reactive applications.
|
||||
|
||||
You can register multiple OAuth2 clients and providers under the `spring.security.oauth2.client` prefix, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
security:
|
||||
oauth2:
|
||||
client:
|
||||
registration:
|
||||
my-login-client:
|
||||
client-id: "abcd"
|
||||
client-secret: "password"
|
||||
client-name: "Client for OpenID Connect"
|
||||
provider: "my-oauth-provider"
|
||||
scope: "openid,profile,email,phone,address"
|
||||
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
|
||||
client-authentication-method: "client_secret_basic"
|
||||
authorization-grant-type: "authorization_code"
|
||||
|
||||
my-client-1:
|
||||
client-id: "abcd"
|
||||
client-secret: "password"
|
||||
client-name: "Client for user scope"
|
||||
provider: "my-oauth-provider"
|
||||
scope: "user"
|
||||
redirect-uri: "{baseUrl}/authorized/user"
|
||||
client-authentication-method: "client_secret_basic"
|
||||
authorization-grant-type: "authorization_code"
|
||||
|
||||
my-client-2:
|
||||
client-id: "abcd"
|
||||
client-secret: "password"
|
||||
client-name: "Client for email scope"
|
||||
provider: "my-oauth-provider"
|
||||
scope: "email"
|
||||
redirect-uri: "{baseUrl}/authorized/email"
|
||||
client-authentication-method: "client_secret_basic"
|
||||
authorization-grant-type: "authorization_code"
|
||||
|
||||
provider:
|
||||
my-oauth-provider:
|
||||
authorization-uri: "https://my-auth-server.com/oauth2/authorize"
|
||||
token-uri: "https://my-auth-server.com/oauth2/token"
|
||||
user-info-uri: "https://my-auth-server.com/userinfo"
|
||||
user-info-authentication-method: "header"
|
||||
jwk-set-uri: "https://my-auth-server.com/oauth2/jwks"
|
||||
user-name-attribute: "name"
|
||||
----
|
||||
|
||||
For OpenID Connect providers that support https://openid.net/specs/openid-connect-discovery-1_0.html[OpenID Connect discovery], the configuration can be further simplified.
|
||||
The provider needs to be configured with an `issuer-uri` which is the URI that it asserts as its Issuer Identifier.
|
||||
For example, if the `issuer-uri` provided is "https://example.com", then an "OpenID Provider Configuration Request" will be made to "https://example.com/.well-known/openid-configuration".
|
||||
The result is expected to be an "OpenID Provider Configuration Response".
|
||||
The following example shows how an OpenID Connect Provider can be configured with the `issuer-uri`:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
security:
|
||||
oauth2:
|
||||
client:
|
||||
provider:
|
||||
oidc-provider:
|
||||
issuer-uri: "https://dev-123456.oktapreview.com/oauth2/default/"
|
||||
----
|
||||
|
||||
By default, Spring Security's `OAuth2LoginAuthenticationFilter` only processes URLs matching `/login/oauth2/code/*`.
|
||||
If you want to customize the `redirect-uri` to use a different pattern, you need to provide configuration to process that custom pattern.
|
||||
For example, for servlet applications, you can add your own `SecurityFilterChain` that resembles the following:
|
||||
|
||||
include-code::MyOAuthClientConfiguration[]
|
||||
|
||||
TIP: Spring Boot auto-configures an `InMemoryOAuth2AuthorizedClientService` which is used by Spring Security for the management of client registrations.
|
||||
The `InMemoryOAuth2AuthorizedClientService` has limited capabilities and we recommend using it only for development environments.
|
||||
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
|
||||
|
||||
For common OAuth2 and OpenID providers, including Google, Github, Facebook, and Okta, we provide a set of provider defaults (`google`, `github`, `facebook`, and `okta`, respectively).
|
||||
|
||||
If you do not need to customize these providers, you can set the `provider` attribute to the one for which you need to infer defaults.
|
||||
Also, if the key for the client registration matches a default supported provider, Spring Boot infers that as well.
|
||||
|
||||
In other words, the two configurations in the following example use the Google provider:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
security:
|
||||
oauth2:
|
||||
client:
|
||||
registration:
|
||||
my-client:
|
||||
client-id: "abcd"
|
||||
client-secret: "password"
|
||||
provider: "google"
|
||||
google:
|
||||
client-id: "abcd"
|
||||
client-secret: "password"
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[web.security.oauth2.server]]
|
||||
=== Resource Server
|
||||
|
||||
If you have `spring-security-oauth2-resource-server` on your classpath, Spring Boot can set up an OAuth2 Resource Server.
|
||||
For JWT configuration, a JWK Set URI or OIDC Issuer URI needs to be specified, as shown in the following examples:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
security:
|
||||
oauth2:
|
||||
resourceserver:
|
||||
jwt:
|
||||
jwk-set-uri: "https://example.com/oauth2/default/v1/keys"
|
||||
----
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
security:
|
||||
oauth2:
|
||||
resourceserver:
|
||||
jwt:
|
||||
issuer-uri: "https://dev-123456.oktapreview.com/oauth2/default/"
|
||||
----
|
||||
|
||||
NOTE: If the authorization server does not support a JWK Set URI, you can configure the resource server with the Public Key used for verifying the signature of the JWT.
|
||||
This can be done using the configprop:spring.security.oauth2.resourceserver.jwt.public-key-location[] property, where the value needs to point to a file containing the public key in the PEM-encoded x509 format.
|
||||
|
||||
The configprop:spring.security.oauth2.resourceserver.jwt.audiences[] property can be used to specify the expected values of the aud claim in JWTs.
|
||||
For example, to require JWTs to contain an aud claim with the value `my-audience`:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
security:
|
||||
oauth2:
|
||||
resourceserver:
|
||||
jwt:
|
||||
audiences:
|
||||
- "my-audience"
|
||||
----
|
||||
|
||||
The same properties are applicable for both servlet and reactive applications.
|
||||
Alternatively, you can define your own `JwtDecoder` bean for servlet applications or a `ReactiveJwtDecoder` for reactive applications.
|
||||
|
||||
In cases where opaque tokens are used instead of JWTs, you can configure the following properties to validate tokens through introspection:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
security:
|
||||
oauth2:
|
||||
resourceserver:
|
||||
opaquetoken:
|
||||
introspection-uri: "https://example.com/check-token"
|
||||
client-id: "my-client-id"
|
||||
client-secret: "my-client-secret"
|
||||
----
|
||||
|
||||
Again, the same properties are applicable for both servlet and reactive applications.
|
||||
Alternatively, you can define your own `OpaqueTokenIntrospector` bean for servlet applications or a `ReactiveOpaqueTokenIntrospector` for reactive applications.
|
||||
|
||||
|
||||
|
||||
[[web.security.oauth2.authorization-server]]
|
||||
=== Authorization Server
|
||||
|
||||
If you have `spring-security-oauth2-authorization-server` on your classpath, you can take advantage of some auto-configuration to set up a Servlet-based OAuth2 Authorization Server.
|
||||
|
||||
You can register multiple OAuth2 clients under the `spring.security.oauth2.authorizationserver.client` prefix, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
security:
|
||||
oauth2:
|
||||
authorizationserver:
|
||||
client:
|
||||
my-client-1:
|
||||
registration:
|
||||
client-id: "abcd"
|
||||
client-secret: "{noop}secret1"
|
||||
client-authentication-methods:
|
||||
- "client_secret_basic"
|
||||
authorization-grant-types:
|
||||
- "authorization_code"
|
||||
- "refresh_token"
|
||||
redirect-uris:
|
||||
- "https://my-client-1.com/login/oauth2/code/abcd"
|
||||
- "https://my-client-1.com/authorized"
|
||||
scopes:
|
||||
- "openid"
|
||||
- "profile"
|
||||
- "email"
|
||||
- "phone"
|
||||
- "address"
|
||||
require-authorization-consent: true
|
||||
my-client-2:
|
||||
registration:
|
||||
client-id: "efgh"
|
||||
client-secret: "{noop}secret2"
|
||||
client-authentication-methods:
|
||||
- "client_secret_jwt"
|
||||
authorization-grant-types:
|
||||
- "client_credentials"
|
||||
scopes:
|
||||
- "user.read"
|
||||
- "user.write"
|
||||
jwk-set-uri: "https://my-client-2.com/jwks"
|
||||
token-endpoint-authentication-signing-algorithm: "RS256"
|
||||
----
|
||||
|
||||
NOTE: The `client-secret` property must be in a format that can be matched by the configured `PasswordEncoder`.
|
||||
The default instance of `PasswordEncoder` is created via `PasswordEncoderFactories.createDelegatingPasswordEncoder()`.
|
||||
|
||||
The auto-configuration Spring Boot provides for Spring Authorization Server is designed for getting started quickly.
|
||||
Most applications will require customization and will want to define several beans to override auto-configuration.
|
||||
|
||||
The following components can be defined as beans to override auto-configuration specific to Spring Authorization Server:
|
||||
|
||||
* `RegisteredClientRepository`
|
||||
* `AuthorizationServerSettings`
|
||||
* `SecurityFilterChain`
|
||||
* `com.nimbusds.jose.jwk.source.JWKSource<com.nimbusds.jose.proc.SecurityContext>`
|
||||
* `JwtDecoder`
|
||||
|
||||
TIP: Spring Boot auto-configures an `InMemoryRegisteredClientRepository` which is used by Spring Authorization Server for the management of registered clients.
|
||||
The `InMemoryRegisteredClientRepository` has limited capabilities and we recommend using it only for development environments.
|
||||
For production environments, consider using a `JdbcRegisteredClientRepository` or creating your own implementation of `RegisteredClientRepository`.
|
||||
|
||||
Additional information can be found in the {url-spring-authorization-server-docs}/getting-started.html[Getting Started] chapter of the {url-spring-authorization-server-docs}[Spring Authorization Server Reference Guide].
|
||||
|
||||
|
||||
|
||||
[[web.security.saml2]]
|
||||
== SAML 2.0
|
||||
|
||||
|
||||
|
||||
[[web.security.saml2.relying-party]]
|
||||
=== 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`.
|
||||
|
||||
A relying party registration represents a paired configuration between an Identity Provider, IDP, and a Service Provider, SP.
|
||||
You can register multiple relying parties under the `spring.security.saml2.relyingparty` prefix, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
security:
|
||||
saml2:
|
||||
relyingparty:
|
||||
registration:
|
||||
my-relying-party1:
|
||||
signing:
|
||||
credentials:
|
||||
- private-key-location: "path-to-private-key"
|
||||
certificate-location: "path-to-certificate"
|
||||
decryption:
|
||||
credentials:
|
||||
- private-key-location: "path-to-private-key"
|
||||
certificate-location: "path-to-certificate"
|
||||
singlelogout:
|
||||
url: "https://myapp/logout/saml2/slo"
|
||||
response-url: "https://remoteidp2.slo.url"
|
||||
binding: "POST"
|
||||
assertingparty:
|
||||
verification:
|
||||
credentials:
|
||||
- certificate-location: "path-to-verification-cert"
|
||||
entity-id: "remote-idp-entity-id1"
|
||||
sso-url: "https://remoteidp1.sso.url"
|
||||
|
||||
my-relying-party2:
|
||||
signing:
|
||||
credentials:
|
||||
- private-key-location: "path-to-private-key"
|
||||
certificate-location: "path-to-certificate"
|
||||
decryption:
|
||||
credentials:
|
||||
- private-key-location: "path-to-private-key"
|
||||
certificate-location: "path-to-certificate"
|
||||
assertingparty:
|
||||
verification:
|
||||
credentials:
|
||||
- certificate-location: "path-to-other-verification-cert"
|
||||
entity-id: "remote-idp-entity-id2"
|
||||
sso-url: "https://remoteidp2.sso.url"
|
||||
singlelogout:
|
||||
url: "https://remoteidp2.slo.url"
|
||||
response-url: "https://myapp/logout/saml2/slo"
|
||||
binding: "POST"
|
||||
----
|
||||
|
||||
For SAML2 logout, by default, Spring Security's `Saml2LogoutRequestFilter` and `Saml2LogoutResponseFilter` only process URLs matching `/logout/saml2/slo`.
|
||||
If you want to customize the `url` to which AP-initiated logout requests get sent to or the `response-url` to which an AP sends logout responses to, to use a different pattern, you need to provide configuration to process that custom pattern.
|
||||
For example, for servlet applications, you can add your own `SecurityFilterChain` that resembles the following:
|
||||
|
||||
include-code::MySamlRelyingPartyConfiguration[]
|
||||
@@ -0,0 +1,57 @@
|
||||
[[web.spring-session]]
|
||||
= Spring Session
|
||||
|
||||
Spring Boot provides {url-spring-session-site}[Spring Session] auto-configuration for a wide range of data stores.
|
||||
When building a servlet web application, the following stores can be auto-configured:
|
||||
|
||||
* Redis
|
||||
* JDBC
|
||||
* Hazelcast
|
||||
* MongoDB
|
||||
|
||||
Additionally, {url-spring-boot-for-apache-geode-site}[Spring Boot for Apache Geode] provides {url-spring-boot-for-apache-geode-docs}#geode-session[auto-configuration for using Apache Geode as a session store].
|
||||
|
||||
The servlet auto-configuration replaces the need to use `@Enable*HttpSession`.
|
||||
|
||||
If a single Spring Session module is present on the classpath, Spring Boot uses that store implementation automatically.
|
||||
If you have more than one implementation, Spring Boot uses the following order for choosing a specific implementation:
|
||||
|
||||
. Redis
|
||||
. JDBC
|
||||
. Hazelcast
|
||||
. MongoDB
|
||||
. If none of Redis, JDBC, Hazelcast and MongoDB are available, we do not configure a `SessionRepository`.
|
||||
|
||||
|
||||
When building a reactive web application, the following stores can be auto-configured:
|
||||
|
||||
* Redis
|
||||
* MongoDB
|
||||
|
||||
The reactive auto-configuration replaces the need to use `@Enable*WebSession`.
|
||||
|
||||
Similar to the servlet configuration, if you have more than one implementation, Spring Boot uses the following order for choosing a specific implementation:
|
||||
|
||||
. Redis
|
||||
. MongoDB
|
||||
. If neither Redis nor MongoDB are available, we do not configure a `ReactiveSessionRepository`.
|
||||
|
||||
|
||||
Each store has specific additional settings.
|
||||
For instance, it is possible to customize the name of the table for the JDBC store, as shown in the following example:
|
||||
|
||||
[configprops,yaml]
|
||||
----
|
||||
spring:
|
||||
session:
|
||||
jdbc:
|
||||
table-name: "SESSIONS"
|
||||
----
|
||||
|
||||
For setting the timeout of the session you can use the configprop:spring.session.timeout[] property.
|
||||
If that property is not set with a servlet web application, the auto-configuration falls back to the value of configprop:server.servlet.session.timeout[].
|
||||
|
||||
|
||||
You can take control over Spring Session's configuration using `@Enable*HttpSession` (servlet) or `@Enable*WebSession` (reactive).
|
||||
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.
|
||||
@@ -0,0 +1,91 @@
|
||||
* Reference Guides
|
||||
|
||||
** xref:reference:using/index.adoc[]
|
||||
*** xref:reference:using/build-systems.adoc[]
|
||||
*** xref:reference:using/structuring-your-code.adoc[]
|
||||
*** xref:reference:using/configuration-classes.adoc[]
|
||||
*** xref:reference:using/auto-configuration.adoc[]
|
||||
*** xref:reference:using/spring-beans-and-dependency-injection.adoc[]
|
||||
*** xref:reference:using/using-the-springbootapplication-annotation.adoc[]
|
||||
*** xref:reference:using/running-your-application.adoc[]
|
||||
*** xref:reference:using/devtools.adoc[]
|
||||
*** xref:reference:using/packaging-for-production.adoc[]
|
||||
|
||||
** xref:reference:features/index.adoc[]
|
||||
*** xref:reference:features/spring-application.adoc[]
|
||||
*** xref:reference:features/external-config.adoc[]
|
||||
*** xref:reference:features/profiles.adoc[]
|
||||
*** xref:reference:features/logging.adoc[]
|
||||
*** xref:reference:features/internationalization.adoc[]
|
||||
*** xref:reference:features/aop.adoc[]
|
||||
*** xref:reference:features/json.adoc[]
|
||||
*** xref:reference:features/task-execution-and-scheduling.adoc[]
|
||||
*** xref:reference:features/testing.adoc[]
|
||||
*** xref:reference:features/docker-compose.adoc[]
|
||||
*** xref:reference:features/testcontainers.adoc[]
|
||||
*** xref:reference:features/developing-auto-configuration.adoc[]
|
||||
*** xref:reference:features/kotlin.adoc[]
|
||||
*** xref:reference:features/ssl.adoc[]
|
||||
|
||||
** xref:reference:web/index.adoc[]
|
||||
*** xref:reference:web/servlet.adoc[]
|
||||
*** xref:reference:web/reactive.adoc[]
|
||||
*** xref:reference:web/graceful-shutdown.adoc[]
|
||||
*** xref:reference:web/spring-security.adoc[]
|
||||
*** xref:reference:web/spring-session.adoc[]
|
||||
*** xref:reference:web/spring-graphql.adoc[]
|
||||
*** xref:reference:web/spring-hateoas.adoc[]
|
||||
|
||||
** xref:reference:data/index.adoc[]
|
||||
*** xref:reference:data/sql.adoc[]
|
||||
*** xref:reference:data/nosql.adoc[]
|
||||
|
||||
** xref:reference:io/index.adoc[]
|
||||
*** xref:reference:io/caching.adoc[]
|
||||
*** xref:reference:io/hazelcast.adoc[]
|
||||
*** xref:reference:io/quartz.adoc[]
|
||||
*** xref:reference:io/email.adoc[]
|
||||
*** xref:reference:io/validation.adoc[]
|
||||
*** xref:reference:io/rest-client.adoc[]
|
||||
*** xref:reference:io/webservices.adoc[]
|
||||
*** xref:reference:io/jta.adoc[]
|
||||
|
||||
** xref:reference:messaging/index.adoc[]
|
||||
*** xref:reference:messaging/jms.adoc[]
|
||||
*** xref:reference:messaging/amqp.adoc[]
|
||||
*** xref:reference:messaging/kafka.adoc[]
|
||||
*** xref:reference:messaging/pulsar.adoc[]
|
||||
*** xref:reference:messaging/rsocket.adoc[]
|
||||
*** xref:reference:messaging/spring-integration.adoc[]
|
||||
*** xref:reference:messaging/websockets.adoc[]
|
||||
|
||||
** xref:reference:container-images/index.adoc[]
|
||||
*** xref:reference:container-images/efficient-images.adoc[]
|
||||
*** xref:reference:container-images/dockerfiles.adoc[]
|
||||
*** xref:reference:container-images/cloud-native-buildpacks.adoc[]
|
||||
|
||||
** xref:reference:actuator/index.adoc[]
|
||||
*** xref:reference:actuator/enabling.adoc[]
|
||||
*** xref:reference:actuator/endpoints.adoc[]
|
||||
*** xref:reference:actuator/monitoring.adoc[]
|
||||
*** xref:reference:actuator/jmx.adoc[]
|
||||
*** xref:reference:actuator/observability.adoc[]
|
||||
*** xref:reference:actuator/loggers.adoc[]
|
||||
*** xref:reference:actuator/metrics.adoc[]
|
||||
*** xref:reference:actuator/tracing.adoc[]
|
||||
*** xref:reference:actuator/auditing.adoc[]
|
||||
*** xref:reference:actuator/http-exchanges.adoc[]
|
||||
*** xref:reference:actuator/process-monitoring.adoc[]
|
||||
*** xref:reference:actuator/cloud-foundry.adoc[]
|
||||
|
||||
** xref:reference:deployment/index.adoc[]
|
||||
*** xref:reference:deployment/cloud.adoc[]
|
||||
*** xref:reference:deployment/installing.adoc[]
|
||||
*** xref:reference:deployment/efficient.adoc[]
|
||||
|
||||
** xref:reference:native-image/index.adoc[]
|
||||
*** xref:reference:native-image/introducing-graalvm-native-images.adoc[]
|
||||
*** xref:reference:native-image/developing-your-first-application.adoc[]
|
||||
*** xref:reference:native-image/testing-native-applications.adoc[]
|
||||
*** xref:reference:native-image/advanced-topics.adoc[]
|
||||
|
||||
Reference in New Issue
Block a user