Migrate class references to full javadoc links

Update documentation to use `javadoc:...` macro for class and interface
references.

Migrated using https://github.com/philwebb/asciidoctor-javadoc-migration

See gh-43239
This commit is contained in:
Phillip Webb 2024-11-20 20:39:32 -08:00
parent 0e62778612
commit e9e018c598
89 changed files with 1869 additions and 1869 deletions

View File

@ -41,7 +41,7 @@ To enable that feature, add the following dependency to your project:
</dependency>
----
WARNING: Properties that are added late to the environment, such as when using `@PropertySource`, will not be taken into account.
WARNING: Properties that are added late to the environment, such as when using javadoc:org.springframework.context.annotation.PropertySource[format=annotation], will not be taken into account.
NOTE: Once you finish the migration, please make sure to remove this module from your project's dependencies.

View File

@ -12,8 +12,8 @@ If you need to, you may use this library directly.
[[build-tool-plugins.other-build-systems.repackaging-archives]]
== Repackaging Archives
To repackage an existing archive so that it becomes a self-contained executable archive, use `org.springframework.boot.loader.tools.Repackager`.
The `Repackager` class takes a single constructor argument that refers to an existing jar or war archive.
To repackage an existing archive so that it becomes a self-contained executable archive, use javadoc:org.springframework.boot.loader.tools.Repackager[].
The javadoc:org.springframework.boot.loader.tools.Repackager[] class takes a single constructor argument that refers to an existing jar or war archive.
Use one of the two available `repackage()` methods to either replace the original file or write to a new destination.
Various settings can also be configured on the repackager before it is run.
@ -22,8 +22,8 @@ Various settings can also be configured on the repackager before it is run.
[[build-tool-plugins.other-build-systems.nested-libraries]]
== Nested Libraries
When repackaging an archive, you can include references to dependency files by using the `org.springframework.boot.loader.tools.Libraries` interface.
We do not provide any concrete implementations of `Libraries` here as they are usually build-system-specific.
When repackaging an archive, you can include references to dependency files by using the javadoc:org.springframework.boot.loader.tools.Libraries[] interface.
We do not provide any concrete implementations of javadoc:org.springframework.boot.loader.tools.Libraries[] here as they are usually build-system-specific.
If your archive already includes libraries, you can use javadoc:org.springframework.boot.loader.tools.Libraries#NONE[].

View File

@ -20,20 +20,20 @@ For more detail, see the javadoc:org.springframework.boot.actuate.autoconfigure.
[[howto.actuator.customizing-sanitization]]
== Customizing Sanitization
To take control over the sanitization, define a `SanitizingFunction` bean.
The `SanitizableData` with which the function is called provides access to the key and value as well as the `org.springframework.core.env.PropertySource` from which they came.
To take control over the sanitization, define a javadoc:org.springframework.boot.actuate.endpoint.SanitizingFunction[] bean.
The javadoc:org.springframework.boot.actuate.endpoint.SanitizableData[] with which the function is called provides access to the key and value as well as the javadoc:org.springframework.core.env.PropertySource[] from which they came.
This allows you to, for example, sanitize every value that comes from a particular property source.
Each `SanitizingFunction` is called in order until a function changes the value of the sanitizable data.
Each javadoc:org.springframework.boot.actuate.endpoint.SanitizingFunction[] is called in order until a function changes the value of the sanitizable data.
[[howto.actuator.map-health-indicators-to-metrics]]
== Map Health Indicators to Micrometer Metrics
Spring Boot health indicators return a `org.springframework.boot.actuate.health.Status` type to indicate the overall system health.
Spring Boot health indicators return a javadoc:org.springframework.boot.actuate.health.Status[] type to indicate the overall system health.
If you want to monitor or alert on levels of health for a particular application, you can export these statuses as metrics with Micrometer.
By default, the status codes "`UP`", "`DOWN`", "`OUT_OF_SERVICE`" and "`UNKNOWN`" are used by Spring Boot.
To export these, you will need to convert these states to some set of numbers so that they can be used with a Micrometer `Gauge`.
To export these, you will need to convert these states to some set of numbers so that they can be used with a Micrometer javadoc:io.micrometer.core.instrument.Gauge[].
The following example shows one way to write such an exporter:

View File

@ -12,11 +12,11 @@ javadoc:org.springframework.boot.diagnostics.FailureAnalyzer[] is a great way to
Spring Boot provides such an analyzer for application-context-related exceptions, JSR-303 validations, and more.
You can also create your own.
`AbstractFailureAnalyzer` is a convenient extension of `FailureAnalyzer` that checks the presence of a specified exception type in the exception to handle.
javadoc:org.springframework.boot.diagnostics.AbstractFailureAnalyzer[] is a convenient extension of javadoc:org.springframework.boot.diagnostics.FailureAnalyzer[] that checks the presence of a specified exception type in the exception to handle.
You can extend from that so that your implementation gets a chance to handle the exception only when it is actually present.
If, for whatever reason, you cannot handle the exception, return `null` to give another implementation a chance to handle the exception.
`FailureAnalyzer` implementations must be registered in `META-INF/spring.factories`.
javadoc:org.springframework.boot.diagnostics.FailureAnalyzer[] implementations must be registered in `META-INF/spring.factories`.
The following example registers `+ProjectConstraintViolationFailureAnalyzer+`:
[source,properties]
@ -25,7 +25,7 @@ org.springframework.boot.diagnostics.FailureAnalyzer=\
com.example.ProjectConstraintViolationFailureAnalyzer
----
NOTE: If you need access to the `BeanFactory` or the `Environment`, declare them as constructor arguments in your `FailureAnalyzer` implementation.
NOTE: If you need access to the javadoc:org.springframework.beans.factory.BeanFactory[] or the javadoc:org.springframework.core.env.Environment[], declare them as constructor arguments in your javadoc:org.springframework.boot.diagnostics.FailureAnalyzer[] implementation.
@ -34,7 +34,7 @@ NOTE: If you need access to the `BeanFactory` or the `Environment`, declare them
The Spring Boot auto-configuration tries its best to "`do the right thing`", but sometimes things fail, and it can be hard to tell why.
There is a really useful `ConditionEvaluationReport` available in any Spring Boot `ApplicationContext`.
There is a really useful javadoc:org.springframework.boot.autoconfigure.condition.ConditionEvaluationReport[] available in any Spring Boot javadoc:org.springframework.context.ApplicationContext[].
You can see it if you enable `DEBUG` logging output.
If you use the `spring-boot-actuator` (see the xref:actuator.adoc[] section), there is also a `conditions` endpoint that renders the report in JSON.
Use that endpoint to debug the application and see what features have been added (and which have not been added) by Spring Boot at runtime.
@ -46,31 +46,31 @@ When reading the code, remember the following rules of thumb:
Pay special attention to the `+@Conditional*+` annotations to find out what features they enable and when.
Add `--debug` to the command line or the System property `-Ddebug` to get a log on the console of all the auto-configuration decisions that were made in your app.
In a running application with actuator enabled, look at the `conditions` endpoint (`/actuator/conditions` or the JMX equivalent) for the same information.
* Look for classes that are `@ConfigurationProperties` (such as javadoc:org.springframework.boot.autoconfigure.web.ServerProperties[]) and read from there the available external configuration options.
The `@ConfigurationProperties` annotation has a `name` attribute that acts as a prefix to external properties.
Thus, `ServerProperties` has `prefix="server"` and its configuration properties are `server.port`, `server.address`, and others.
* Look for classes that are javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] (such as javadoc:org.springframework.boot.autoconfigure.web.ServerProperties[]) and read from there the available external configuration options.
The javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] annotation has a `name` attribute that acts as a prefix to external properties.
Thus, javadoc:org.springframework.boot.autoconfigure.web.ServerProperties[] has `prefix="server"` and its configuration properties are `server.port`, `server.address`, and others.
In a running application with actuator enabled, look at the `configprops` endpoint.
* Look for uses of the `bind` method on the `Binder` to pull configuration values explicitly out of the `Environment` in a relaxed manner.
* Look for uses of the `bind` method on the javadoc:org.springframework.boot.context.properties.bind.Binder[] to pull configuration values explicitly out of the javadoc:org.springframework.core.env.Environment[] in a relaxed manner.
It is often used with a prefix.
* Look for `@Value` annotations that bind directly to the `Environment`.
* Look for `@ConditionalOnExpression` annotations that switch features on and off in response to SpEL expressions, normally evaluated with placeholders resolved from the `Environment`.
* Look for javadoc:org.springframework.beans.factory.annotation.Value[format=annotation] annotations that bind directly to the javadoc:org.springframework.core.env.Environment[].
* Look for javadoc:org.springframework.boot.autoconfigure.condition.ConditionalOnExpression[format=annotation] annotations that switch features on and off in response to SpEL expressions, normally evaluated with placeholders resolved from the javadoc:org.springframework.core.env.Environment[].
[[howto.application.customize-the-environment-or-application-context]]
== Customize the Environment or ApplicationContext Before It Starts
A `SpringApplication` has `ApplicationListener` and `ApplicationContextInitializer` implementations that are used to apply customizations to the context or environment.
A javadoc:org.springframework.boot.SpringApplication[] has javadoc:org.springframework.context.ApplicationListener[] and javadoc:org.springframework.context.ApplicationContextInitializer[] implementations that are used to apply customizations to the context or environment.
Spring Boot loads a number of such customizations for use internally from `META-INF/spring.factories`.
There is more than one way to register additional customizations:
* Programmatically, per application, by calling the `addListeners` and `addInitializers` methods on `SpringApplication` before you run it.
* Programmatically, per application, by calling the `addListeners` and `addInitializers` methods on javadoc:org.springframework.boot.SpringApplication[] before you run it.
* Declaratively, for all applications, by adding a `META-INF/spring.factories` and packaging a jar file that the applications all use as a library.
The `SpringApplication` sends some special `ApplicationEvents` to the listeners (some even before the context is created) and then registers the listeners for events published by the `ApplicationContext` as well.
The javadoc:org.springframework.boot.SpringApplication[] sends some special javadoc:org.springframework.test.context.event.ApplicationEvents[] to the listeners (some even before the context is created) and then registers the listeners for events published by the javadoc:org.springframework.context.ApplicationContext[] as well.
See xref:reference:features/spring-application.adoc#features.spring-application.application-events-and-listeners[] in the "`Spring Boot Features`" section for a complete list.
It is also possible to customize the `Environment` before the application context is refreshed by using `EnvironmentPostProcessor`.
It is also possible to customize the javadoc:org.springframework.core.env.Environment[] before the application context is refreshed by using javadoc:org.springframework.boot.env.EnvironmentPostProcessor[].
Each implementation should be registered in `META-INF/spring.factories`, as shown in the following example:
[source]
@ -78,18 +78,18 @@ Each implementation should be registered in `META-INF/spring.factories`, as show
org.springframework.boot.env.EnvironmentPostProcessor=com.example.YourEnvironmentPostProcessor
----
The implementation can load arbitrary files and add them to the `Environment`.
The implementation can load arbitrary files and add them to the javadoc:org.springframework.core.env.Environment[].
For instance, the following example loads a YAML configuration file from the classpath:
include-code::MyEnvironmentPostProcessor[]
TIP: The `Environment` has already been prepared with all the usual property sources that Spring Boot loads by default.
TIP: The javadoc:org.springframework.core.env.Environment[] has already been prepared with all the usual property sources that Spring Boot loads by default.
It is therefore possible to get the location of the file from the environment.
The preceding example adds the `custom-resource` property source at the end of the list so that a key defined in any of the usual other locations takes precedence.
A custom implementation may define another order.
CAUTION: While using `@PropertySource` on your `@SpringBootApplication` may seem to be a convenient way to load a custom resource in the `Environment`, we do not recommend it.
Such property sources are not added to the `Environment` until the application context is being refreshed.
CAUTION: While using javadoc:org.springframework.context.annotation.PropertySource[format=annotation] on your javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation] may seem to be a convenient way to load a custom resource in the javadoc:org.springframework.core.env.Environment[], we do not recommend it.
Such property sources are not added to the javadoc:org.springframework.core.env.Environment[] until the application context is being refreshed.
This is too late to configure certain properties such as `+logging.*+` and `+spring.main.*+` which are read before refresh begins.
@ -97,7 +97,7 @@ This is too late to configure certain properties such as `+logging.*+` and `+spr
[[howto.application.context-hierarchy]]
== Build an ApplicationContext Hierarchy (Adding a Parent or Root Context)
You can use the `SpringApplicationBuilder` class to create parent/child `ApplicationContext` hierarchies.
You can use the javadoc:org.springframework.boot.builder.SpringApplicationBuilder[] class to create parent/child javadoc:org.springframework.context.ApplicationContext[] hierarchies.
See xref:reference:features/spring-application.adoc#features.spring-application.fluent-builder-api[] in the "`Spring Boot Features`" section for more information.
@ -106,8 +106,8 @@ See xref:reference:features/spring-application.adoc#features.spring-application.
== Create a Non-web Application
Not all Spring applications have to be web applications (or web services).
If you want to execute some code in a `main` method but also bootstrap a Spring application to set up the infrastructure to use, you can use the `SpringApplication` features of Spring Boot.
A `SpringApplication` changes its `ApplicationContext` class, depending on whether it thinks it needs a web application or not.
If you want to execute some code in a `main` method but also bootstrap a Spring application to set up the infrastructure to use, you can use the javadoc:org.springframework.boot.SpringApplication[] features of Spring Boot.
A javadoc:org.springframework.boot.SpringApplication[] changes its javadoc:org.springframework.context.ApplicationContext[] class, depending on whether it thinks it needs a web application or not.
The first thing you can do to help it is to leave server-related dependencies (such as the servlet API) off the classpath.
If you cannot do that (for example, if you run two applications from the same code base) then you can explicitly call `setWebApplicationType(WebApplicationType.NONE)` on your `SpringApplication` instance or set the `applicationContextClass` property (through the Java API or with external properties).
Application code that you want to run as your business logic can be implemented as a `CommandLineRunner` and dropped into the context as a `@Bean` definition.
If you cannot do that (for example, if you run two applications from the same code base) then you can explicitly call `setWebApplicationType(WebApplicationType.NONE)` on your javadoc:org.springframework.boot.SpringApplication[] instance or set the `applicationContextClass` property (through the Java API or with external properties).
Application code that you want to run as your business logic can be implemented as a javadoc:org.springframework.boot.CommandLineRunner[] and dropped into the context as a javadoc:org.springframework.context.annotation.Bean[format=annotation] definition.

View File

@ -9,11 +9,11 @@ This section addresses those questions.
[[howto.batch.specifying-a-data-source]]
== Specifying a Batch Data Source
By default, batch applications require a `DataSource` to store job details.
Spring Batch expects a single `DataSource` by default.
To have it use a `DataSource` other than the applications main `DataSource`, declare a `DataSource` bean, annotating its `@Bean` method with `@BatchDataSource`.
If you do so and want two data sources (for example by retaining the main auto-configured `DataSource`), set the `defaultCandidate` attribute of the `@Bean` annotation to `false`.
To take greater control, add `@EnableBatchProcessing` to one of your `@Configuration` classes or extend `DefaultBatchConfiguration`.
By default, batch applications require a javadoc:javax.sql.DataSource[] to store job details.
Spring Batch expects a single javadoc:javax.sql.DataSource[] by default.
To have it use a javadoc:javax.sql.DataSource[] other than the applications main javadoc:javax.sql.DataSource[], declare a javadoc:javax.sql.DataSource[] bean, annotating its javadoc:org.springframework.context.annotation.Bean[format=annotation] method with javadoc:org.springframework.boot.autoconfigure.batch.BatchDataSource[format=annotation].
If you do so and want two data sources (for example by retaining the main auto-configured javadoc:javax.sql.DataSource[]), set the `defaultCandidate` attribute of the javadoc:org.springframework.context.annotation.Bean[format=annotation] annotation to `false`.
To take greater control, add javadoc:org.springframework.batch.core.configuration.annotation.EnableBatchProcessing[format=annotation] to one of your javadoc:org.springframework.context.annotation.Configuration[format=annotation] classes or extend javadoc:org.springframework.batch.core.configuration.support.DefaultBatchConfiguration[].
See the API documentation of javadoc:{url-spring-batch-javadoc}/org.springframework.batch.core.configuration.annotation.EnableBatchProcessing[format=annotation]
and javadoc:{url-spring-batch-javadoc}/org.springframework.batch.core.configuration.support.DefaultBatchConfiguration[] for more details.
@ -24,16 +24,16 @@ For more info about Spring Batch, see the {url-spring-batch-site}[Spring Batch p
[[howto.batch.specifying-a-transaction-manager]]
== Specifying a Batch Transaction Manager
Similar to xref:batch.adoc#howto.batch.specifying-a-data-source[], you can define a `PlatformTransactionManager` for use in batch processing by annotating its `@Bean` method with `@BatchTransactionManager`.
If you do so and want two transaction managers (for example by retaining the auto-configured `PlatformTransactionManager`), set the `defaultCandidate` attribute of the `@Bean` annotation to `false`.
Similar to xref:batch.adoc#howto.batch.specifying-a-data-source[], you can define a javadoc:org.springframework.transaction.PlatformTransactionManager[] for use in batch processing by annotating its javadoc:org.springframework.context.annotation.Bean[format=annotation] method with javadoc:org.springframework.boot.autoconfigure.batch.BatchTransactionManager[format=annotation].
If you do so and want two transaction managers (for example by retaining the auto-configured javadoc:org.springframework.transaction.PlatformTransactionManager[]), set the `defaultCandidate` attribute of the javadoc:org.springframework.context.annotation.Bean[format=annotation] annotation to `false`.
[[howto.batch.specifying-a-task-executor]]
== Specifying a Batch Task Executor
Similar to xref:batch.adoc#howto.batch.specifying-a-data-source[], you can define a `TaskExecutor` for use in batch processing by annotating its `@Bean` method with `@BatchTaskExecutor`.
If you do so and want two task executors (for example by retaining the auto-configured `TaskExecutor`), set the `defaultCandidate` attribute of the `@Bean` annotation to `false`.
Similar to xref:batch.adoc#howto.batch.specifying-a-data-source[], you can define a javadoc:org.springframework.core.task.TaskExecutor[] for use in batch processing by annotating its javadoc:org.springframework.context.annotation.Bean[format=annotation] method with javadoc:org.springframework.boot.autoconfigure.batch.BatchTaskExecutor[format=annotation].
If you do so and want two task executors (for example by retaining the auto-configured javadoc:org.springframework.core.task.TaskExecutor[]), set the `defaultCandidate` attribute of the javadoc:org.springframework.context.annotation.Bean[format=annotation] annotation to `false`.
@ -42,10 +42,10 @@ If you do so and want two task executors (for example by retaining the auto-conf
Spring Batch auto-configuration is enabled by adding `spring-boot-starter-batch` to your application's classpath.
If a single `org.springframework.batch.core.Job` bean is found in the application context, it is executed on startup (see javadoc:org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner[] for details).
If multiple `org.springframework.batch.core.Job` beans are found, the job that should be executed must be specified using configprop:spring.batch.job.name[].
If a single javadoc:org.springframework.batch.core.Job[] bean is found in the application context, it is executed on startup (see javadoc:org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner[] for details).
If multiple javadoc:org.springframework.batch.core.Job[] beans are found, the job that should be executed must be specified using configprop:spring.batch.job.name[].
To disable running a `org.springframework.batch.core.Job` found in the application context, set the configprop:spring.batch.job.enabled[] to `false`.
To disable running a javadoc:org.springframework.batch.core.Job[] found in the application context, set the configprop:spring.batch.job.enabled[] to `false`.
See {code-spring-boot-autoconfigure-src}/batch/BatchAutoConfiguration.java[`BatchAutoConfiguration`] for more details.
@ -54,7 +54,7 @@ See {code-spring-boot-autoconfigure-src}/batch/BatchAutoConfiguration.java[`Batc
[[howto.batch.running-from-the-command-line]]
== Running From the Command Line
Spring Boot converts any command line argument starting with `--` to a property to add to the `Environment`, see xref:reference:features/external-config.adoc#features.external-config.command-line-args[accessing command line properties].
Spring Boot converts any command line argument starting with `--` to a property to add to the javadoc:org.springframework.core.env.Environment[], see xref:reference:features/external-config.adoc#features.external-config.command-line-args[accessing command line properties].
This should not be used to pass arguments to batch jobs.
To specify batch arguments on the command line, use the regular format (that is without `--`), as shown in the following example:
@ -63,7 +63,7 @@ To specify batch arguments on the command line, use the regular format (that is
$ java -jar myapp.jar someParameter=someValue anotherParameter=anotherValue
----
If you specify a property of the `Environment` on the command line, it is ignored by the job.
If you specify a property of the javadoc:org.springframework.core.env.Environment[] on the command line, it is ignored by the job.
Consider the following command:
[source,shell]
@ -78,17 +78,17 @@ This provides only one argument to the batch job: `someParameter=someValue`.
[[howto.batch.restarting-a-failed-job]]
== Restarting a Stopped or Failed Job
To restart a failed `org.springframework.batch.core.Job`, all parameters (identifying and non-identifying) must be re-specified on the command line.
To restart a failed javadoc:org.springframework.batch.core.Job[], all parameters (identifying and non-identifying) must be re-specified on the command line.
Non-identifying parameters are *not* copied from the previous execution.
This allows them to be modified or removed.
NOTE: When you're using a custom `JobParametersIncrementer`, you have to gather all parameters managed by the incrementer to restart a failed execution.
NOTE: When you're using a custom javadoc:org.springframework.batch.core.JobParametersIncrementer[], you have to gather all parameters managed by the incrementer to restart a failed execution.
[[howto.batch.storing-job-repository]]
== Storing the Job Repository
Spring Batch requires a data store for the `org.springframework.batch.core.Job` repository.
Spring Batch requires a data store for the javadoc:org.springframework.batch.core.Job[] repository.
If you use Spring Boot, you must use an actual database.
Note that it can be an in-memory database, see {url-spring-batch-docs}/job.html#configuringJobRepository[Configuring a Job Repository].

View File

@ -11,7 +11,7 @@ This section answers common questions about these plugins.
Both the Maven plugin and the Gradle plugin allow generating build information containing the coordinates, name, and version of the project.
The plugins can also be configured to add additional properties through configuration.
When such a file is present, Spring Boot auto-configures a `BuildProperties` bean.
When such a file is present, Spring Boot auto-configures a javadoc:org.springframework.boot.info.BuildProperties[] bean.
To generate build information with Maven, add an execution for the `build-info` goal, as shown in the following example:
@ -83,7 +83,7 @@ Both the Maven and Gradle plugins allow the properties that are included in `git
TIP: The commit time in `git.properties` is expected to match the following format: `yyyy-MM-dd'T'HH:mm:ssZ`.
This is the default format for both plugins listed above.
Using this format lets the time be parsed into a `java.util.Date` and its format, when serialized to JSON, to be controlled by Jackson's date serialization configuration settings.
Using this format lets the time be parsed into a javadoc:java.util.Date[] and its format, when serialized to JSON, to be controlled by Jackson's date serialization configuration settings.
@ -309,7 +309,7 @@ To make it executable, you can either use the `spring-boot-antlib` module or you
. Add the `provided` (embedded container) dependencies in a nested `BOOT-INF/lib` directory for a jar or `WEB-INF/lib-provided` for a war.
Remember *not* to compress the entries in the archive.
. Add the `spring-boot-loader` classes at the root of the archive (so that the `Main-Class` is available).
. Use the appropriate launcher (such as `JarLauncher` for a jar file) as a `Main-Class` attribute in the manifest and specify the other properties it needs as manifest entries -- principally, by setting a `Start-Class` property.
. Use the appropriate launcher (such as javadoc:org.springframework.boot.loader.launch.JarLauncher[] for a jar file) as a `Main-Class` attribute in the manifest and specify the other properties it needs as manifest entries -- principally, by setting a `Start-Class` property.
The following example shows how to build an executable archive with Ant:

View File

@ -9,9 +9,9 @@ This section answers questions related to doing so.
[[howto.data-access.configure-custom-datasource]]
== Configure a Custom DataSource
To configure your own `DataSource`, define a `@Bean` of that type in your configuration.
Spring Boot reuses your `DataSource` anywhere one is required, including database initialization.
If you need to externalize some settings, you can bind your `DataSource` to the environment (see xref:reference:features/external-config.adoc#features.external-config.typesafe-configuration-properties.third-party-configuration[]).
To configure your own javadoc:javax.sql.DataSource[], define a javadoc:org.springframework.context.annotation.Bean[format=annotation] of that type in your configuration.
Spring Boot reuses your javadoc:javax.sql.DataSource[] anywhere one is required, including database initialization.
If you need to externalize some settings, you can bind your javadoc:javax.sql.DataSource[] to the environment (see xref:reference:features/external-config.adoc#features.external-config.typesafe-configuration-properties.third-party-configuration[]).
The following example shows how to define a data source in a bean:
@ -28,17 +28,17 @@ app:
pool-size: 30
----
Assuming that `+SomeDataSource+` has regular JavaBean properties for the URL, the username, and the pool size, these settings are bound automatically before the `DataSource` is made available to other components.
Assuming that `+SomeDataSource+` has regular JavaBean properties for the URL, the username, and the pool size, these settings are bound automatically before the javadoc:javax.sql.DataSource[] is made available to other components.
Spring Boot also provides a utility builder class, called `DataSourceBuilder`, that can be used to create one of the standard data sources (if it is on the classpath).
Spring Boot also provides a utility builder class, called javadoc:org.springframework.boot.jdbc.DataSourceBuilder[], that can be used to create one of the standard data sources (if it is on the classpath).
The builder can detect which one to use based on what is available on the classpath.
It also auto-detects the driver based on the JDBC URL.
The following example shows how to create a data source by using a `DataSourceBuilder`:
The following example shows how to create a data source by using a javadoc:org.springframework.boot.jdbc.DataSourceBuilder[]:
include-code::builder/MyDataSourceConfiguration[]
To run an app with that `DataSource`, all you need is the connection information.
To run an app with that javadoc:javax.sql.DataSource[], all you need is the connection information.
Pool-specific settings can also be provided.
Check the implementation that is going to be used at runtime for more details.
@ -54,10 +54,10 @@ app:
pool-size: 30
----
However, there is a catch due to the method's `DataSource` return type.
This hides the actual type of the connection pool so no configuration property metadata is generated for your custom `DataSource` and no auto-completion is available in your IDE.
To address this problem, use the builder's `type(Class)` method to specify the type of `DataSource` to be built and update the method's return type.
For example, the following shows how to create a `HikariDataSource` with `DataSourceBuilder`:
However, there is a catch due to the method's javadoc:javax.sql.DataSource[] return type.
This hides the actual type of the connection pool so no configuration property metadata is generated for your custom javadoc:javax.sql.DataSource[] and no auto-completion is available in your IDE.
To address this problem, use the builder's `type(Class)` method to specify the type of javadoc:javax.sql.DataSource[] to be built and update the method's return type.
For example, the following shows how to create a javadoc:com.zaxxer.hikari.HikariDataSource[] with javadoc:org.springframework.boot.jdbc.DataSourceBuilder[]:
include-code::simple/MyDataSourceConfiguration[]
@ -74,15 +74,15 @@ app:
pool-size: 30
----
To address this problem, make use of `DataSourceProperties` which will handle the `url` to `jdbc-url` translation for you.
You can initialize a `DataSourceBuilder` from the state of any `DataSourceProperties` object using its `initializeDataSourceBuilder()` method.
You could inject the `DataSourceProperties` that Spring Boot creates automatically, however, that would split your configuration across `+spring.datasource.*+` and `+app.datasource.*+`.
To avoid this, define a custom `DataSourceProperties` with a custom configuration properties prefix, as shown in the following example:
To address this problem, make use of javadoc:org.springframework.boot.autoconfigure.jdbc.DataSourceProperties[] which will handle the `url` to `jdbc-url` translation for you.
You can initialize a javadoc:org.springframework.boot.jdbc.DataSourceBuilder[] from the state of any javadoc:org.springframework.boot.autoconfigure.jdbc.DataSourceProperties[] object using its `initializeDataSourceBuilder()` method.
You could inject the javadoc:org.springframework.boot.autoconfigure.jdbc.DataSourceProperties[] that Spring Boot creates automatically, however, that would split your configuration across `+spring.datasource.*+` and `+app.datasource.*+`.
To avoid this, define a custom javadoc:org.springframework.boot.autoconfigure.jdbc.DataSourceProperties[] with a custom configuration properties prefix, as shown in the following example:
include-code::configurable/MyDataSourceConfiguration[]
This setup is equivalent to what Spring Boot does for you by default, except that the pool's type is specified in code and its settings are exposed as `app.datasource.configuration.*` properties.
`DataSourceProperties` takes care of the `url` to `jdbc-url` translation, so you can configure it as follows:
javadoc:org.springframework.boot.autoconfigure.jdbc.DataSourceProperties[] takes care of the `url` to `jdbc-url` translation, so you can configure it as follows:
[configprops%novalidate,yaml]
----
@ -97,8 +97,8 @@ app:
Note that, as the custom configuration specifies in code that Hikari should be used, `app.datasource.type` will have no effect.
As described in xref:reference:data/sql.adoc#data.sql.datasource.connection-pool[], `DataSourceBuilder` supports several different connection pools.
To use a pool other than Hikari, add it to the classpath, use the `type(Class)` method to specify the pool class to use, and update the `@Bean` method's return type to match.
As described in xref:reference:data/sql.adoc#data.sql.datasource.connection-pool[], javadoc:org.springframework.boot.jdbc.DataSourceBuilder[] supports several different connection pools.
To use a pool other than Hikari, add it to the classpath, use the `type(Class)` method to specify the pool class to use, and update the javadoc:org.springframework.context.annotation.Bean[format=annotation] method's return type to match.
This will also provide you with configuration property metadata for the specific connection pool that you've chosen.
TIP: Spring Boot will expose Hikari-specific settings to `spring.datasource.hikari`.
@ -111,17 +111,17 @@ See xref:reference:data/sql.adoc#data.sql.datasource[] and the {code-spring-boot
[[howto.data-access.configure-two-datasources]]
== Configure Two DataSources
To define an additional `DataSource`, an approach that's similar to the previous section can be used.
A key difference is that the `DataSource` `@Bean` must be declared with `defaultCandidate=false`.
This prevents the auto-configured `DataSource` from backing off.
To define an additional javadoc:javax.sql.DataSource[], an approach that's similar to the previous section can be used.
A key difference is that the javadoc:javax.sql.DataSource[] javadoc:org.springframework.context.annotation.Bean[format=annotation] must be declared with `defaultCandidate=false`.
This prevents the auto-configured javadoc:javax.sql.DataSource[] from backing off.
NOTE: The {url-spring-framework-docs}/core/beans/dependencies/factory-autowire.html#beans-factory-autowire-candidate[Spring Framework reference documentation] describes this feature in more details.
To allow the additional `DataSource` to be injected where it's needed, also annotate it with `@Qualifier` as shown in the following example:
To allow the additional javadoc:javax.sql.DataSource[] to be injected where it's needed, also annotate it with javadoc:org.springframework.beans.factory.annotation.Qualifier[format=annotation] as shown in the following example:
include-code::MyAdditionalDataSourceConfiguration[]
To consume the additional `DataSource`, annotate the injection point with the same `@Qualifier`.
To consume the additional javadoc:javax.sql.DataSource[], annotate the injection point with the same javadoc:org.springframework.beans.factory.annotation.Qualifier[format=annotation].
The auto-configured and additional data sources can be configured as follows:
@ -142,15 +142,15 @@ app:
max-total: 30
----
More advanced, implementation-specific, configuration of the auto-configured `DataSource` is available through the `spring.datasource.configuration.*` properties.
You can apply the same concept to the additional `DataSource` as well, as shown in the following example:
More advanced, implementation-specific, configuration of the auto-configured javadoc:javax.sql.DataSource[] is available through the `spring.datasource.configuration.*` properties.
You can apply the same concept to the additional javadoc:javax.sql.DataSource[] as well, as shown in the following example:
include-code::MyCompleteAdditionalDataSourceConfiguration[]
The preceding example configures the additional data source with the same logic as Spring Boot would use in auto-configuration.
Note that the `app.datasource.configuration.*` properties provide advanced settings based on the chosen implementation.
As with xref:how-to:data-access.adoc#howto.data-access.configure-custom-datasource[configuring a single custom `DataSource`], the type of one or both of the `DataSource` beans can be customized using the `type(Class)` method on `DataSourceBuilder`.
As with xref:how-to:data-access.adoc#howto.data-access.configure-custom-datasource[configuring a single custom javadoc:javax.sql.DataSource[]], the type of one or both of the javadoc:javax.sql.DataSource[] beans can be customized using the `type(Class)` method on javadoc:org.springframework.boot.jdbc.DataSourceBuilder[].
See xref:reference:data/sql.adoc#data.sql.datasource.connection-pool[] for details of the supported types.
@ -158,14 +158,14 @@ See xref:reference:data/sql.adoc#data.sql.datasource.connection-pool[] for detai
[[howto.data-access.spring-data-repositories]]
== Use Spring Data Repositories
Spring Data can create implementations of `org.springframework.data.repository.Repository` interfaces of various flavors.
Spring Boot handles all of that for you, as long as those `org.springframework.data.repository.Repository` implementations are included in one of the xref:reference:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages], typically the package (or a sub-package) of your main application class that is annotated with `@SpringBootApplication` or `@EnableAutoConfiguration`.
Spring Data can create implementations of javadoc:org.springframework.data.repository.Repository[] interfaces of various flavors.
Spring Boot handles all of that for you, as long as those javadoc:org.springframework.data.repository.Repository[] implementations are included in one of the xref:reference:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages], typically the package (or a sub-package) of your main application class that is annotated with javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation] or javadoc:org.springframework.boot.autoconfigure.EnableAutoConfiguration[format=annotation].
For many applications, all you need is to put the right Spring Data dependencies on your classpath.
There is a `spring-boot-starter-data-jpa` for JPA, `spring-boot-starter-data-mongodb` for Mongodb, and various other starters for supported technologies.
To get started, create some repository interfaces to handle your `@Entity` objects.
To get started, create some repository interfaces to handle your javadoc:jakarta.persistence.Entity[format=annotation] objects.
Spring Boot determines the location of your `org.springframework.data.repository.Repository` implementations by scanning the xref:reference:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages].
Spring Boot determines the location of your javadoc:org.springframework.data.repository.Repository[] implementations by scanning the xref:reference:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages].
For more control, use the `@Enable…Repositories` annotations from Spring Data.
For more about Spring Data, see the {url-spring-data-site}[Spring Data project page].
@ -175,8 +175,8 @@ For more about Spring Data, see the {url-spring-data-site}[Spring Data project p
[[howto.data-access.separate-entity-definitions-from-spring-configuration]]
== Separate @Entity Definitions from Spring Configuration
Spring Boot determines the location of your `@Entity` definitions by scanning the xref:reference:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages].
For more control, use the `@EntityScan` annotation, as shown in the following example:
Spring Boot determines the location of your javadoc:jakarta.persistence.Entity[format=annotation] definitions by scanning the xref:reference:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages].
For more control, use the javadoc:org.springframework.boot.autoconfigure.domain.EntityScan[format=annotation] annotation, as shown in the following example:
include-code::MyApplication[]
@ -185,7 +185,7 @@ include-code::MyApplication[]
[[howto.data-access.filter-scanned-entity-definitions]]
== Filter Scanned @Entity Definitions
It is possible to filter the `@Entity` definitions using a `ManagedClassNameFilter` bean.
It is possible to filter the javadoc:jakarta.persistence.Entity[format=annotation] definitions using a javadoc:org.springframework.orm.jpa.persistenceunit.ManagedClassNameFilter[] bean.
This can be useful in tests when only a sub-set of the available entities should be considered.
In the following example, only entities from the `com.example.app.customer` package are included:
@ -200,7 +200,7 @@ Spring Data JPA already provides some vendor-independent configuration options (
Some of them are automatically detected according to the context so you should not have to set them.
The `spring.jpa.hibernate.ddl-auto` is a special case, because, depending on runtime conditions, it has different defaults.
If an embedded database is used and no schema manager (such as Liquibase or Flyway) is handling the `DataSource`, it defaults to `create-drop`.
If an embedded database is used and no schema manager (such as Liquibase or Flyway) is handling the javadoc:javax.sql.DataSource[], it defaults to `create-drop`.
In all other cases, it defaults to `none`.
The dialect to use is detected by the JPA provider.
@ -218,7 +218,7 @@ spring:
show-sql: true
----
In addition, all properties in `+spring.jpa.properties.*+` are passed through as normal JPA properties (with the prefix stripped) when the local `EntityManagerFactory` is created.
In addition, all properties in `+spring.jpa.properties.*+` are passed through as normal JPA properties (with the prefix stripped) when the local javadoc:jakarta.persistence.EntityManagerFactory[] is created.
[WARNING]
====
@ -229,7 +229,7 @@ For example, if you want to configure Hibernate's batch size you must use `+spri
If you use other forms, such as `batchSize` or `batch-size`, Hibernate will not apply the setting.
====
TIP: If you need to apply advanced customization to Hibernate properties, consider registering a `HibernatePropertiesCustomizer` bean that will be invoked prior to creating the `EntityManagerFactory`.
TIP: If you need to apply advanced customization to Hibernate properties, consider registering a javadoc:org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer[] bean that will be invoked prior to creating the javadoc:jakarta.persistence.EntityManagerFactory[].
This takes precedence over anything that is applied by the auto-configuration.
@ -239,13 +239,13 @@ This takes precedence over anything that is applied by the auto-configuration.
Hibernate uses {url-hibernate-userguide}#naming[two different naming strategies] to map names from the object model to the corresponding database names.
The fully qualified class name of the physical and the implicit strategy implementations can be configured by setting the `spring.jpa.hibernate.naming.physical-strategy` and `spring.jpa.hibernate.naming.implicit-strategy` properties, respectively.
Alternatively, if `ImplicitNamingStrategy` or `PhysicalNamingStrategy` beans are available in the application context, Hibernate will be automatically configured to use them.
Alternatively, if javadoc:org.hibernate.boot.model.naming.ImplicitNamingStrategy[] or javadoc:org.hibernate.boot.model.naming.PhysicalNamingStrategy[] beans are available in the application context, Hibernate will be automatically configured to use them.
By default, Spring Boot configures the physical naming strategy with `CamelCaseToUnderscoresNamingStrategy`.
By default, Spring Boot configures the physical naming strategy with javadoc:org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy[].
Using this strategy, all dots are replaced by underscores and camel casing is replaced by underscores as well.
Additionally, by default, all table names are generated in lower case.
For example, a `+TelephoneNumber+` entity is mapped to the `telephone_number` table.
If your schema requires mixed-case identifiers, define a custom `CamelCaseToUnderscoresNamingStrategy` bean, as shown in the following example:
If your schema requires mixed-case identifiers, define a custom javadoc:org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy[] bean, as shown in the following example:
include-code::spring/MyHibernateConfiguration[]
@ -275,12 +275,12 @@ Hibernate {url-hibernate-userguide}#caching[second-level cache] can be configure
Rather than configuring Hibernate to lookup the cache provider again, it is better to provide the one that is available in the context whenever possible.
To do this with JCache, first make sure that `org.hibernate.orm:hibernate-jcache` is available on the classpath.
Then, add a `HibernatePropertiesCustomizer` bean as shown in the following example:
Then, add a javadoc:org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer[] bean as shown in the following example:
include-code::MyHibernateSecondLevelCacheConfiguration[]
This customizer will configure Hibernate to use the same `org.springframework.cache.CacheManager` as the one that the application uses.
It is also possible to use separate `org.springframework.cache.CacheManager` instances.
This customizer will configure Hibernate to use the same javadoc:org.springframework.cache.CacheManager[] as the one that the application uses.
It is also possible to use separate javadoc:org.springframework.cache.CacheManager[] instances.
For details, see {url-hibernate-userguide}#caching-provider-jcache[the Hibernate user guide].
@ -288,20 +288,20 @@ For details, see {url-hibernate-userguide}#caching-provider-jcache[the Hibernate
[[howto.data-access.dependency-injection-in-hibernate-components]]
== Use Dependency Injection in Hibernate Components
By default, Spring Boot registers a `org.hibernate.resource.beans.container.spi.BeanContainer` implementation that uses the `BeanFactory` so that converters and entity listeners can use regular dependency injection.
By default, Spring Boot registers a javadoc:org.hibernate.resource.beans.container.spi.BeanContainer[] implementation that uses the javadoc:org.springframework.beans.factory.BeanFactory[] so that converters and entity listeners can use regular dependency injection.
You can disable or tune this behavior by registering a `HibernatePropertiesCustomizer` that removes or changes the `hibernate.resource.beans.container` property.
You can disable or tune this behavior by registering a javadoc:org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer[] that removes or changes the `hibernate.resource.beans.container` property.
[[howto.data-access.use-custom-entity-manager]]
== Use a Custom EntityManagerFactory
To take full control of the configuration of the `EntityManagerFactory`, you need to add a `@Bean` named '`entityManagerFactory`'.
To take full control of the configuration of the javadoc:jakarta.persistence.EntityManagerFactory[], you need to add a javadoc:org.springframework.context.annotation.Bean[format=annotation] named '`entityManagerFactory`'.
Spring Boot auto-configuration switches off its entity manager in the presence of a bean of that type.
NOTE: When you create a bean for `LocalContainerEntityManagerFactoryBean` yourself, any customization that was applied during the creation of the auto-configured `LocalContainerEntityManagerFactoryBean` is lost.
Make sure to use the auto-configured `org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder` to retain JPA and vendor properties.
NOTE: When you create a bean for javadoc:org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean[] yourself, any customization that was applied during the creation of the auto-configured javadoc:org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean[] is lost.
Make sure to use the auto-configured javadoc:org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder[] to retain JPA and vendor properties.
This is particularly important if you were relying on `spring.jpa.*` properties for configuring things like the naming strategy or the DDL mode.
@ -309,14 +309,14 @@ This is particularly important if you were relying on `spring.jpa.*` properties
[[howto.data-access.use-multiple-entity-managers]]
== Using Multiple EntityManagerFactories
If you need to use JPA against multiple datasources, you likely need one `EntityManagerFactory` per datasource.
The `LocalContainerEntityManagerFactoryBean` from Spring ORM allows you to configure an `EntityManagerFactory` for your needs.
You can also reuse `JpaProperties` to bind settings for a second `EntityManagerFactory`.
Building upon xref:how-to:data-access.adoc#howto.data-access.configure-two-datasources[the example for configuring a second `DataSource`], a second `EntityManagerFactory` can be defined as shown in the following example:
If you need to use JPA against multiple datasources, you likely need one javadoc:jakarta.persistence.EntityManagerFactory[] per datasource.
The javadoc:org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean[] from Spring ORM allows you to configure an javadoc:jakarta.persistence.EntityManagerFactory[] for your needs.
You can also reuse javadoc:org.springframework.boot.autoconfigure.orm.jpa.JpaProperties[] to bind settings for a second javadoc:jakarta.persistence.EntityManagerFactory[].
Building upon xref:how-to:data-access.adoc#howto.data-access.configure-two-datasources[the example for configuring a second javadoc:javax.sql.DataSource[]], a second javadoc:jakarta.persistence.EntityManagerFactory[] can be defined as shown in the following example:
include-code::MyAdditionalEntityManagerFactoryConfiguration[]
The example above creates an `EntityManagerFactory` using the `DataSource` bean qualified with `@Qualifier("second")`.
The example above creates an javadoc:jakarta.persistence.EntityManagerFactory[] using the javadoc:javax.sql.DataSource[] bean qualified with `@Qualifier("second")`.
It scans entities located in the same package as `+Order+`.
It is possible to map additional JPA properties using the `+app.jpa+` namespace.
The use of `@Bean(defaultCandidate=false)` allows the `secondJpaProperties` and `secondEntityManagerFactory` beans to be defined without interfering with auto-configured beans of the same type.
@ -324,10 +324,10 @@ The use of `@Bean(defaultCandidate=false)` allows the `secondJpaProperties` and
NOTE: The {url-spring-framework-docs}/core/beans/dependencies/factory-autowire.html#beans-factory-autowire-candidate[Spring Framework reference documentation] describes this feature in more details.
You should provide a similar configuration for any more additional data sources for which you need JPA access.
To complete the picture, you need to configure a `JpaTransactionManager` for each `EntityManagerFactory` as well.
To complete the picture, you need to configure a javadoc:org.springframework.orm.jpa.JpaTransactionManager[] for each javadoc:jakarta.persistence.EntityManagerFactory[] as well.
Alternatively, you might be able to use a JTA transaction manager that spans both.
If you use Spring Data, you need to configure `@EnableJpaRepositories` accordingly, as shown in the following examples:
If you use Spring Data, you need to configure javadoc:org.springframework.data.jpa.repository.config.EnableJpaRepositories[format=annotation] accordingly, as shown in the following examples:
include-code::OrderConfiguration[]
@ -339,7 +339,7 @@ include-code::CustomerConfiguration[]
== Use a Traditional persistence.xml File
Spring Boot will not search for or use a `META-INF/persistence.xml` by default.
If you prefer to use a traditional `persistence.xml`, you need to define your own `@Bean` of type `LocalEntityManagerFactoryBean` (with an ID of '`entityManagerFactory`') and set the persistence unit name there.
If you prefer to use a traditional `persistence.xml`, you need to define your own javadoc:org.springframework.context.annotation.Bean[format=annotation] of type javadoc:org.springframework.orm.jpa.LocalEntityManagerFactoryBean[] (with an ID of '`entityManagerFactory`') and set the persistence unit name there.
See {code-spring-boot-autoconfigure-src}/orm/jpa/JpaBaseConfiguration.java[`JpaBaseConfiguration`] for the default settings.
@ -348,12 +348,12 @@ See {code-spring-boot-autoconfigure-src}/orm/jpa/JpaBaseConfiguration.java[`JpaB
[[howto.data-access.use-spring-data-jpa-and-mongo-repositories]]
== Use Spring Data JPA and Mongo Repositories
Spring Data JPA and Spring Data Mongo can both automatically create `org.springframework.data.repository.Repository` implementations for you.
Spring Data JPA and Spring Data Mongo can both automatically create javadoc:org.springframework.data.repository.Repository[] implementations for you.
If they are both present on the classpath, you might have to do some extra configuration to tell Spring Boot which repositories to create.
The most explicit way to do that is to use the standard Spring Data `@EnableJpaRepositories` and `@EnableMongoRepositories` annotations and provide the location of your `org.springframework.data.repository.Repository` interfaces.
The most explicit way to do that is to use the standard Spring Data javadoc:org.springframework.data.jpa.repository.config.EnableJpaRepositories[format=annotation] and javadoc:org.springframework.data.mongodb.repository.config.EnableMongoRepositories[format=annotation] annotations and provide the location of your javadoc:org.springframework.data.repository.Repository[] interfaces.
There are also flags (`+spring.data.*.repositories.enabled+` and `+spring.data.*.repositories.type+`) that you can use to switch the auto-configured repositories on and off in external configuration.
Doing so is useful, for instance, in case you want to switch off the Mongo repositories and still use the auto-configured `MongoTemplate`.
Doing so is useful, for instance, in case you want to switch off the Mongo repositories and still use the auto-configured javadoc:org.springframework.data.mongodb.core.MongoTemplate[].
The same obstacle and the same features exist for other auto-configured Spring Data repository types (Elasticsearch, Redis, and others).
To work with them, change the names of the annotations and flags accordingly.
@ -372,13 +372,13 @@ Note that if you are using Spring Data REST, you must use the properties in the
[[howto.data-access.exposing-spring-data-repositories-as-rest]]
== Expose Spring Data Repositories as REST Endpoint
Spring Data REST can expose the `org.springframework.data.repository.Repository` implementations as REST endpoints for you,
Spring Data REST can expose the javadoc:org.springframework.data.repository.Repository[] implementations as REST endpoints for you,
provided Spring MVC has been enabled for the application.
Spring Boot exposes a set of useful properties (from the `spring.data.rest` namespace) that customize the javadoc:{url-spring-data-rest-javadoc}/org.springframework.data.rest.core.config.RepositoryRestConfiguration[].
If you need to provide additional customization, you should use a javadoc:{url-spring-data-rest-javadoc}/org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer[] bean.
NOTE: If you do not specify any order on your custom `RepositoryRestConfigurer`, it runs after the one Spring Boot uses internally.
NOTE: If you do not specify any order on your custom javadoc:org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer[], it runs after the one Spring Boot uses internally.
If you need to specify an order, make sure it is higher than 0.
@ -390,8 +390,8 @@ If you want to configure a component that JPA uses, then you need to ensure that
When the component is auto-configured, Spring Boot takes care of this for you.
For example, when Flyway is auto-configured, Hibernate is configured to depend on Flyway so that Flyway has a chance to initialize the database before Hibernate tries to use it.
If you are configuring a component yourself, you can use an `EntityManagerFactoryDependsOnPostProcessor` subclass as a convenient way of setting up the necessary dependencies.
For example, if you use Hibernate Search with Elasticsearch as its index manager, any `EntityManagerFactory` beans must be configured to depend on the `elasticsearchClient` bean, as shown in the following example:
If you are configuring a component yourself, you can use an javadoc:org.springframework.boot.autoconfigure.orm.jpa.EntityManagerFactoryDependsOnPostProcessor[] subclass as a convenient way of setting up the necessary dependencies.
For example, if you use Hibernate Search with Elasticsearch as its index manager, any javadoc:jakarta.persistence.EntityManagerFactory[] beans must be configured to depend on the `elasticsearchClient` bean, as shown in the following example:
include-code::ElasticsearchEntityManagerFactoryDependsOnPostProcessor[]
@ -400,7 +400,7 @@ include-code::ElasticsearchEntityManagerFactoryDependsOnPostProcessor[]
[[howto.data-access.configure-jooq-with-multiple-datasources]]
== Configure jOOQ with Two DataSources
If you need to use jOOQ with multiple data sources, you should create your own `DSLContext` for each one.
If you need to use jOOQ with multiple data sources, you should create your own javadoc:org.jooq.DSLContext[] for each one.
See {code-spring-boot-autoconfigure-src}/jooq/JooqAutoConfiguration.java[`JooqAutoConfiguration`] for more details.
TIP: In particular, `JooqExceptionTranslator` and `SpringTransactionProvider` can be reused to provide similar features to what the auto-configuration does with a single `DataSource`.
TIP: In particular, javadoc:org.springframework.boot.autoconfigure.jooq.JooqExceptionTranslator[] and javadoc:org.springframework.boot.autoconfigure.jooq.SpringTransactionProvider[] can be reused to provide similar features to what the auto-configuration does with a single javadoc:javax.sql.DataSource[].

View File

@ -13,7 +13,7 @@ It is recommended to use a single mechanism for schema generation.
You can set configprop:spring.jpa.hibernate.ddl-auto[] to control Hibernate's database initialization.
Supported values are `none`, `validate`, `update`, `create`, and `create-drop`.
Spring Boot chooses a default value for you based on whether you are using an embedded database.
An embedded database is identified by looking at the `java.sql.Connection` type and JDBC url.
An embedded database is identified by looking at the javadoc:java.sql.Connection[] type and JDBC url.
`hsqldb`, `h2`, or `derby` are embedded databases and others are not.
If an embedded database is identified and no schema manager (Flyway or Liquibase) has been detected, `ddl-auto` defaults to `create-drop`.
In all other cases, it defaults to `none`.
@ -33,7 +33,7 @@ It is a Hibernate feature (and has nothing to do with Spring).
[[howto.data-initialization.using-basic-sql-scripts]]
== Initialize a Database Using Basic SQL Scripts
Spring Boot can automatically create the schema (DDL scripts) of your JDBC `DataSource` or R2DBC `io.r2dbc.spi.ConnectionFactory` and initialize its data (DML scripts).
Spring Boot can automatically create the schema (DDL scripts) of your JDBC javadoc:javax.sql.DataSource[] or R2DBC javadoc:io.r2dbc.spi.ConnectionFactory[] and initialize its data (DML scripts).
By default, it loads schema scripts from `optional:classpath*:schema.sql` and data scripts from `optional:classpath*:data.sql`.
The locations of these schema and data scripts can be customized using configprop:spring.sql.init.schema-locations[] and configprop:spring.sql.init.data-locations[] respectively.
@ -51,10 +51,10 @@ By default, Spring Boot enables the fail-fast feature of its script-based databa
This means that, if the scripts cause exceptions, the application fails to start.
You can tune that behavior by setting configprop:spring.sql.init.continue-on-error[].
Script-based `DataSource` initialization is performed, by default, before any JPA `EntityManagerFactory` beans are created.
Script-based javadoc:javax.sql.DataSource[] initialization is performed, by default, before any JPA javadoc:jakarta.persistence.EntityManagerFactory[] beans are created.
`schema.sql` can be used to create the schema for JPA-managed entities and `data.sql` can be used to populate it.
While we do not recommend using multiple data source initialization technologies, if you want script-based `DataSource` initialization to be able to build upon the schema creation performed by Hibernate, set configprop:spring.jpa.defer-datasource-initialization[] to `true`.
This will defer data source initialization until after any `EntityManagerFactory` beans have been created and initialized.
While we do not recommend using multiple data source initialization technologies, if you want script-based javadoc:javax.sql.DataSource[] initialization to be able to build upon the schema creation performed by Hibernate, set configprop:spring.jpa.defer-datasource-initialization[] to `true`.
This will defer data source initialization until after any javadoc:jakarta.persistence.EntityManagerFactory[] beans have been created and initialized.
`schema.sql` can then be used to make additions to any schema creation performed by Hibernate and `data.sql` can be used to populate it.
NOTE: The initialization scripts support `--` for single line comments and `/++*++ ++*++/` for block comments.
@ -129,25 +129,25 @@ Rather than using `db/migration`, the preceding configuration sets the directory
The list of supported databases is available in javadoc:org.springframework.boot.jdbc.DatabaseDriver[].
Migrations can also be written in Java.
Flyway will be auto-configured with any beans that implement `JavaMigration`.
Flyway will be auto-configured with any beans that implement javadoc:org.flywaydb.core.api.migration.JavaMigration[].
javadoc:org.springframework.boot.autoconfigure.flyway.FlywayProperties[] provides most of Flyway's settings and a small set of additional properties that can be used to disable the migrations or switch off the location checking.
If you need more control over the configuration, consider registering a `FlywayConfigurationCustomizer` bean.
If you need more control over the configuration, consider registering a javadoc:org.springframework.boot.autoconfigure.flyway.FlywayConfigurationCustomizer[] bean.
Spring Boot calls `Flyway.migrate()` to perform the database migration.
If you would like more control, provide a `@Bean` that implements javadoc:org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy[].
If you would like more control, provide a javadoc:org.springframework.context.annotation.Bean[format=annotation] that implements javadoc:org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy[].
Flyway supports SQL and Java https://documentation.red-gate.com/fd/callback-concept-184127466.html[callbacks].
To use SQL-based callbacks, place the callback scripts in the `classpath:db/migration` directory.
To use Java-based callbacks, create one or more beans that implement `org.flywaydb.core.api.callback.Callback`.
Any such beans are automatically registered with `Flyway`.
They can be ordered by using `@org.springframework.core.annotation.Order` or by implementing `org.springframework.core.Ordered`.
To use Java-based callbacks, create one or more beans that implement javadoc:org.flywaydb.core.api.callback.Callback[].
Any such beans are automatically registered with javadoc:org.flywaydb.core.Flyway[].
They can be ordered by using javadoc:org.springframework.core.annotation.Order[format=annotation] or by implementing javadoc:org.springframework.core.Ordered[].
By default, Flyway autowires the (`@Primary`) `DataSource` in your context and uses that for migrations.
If you like to use a different `DataSource`, you can create one and mark its `@Bean` as `@FlywayDataSource`.
If you do so and want two data sources (for example by retaining the main auto-configured `DataSource`), remember to set the `defaultCandidate` attribute of the `@Bean` annotation to `false`.
Alternatively, you can use Flyway's native `DataSource` by setting `spring.flyway.[url,user,password]` in external properties.
Setting either `spring.flyway.url` or `spring.flyway.user` is sufficient to cause Flyway to use its own `DataSource`.
By default, Flyway autowires the (`@Primary`) javadoc:javax.sql.DataSource[] in your context and uses that for migrations.
If you like to use a different javadoc:javax.sql.DataSource[], you can create one and mark its javadoc:org.springframework.context.annotation.Bean[format=annotation] as javadoc:org.springframework.boot.autoconfigure.flyway.FlywayDataSource[format=annotation].
If you do so and want two data sources (for example by retaining the main auto-configured javadoc:javax.sql.DataSource[]), remember to set the `defaultCandidate` attribute of the javadoc:org.springframework.context.annotation.Bean[format=annotation] annotation to `false`.
Alternatively, you can use Flyway's native javadoc:javax.sql.DataSource[] by setting `spring.flyway.[url,user,password]` in external properties.
Setting either `spring.flyway.url` or `spring.flyway.user` is sufficient to cause Flyway to use its own javadoc:javax.sql.DataSource[].
If any of the three properties has not been set, the value of its equivalent `spring.datasource` property will be used.
You can also use Flyway to provide data for specific scenarios.
@ -181,16 +181,16 @@ It is not possible to use two different ways to initialize the database (for exa
By default, the master change log is read from `db/changelog/db.changelog-master.yaml`, but you can change the location by setting `spring.liquibase.change-log`.
In addition to YAML, Liquibase also supports JSON, XML, and SQL change log formats.
By default, Liquibase autowires the (`@Primary`) `DataSource` in your context and uses that for migrations.
If you need to use a different `DataSource`, you can create one and mark its `@Bean` as `@LiquibaseDataSource`.
If you do so and want two data sources (for example by retaining the main auto-configured `DataSource`), remember to set the `defaultCandidate` attribute of the `@Bean` annotation to `false`.
Alternatively, you can use Liquibase's native `DataSource` by setting `spring.liquibase.[driver-class-name,url,user,password]` in external properties.
Setting either `spring.liquibase.url` or `spring.liquibase.user` is sufficient to cause Liquibase to use its own `DataSource`.
By default, Liquibase autowires the (`@Primary`) javadoc:javax.sql.DataSource[] in your context and uses that for migrations.
If you need to use a different javadoc:javax.sql.DataSource[], you can create one and mark its javadoc:org.springframework.context.annotation.Bean[format=annotation] as javadoc:org.springframework.boot.autoconfigure.liquibase.LiquibaseDataSource[format=annotation].
If you do so and want two data sources (for example by retaining the main auto-configured javadoc:javax.sql.DataSource[]), remember to set the `defaultCandidate` attribute of the javadoc:org.springframework.context.annotation.Bean[format=annotation] annotation to `false`.
Alternatively, you can use Liquibase's native javadoc:javax.sql.DataSource[] by setting `spring.liquibase.[driver-class-name,url,user,password]` in external properties.
Setting either `spring.liquibase.url` or `spring.liquibase.user` is sufficient to cause Liquibase to use its own javadoc:javax.sql.DataSource[].
If any of the three properties has not been set, the value of its equivalent `spring.datasource` property will be used.
See javadoc:org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties[] for details about available settings such as contexts, the default schema, and others.
You can also use a `Customizer<Liquibase>` bean if you want to customize the `liquibase.Liquibase` instance before it is being used.
You can also use a `Customizer<Liquibase>` bean if you want to customize the javadoc:{url-liquibase-javadoc}/liquibase.Liquibase[] instance before it is being used.
@ -241,7 +241,7 @@ It includes the production changelog and then declares a new changeset, whose `r
You can now use for example the https://docs.liquibase.com/change-types/insert.html[insert changeset] to insert data or the https://docs.liquibase.com/change-types/sql.html[sql changeset] to execute SQL directly.
The last thing to do is to configure Spring Boot to activate the `test` profile when running tests.
To do this, you can add the `@ActiveProfiles("test")` annotation to your `@SpringBootTest` annotated test classes.
To do this, you can add the `@ActiveProfiles("test")` annotation to your javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation] annotated test classes.
@ -260,15 +260,15 @@ If, during startup, your application tries to access the database and it has not
Spring Boot will automatically detect beans of the following types that initialize an SQL database:
- `DataSourceScriptDatabaseInitializer`
- `EntityManagerFactory`
- `Flyway`
- `FlywayMigrationInitializer`
- `R2dbcScriptDatabaseInitializer`
- `SpringLiquibase`
- javadoc:org.springframework.boot.jdbc.init.DataSourceScriptDatabaseInitializer[]
- javadoc:jakarta.persistence.EntityManagerFactory[]
- javadoc:org.flywaydb.core.Flyway[]
- javadoc:org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer[]
- javadoc:org.springframework.boot.r2dbc.init.R2dbcScriptDatabaseInitializer[]
- javadoc:liquibase.integration.spring.SpringLiquibase[]
If you are using a third-party starter for a database initialization library, it may provide a detector such that beans of other types are also detected automatically.
To have other beans be detected, register an implementation of `DatabaseInitializerDetector` in `META-INF/spring.factories`.
To have other beans be detected, register an implementation of javadoc:org.springframework.boot.sql.init.dependency.DatabaseInitializerDetector[] in `META-INF/spring.factories`.
@ -277,13 +277,13 @@ To have other beans be detected, register an implementation of `DatabaseInitiali
Spring Boot will automatically detect beans of the following types that depends upon database initialization:
- `AbstractEntityManagerFactoryBean` (unless configprop:spring.jpa.defer-datasource-initialization[] is set to `true`)
- `DSLContext` (jOOQ)
- `EntityManagerFactory` (unless configprop:spring.jpa.defer-datasource-initialization[] is set to `true`)
- `JdbcClient`
- `JdbcOperations`
- `NamedParameterJdbcOperations`
- javadoc:org.springframework.orm.jpa.AbstractEntityManagerFactoryBean[] (unless configprop:spring.jpa.defer-datasource-initialization[] is set to `true`)
- javadoc:org.jooq.DSLContext[] (jOOQ)
- javadoc:jakarta.persistence.EntityManagerFactory[] (unless configprop:spring.jpa.defer-datasource-initialization[] is set to `true`)
- javadoc:org.springframework.jdbc.core.simple.JdbcClient[]
- javadoc:org.springframework.jdbc.core.JdbcOperations[]
- javadoc:org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations[]
If you are using a third-party starter data access library, it may provide a detector such that beans of other types are also detected automatically.
To have other beans be detected, register an implementation of `DependsOnDatabaseInitializationDetector` in `META-INF/spring.factories`.
Alternatively, annotate the bean's class or its `@Bean` method with `@DependsOnDatabaseInitialization`.
To have other beans be detected, register an implementation of javadoc:org.springframework.boot.sql.init.dependency.DependsOnDatabaseInitializationDetector[] in `META-INF/spring.factories`.
Alternatively, annotate the bean's class or its javadoc:org.springframework.context.annotation.Bean[format=annotation] method with javadoc:org.springframework.boot.sql.init.dependency.DependsOnDatabaseInitialization[format=annotation].

View File

@ -94,7 +94,7 @@ By default, metadata about the running application as well as service connection
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:
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 javadoc:org.springframework.core.env.Environment[] abstraction, as shown in the following example:
include-code::MyBean[]
@ -161,7 +161,7 @@ The following example shows the `Procfile` for our starter REST application:
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.
Spring Boot makes `-D` arguments available as properties accessible from a Spring javadoc:org.springframework.core.env.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.

View File

@ -11,9 +11,9 @@ This section answers common questions about traditional deployment.
WARNING: Because Spring WebFlux does not strictly depend on the servlet API and applications are deployed by default on an embedded Reactor Netty server, War deployment is not supported for WebFlux applications.
The first step in producing a deployable war file is to provide a `SpringBootServletInitializer` subclass and override its `configure` method.
The first step in producing a deployable war file is to provide a javadoc:org.springframework.boot.web.servlet.support.SpringBootServletInitializer[] subclass and override its `configure` method.
Doing so makes use of Spring Framework's servlet 3.0 support and lets you configure your application when it is launched by the servlet container.
Typically, you should update your application's main class to extend `SpringBootServletInitializer`, as shown in the following example:
Typically, you should update your application's main class to extend javadoc:org.springframework.boot.web.servlet.support.SpringBootServletInitializer[], as shown in the following example:
include-code::MyApplication[]
@ -72,27 +72,27 @@ This means that, in addition to being deployable to a servlet container, you can
[[howto.traditional-deployment.convert-existing-application]]
== Convert an Existing Application to Spring Boot
To convert an existing non-web Spring application to a Spring Boot application, replace the code that creates your `ApplicationContext` and replace it with calls to `SpringApplication` or `SpringApplicationBuilder`.
To convert an existing non-web Spring application to a Spring Boot application, replace the code that creates your javadoc:org.springframework.context.ApplicationContext[] and replace it with calls to javadoc:org.springframework.boot.SpringApplication[] or javadoc:org.springframework.boot.builder.SpringApplicationBuilder[].
Spring MVC web applications are generally amenable to first creating a deployable war application and then migrating it later to an executable war or jar.
To create a deployable war by extending `SpringBootServletInitializer` (for example, in a class called `+Application+`) and adding the Spring Boot `@SpringBootApplication` annotation, use code similar to that shown in the following example:
To create a deployable war by extending javadoc:org.springframework.boot.web.servlet.support.SpringBootServletInitializer[] (for example, in a class called `+Application+`) and adding the Spring Boot javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation] annotation, use code similar to that shown in the following example:
include-code::MyApplication[tag=!main]
Remember that, whatever you put in the `sources` is merely a Spring `ApplicationContext`.
Remember that, whatever you put in the `sources` is merely a Spring javadoc:org.springframework.context.ApplicationContext[].
Normally, anything that already works should work here.
There might be some beans you can remove later and let Spring Boot provide its own defaults for them, but it should be possible to get something working before you need to do that.
Static resources can be moved to `/public` (or `/static` or `/resources` or `/META-INF/resources`) in the classpath root.
The same applies to `messages.properties` (which Spring Boot automatically detects in the root of the classpath).
Vanilla usage of Spring `DispatcherServlet` and Spring Security should require no further changes.
Vanilla usage of Spring javadoc:org.springframework.web.servlet.DispatcherServlet[] and Spring Security should require no further changes.
If you have other features in your application (for instance, using other servlets or filters), you may need to add some configuration to your `+Application+` context, by replacing those elements from the `web.xml`, as follows:
* A `@Bean` of type `Servlet` or `ServletRegistrationBean` installs that bean in the container as if it were a `<servlet/>` and `<servlet-mapping/>` in `web.xml`.
* A `@Bean` of type `Filter` or `FilterRegistrationBean` behaves similarly (as a `<filter/>` and `<filter-mapping/>`).
* An `ApplicationContext` in an XML file can be added through an `@ImportResource` in your `+Application+`.
Alternatively, cases where annotation configuration is heavily used already can be recreated in a few lines as `@Bean` definitions.
* A javadoc:org.springframework.context.annotation.Bean[format=annotation] of type javadoc:jakarta.servlet.Servlet[] or javadoc:org.springframework.boot.web.servlet.ServletRegistrationBean[] installs that bean in the container as if it were a `<servlet/>` and `<servlet-mapping/>` in `web.xml`.
* A javadoc:org.springframework.context.annotation.Bean[format=annotation] of type javadoc:jakarta.servlet.Filter[] or javadoc:org.springframework.boot.web.servlet.FilterRegistrationBean[] behaves similarly (as a `<filter/>` and `<filter-mapping/>`).
* An javadoc:org.springframework.context.ApplicationContext[] in an XML file can be added through an javadoc:org.springframework.context.annotation.ImportResource[format=annotation] in your `+Application+`.
Alternatively, cases where annotation configuration is heavily used already can be recreated in a few lines as javadoc:org.springframework.context.annotation.Bean[format=annotation] definitions.
Once the war file is working, you can make it executable by adding a `main` method to your `+Application+`, as shown in the following example:
@ -100,7 +100,7 @@ include-code::MyApplication[tag=main]
[NOTE]
====
If you intend to start your application as a war or as an executable application, you need to share the customizations of the builder in a method that is both available to the `SpringBootServletInitializer` callback and in the `main` method in a class similar to the following:
If you intend to start your application as a war or as an executable application, you need to share the customizations of the builder in a method that is both available to the javadoc:org.springframework.boot.web.servlet.support.SpringBootServletInitializer[] callback and in the `main` method in a class similar to the following:
include-code::both/MyApplication[]
====
@ -115,11 +115,11 @@ Applications can fall into more than one category:
All of these should be amenable to translation, but each might require slightly different techniques.
Servlet 3.0+ applications might translate pretty easily if they already use the Spring Servlet 3.0+ initializer support classes.
Normally, all the code from an existing `WebApplicationInitializer` can be moved into a `SpringBootServletInitializer`.
If your existing application has more than one `ApplicationContext` (for example, if it uses `AbstractDispatcherServletInitializer`) then you might be able to combine all your context sources into a single `SpringApplication`.
Normally, all the code from an existing javadoc:org.springframework.web.WebApplicationInitializer[] can be moved into a javadoc:org.springframework.boot.web.servlet.support.SpringBootServletInitializer[].
If your existing application has more than one javadoc:org.springframework.context.ApplicationContext[] (for example, if it uses javadoc:org.springframework.web.servlet.support.AbstractDispatcherServletInitializer[]) then you might be able to combine all your context sources into a single javadoc:org.springframework.boot.SpringApplication[].
The main complication you might encounter is if combining does not work and you need to maintain the context hierarchy.
See the xref:application.adoc#howto.application.context-hierarchy[entry on building a hierarchy] for examples.
An existing parent context that contains web-specific features usually needs to be broken up so that all the `ServletContextAware` components are in the child context.
An existing parent context that contains web-specific features usually needs to be broken up so that all the javadoc:org.springframework.web.context.ServletContextAware[] components are in the child context.
Applications that are not already Spring applications might be convertible to Spring Boot applications, and the previously mentioned guidance may help.
However, you may yet encounter problems.
@ -130,7 +130,7 @@ In that case, we suggest https://stackoverflow.com/questions/tagged/spring-boot[
[[howto.traditional-deployment.weblogic]]
== Deploying a WAR to WebLogic
To deploy a Spring Boot application to WebLogic, you must ensure that your servlet initializer *directly* implements `WebApplicationInitializer` (even if you extend from a base class that already implements it).
To deploy a Spring Boot application to WebLogic, you must ensure that your servlet initializer *directly* implements javadoc:org.springframework.web.WebApplicationInitializer[] (even if you extend from a base class that already implements it).
A typical initializer for WebLogic should resemble the following example:

View File

@ -8,7 +8,7 @@ This section includes topics relating to the Docker Compose support in Spring Bo
[[howto.docker-compose.jdbc-url]]
== Customizing the JDBC URL
When using `JdbcConnectionDetails` with Docker Compose, the parameters of the JDBC URL
When using javadoc:org.springframework.boot.autoconfigure.jdbc.JdbcConnectionDetails[] with Docker Compose, the parameters of the JDBC URL
can be customized by applying the `+org.springframework.boot.jdbc.parameters+` label to the
service. For example:

View File

@ -9,8 +9,8 @@ This section answers questions related to using them.
[[howto.http-clients.rest-template-proxy-configuration]]
== Configure RestTemplate to Use a Proxy
As described in xref:reference:io/rest-client.adoc#io.rest-client.resttemplate.customization[RestTemplate Customization], you can use a `RestTemplateCustomizer` with `RestTemplateBuilder` to build a customized `RestTemplate`.
This is the recommended approach for creating a `RestTemplate` configured to use a proxy.
As described in xref:reference:io/rest-client.adoc#io.rest-client.resttemplate.customization[RestTemplate Customization], you can use a javadoc:org.springframework.boot.web.client.RestTemplateCustomizer[] with javadoc:org.springframework.boot.web.client.RestTemplateBuilder[] to build a customized javadoc:org.springframework.web.client.RestTemplate[].
This is the recommended approach for creating a javadoc:org.springframework.web.client.RestTemplate[] configured to use a proxy.
The exact details of the proxy configuration depend on the underlying client request factory that is being used.
@ -19,11 +19,11 @@ The exact details of the proxy configuration depend on the underlying client req
[[howto.http-clients.webclient-reactor-netty-customization]]
== Configure the TcpClient used by a Reactor Netty-based WebClient
When Reactor Netty is on the classpath a Reactor Netty-based `WebClient` is auto-configured.
To customize the client's handling of network connections, provide a `ClientHttpConnector` bean.
The following example configures a 60 second connect timeout and adds a `io.netty.handler.timeout.ReadTimeoutHandler`:
When Reactor Netty is on the classpath a Reactor Netty-based javadoc:org.springframework.web.reactive.function.client.WebClient[] is auto-configured.
To customize the client's handling of network connections, provide a javadoc:org.springframework.http.client.reactive.ClientHttpConnector[] bean.
The following example configures a 60 second connect timeout and adds a javadoc:io.netty.handler.timeout.ReadTimeoutHandler[]:
include-code::MyReactorNettyClientConfiguration[]
TIP: Note the use of `ReactorResourceFactory` for the connection provider and event loop resources.
TIP: Note the use of javadoc:org.springframework.http.client.ReactorResourceFactory[] for the connection provider and event loop resources.
This ensures efficient sharing of resources for the server receiving requests and the client making requests.

View File

@ -10,7 +10,7 @@ Spring Security can be used to secure a Jersey-based web application in much the
However, if you want to use Spring Security's method-level security with Jersey, you must configure Jersey to use `setStatus(int)` rather `sendError(int)`.
This prevents Jersey from committing the response before Spring Security has had an opportunity to report an authentication or authorization failure to the client.
The `jersey.config.server.response.setStatusOverSendError` property must be set to `true` on the application's `org.glassfish.jersey.server.ResourceConfig` bean, as shown in the following example:
The `jersey.config.server.response.setStatusOverSendError` property must be set to `true` on the application's javadoc:org.glassfish.jersey.server.ResourceConfig[] bean, as shown in the following example:
include-code::JerseySetStatusOverSendErrorConfig[]
@ -21,6 +21,6 @@ include-code::JerseySetStatusOverSendErrorConfig[]
To use Jersey alongside another web framework, such as Spring MVC, it should be configured so that it will allow the other framework to handle requests that it cannot handle.
First, configure Jersey to use a filter rather than a servlet by configuring the configprop:spring.jersey.type[] application property with a value of `filter`.
Second, configure your `org.glassfish.jersey.server.ResourceConfig` to forward requests that would have resulted in a 404, as shown in the following example.
Second, configure your javadoc:org.glassfish.jersey.server.ResourceConfig[] to forward requests that would have resulted in a 404, as shown in the following example.
include-code::JerseyConfig[]

View File

@ -15,7 +15,7 @@ If you use Maven, the following dependency adds logging for you:
</dependency>
----
Spring Boot has a `LoggingSystem` abstraction that attempts to configure logging based on the content of the classpath.
Spring Boot has a javadoc:org.springframework.boot.logging.LoggingSystem[] abstraction that attempts to configure logging based on the content of the classpath.
If Logback is available, it is the first choice.
If the only change you need to make to logging is to set the levels of various loggers, you can do so in `application.properties` by using the "logging.level" prefix, as shown in the following example:
@ -30,7 +30,7 @@ logging:
You can also set the location of a file to which the log will be written (in addition to the console) by using `logging.file.name`.
To configure the more fine-grained settings of a logging system, you need to use the native configuration format supported by the `LoggingSystem` in question.
To configure the more fine-grained settings of a logging system, you need to use the native configuration format supported by the javadoc:org.springframework.boot.logging.LoggingSystem[] in question.
By default, Spring Boot picks up the native configuration from its default location for the system (such as `classpath:logback.xml` for Logback), but you can set the location of the config file by using the configprop:logging.config[] property.
@ -50,10 +50,10 @@ These includes are designed to allow certain common Spring Boot conventions to b
The following files are provided under `org/springframework/boot/logging/logback/`:
* `defaults.xml` - Provides conversion rules, pattern properties and common logger configurations.
* `console-appender.xml` - Adds a `ch.qos.logback.core.ConsoleAppender` using the `CONSOLE_LOG_PATTERN`.
* `structured-console-appender.xml` - Adds a `ch.qos.logback.core.ConsoleAppender` using structured logging in the `CONSOLE_LOG_STRUCTURED_FORMAT`.
* `file-appender.xml` - Adds a `ch.qos.logback.core.rolling.RollingFileAppender` using the `FILE_LOG_PATTERN` and `ROLLING_FILE_NAME_PATTERN` with appropriate settings.
* `structured-file-appender.xml` - Adds a `ch.qos.logback.core.rolling.RollingFileAppender` using the `ROLLING_FILE_NAME_PATTERN` with structured logging in the `FILE_LOG_STRUCTURED_FORMAT`.
* `console-appender.xml` - Adds a javadoc:ch.qos.logback.core.ConsoleAppender[] using the `CONSOLE_LOG_PATTERN`.
* `structured-console-appender.xml` - Adds a javadoc:ch.qos.logback.core.ConsoleAppender[] using structured logging in the `CONSOLE_LOG_STRUCTURED_FORMAT`.
* `file-appender.xml` - Adds a javadoc:ch.qos.logback.core.rolling.RollingFileAppender[] using the `FILE_LOG_PATTERN` and `ROLLING_FILE_NAME_PATTERN` with appropriate settings.
* `structured-file-appender.xml` - Adds a javadoc:ch.qos.logback.core.rolling.RollingFileAppender[] using the `ROLLING_FILE_NAME_PATTERN` with structured logging in the `FILE_LOG_STRUCTURED_FORMAT`.
In addition, a legacy `base.xml` file is provided for compatibility with earlier versions of Spring Boot.
@ -72,7 +72,7 @@ A typical custom `logback.xml` file would look something like this:
</configuration>
----
Your logback configuration file can also make use of System properties that the `LoggingSystem` takes care of creating for you:
Your logback configuration file can also make use of System properties that the javadoc:org.springframework.boot.logging.LoggingSystem[] takes care of creating for you:
* `$\{PID}`: The current process ID.
* `$\{LOG_FILE}`: Whether `logging.file.name` was set in Boot's external configuration.

View File

@ -10,8 +10,8 @@ This section answers questions that arise from using messaging with Spring Boot.
== Disable Transacted JMS Session
If your JMS broker does not support transacted sessions, you have to disable the support of transactions altogether.
If you create your own `JmsListenerContainerFactory`, there is nothing to do, since, by default it cannot be transacted.
If you want to use the `DefaultJmsListenerContainerFactoryConfigurer` to reuse Spring Boot's default, you can disable transacted sessions, as follows:
If you create your own javadoc:org.springframework.jms.config.JmsListenerContainerFactory[], there is nothing to do, since, by default it cannot be transacted.
If you want to use the javadoc:org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer[] to reuse Spring Boot's default, you can disable transacted sessions, as follows:
include-code::MyJmsConfiguration[]

View File

@ -40,7 +40,7 @@ For Gradle, you need to ensure that your build includes the `org.graalvm.buildto
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.
For example, you could use the Spring javadoc:org.springframework.web.reactive.function.client.WebClient[] to call your application REST endpoints.
Or you might consider using a project like Selenium to check your application's HTML responses.
@ -57,15 +57,15 @@ 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.
For example, you can continue to use the javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation] annotation.
You can also use Spring Boot xref:reference:testing/spring-boot-applications.adoc#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.
* Tests are analyzed in order to discover any javadoc:org.springframework.context.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 also includes the JUnit javadoc:org.junit.platform.engine.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.

View File

@ -98,7 +98,7 @@ To use Spring property placeholders together with automatic expansion, escape th
[[howto.properties-and-configuration.externalize-configuration]]
== Externalize the Configuration of SpringApplication
A `SpringApplication` has bean property setters, so you can use its Java API as you create the application to modify its behavior.
A javadoc:org.springframework.boot.SpringApplication[] has bean property setters, so you can use its Java API as you create the application to modify its behavior.
Alternatively, you can externalize the configuration by setting properties in `+spring.main.*+`.
For example, in `application.properties`, you might have the following settings:
@ -113,11 +113,11 @@ spring:
Then the Spring Boot banner is not printed on startup, and the application is not starting an embedded web server.
Properties defined in external configuration override and replace the values specified with the Java API, with the notable exception of the primary sources.
Primary sources are those provided to the `SpringApplication` constructor:
Primary sources are those provided to the javadoc:org.springframework.boot.SpringApplication[] constructor:
include-code::application/MyApplication[]
Or to `sources(...)` method of a `SpringApplicationBuilder`:
Or to `sources(...)` method of a javadoc:org.springframework.boot.builder.SpringApplicationBuilder[]:
include-code::builder/MyApplication[]
@ -131,7 +131,7 @@ spring:
banner-mode: "console"
----
The actual application will show the banner (as overridden by configuration) and use three sources for the `ApplicationContext`.
The actual application will show the banner (as overridden by configuration) and use three sources for the javadoc:org.springframework.context.ApplicationContext[].
The application sources are:
. `MyApplication` (from the code)
@ -143,13 +143,13 @@ The application sources are:
[[howto.properties-and-configuration.external-properties-location]]
== Change the Location of External Properties of an Application
By default, properties from different sources are added to the Spring `Environment` in a defined order (see xref:reference:features/external-config.adoc[] in the "`Spring Boot Features`" section for the exact order).
By default, properties from different sources are added to the Spring javadoc:org.springframework.core.env.Environment[] in a defined order (see xref:reference:features/external-config.adoc[] in the "`Spring Boot Features`" section for the exact order).
You can also provide the following System properties (or environment variables) to change the behavior:
* configprop:spring.config.name[] (configprop:spring.config.name[format=envvar]): Defaults to `application` as the root of the file name.
* configprop:spring.config.location[] (configprop:spring.config.location[format=envvar]): The file to load (such as a classpath resource or a URL).
A separate `Environment` property source is set up for this document and it can be overridden by system properties, environment variables, or the command line.
A separate javadoc:org.springframework.core.env.Environment[] property source is set up for this document and it can be overridden by system properties, environment variables, or the command line.
No matter what you set in the environment, Spring Boot always loads `application.properties` as described above.
By default, if YAML is used, then files with the '`.yaml`' and '`.yml`' extensions are also added to the list.
@ -174,7 +174,7 @@ TIP: If you inherit from the `spring-boot-starter-parent` POM, the default filte
If you have enabled Maven filtering for the `application.properties` directly, you may want to also change the default filter token to use https://maven.apache.org/plugins/maven-resources-plugin/resources-mojo.html#delimiters[other delimiters].
NOTE: In this specific case, the port binding works in a PaaS environment such as Heroku or Cloud Foundry.
On those two platforms, the `PORT` environment variable is set automatically and Spring can bind to capitalized synonyms for `Environment` properties.
On those two platforms, the `PORT` environment variable is set automatically and Spring can bind to capitalized synonyms for javadoc:org.springframework.core.env.Environment[] properties.
@ -197,7 +197,7 @@ server:
Create a file called `application.yaml` and put it in the root of your classpath.
Then add `snakeyaml` to your dependencies (Maven coordinates `org.yaml:snakeyaml`, already included if you use the `spring-boot-starter`).
A YAML file is parsed to a Java `Map<String,Object>` (like a JSON object), and Spring Boot flattens the map so that it is one level deep and has period-separated keys, as many people are used to with `Properties` files in Java.
A YAML file is parsed to a Java `Map<String,Object>` (like a JSON object), and Spring Boot flattens the map so that it is one level deep and has period-separated keys, as many people are used to with javadoc:java.util.Properties[] files in Java.
The preceding example YAML corresponds to the following `application.properties` file:
@ -216,7 +216,7 @@ See xref:reference:features/external-config.adoc#features.external-config.yaml[]
[[howto.properties-and-configuration.set-active-spring-profiles]]
== Set the Active Spring Profiles
The Spring `Environment` has an API for this, but you would normally set a System property (configprop:spring.profiles.active[]) or an OS environment variable (configprop:spring.profiles.active[format=envvar]).
The Spring javadoc:org.springframework.core.env.Environment[] has an API for this, but you would normally set a System property (configprop:spring.profiles.active[]) or an OS environment variable (configprop:spring.profiles.active[format=envvar]).
Also, you can launch your application with a `-D` argument (remember to put it before the main class or jar archive), as follows:
[source,shell]
@ -302,8 +302,8 @@ Later values override earlier values.
Spring Boot binds external properties from `application.properties` (or YAML files and other places) into an application at runtime.
There is not (and technically cannot be) an exhaustive list of all supported properties in a single location, because contributions can come from additional jar files on your classpath.
A running application with the Actuator features has a `configprops` endpoint that shows all the bound and bindable properties available through `@ConfigurationProperties`.
A running application with the Actuator features has a `configprops` endpoint that shows all the bound and bindable properties available through javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation].
The appendix includes an xref:appendix:application-properties/index.adoc[`application.properties`] example with a list of the most common properties supported by Spring Boot.
The definitive list comes from searching the source code for `@ConfigurationProperties` and `@Value` annotations as well as the occasional use of `Binder`.
The definitive list comes from searching the source code for javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] and javadoc:org.springframework.beans.factory.annotation.Value[format=annotation] annotations as well as the occasional use of javadoc:org.springframework.boot.context.properties.bind.Binder[].
For more about the exact ordering of loading properties, see xref:reference:features/external-config.adoc[].

View File

@ -10,17 +10,17 @@ For more about Spring Security, see the {url-spring-security-site}[Spring Securi
[[howto.security.switch-off-spring-boot-configuration]]
== Switch Off the Spring Boot Security Configuration
If you define a `@Configuration` with a `SecurityFilterChain` bean in your application, this action switches off the default webapp security settings in Spring Boot.
If you define a javadoc:org.springframework.context.annotation.Configuration[format=annotation] with a javadoc:org.springframework.security.web.SecurityFilterChain[] bean in your application, this action switches off the default webapp security settings in Spring Boot.
[[howto.security.change-user-details-service-and-add-user-accounts]]
== Change the UserDetailsService and Add User Accounts
If you provide a `@Bean` of type `AuthenticationManager`, `org.springframework.security.authentication.AuthenticationProvider`, or `UserDetailsService`, the default `@Bean` for `InMemoryUserDetailsManager` is not created.
If you provide a javadoc:org.springframework.context.annotation.Bean[format=annotation] of type javadoc:org.springframework.security.authentication.AuthenticationManager[], javadoc:org.springframework.security.authentication.AuthenticationProvider[], or javadoc:org.springframework.security.core.userdetails.UserDetailsService[], the default javadoc:org.springframework.context.annotation.Bean[format=annotation] for javadoc:org.springframework.security.provisioning.InMemoryUserDetailsManager[] is not created.
This means you have the full feature set of Spring Security available (such as {url-spring-security-docs}/servlet/authentication/index.html[various authentication options]).
The easiest way to add user accounts is by providing your own `UserDetailsService` bean.
The easiest way to add user accounts is by providing your own javadoc:org.springframework.security.core.userdetails.UserDetailsService[] bean.
@ -28,7 +28,7 @@ The easiest way to add user accounts is by providing your own `UserDetailsServic
== Enable HTTPS When Running Behind a Proxy Server
Ensuring that all your main endpoints are only available over HTTPS is an important chore for any application.
If you use Tomcat as a servlet container, then Spring Boot adds Tomcat's own `RemoteIpValve` automatically if it detects some environment settings, allowing you to rely on the `HttpServletRequest` to report whether it is secure or not (even downstream of a proxy server that handles the real SSL termination).
If you use Tomcat as a servlet container, then Spring Boot adds Tomcat's own javadoc:org.apache.catalina.valves.RemoteIpValve[] automatically if it detects some environment settings, allowing you to rely on the javadoc:jakarta.servlet.http.HttpServletRequest[] to report whether it is secure or not (even downstream of a proxy server that handles the real SSL termination).
The standard behavior is determined by the presence or absence of certain request headers (`x-forwarded-for` and `x-forwarded-proto`), whose names are conventional, so it should work with most front-end proxies.
You can switch on the valve by adding some entries to `application.properties`, as shown in the following example:
@ -42,8 +42,8 @@ server:
----
(The presence of either of those properties switches on the valve.
Alternatively, you can add the `RemoteIpValve` by customizing the `TomcatServletWebServerFactory` using a `WebServerFactoryCustomizer` bean.)
Alternatively, you can add the javadoc:org.apache.catalina.valves.RemoteIpValve[] by customizing the javadoc:org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory[] using a javadoc:org.springframework.boot.web.server.WebServerFactoryCustomizer[] bean.)
To configure Spring Security to require a secure channel for all (or some) requests, consider adding your own `SecurityFilterChain` bean that adds the following `HttpSecurity` configuration:
To configure Spring Security to require a secure channel for all (or some) requests, consider adding your own javadoc:org.springframework.security.web.SecurityFilterChain[] bean that adds the following javadoc:org.springframework.security.config.annotation.web.builders.HttpSecurity[] configuration:
include-code::MySecurityConfig[]

View File

@ -10,7 +10,7 @@ This section answers common questions about Spring MVC and Spring Boot.
[[howto.spring-mvc.write-json-rest-service]]
== Write a JSON REST Service
Any Spring `@RestController` in a Spring Boot application should render JSON response by default as long as Jackson2 is on the classpath, as shown in the following example:
Any Spring javadoc:org.springframework.web.bind.annotation.RestController[format=annotation] in a Spring Boot application should render JSON response by default as long as Jackson2 is on the classpath, as shown in the following example:
include-code::MyController[]
@ -34,7 +34,7 @@ To use the Jackson XML renderer, add the following dependency to your project:
</dependency>
----
If Jackson's XML extension is not available and JAXB is available, XML can be rendered with the additional requirement of having `MyThing` annotated as `@XmlRootElement`, as shown in the following example:
If Jackson's XML extension is not available and JAXB is available, XML can be rendered with the additional requirement of having `MyThing` annotated as javadoc:jakarta.xml.bind.annotation.XmlRootElement[format=annotation], as shown in the following example:
include-code::MyThing[]
@ -55,10 +55,10 @@ NOTE: To get the server to render XML instead of JSON, you might have to send an
[[howto.spring-mvc.customize-jackson-objectmapper]]
== Customize the Jackson ObjectMapper
Spring MVC (client and server side) uses `HttpMessageConverters` to negotiate content conversion in an HTTP exchange.
If Jackson is on the classpath, you already get the default converter(s) provided by `Jackson2ObjectMapperBuilder`, an instance of which is auto-configured for you.
Spring MVC (client and server side) uses javadoc:org.springframework.boot.autoconfigure.http.HttpMessageConverters[] to negotiate content conversion in an HTTP exchange.
If Jackson is on the classpath, you already get the default converter(s) provided by javadoc:org.springframework.http.converter.json.Jackson2ObjectMapperBuilder[], an instance of which is auto-configured for you.
The `ObjectMapper` (or `XmlMapper` for Jackson XML converter) instance (created by default) has the following customized properties:
The javadoc:com.fasterxml.jackson.databind.ObjectMapper[] (or javadoc:com.fasterxml.jackson.dataformat.xml.XmlMapper[] for Jackson XML converter) instance (created by default) has the following customized properties:
* `MapperFeature.DEFAULT_VIEW_INCLUSION` is disabled
* `DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES` is disabled
@ -67,22 +67,22 @@ The `ObjectMapper` (or `XmlMapper` for Jackson XML converter) instance (created
Spring Boot also has some features to make it easier to customize this behavior.
You can configure the `ObjectMapper` and `XmlMapper` instances by using the environment.
You can configure the javadoc:com.fasterxml.jackson.databind.ObjectMapper[] and javadoc:com.fasterxml.jackson.dataformat.xml.XmlMapper[] instances by using the environment.
Jackson provides an extensive suite of on/off features that can be used to configure various aspects of its processing.
These features are described in several enums (in Jackson) that map onto properties in the environment:
|===
| Enum | Property | Values
| `com.fasterxml.jackson.databind.cfg.EnumFeature`
| javadoc:com.fasterxml.jackson.databind.cfg.EnumFeature[]
| `spring.jackson.datatype.enum.<feature_name>`
| `true`, `false`
| `com.fasterxml.jackson.databind.cfg.JsonNodeFeature`
| javadoc:com.fasterxml.jackson.databind.cfg.JsonNodeFeature[]
| `spring.jackson.datatype.json-node.<feature_name>`
| `true`, `false`
| `com.fasterxml.jackson.databind.DeserializationFeature`
| javadoc:com.fasterxml.jackson.databind.DeserializationFeature[]
| `spring.jackson.deserialization.<feature_name>`
| `true`, `false`
@ -90,7 +90,7 @@ These features are described in several enums (in Jackson) that map onto propert
| `spring.jackson.generator.<feature_name>`
| `true`, `false`
| `com.fasterxml.jackson.databind.MapperFeature`
| javadoc:com.fasterxml.jackson.databind.MapperFeature[]
| `spring.jackson.mapper.<feature_name>`
| `true`, `false`
@ -98,7 +98,7 @@ These features are described in several enums (in Jackson) that map onto propert
| `spring.jackson.parser.<feature_name>`
| `true`, `false`
| `com.fasterxml.jackson.databind.SerializationFeature`
| javadoc:com.fasterxml.jackson.databind.SerializationFeature[]
| `spring.jackson.serialization.<feature_name>`
| `true`, `false`
@ -110,20 +110,20 @@ These features are described in several enums (in Jackson) that map onto propert
For example, to enable pretty print, set `spring.jackson.serialization.indent_output=true`.
Note that, thanks to the use of xref:reference:features/external-config.adoc#features.external-config.typesafe-configuration-properties.relaxed-binding[relaxed binding], the case of `indent_output` does not have to match the case of the corresponding enum constant, which is `INDENT_OUTPUT`.
This environment-based configuration is applied to the auto-configured `Jackson2ObjectMapperBuilder` bean and applies to any mappers created by using the builder, including the auto-configured `ObjectMapper` bean.
This environment-based configuration is applied to the auto-configured javadoc:org.springframework.http.converter.json.Jackson2ObjectMapperBuilder[] bean and applies to any mappers created by using the builder, including the auto-configured javadoc:com.fasterxml.jackson.databind.ObjectMapper[] bean.
The context's `Jackson2ObjectMapperBuilder` can be customized by one or more `Jackson2ObjectMapperBuilderCustomizer` beans.
The context's javadoc:org.springframework.http.converter.json.Jackson2ObjectMapperBuilder[] can be customized by one or more javadoc:org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer[] beans.
Such customizer beans can be ordered (Boot's own customizer has an order of 0), letting additional customization be applied both before and after Boot's customization.
Any beans of type `com.fasterxml.jackson.databind.Module` are automatically registered with the auto-configured `Jackson2ObjectMapperBuilder` and are applied to any `ObjectMapper` instances that it creates.
Any beans of type javadoc:com.fasterxml.jackson.databind.Module[] are automatically registered with the auto-configured javadoc:org.springframework.http.converter.json.Jackson2ObjectMapperBuilder[] and are applied to any javadoc:com.fasterxml.jackson.databind.ObjectMapper[] instances that it creates.
This provides a global mechanism for contributing custom modules when you add new features to your application.
If you want to replace the default `ObjectMapper` completely, either define a `@Bean` of that type or, if you prefer the builder-based approach, define a `Jackson2ObjectMapperBuilder` `@Bean`.
When defining an `ObjectMapper` bean, marking it as `@Primary` is recommended as the auto-configuration's `ObjectMapper` that it will replace is `@Primary`.
Note that, in either case, doing so disables all auto-configuration of the `ObjectMapper`.
If you want to replace the default javadoc:com.fasterxml.jackson.databind.ObjectMapper[] completely, either define a javadoc:org.springframework.context.annotation.Bean[format=annotation] of that type or, if you prefer the builder-based approach, define a javadoc:org.springframework.http.converter.json.Jackson2ObjectMapperBuilder[] javadoc:org.springframework.context.annotation.Bean[format=annotation].
When defining an javadoc:com.fasterxml.jackson.databind.ObjectMapper[] bean, marking it as javadoc:org.springframework.context.annotation.Primary[format=annotation] is recommended as the auto-configuration's javadoc:com.fasterxml.jackson.databind.ObjectMapper[] that it will replace is javadoc:org.springframework.context.annotation.Primary[format=annotation].
Note that, in either case, doing so disables all auto-configuration of the javadoc:com.fasterxml.jackson.databind.ObjectMapper[].
If you provide any `@Beans` of type `MappingJackson2HttpMessageConverter`, they replace the default value in the MVC configuration.
Also, a convenience bean of type `HttpMessageConverters` is provided (and is always available if you use the default MVC configuration).
If you provide any javadoc:java.beans.Beans[format=annotation] of type javadoc:org.springframework.http.converter.json.MappingJackson2HttpMessageConverter[], they replace the default value in the MVC configuration.
Also, a convenience bean of type javadoc:org.springframework.boot.autoconfigure.http.HttpMessageConverters[] is provided (and is always available if you use the default MVC configuration).
It has some useful methods to access the default and user-enhanced message converters.
See the xref:spring-mvc.adoc#howto.spring-mvc.customize-responsebody-rendering[] section and the {code-spring-boot-autoconfigure-src}/web/servlet/WebMvcAutoConfiguration.java[`WebMvcAutoConfiguration`] source code for more details.
@ -133,15 +133,15 @@ See the xref:spring-mvc.adoc#howto.spring-mvc.customize-responsebody-rendering[]
[[howto.spring-mvc.customize-responsebody-rendering]]
== Customize the @ResponseBody Rendering
Spring uses `HttpMessageConverters` to render `@ResponseBody` (or responses from `@RestController`).
Spring uses javadoc:org.springframework.boot.autoconfigure.http.HttpMessageConverters[] to render javadoc:org.springframework.web.bind.annotation.ResponseBody[format=annotation] (or responses from javadoc:org.springframework.web.bind.annotation.RestController[format=annotation]).
You can contribute additional converters by adding beans of the appropriate type in a Spring Boot context.
If a bean you add is of a type that would have been included by default anyway (such as `MappingJackson2HttpMessageConverter` for JSON conversions), it replaces the default value.
A convenience bean of type `HttpMessageConverters` is provided and is always available if you use the default MVC configuration.
It has some useful methods to access the default and user-enhanced message converters (For example, it can be useful if you want to manually inject them into a custom `RestTemplate`).
If a bean you add is of a type that would have been included by default anyway (such as javadoc:org.springframework.http.converter.json.MappingJackson2HttpMessageConverter[] for JSON conversions), it replaces the default value.
A convenience bean of type javadoc:org.springframework.boot.autoconfigure.http.HttpMessageConverters[] is provided and is always available if you use the default MVC configuration.
It has some useful methods to access the default and user-enhanced message converters (For example, it can be useful if you want to manually inject them into a custom javadoc:org.springframework.web.client.RestTemplate[]).
As in normal MVC usage, any `WebMvcConfigurer` beans that you provide can also contribute converters by overriding the `configureMessageConverters` method.
As in normal MVC usage, any javadoc:org.springframework.web.servlet.config.annotation.WebMvcConfigurer[] beans that you provide can also contribute converters by overriding the `configureMessageConverters` method.
However, unlike with normal MVC, you can supply only additional converters that you need (because Spring Boot uses the same mechanism to contribute its defaults).
Finally, if you opt out of the default Spring Boot MVC configuration by providing your own `@EnableWebMvc` configuration, you can take control completely and do everything manually by using `getMessageConverters` from `WebMvcConfigurationSupport`.
Finally, if you opt out of the default Spring Boot MVC configuration by providing your own javadoc:org.springframework.web.servlet.config.annotation.EnableWebMvc[format=annotation] configuration, you can take control completely and do everything manually by using `getMessageConverters` from javadoc:org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport[].
See the {code-spring-boot-autoconfigure-src}/web/servlet/WebMvcAutoConfiguration.java[`WebMvcAutoConfiguration`] source code for more details.
@ -150,12 +150,12 @@ See the {code-spring-boot-autoconfigure-src}/web/servlet/WebMvcAutoConfiguration
[[howto.spring-mvc.multipart-file-uploads]]
== Handling Multipart File Uploads
Spring Boot embraces the servlet 5 `jakarta.servlet.http.Part` API to support uploading files.
Spring Boot embraces the servlet 5 javadoc:jakarta.servlet.http.Part[] API to support uploading files.
By default, Spring Boot configures Spring MVC with a maximum size of 1MB per file and a maximum of 10MB of file data in a single request.
You may override these values, the location to which intermediate data is stored (for example, to the `/tmp` directory), and the threshold past which data is flushed to disk by using the properties exposed in the `MultipartProperties` class.
You may override these values, the location to which intermediate data is stored (for example, to the `/tmp` directory), and the threshold past which data is flushed to disk by using the properties exposed in the javadoc:org.springframework.boot.autoconfigure.web.servlet.MultipartProperties[] class.
For example, if you want to specify that files be unlimited, set the configprop:spring.servlet.multipart.max-file-size[] property to `-1`.
The multipart support is helpful when you want to receive multipart encoded file data as a `@RequestParam`-annotated parameter of type `MultipartFile` in a Spring MVC controller handler method.
The multipart support is helpful when you want to receive multipart encoded file data as a javadoc:org.springframework.web.bind.annotation.RequestParam[format=annotation]-annotated parameter of type javadoc:org.springframework.web.multipart.MultipartFile[] in a Spring MVC controller handler method.
See the {code-spring-boot-autoconfigure-src}/web/servlet/MultipartAutoConfiguration.java[`MultipartAutoConfiguration`] source for more details.
@ -177,17 +177,17 @@ spring:
path: "/mypath"
----
If you have additional servlets you can declare a `@Bean` of type `Servlet` or `ServletRegistrationBean` for each and Spring Boot will register them transparently to the container.
Because servlets are registered that way, they can be mapped to a sub-context of the `DispatcherServlet` without invoking it.
If you have additional servlets you can declare a javadoc:org.springframework.context.annotation.Bean[format=annotation] of type javadoc:jakarta.servlet.Servlet[] or javadoc:org.springframework.boot.web.servlet.ServletRegistrationBean[] for each and Spring Boot will register them transparently to the container.
Because servlets are registered that way, they can be mapped to a sub-context of the javadoc:org.springframework.web.servlet.DispatcherServlet[] without invoking it.
Configuring the `DispatcherServlet` yourself is unusual but if you really need to do it, a `@Bean` of type `DispatcherServletPath` must be provided as well to provide the path of your custom `DispatcherServlet`.
Configuring the javadoc:org.springframework.web.servlet.DispatcherServlet[] yourself is unusual but if you really need to do it, a javadoc:org.springframework.context.annotation.Bean[format=annotation] of type javadoc:org.springframework.boot.autoconfigure.web.servlet.DispatcherServletPath[] must be provided as well to provide the path of your custom javadoc:org.springframework.web.servlet.DispatcherServlet[].
[[howto.spring-mvc.switch-off-default-configuration]]
== Switch Off the Default MVC Configuration
The easiest way to take complete control over MVC configuration is to provide your own `@Configuration` with the `@EnableWebMvc` annotation.
The easiest way to take complete control over MVC configuration is to provide your own javadoc:org.springframework.context.annotation.Configuration[format=annotation] with the javadoc:org.springframework.web.servlet.config.annotation.EnableWebMvc[format=annotation] annotation.
Doing so leaves all MVC configuration in your hands.
@ -195,46 +195,46 @@ Doing so leaves all MVC configuration in your hands.
[[howto.spring-mvc.customize-view-resolvers]]
== Customize ViewResolvers
A `org.springframework.web.servlet.ViewResolver` is a core component of Spring MVC, translating view names in `@Controller` to actual `org.springframework.web.servlet.View` implementations.
Note that view resolvers are mainly used in UI applications, rather than REST-style services (a `org.springframework.web.servlet.View` is not used to render a `@ResponseBody`).
There are many implementations of `org.springframework.web.servlet.ViewResolver` to choose from, and Spring on its own is not opinionated about which ones you should use.
A javadoc:org.springframework.web.servlet.ViewResolver[] is a core component of Spring MVC, translating view names in javadoc:org.springframework.stereotype.Controller[format=annotation] to actual javadoc:org.springframework.web.servlet.View[] implementations.
Note that view resolvers are mainly used in UI applications, rather than REST-style services (a javadoc:org.springframework.web.servlet.View[] is not used to render a javadoc:org.springframework.web.bind.annotation.ResponseBody[format=annotation]).
There are many implementations of javadoc:org.springframework.web.servlet.ViewResolver[] to choose from, and Spring on its own is not opinionated about which ones you should use.
Spring Boot, on the other hand, installs one or two for you, depending on what it finds on the classpath and in the application context.
The `DispatcherServlet` uses all the resolvers it finds in the application context, trying each one in turn until it gets a result.
The javadoc:org.springframework.web.servlet.DispatcherServlet[] uses all the resolvers it finds in the application context, trying each one in turn until it gets a result.
If you add your own, you have to be aware of the order and in which position your resolver is added.
`WebMvcAutoConfiguration` adds the following `org.springframework.web.servlet.ViewResolver` beans to your context:
javadoc:org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration[] adds the following javadoc:org.springframework.web.servlet.ViewResolver[] beans to your context:
* An `InternalResourceViewResolver` named '`defaultViewResolver`'.
* An javadoc:org.springframework.web.servlet.view.InternalResourceViewResolver[] named '`defaultViewResolver`'.
This one locates physical resources that can be rendered by using the `+DefaultServlet+` (including static resources and JSP pages, if you use those).
It applies a prefix and a suffix to the view name and then looks for a physical resource with that path in the servlet context (the defaults are both empty but are accessible for external configuration through `spring.mvc.view.prefix` and `spring.mvc.view.suffix`).
You can override it by providing a bean of the same type.
* A `BeanNameViewResolver` named '`beanNameViewResolver`'.
This is a useful member of the view resolver chain and picks up any beans with the same name as the `org.springframework.web.servlet.View` being resolved.
* A javadoc:org.springframework.web.servlet.view.BeanNameViewResolver[] named '`beanNameViewResolver`'.
This is a useful member of the view resolver chain and picks up any beans with the same name as the javadoc:org.springframework.web.servlet.View[] being resolved.
It should not be necessary to override or replace it.
* A `ContentNegotiatingViewResolver` named '`viewResolver`' is added only if there *are* actually beans of type `org.springframework.web.servlet.View` present.
* A javadoc:org.springframework.web.servlet.view.ContentNegotiatingViewResolver[] named '`viewResolver`' is added only if there *are* actually beans of type javadoc:org.springframework.web.servlet.View[] present.
This is a composite resolver, delegating to all the others and attempting to find a match to the '`Accept`' HTTP header sent by the client.
There is a useful https://spring.io/blog/2013/06/03/content-negotiation-using-views[blog about `ContentNegotiatingViewResolver`] that you might like to study to learn more, and you might also look at the source code for detail.
You can switch off the auto-configured `ContentNegotiatingViewResolver` by defining a bean named '`viewResolver`'.
* If you use Thymeleaf, you also have a `ThymeleafViewResolver` named '`thymeleafViewResolver`'.
There is a useful https://spring.io/blog/2013/06/03/content-negotiation-using-views[blog about javadoc:org.springframework.web.servlet.view.ContentNegotiatingViewResolver[]] that you might like to study to learn more, and you might also look at the source code for detail.
You can switch off the auto-configured javadoc:org.springframework.web.servlet.view.ContentNegotiatingViewResolver[] by defining a bean named '`viewResolver`'.
* If you use Thymeleaf, you also have a javadoc:org.thymeleaf.spring6.view.ThymeleafViewResolver[] named '`thymeleafViewResolver`'.
It looks for resources by surrounding the view name with a prefix and suffix.
The prefix is `spring.thymeleaf.prefix`, and the suffix is `spring.thymeleaf.suffix`.
The values of the prefix and suffix default to '`classpath:/templates/`' and '`.html`', respectively.
You can override `ThymeleafViewResolver` by providing a bean of the same name.
* If you use FreeMarker, you also have a `org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver` named '`freeMarkerViewResolver`'.
You can override javadoc:org.thymeleaf.spring6.view.ThymeleafViewResolver[] by providing a bean of the same name.
* If you use FreeMarker, you also have a javadoc:org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver[] named '`freeMarkerViewResolver`'.
It looks for resources in a loader path (which is externalized to `spring.freemarker.templateLoaderPath` and has a default value of '`classpath:/templates/`') by surrounding the view name with a prefix and a suffix.
The prefix is externalized to `spring.freemarker.prefix`, and the suffix is externalized to `spring.freemarker.suffix`.
The default values of the prefix and suffix are empty and '`.ftlh`', respectively.
You can override `org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver` by providing a bean of the same name.
FreeMarker variables can be customized by defining a bean of type `FreeMarkerVariablesCustomizer`.
* If you use Groovy templates (actually, if `groovy-templates` is on your classpath), you also have a `GroovyMarkupViewResolver` named '`groovyMarkupViewResolver`'.
You can override javadoc:org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver[] by providing a bean of the same name.
FreeMarker variables can be customized by defining a bean of type javadoc:org.springframework.boot.autoconfigure.freemarker.FreeMarkerVariablesCustomizer[].
* If you use Groovy templates (actually, if `groovy-templates` is on your classpath), you also have a javadoc:org.springframework.web.servlet.view.groovy.GroovyMarkupViewResolver[] named '`groovyMarkupViewResolver`'.
It looks for resources in a loader path by surrounding the view name with a prefix and suffix (externalized to `spring.groovy.template.prefix` and `spring.groovy.template.suffix`).
The prefix and suffix have default values of '`classpath:/templates/`' and '`.tpl`', respectively.
You can override `GroovyMarkupViewResolver` by providing a bean of the same name.
* If you use Mustache, you also have a `org.springframework.boot.web.servlet.view.MustacheViewResolver` named '`mustacheViewResolver`'.
You can override javadoc:org.springframework.web.servlet.view.groovy.GroovyMarkupViewResolver[] by providing a bean of the same name.
* If you use Mustache, you also have a javadoc:org.springframework.boot.web.servlet.view.MustacheViewResolver[] named '`mustacheViewResolver`'.
It looks for resources by surrounding the view name with a prefix and suffix.
The prefix is `spring.mustache.prefix`, and the suffix is `spring.mustache.suffix`.
The values of the prefix and suffix default to '`classpath:/templates/`' and '`.mustache`', respectively.
You can override `org.springframework.boot.web.servlet.view.MustacheViewResolver` by providing a bean of the same name.
You can override javadoc:org.springframework.boot.web.servlet.view.MustacheViewResolver[] by providing a bean of the same name.
For more detail, see the following sections:
@ -257,8 +257,8 @@ Note that Spring Boot still tries to resolve the error view, so you should proba
Overriding the error page with your own depends on the templating technology that you use.
For example, if you use Thymeleaf, you can add an `error.html` template.
If you use FreeMarker, you can add an `error.ftlh` template.
In general, you need a `org.springframework.web.servlet.View` that resolves with a name of `error` or a `@Controller` that handles the `/error` path.
Unless you replaced some of the default configuration, you should find a `BeanNameViewResolver` in your `ApplicationContext`, so a `@Bean` named `error` would be one way of doing that.
In general, you need a javadoc:org.springframework.web.servlet.View[] that resolves with a name of `error` or a javadoc:org.springframework.stereotype.Controller[format=annotation] that handles the `/error` path.
Unless you replaced some of the default configuration, you should find a javadoc:org.springframework.web.servlet.view.BeanNameViewResolver[] in your javadoc:org.springframework.context.ApplicationContext[], so a javadoc:org.springframework.context.annotation.Bean[format=annotation] named `error` would be one way of doing that.
See {code-spring-boot-autoconfigure-src}/web/servlet/error/ErrorMvcAutoConfiguration.java[`ErrorMvcAutoConfiguration`] for more options.
See also the section on xref:reference:web/servlet.adoc#web.servlet.spring-mvc.error-handling[] for details of how to register handlers in the servlet container.

View File

@ -14,7 +14,7 @@ For example, the test in the snippet below will run with an authenticated user t
include-code::MySecurityTests[]
Spring Security provides comprehensive integration with Spring MVC Test, and this can also be used when testing controllers using the `@WebMvcTest` slice and `MockMvc`.
Spring Security provides comprehensive integration with Spring MVC Test, and this can also be used when testing controllers using the javadoc:org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest[format=annotation] slice and javadoc:org.springframework.test.web.servlet.MockMvc[].
For additional details on Spring Security's testing support, see Spring Security's {url-spring-security-docs}/servlet/test/index.html[reference documentation].
@ -22,18 +22,18 @@ For additional details on Spring Security's testing support, see Spring Security
[[howto.testing.slice-tests]]
== Structure `@Configuration` Classes for Inclusion in Slice Tests
== Structure javadoc:org.springframework.context.annotation.Configuration[format=annotation] Classes for Inclusion in Slice Tests
Slice tests work by restricting Spring Framework's component scanning to a limited set of components based on their type.
For any beans that are not created through component scanning, for example, beans that are created using the `@Bean` annotation, slice tests will not be able to include/exclude them from the application context.
For any beans that are not created through component scanning, for example, beans that are created using the javadoc:org.springframework.context.annotation.Bean[format=annotation] annotation, slice tests will not be able to include/exclude them from the application context.
Consider this example:
include-code::MyConfiguration[]
For a `@WebMvcTest` for an application with the above `@Configuration` class, you might expect to have the `SecurityFilterChain` bean in the application context so that you can test if your controller endpoints are secured properly.
For a javadoc:org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest[format=annotation] for an application with the above javadoc:org.springframework.context.annotation.Configuration[format=annotation] class, you might expect to have the javadoc:org.springframework.security.web.SecurityFilterChain[] bean in the application context so that you can test if your controller endpoints are secured properly.
However, `MyConfiguration` is not picked up by @WebMvcTest's component scanning filter because it doesn't match any of the types specified by the filter.
You can include the configuration explicitly by annotating the test class with `@Import(MyConfiguration.class)`.
This will load all the beans in `MyConfiguration` including the `HikariDataSource` bean which isn't required when testing the web tier.
This will load all the beans in `MyConfiguration` including the javadoc:com.zaxxer.hikari.HikariDataSource[] bean which isn't required when testing the web tier.
Splitting the configuration class into two will enable importing just the security configuration.
include-code::MySecurityConfiguration[]

View File

@ -55,7 +55,7 @@ dependencies {
}
----
NOTE: `spring-boot-starter-reactor-netty` is required to use the `WebClient` class, so you may need to keep a dependency on Netty even when you need to include a different HTTP server.
NOTE: `spring-boot-starter-reactor-netty` is required to use the javadoc:org.springframework.web.reactive.function.client.WebClient[] class, so you may need to keep a dependency on Netty even when you need to include a different HTTP server.
@ -63,7 +63,7 @@ NOTE: `spring-boot-starter-reactor-netty` is required to use the `WebClient` cla
== Disabling the Web Server
If your classpath contains the necessary bits to start a web server, Spring Boot will automatically start it.
To disable this behavior configure the `WebApplicationType` in your `application.properties`, as shown in the following example:
To disable this behavior configure the javadoc:org.springframework.boot.WebApplicationType[] in your `application.properties`, as shown in the following example:
[configprops,yaml]
----
@ -78,9 +78,9 @@ spring:
== Change the HTTP Port
In a standalone application, the main HTTP port defaults to `8080` but can be set with configprop:server.port[] (for example, in `application.properties` or as a System property).
Thanks to relaxed binding of `Environment` values, you can also use configprop:server.port[format=envvar] (for example, as an OS environment variable).
Thanks to relaxed binding of javadoc:org.springframework.core.env.Environment[] values, you can also use configprop:server.port[format=envvar] (for example, as an OS environment variable).
To switch off the HTTP endpoints completely but still create a `WebApplicationContext`, use `server.port=-1` (doing so is sometimes useful for testing).
To switch off the HTTP endpoints completely but still create a javadoc:org.springframework.web.context.WebApplicationContext[], use `server.port=-1` (doing so is sometimes useful for testing).
For more details, see xref:reference:web/servlet.adoc#web.servlet.embedded-container.customizing[Customizing Embedded Servlet Containers] in the '`Spring Boot Features`' section, or the javadoc:org.springframework.boot.autoconfigure.web.ServerProperties[] class.
@ -96,16 +96,16 @@ To scan for a free port (using OS natives to prevent clashes) use `server.port=0
[[howto.webserver.discover-port]]
== Discover the HTTP Port at Runtime
You can access the port the server is running on from log output or from the `WebServerApplicationContext` through its `org.springframework.boot.web.server.WebServer`.
The best way to get that and be sure it has been initialized is to add a `@Bean` of type `ApplicationListener<WebServerInitializedEvent>` and pull the container out of the event when it is published.
You can access the port the server is running on from log output or from the javadoc:org.springframework.boot.web.context.WebServerApplicationContext[] through its javadoc:org.springframework.boot.web.server.WebServer[].
The best way to get that and be sure it has been initialized is to add a javadoc:org.springframework.context.annotation.Bean[format=annotation] of type `ApplicationListener<WebServerInitializedEvent>` and pull the container out of the event when it is published.
Tests that use `@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)` can also inject the actual port into a field by using the `@LocalServerPort` annotation, as shown in the following example:
Tests that use `@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)` can also inject the actual port into a field by using the javadoc:org.springframework.boot.test.web.server.LocalServerPort[format=annotation] annotation, as shown in the following example:
include-code::MyWebIntegrationTests[]
[NOTE]
====
`@LocalServerPort` is a meta-annotation for `@Value("${local.server.port}")`.
javadoc:org.springframework.boot.test.web.server.LocalServerPort[format=annotation] is a meta-annotation for `@Value("${local.server.port}")`.
Do not try to inject the port in a regular application.
As we just saw, the value is set only after the container has been initialized.
Contrary to a test, application code callbacks are processed early (before the value is actually available).
@ -308,9 +308,9 @@ The example below is for Tomcat with the `spring-boot-starter-web` (servlet stac
include-code::MyTomcatWebServerCustomizer[]
NOTE: Spring Boot uses that infrastructure internally to auto-configure the server.
Auto-configured `WebServerFactoryCustomizer` beans have an order of `0` and will be processed before any user-defined customizers, unless it has an explicit order that states otherwise.
Auto-configured javadoc:org.springframework.boot.web.server.WebServerFactoryCustomizer[] beans have an order of `0` and will be processed before any user-defined customizers, unless it has an explicit order that states otherwise.
Once you have got access to a `org.springframework.boot.web.server.WebServerFactory` using the customizer, you can use it to configure specific parts, like connectors, server resources, or the server itself - all using server-specific APIs.
Once you have got access to a javadoc:org.springframework.boot.web.server.WebServerFactory[] using the customizer, you can use it to configure specific parts, like connectors, server resources, or the server itself - all using server-specific APIs.
In addition Spring Boot provides:
@ -320,23 +320,23 @@ In addition Spring Boot provides:
| Server | Servlet stack | Reactive stack
| Tomcat
| `TomcatServletWebServerFactory`
| `TomcatReactiveWebServerFactory`
| javadoc:org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory[]
| javadoc:org.springframework.boot.web.embedded.tomcat.TomcatReactiveWebServerFactory[]
| Jetty
| `JettyServletWebServerFactory`
| `JettyReactiveWebServerFactory`
| javadoc:org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory[]
| javadoc:org.springframework.boot.web.embedded.jetty.JettyReactiveWebServerFactory[]
| Undertow
| `UndertowServletWebServerFactory`
| `UndertowReactiveWebServerFactory`
| javadoc:org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory[]
| javadoc:org.springframework.boot.web.embedded.undertow.UndertowReactiveWebServerFactory[]
| Reactor
| N/A
| `NettyReactiveWebServerFactory`
| javadoc:org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory[]
|===
As a last resort, you can also declare your own `org.springframework.boot.web.server.WebServerFactory` bean, which will override the one provided by Spring Boot.
As a last resort, you can also declare your own javadoc:org.springframework.boot.web.server.WebServerFactory[] bean, which will override the one provided by Spring Boot.
When you do so, auto-configured customizers are still applied on your custom factory, so use that option carefully.
@ -344,7 +344,7 @@ When you do so, auto-configured customizers are still applied on your custom fac
[[howto.webserver.add-servlet-filter-listener]]
== Add a Servlet, Filter, or Listener to an Application
In a servlet stack application, that is with the `spring-boot-starter-web`, there are two ways to add `Servlet`, `Filter`, `ServletContextListener`, and the other listeners supported by the Servlet API to your application:
In a servlet stack application, that is with the `spring-boot-starter-web`, there are two ways to add javadoc:jakarta.servlet.Servlet[], javadoc:jakarta.servlet.Filter[], javadoc:jakarta.servlet.ServletContextListener[], and the other listeners supported by the Servlet API to your application:
* xref:webserver.adoc#howto.webserver.add-servlet-filter-listener.spring-bean[]
* xref:webserver.adoc#howto.webserver.add-servlet-filter-listener.using-scanning[]
@ -354,13 +354,13 @@ In a servlet stack application, that is with the `spring-boot-starter-web`, ther
[[howto.webserver.add-servlet-filter-listener.spring-bean]]
=== Add a Servlet, Filter, or Listener by Using a Spring Bean
To add a `Servlet`, `Filter`, or servlet `*Listener` by using a Spring bean, you must provide a `@Bean` definition for it.
To add a javadoc:jakarta.servlet.Servlet[], javadoc:jakarta.servlet.Filter[], or servlet `*Listener` by using a Spring bean, you must provide a javadoc:org.springframework.context.annotation.Bean[format=annotation] definition for it.
Doing so can be very useful when you want to inject configuration or dependencies.
However, you must be very careful that they do not cause eager initialization of too many other beans, because they have to be installed in the container very early in the application lifecycle.
(For example, it is not a good idea to have them depend on your `DataSource` or JPA configuration.)
(For example, it is not a good idea to have them depend on your javadoc:javax.sql.DataSource[] or JPA configuration.)
You can work around such restrictions by initializing the beans lazily when first used instead of on initialization.
In the case of filters and servlets, you can also add mappings and init parameters by adding a `FilterRegistrationBean` or a `ServletRegistrationBean` instead of or in addition to the underlying component.
In the case of filters and servlets, you can also add mappings and init parameters by adding a javadoc:org.springframework.boot.web.servlet.FilterRegistrationBean[] or a javadoc:org.springframework.boot.web.servlet.ServletRegistrationBean[] instead of or in addition to the underlying component.
[NOTE]
====
@ -375,8 +375,8 @@ Like any other Spring bean, you can define the order of servlet filter beans; pl
[[howto.webserver.add-servlet-filter-listener.spring-bean.disable]]
==== Disable Registration of a Servlet or Filter
As xref:webserver.adoc#howto.webserver.add-servlet-filter-listener.spring-bean[described earlier], any `Servlet` or `Filter` beans are registered with the servlet container automatically.
To disable registration of a particular `Filter` or `Servlet` bean, create a registration bean for it and mark it as disabled, as shown in the following example:
As xref:webserver.adoc#howto.webserver.add-servlet-filter-listener.spring-bean[described earlier], any javadoc:jakarta.servlet.Servlet[] or javadoc:jakarta.servlet.Filter[] beans are registered with the servlet container automatically.
To disable registration of a particular javadoc:jakarta.servlet.Filter[] or javadoc:jakarta.servlet.Servlet[] bean, create a registration bean for it and mark it as disabled, as shown in the following example:
include-code::MyFilterConfiguration[]
@ -385,8 +385,8 @@ include-code::MyFilterConfiguration[]
[[howto.webserver.add-servlet-filter-listener.using-scanning]]
=== Add Servlets, Filters, and Listeners by Using Classpath Scanning
`@WebServlet`, `@jakarta.servlet.annotation.WebFilter`, and `@WebListener` annotated classes can be automatically registered with an embedded servlet container by annotating a `@Configuration` class with `@ServletComponentScan` and specifying the package(s) containing the components that you want to register.
By default, `@ServletComponentScan` scans from the package of the annotated class.
javadoc:jakarta.servlet.annotation.WebServlet[format=annotation], javadoc:jakarta.servlet.annotation.WebFilter[format=annotation], and javadoc:jakarta.servlet.annotation.WebListener[format=annotation] annotated classes can be automatically registered with an embedded servlet container by annotating a javadoc:org.springframework.context.annotation.Configuration[format=annotation] class with javadoc:org.springframework.boot.web.servlet.ServletComponentScan[format=annotation] and specifying the package(s) containing the components that you want to register.
By default, javadoc:org.springframework.boot.web.servlet.ServletComponentScan[format=annotation] scans from the package of the annotated class.
@ -498,14 +498,14 @@ server:
NOTE: You can trust all proxies by setting the `internal-proxies` to empty (but do not do so in production).
You can take complete control of the configuration of Tomcat's `RemoteIpValve` by switching the automatic one off (to do so, set `server.forward-headers-strategy=NONE`) and adding a new valve instance using a `WebServerFactoryCustomizer` bean.
You can take complete control of the configuration of Tomcat's javadoc:org.apache.catalina.valves.RemoteIpValve[] by switching the automatic one off (to do so, set `server.forward-headers-strategy=NONE`) and adding a new valve instance using a javadoc:org.springframework.boot.web.server.WebServerFactoryCustomizer[] bean.
[[howto.webserver.enable-multiple-connectors-in-tomcat]]
== Enable Multiple Connectors with Tomcat
You can add an `org.apache.catalina.connector.Connector` to the `TomcatServletWebServerFactory`, which can allow multiple connectors, including HTTP and HTTPS connectors, as shown in the following example:
You can add an javadoc:org.apache.catalina.connector.Connector[] to the javadoc:org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory[], which can allow multiple connectors, including HTTP and HTTPS connectors, as shown in the following example:
include-code::MyTomcatConfiguration[]
@ -531,7 +531,7 @@ server:
[[howto.webserver.enable-multiple-listeners-in-undertow]]
== Enable Multiple Listeners with Undertow
Add an `UndertowBuilderCustomizer` to the `UndertowServletWebServerFactory` and add a listener to the `io.undertow.Undertow.Builder`, as shown in the following example:
Add an javadoc:org.springframework.boot.web.embedded.undertow.UndertowBuilderCustomizer[] to the javadoc:org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory[] and add a listener to the `io.undertow.Undertow.Builder`, as shown in the following example:
include-code::MyUndertowConfiguration[]
@ -540,9 +540,9 @@ include-code::MyUndertowConfiguration[]
[[howto.webserver.create-websocket-endpoints-using-serverendpoint]]
== Create WebSocket Endpoints Using @ServerEndpoint
If you want to use `@ServerEndpoint` in a Spring Boot application that used an embedded container, you must declare a single `ServerEndpointExporter` `@Bean`, as shown in the following example:
If you want to use javadoc:jakarta.websocket.server.ServerEndpoint[format=annotation] in a Spring Boot application that used an embedded container, you must declare a single javadoc:org.springframework.web.socket.server.standard.ServerEndpointExporter[] javadoc:org.springframework.context.annotation.Bean[format=annotation], as shown in the following example:
include-code::MyWebSocketConfiguration[]
The bean shown in the preceding example registers any `@ServerEndpoint` annotated beans with the underlying WebSocket container.
When deployed to a standalone servlet container, this role is performed by a servlet container initializer, and the `ServerEndpointExporter` bean is not required.
The bean shown in the preceding example registers any javadoc:jakarta.websocket.server.ServerEndpoint[format=annotation] annotated beans with the underlying WebSocket container.
When deployed to a standalone servlet container, this role is performed by a servlet container initializer, and the javadoc:org.springframework.web.socket.server.standard.ServerEndpointExporter[] bean is not required.

View File

@ -4,17 +4,17 @@
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.
You can enable auditing by providing a bean of type javadoc:org.springframework.boot.actuate.audit.AuditEventRepository[] in your application's configuration.
For convenience, Spring Boot offers an javadoc:org.springframework.boot.actuate.audit.InMemoryAuditEventRepository[].
javadoc:org.springframework.boot.actuate.audit.InMemoryAuditEventRepository[] has limited capabilities, and we recommend using it only for development environments.
For production environments, consider creating your own alternative javadoc:org.springframework.boot.actuate.audit.AuditEventRepository[] implementation.
[[actuator.auditing.custom]]
== Custom Auditing
To customize published security events, you can provide your own implementations of `AbstractAuthenticationAuditListener` and `AbstractAuthorizationAuditListener`.
To customize published security events, you can provide your own implementations of javadoc:org.springframework.boot.actuate.security.AbstractAuthenticationAuditListener[] and javadoc:org.springframework.boot.actuate.security.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`).
To do so, either inject the javadoc:org.springframework.boot.actuate.audit.AuditEventRepository[] bean into your own components and use that directly or publish an javadoc:org.springframework.boot.actuate.audit.listener.AuditApplicationEvent[] with the Spring javadoc:org.springframework.context.ApplicationEventPublisher[] (by implementing javadoc:org.springframework.context.ApplicationEventPublisherAware[]).

View File

@ -2,7 +2,7 @@
= 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 `/cloudfoundryapplication` path provides an alternative secured route to all javadoc:org.springframework.boot.actuate.endpoint.annotation.Endpoint[format=annotation] 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.

View File

@ -21,7 +21,7 @@ The following technology-agnostic endpoints are available:
| `auditevents`
| Exposes audit events information for the current application.
Requires an `AuditEventRepository` bean.
Requires an javadoc:org.springframework.boot.actuate.audit.AuditEventRepository[] bean.
| `beans`
| Displays a complete list of all the Spring beans in your application.
@ -33,23 +33,23 @@ The following technology-agnostic endpoints are available:
| Shows the conditions that were evaluated on configuration and auto-configuration classes and the reasons why they did or did not match.
| `configprops`
| Displays a collated list of all `@ConfigurationProperties`.
| Displays a collated list of all javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation].
Subject to xref:actuator/endpoints.adoc#actuator.endpoints.sanitization[sanitization].
| `env`
| Exposes properties from Spring's `ConfigurableEnvironment`.
| Exposes properties from Spring's javadoc:org.springframework.core.env.ConfigurableEnvironment[].
Subject to xref:actuator/endpoints.adoc#actuator.endpoints.sanitization[sanitization].
| `flyway`
| Shows any Flyway database migrations that have been applied.
Requires one or more `Flyway` beans.
Requires one or more javadoc:org.flywaydb.core.Flyway[] beans.
| `health`
| Shows application health information.
| `httpexchanges`
| Displays HTTP exchange information (by default, the last 100 HTTP request-response exchanges).
Requires an `HttpExchangeRepository` bean.
Requires an javadoc:org.springframework.boot.actuate.web.exchanges.HttpExchangeRepository[] bean.
| `info`
| Displays arbitrary application info.
@ -63,13 +63,13 @@ Subject to xref:actuator/endpoints.adoc#actuator.endpoints.sanitization[sanitiza
| `liquibase`
| Shows any Liquibase database migrations that have been applied.
Requires one or more `liquibase.Liquibase` beans.
Requires one or more javadoc:{url-liquibase-javadoc}/liquibase.Liquibase[] beans.
| `metrics`
| Shows "`metrics`" information for the current application.
| `mappings`
| Displays a collated list of all `@RequestMapping` paths.
| Displays a collated list of all javadoc:org.springframework.web.bind.annotation.RequestMapping[format=annotation] paths.
|`quartz`
|Shows information about Quartz Scheduler jobs.
@ -88,8 +88,8 @@ Subject to xref:actuator/endpoints.adoc#actuator.endpoints.sanitization[sanitiza
Disabled by default.
| `startup`
| Shows the xref:features/spring-application.adoc#features.spring-application.startup-tracking[startup steps data] collected by the `ApplicationStartup`.
Requires the `SpringApplication` to be configured with a `BufferingApplicationStartup`.
| Shows the xref:features/spring-application.adoc#features.spring-application.startup-tracking[startup steps data] collected by the javadoc:org.springframework.core.metrics.ApplicationStartup[].
Requires the javadoc:org.springframework.boot.SpringApplication[] to be configured with a javadoc:org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup[].
| `threaddump`
| Performs a thread dump.
@ -158,9 +158,9 @@ This property takes precedence over the default access or an individual endpoint
Set it to `none` to make all endpoints inaccessible.
Set it to `read-only` to only allow read access to endpoints.
For `@Endpoint`, `@JmxEndpoint`, and `@WebEndpoint`, read access equates to the endpoint methods annotated with `@ReadOperation`.
For `@ControllerEndpoint` and `@RestControllerEndpoint`, read access equates to request mappings that can handle `GET` and `HEAD` requests.
For `@ServletEndpoint`, read access equates to `GET` and `HEAD` requests.
For javadoc:org.springframework.boot.actuate.endpoint.annotation.Endpoint[format=annotation], javadoc:org.springframework.boot.actuate.endpoint.jmx.annotation.JmxEndpoint[format=annotation], and javadoc:org.springframework.boot.actuate.endpoint.web.annotation.WebEndpoint[format=annotation], read access equates to the endpoint methods annotated with javadoc:org.springframework.boot.actuate.endpoint.annotation.ReadOperation[format=annotation].
For javadoc:org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpoint[format=annotation] and javadoc:org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint[format=annotation], read access equates to request mappings that can handle `GET` and `HEAD` requests.
For javadoc:org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpoint[format=annotation], read access equates to `GET` and `HEAD` requests.
@ -222,7 +222,7 @@ NOTE: `*` has a special meaning in YAML, so be sure to add quotation marks if yo
NOTE: If your application is exposed publicly, we strongly recommend that you also xref:actuator/endpoints.adoc#actuator.endpoints.security[secure your endpoints].
TIP: If you want to implement your own strategy for when endpoints are exposed, you can register an `EndpointFilter` bean.
TIP: If you want to implement your own strategy for when endpoints are exposed, you can register an javadoc:org.springframework.boot.actuate.endpoint.EndpointFilter[] bean.
@ -234,17 +234,17 @@ You can use the configprop:management.endpoints.web.exposure.include[] property
NOTE: Before setting the `management.endpoints.web.exposure.include`, ensure that the exposed actuators do not contain sensitive information, are secured by placing them behind a firewall, or are secured by something like Spring Security.
If Spring Security is on the classpath and no other `SecurityFilterChain` bean is present, all actuators other than `/health` are secured by Spring Boot auto-configuration.
If you define a custom `SecurityFilterChain` bean, Spring Boot auto-configuration backs off and lets you fully control the actuator access rules.
If Spring Security is on the classpath and no other javadoc:org.springframework.security.web.SecurityFilterChain[] bean is present, all actuators other than `/health` are secured by Spring Boot auto-configuration.
If you define a custom javadoc:org.springframework.security.web.SecurityFilterChain[] bean, Spring Boot auto-configuration backs off and lets you fully control the actuator access rules.
If you wish to configure custom security for HTTP endpoints (for example, to allow only users with a certain role to access them), Spring Boot provides some convenient `org.springframework.security.web.util.matcher.RequestMatcher` objects that you can use in combination with Spring Security.
If you wish to configure custom security for HTTP endpoints (for example, to allow only users with a certain role to access them), Spring Boot provides some convenient javadoc:org.springframework.security.web.util.matcher.RequestMatcher[] objects that you can use in combination with Spring Security.
A typical Spring Security configuration might look something like the following example:
include-code::typical/MySecurityConfiguration[]
The preceding example uses `EndpointRequest.toAnyEndpoint()` to match a request to any endpoint and then ensures that all have the `ENDPOINT_ADMIN` role.
Several other matcher methods are also available on `org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest`.
Several other matcher methods are also available on javadoc:org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest[].
See the xref:api:rest/actuator/index.adoc[API documentation] for details.
If you deploy applications behind a firewall, you may prefer that all your actuator endpoints can be accessed without requiring authentication.
@ -264,7 +264,7 @@ Additionally, if Spring Security is present, you would need to add custom securi
include-code::exposeall/MySecurityConfiguration[]
NOTE: In both of the preceding examples, the configuration applies only to the actuator endpoints.
Since Spring Boot's security configuration backs off completely in the presence of any `SecurityFilterChain` bean, you need to configure an additional `SecurityFilterChain` bean with rules that apply to the rest of the application.
Since Spring Boot's security configuration backs off completely in the presence of any javadoc:org.springframework.security.web.SecurityFilterChain[] bean, you need to configure an additional javadoc:org.springframework.security.web.SecurityFilterChain[] bean with rules that apply to the rest of the application.
@ -313,8 +313,8 @@ Values can only be viewed in an unsanitized form when:
The `show-values` property can be configured for sanitizable endpoints to one of the following values:
- `never` - values are always fully sanitized (replaced by `+******+`)
- `always` - values are shown to all users (as long as no `SanitizingFunction` bean applies)
- `when-authorized` - values are shown only to authorized users (as long as no `SanitizingFunction` bean applies)
- `always` - values are shown to all users (as long as no javadoc:org.springframework.boot.actuate.endpoint.SanitizingFunction[] bean applies)
- `when-authorized` - values are shown only to authorized users (as long as no javadoc:org.springframework.boot.actuate.endpoint.SanitizingFunction[] bean applies)
For HTTP endpoints, a user is considered to be authorized if they have authenticated and have the roles configured by the endpoint's roles property.
By default, any authenticated user is authorized.
@ -386,7 +386,7 @@ TIP: See javadoc:org.springframework.boot.actuate.autoconfigure.endpoint.web.Cor
[[actuator.endpoints.implementing-custom]]
== Implementing Custom Endpoints
If you add a `@Bean` annotated with `@Endpoint`, any methods annotated with `@ReadOperation`, `@WriteOperation`, or `@DeleteOperation` are automatically exposed over JMX and, in a web application, over HTTP as well.
If you add a javadoc:org.springframework.context.annotation.Bean[format=annotation] annotated with javadoc:org.springframework.boot.actuate.endpoint.annotation.Endpoint[format=annotation], any methods annotated with javadoc:org.springframework.boot.actuate.endpoint.annotation.ReadOperation[format=annotation], javadoc:org.springframework.boot.actuate.endpoint.annotation.WriteOperation[format=annotation], or javadoc:org.springframework.boot.actuate.endpoint.annotation.DeleteOperation[format=annotation] are automatically exposed over JMX and, in a web application, over HTTP as well.
Endpoints can be exposed over HTTP by using Jersey, Spring MVC, or Spring WebFlux.
If both Jersey and Spring MVC are available, Spring MVC is used.
@ -394,14 +394,14 @@ The following example exposes a read operation that returns a custom object:
include-code::MyEndpoint[tag=read]
You can also write technology-specific endpoints by using `@JmxEndpoint` or `@WebEndpoint`.
You can also write technology-specific endpoints by using javadoc:org.springframework.boot.actuate.endpoint.jmx.annotation.JmxEndpoint[format=annotation] or javadoc:org.springframework.boot.actuate.endpoint.web.annotation.WebEndpoint[format=annotation].
These endpoints are restricted to their respective technologies.
For example, `@WebEndpoint` is exposed only over HTTP and not over JMX.
For example, javadoc:org.springframework.boot.actuate.endpoint.web.annotation.WebEndpoint[format=annotation] is exposed only over HTTP and not over JMX.
You can write technology-specific extensions by using `@EndpointWebExtension` and `@EndpointJmxExtension`.
You can write technology-specific extensions by using javadoc:org.springframework.boot.actuate.endpoint.web.annotation.EndpointWebExtension[format=annotation] and javadoc:org.springframework.boot.actuate.endpoint.jmx.annotation.EndpointJmxExtension[format=annotation].
These annotations let you provide technology-specific operations to augment an existing endpoint.
Finally, if you need access to web-framework-specific functionality, you can implement servlet or Spring `@Controller` and `@RestController` endpoints at the cost of them not being available over JMX or when using a different web framework.
Finally, if you need access to web-framework-specific functionality, you can implement servlet or Spring javadoc:org.springframework.stereotype.Controller[format=annotation] and javadoc:org.springframework.web.bind.annotation.RestController[format=annotation] endpoints at the cost of them not being available over JMX or when using a different web framework.
@ -412,7 +412,7 @@ Operations on an endpoint receive input through their parameters.
When exposed over the web, the values for these parameters are taken from the URL's query parameters and from the JSON request body.
When exposed over JMX, the parameters are mapped to the parameters of the MBean's operations.
Parameters are required by default.
They can be made optional by annotating them with either `+@javax.annotation.Nullable+` or `@org.springframework.lang.Nullable`.
They can be made optional by annotating them with either `+@javax.annotation.Nullable+` or javadoc:org.springframework.lang.Nullable[format=annotation].
You can map each root property in the JSON request body to a parameter of the endpoint.
Consider the following JSON request body:
@ -430,7 +430,7 @@ You can use this to invoke a write operation that takes `String name` and `int c
include-code::../MyEndpoint[tag=write]
TIP: Because endpoints are technology agnostic, only simple types can be specified in the method signature.
In particular, declaring a single parameter with a `CustomData` type that defines a `name` and `counter` properties is not supported.
In particular, declaring a single parameter with a javadoc:liquibase.report.CustomData[] type that defines a `name` and `counter` properties is not supported.
NOTE: To let the input be mapped to the operation method's parameters, Java code that implements an endpoint should be compiled with `-parameters`.
For Kotlin code, please review {url-spring-framework-docs}/languages/kotlin/classes-interfaces.html[the recommendation] of the Spring Framework reference.
@ -442,14 +442,14 @@ This will happen automatically if you use Spring Boot's Gradle plugin or if you
==== Input Type Conversion
The parameters passed to endpoint operation methods are, if necessary, automatically converted to the required type.
Before calling an operation method, the input received over JMX or HTTP is converted to the required types by using an instance of `ApplicationConversionService` as well as any `org.springframework.core.convert.converter.Converter` or `org.springframework.core.convert.converter.GenericConverter` beans qualified with `@EndpointConverter`.
Before calling an operation method, the input received over JMX or HTTP is converted to the required types by using an instance of javadoc:org.springframework.boot.convert.ApplicationConversionService[] as well as any javadoc:org.springframework.core.convert.converter.Converter[] or javadoc:org.springframework.core.convert.converter.GenericConverter[] beans qualified with javadoc:org.springframework.boot.actuate.endpoint.annotation.EndpointConverter[format=annotation].
[[actuator.endpoints.implementing-custom.web]]
=== Custom Web Endpoints
Operations on an `@Endpoint`, `@WebEndpoint`, or `@EndpointWebExtension` are automatically exposed over HTTP using Jersey, Spring MVC, or Spring WebFlux.
Operations on an javadoc:org.springframework.boot.actuate.endpoint.annotation.Endpoint[format=annotation], javadoc:org.springframework.boot.actuate.endpoint.web.annotation.WebEndpoint[format=annotation], or javadoc:org.springframework.boot.actuate.endpoint.web.annotation.EndpointWebExtension[format=annotation] are automatically exposed over HTTP using Jersey, Spring MVC, or Spring WebFlux.
If both Jersey and Spring MVC are available, Spring MVC is used.
@ -468,7 +468,7 @@ The path of the predicate is determined by the ID of the endpoint and the base p
The default base path is `/actuator`.
For example, an endpoint with an ID of `sessions` uses `/actuator/sessions` as its path in the predicate.
You can further customize the path by annotating one or more parameters of the operation method with `@org.springframework.boot.actuate.endpoint.annotation.Selector`.
You can further customize the path by annotating one or more parameters of the operation method with javadoc:org.springframework.boot.actuate.endpoint.annotation.Selector[format=annotation].
Such a parameter is added to the path predicate as a path variable.
The variable's value is passed into the operation method when the endpoint operation is invoked.
If you want to capture all remaining path elements, you can add `@Selector(Match=ALL_REMAINING)` to the last parameter and make it a type that is conversion-compatible with a `String[]`.
@ -484,13 +484,13 @@ The HTTP method of the predicate is determined by the operation type, as shown i
|===
| Operation | HTTP method
| `@ReadOperation`
| javadoc:org.springframework.boot.actuate.endpoint.annotation.ReadOperation[format=annotation]
| `GET`
| `@WriteOperation`
| javadoc:org.springframework.boot.actuate.endpoint.annotation.WriteOperation[format=annotation]
| `POST`
| `@DeleteOperation`
| javadoc:org.springframework.boot.actuate.endpoint.annotation.DeleteOperation[format=annotation]
| `DELETE`
|===
@ -499,7 +499,7 @@ The HTTP method of the predicate is determined by the operation type, as shown i
[[actuator.endpoints.implementing-custom.web.consumes-predicates]]
==== Consumes
For a `@WriteOperation` (HTTP `POST`) that uses the request body, the `consumes` clause of the predicate is `application/vnd.spring-boot.actuator.v2+json, application/json`.
For a javadoc:org.springframework.boot.actuate.endpoint.annotation.WriteOperation[format=annotation] (HTTP `POST`) that uses the request body, the `consumes` clause of the predicate is `application/vnd.spring-boot.actuator.v2+json, application/json`.
For all other operations, the `consumes` clause is empty.
@ -507,12 +507,12 @@ For all other operations, the `consumes` clause is empty.
[[actuator.endpoints.implementing-custom.web.produces-predicates]]
==== Produces
The `produces` clause of the predicate can be determined by the `produces` attribute of the `@DeleteOperation`, `@ReadOperation`, and `@WriteOperation` annotations.
The `produces` clause of the predicate can be determined by the `produces` attribute of the javadoc:org.springframework.boot.actuate.endpoint.annotation.DeleteOperation[format=annotation], javadoc:org.springframework.boot.actuate.endpoint.annotation.ReadOperation[format=annotation], and javadoc:org.springframework.boot.actuate.endpoint.annotation.WriteOperation[format=annotation] annotations.
The attribute is optional.
If it is not used, the `produces` clause is determined automatically.
If the operation method returns `void` or `Void`, the `produces` clause is empty.
If the operation method returns a `org.springframework.core.io.Resource`, the `produces` clause is `application/octet-stream`.
If the operation method returns `void` or javadoc:java.lang.Void[], the `produces` clause is empty.
If the operation method returns a javadoc:org.springframework.core.io.Resource[], the `produces` clause is `application/octet-stream`.
For all other operations, the `produces` clause is `application/vnd.spring-boot.actuator.v2+json, application/json`.
@ -522,10 +522,10 @@ For all other operations, the `produces` clause is `application/vnd.spring-boot.
The default response status for an endpoint operation depends on the operation type (read, write, or delete) and what, if anything, the operation returns.
If a `@ReadOperation` returns a value, the response status will be 200 (OK).
If a javadoc:org.springframework.boot.actuate.endpoint.annotation.ReadOperation[format=annotation] returns a value, the response status will be 200 (OK).
If it does not return a value, the response status will be 404 (Not Found).
If a `@WriteOperation` or `@DeleteOperation` returns a value, the response status will be 200 (OK).
If a javadoc:org.springframework.boot.actuate.endpoint.annotation.WriteOperation[format=annotation] or javadoc:org.springframework.boot.actuate.endpoint.annotation.DeleteOperation[format=annotation] returns a value, the response status will be 200 (OK).
If it does not return a value, the response status will be 204 (No Content).
If an operation is invoked without a required parameter or with a parameter that cannot be converted to the required type, the operation method is not called, and the response status will be 400 (Bad Request).
@ -536,7 +536,7 @@ If an operation is invoked without a required parameter or with a parameter that
==== Web Endpoint Range Requests
You can use an HTTP range request to request part of an HTTP resource.
When using Spring MVC or Spring Web Flux, operations that return a `org.springframework.core.io.Resource` automatically support range requests.
When using Spring MVC or Spring Web Flux, operations that return a javadoc:org.springframework.core.io.Resource[] automatically support range requests.
NOTE: Range requests are not supported when using Jersey.
@ -545,8 +545,8 @@ NOTE: Range requests are not supported when using Jersey.
[[actuator.endpoints.implementing-custom.web.security]]
==== Web Endpoint Security
An operation on a web endpoint or a web-specific endpoint extension can receive the current `java.security.Principal` or `org.springframework.boot.actuate.endpoint.SecurityContext` as a method parameter.
The former is typically used in conjunction with either `+@javax.annotation.Nullable+` or `@org.springframework.lang.Nullable` to provide different behavior for authenticated and unauthenticated users.
An operation on a web endpoint or a web-specific endpoint extension can receive the current javadoc:java.security.Principal[] or javadoc:org.springframework.boot.actuate.endpoint.SecurityContext[] as a method parameter.
The former is typically used in conjunction with either `+@javax.annotation.Nullable+` or javadoc:org.springframework.lang.Nullable[format=annotation] to provide different behavior for authenticated and unauthenticated users.
The latter is typically used to perform authorization checks by using its `isUserInRole(String)` method.
@ -580,26 +580,26 @@ You can configure the roles by using the configprop:management.endpoint.health.r
NOTE: If you have secured your application and wish to use `always`, your security configuration must permit access to the health endpoint for both authenticated and unauthenticated users.
Health information is collected from the content of a javadoc:org.springframework.boot.actuate.health.HealthContributorRegistry[] (by default, all javadoc:org.springframework.boot.actuate.health.HealthContributor[] instances defined in your `ApplicationContext`).
Spring Boot includes a number of auto-configured `HealthContributor` beans, and you can also write your own.
Health information is collected from the content of a javadoc:org.springframework.boot.actuate.health.HealthContributorRegistry[] (by default, all javadoc:org.springframework.boot.actuate.health.HealthContributor[] instances defined in your javadoc:org.springframework.context.ApplicationContext[]).
Spring Boot includes a number of auto-configured javadoc:org.springframework.boot.actuate.health.HealthContributor[] beans, and you can also write your own.
A `HealthContributor` can be either a `HealthIndicator` or a `CompositeHealthContributor`.
A `HealthIndicator` provides actual health information, including a `org.springframework.boot.actuate.health.Status`.
A `CompositeHealthContributor` provides a composite of other `HealthContributor` instances.
A javadoc:org.springframework.boot.actuate.health.HealthContributor[] can be either a javadoc:org.springframework.boot.actuate.health.HealthIndicator[] or a javadoc:org.springframework.boot.actuate.health.CompositeHealthContributor[].
A javadoc:org.springframework.boot.actuate.health.HealthIndicator[] provides actual health information, including a javadoc:org.springframework.boot.actuate.health.Status[].
A javadoc:org.springframework.boot.actuate.health.CompositeHealthContributor[] provides a composite of other javadoc:org.springframework.boot.actuate.health.HealthContributor[] instances.
Taken together, contributors form a tree structure to represent the overall system health.
By default, the final system health is derived by a `StatusAggregator`, which sorts the statuses from each `HealthIndicator` based on an ordered list of statuses.
By default, the final system health is derived by a javadoc:org.springframework.boot.actuate.health.StatusAggregator[], which sorts the statuses from each javadoc:org.springframework.boot.actuate.health.HealthIndicator[] based on an ordered list of statuses.
The first status in the sorted list is used as the overall health status.
If no `HealthIndicator` returns a status that is known to the `StatusAggregator`, an `UNKNOWN` status is used.
If no javadoc:org.springframework.boot.actuate.health.HealthIndicator[] returns a status that is known to the javadoc:org.springframework.boot.actuate.health.StatusAggregator[], an `UNKNOWN` status is used.
TIP: You can use the `HealthContributorRegistry` to register and unregister health indicators at runtime.
TIP: You can use the javadoc:org.springframework.boot.actuate.health.HealthContributorRegistry[] to register and unregister health indicators at runtime.
[[actuator.endpoints.health.auto-configured-health-indicators]]
=== Auto-configured HealthIndicators
When appropriate, Spring Boot auto-configures the `HealthIndicator` beans listed in the following table.
When appropriate, Spring Boot auto-configures the javadoc:org.springframework.boot.actuate.health.HealthIndicator[] beans listed in the following table.
You can also enable or disable selected indicators by configuring `management.health.key.enabled`,
with the `key` listed in the following table:
@ -617,7 +617,7 @@ with the `key` listed in the following table:
| `db`
| javadoc:org.springframework.boot.actuate.jdbc.DataSourceHealthIndicator[]
| Checks that a connection to `DataSource` can be obtained.
| Checks that a connection to javadoc:javax.sql.DataSource[] can be obtained.
| `diskspace`
| javadoc:org.springframework.boot.actuate.system.DiskSpaceHealthIndicator[]
@ -670,11 +670,11 @@ with the `key` listed in the following table:
TIP: You can disable them all by setting the configprop:management.health.defaults.enabled[] property.
TIP: The `ssl` `HealthIndicator` has a "warning threshold" property named configprop:management.health.ssl.certificate-validity-warning-threshold[].
If an SSL certificate will be invalid within the time span defined by this threshold, the `HealthIndicator` will warn you but it will still return HTTP 200 to not disrupt the application.
TIP: The `ssl` javadoc:org.springframework.boot.actuate.health.HealthIndicator[] has a "warning threshold" property named configprop:management.health.ssl.certificate-validity-warning-threshold[].
If an SSL certificate will be invalid within the time span defined by this threshold, the javadoc:org.springframework.boot.actuate.health.HealthIndicator[] will warn you but it will still return HTTP 200 to not disrupt the application.
You can use this threshold to give yourself enough lead time to rotate the soon to be expired certificate.
Additional `HealthIndicator` beans are available but are not enabled by default:
Additional javadoc:org.springframework.boot.actuate.health.HealthIndicator[] beans are available but are not enabled by default:
[cols="3,4,6"]
|===
@ -695,23 +695,23 @@ Additional `HealthIndicator` beans are available but are not enabled by default:
=== Writing Custom HealthIndicators
To provide custom health information, you can register Spring beans that implement the javadoc:org.springframework.boot.actuate.health.HealthIndicator[] interface.
You need to provide an implementation of the `health()` method and return a `Health` response.
The `Health` response should include a status and can optionally include additional details to be displayed.
The following code shows a sample `HealthIndicator` implementation:
You need to provide an implementation of the `health()` method and return a javadoc:org.springframework.boot.actuate.health.Health[] response.
The javadoc:org.springframework.boot.actuate.health.Health[] response should include a status and can optionally include additional details to be displayed.
The following code shows a sample javadoc:org.springframework.boot.actuate.health.HealthIndicator[] implementation:
include-code::MyHealthIndicator[]
NOTE: The identifier for a given `HealthIndicator` is the name of the bean without the `HealthIndicator` suffix, if it exists.
NOTE: The identifier for a given javadoc:org.springframework.boot.actuate.health.HealthIndicator[] is the name of the bean without the javadoc:org.springframework.boot.actuate.health.HealthIndicator[] suffix, if it exists.
In the preceding example, the health information is available in an entry named `my`.
TIP: Health indicators are usually called over HTTP and need to respond before any connection timeouts.
Spring Boot will log a warning message for any health indicator that takes longer than 10 seconds to respond.
If you want to configure this threshold, you can use the configprop:management.endpoint.health.logging.slow-indicator-threshold[] property.
In addition to Spring Boot's predefined `org.springframework.boot.actuate.health.Status` types, `Health` can return a custom `org.springframework.boot.actuate.health.Status` that represents a new system state.
In addition to Spring Boot's predefined javadoc:org.springframework.boot.actuate.health.Status[] types, javadoc:org.springframework.boot.actuate.health.Health[] can return a custom javadoc:org.springframework.boot.actuate.health.Status[] that represents a new system state.
In such cases, you also need to provide a custom implementation of the javadoc:org.springframework.boot.actuate.health.StatusAggregator[] interface, or you must configure the default implementation by using the configprop:management.endpoint.health.status.order[] configuration property.
For example, assume a new `org.springframework.boot.actuate.health.Status` with a code of `FATAL` is being used in one of your `HealthIndicator` implementations.
For example, assume a new javadoc:org.springframework.boot.actuate.health.Status[] with a code of `FATAL` is being used in one of your javadoc:org.springframework.boot.actuate.health.HealthIndicator[] implementations.
To configure the severity order, add the following property to your application properties:
[configprops,yaml]
@ -743,7 +743,7 @@ management:
out-of-service: 503
----
TIP: If you need more control, you can define your own `HttpCodeStatusMapper` bean.
TIP: If you need more control, you can define your own javadoc:org.springframework.boot.actuate.health.HttpCodeStatusMapper[] bean.
The following table shows the default status mappings for the built-in statuses:
@ -769,26 +769,26 @@ The following table shows the default status mappings for the built-in statuses:
[[actuator.endpoints.health.reactive-health-indicators]]
=== Reactive Health Indicators
For reactive applications, such as those that use Spring WebFlux, `ReactiveHealthContributor` provides a non-blocking contract for getting application health.
Similar to a traditional `HealthContributor`, health information is collected from the content of a javadoc:org.springframework.boot.actuate.health.ReactiveHealthContributorRegistry[] (by default, all javadoc:org.springframework.boot.actuate.health.HealthContributor[] and javadoc:org.springframework.boot.actuate.health.ReactiveHealthContributor[] instances defined in your `ApplicationContext`).
Regular `HealthContributor` instances that do not check against a reactive API are executed on the elastic scheduler.
For reactive applications, such as those that use Spring WebFlux, javadoc:org.springframework.boot.actuate.health.ReactiveHealthContributor[] provides a non-blocking contract for getting application health.
Similar to a traditional javadoc:org.springframework.boot.actuate.health.HealthContributor[], health information is collected from the content of a javadoc:org.springframework.boot.actuate.health.ReactiveHealthContributorRegistry[] (by default, all javadoc:org.springframework.boot.actuate.health.HealthContributor[] and javadoc:org.springframework.boot.actuate.health.ReactiveHealthContributor[] instances defined in your javadoc:org.springframework.context.ApplicationContext[]).
Regular javadoc:org.springframework.boot.actuate.health.HealthContributor[] instances that do not check against a reactive API are executed on the elastic scheduler.
TIP: In a reactive application, you should use the `ReactiveHealthContributorRegistry` to register and unregister health indicators at runtime.
If you need to register a regular `HealthContributor`, you should wrap it with `ReactiveHealthContributor#adapt`.
TIP: In a reactive application, you should use the javadoc:org.springframework.boot.actuate.health.ReactiveHealthContributorRegistry[] to register and unregister health indicators at runtime.
If you need to register a regular javadoc:org.springframework.boot.actuate.health.HealthContributor[], you should wrap it with `ReactiveHealthContributor#adapt`.
To provide custom health information from a reactive API, you can register Spring beans that implement the javadoc:org.springframework.boot.actuate.health.ReactiveHealthIndicator[] interface.
The following code shows a sample `ReactiveHealthIndicator` implementation:
The following code shows a sample javadoc:org.springframework.boot.actuate.health.ReactiveHealthIndicator[] implementation:
include-code::MyReactiveHealthIndicator[]
TIP: To handle the error automatically, consider extending from `AbstractReactiveHealthIndicator`.
TIP: To handle the error automatically, consider extending from javadoc:org.springframework.boot.actuate.health.AbstractReactiveHealthIndicator[].
[[actuator.endpoints.health.auto-configured-reactive-health-indicators]]
=== Auto-configured ReactiveHealthIndicators
When appropriate, Spring Boot auto-configures the following `ReactiveHealthIndicator` beans:
When appropriate, Spring Boot auto-configures the following javadoc:org.springframework.boot.actuate.health.ReactiveHealthIndicator[] beans:
[cols="2,4,6"]
|===
@ -820,7 +820,7 @@ When appropriate, Spring Boot auto-configures the following `ReactiveHealthIndic
|===
TIP: If necessary, reactive indicators replace the regular ones.
Also, any `HealthIndicator` that is not handled explicitly is wrapped automatically.
Also, any javadoc:org.springframework.boot.actuate.health.HealthIndicator[] that is not handled explicitly is wrapped automatically.
@ -859,7 +859,7 @@ management:
By default, startup will fail if a health group includes or excludes a health indicator that does not exist.
To disable this behavior set configprop:management.endpoint.health.validate-group-membership[] to `false`.
By default, groups inherit the same `StatusAggregator` and `HttpCodeStatusMapper` settings as the system health.
By default, groups inherit the same javadoc:org.springframework.boot.actuate.health.StatusAggregator[] and javadoc:org.springframework.boot.actuate.health.HttpCodeStatusMapper[] settings as the system health.
However, you can also define these on a per-group basis.
You can also override the `show-details` and `roles` properties if required:
@ -879,10 +879,10 @@ management:
out-of-service: 500
----
TIP: You can use `@Qualifier("groupname")` if you need to register custom `StatusAggregator` or `HttpCodeStatusMapper` beans for use with the group.
TIP: You can use `@Qualifier("groupname")` if you need to register custom javadoc:org.springframework.boot.actuate.health.StatusAggregator[] or javadoc:org.springframework.boot.actuate.health.HttpCodeStatusMapper[] beans for use with the group.
A health group can also include/exclude a `CompositeHealthContributor`.
You can also include/exclude only a certain component of a `CompositeHealthContributor`.
A health group can also include/exclude a javadoc:org.springframework.boot.actuate.health.CompositeHealthContributor[].
You can also include/exclude only a certain component of a javadoc:org.springframework.boot.actuate.health.CompositeHealthContributor[].
This can be done using the fully qualified name of the component as follows:
[source,properties]
@ -891,8 +891,8 @@ management.endpoint.health.group.custom.include="test/primary"
management.endpoint.health.group.custom.exclude="test/primary/b"
----
In the example above, the `custom` group will include the `HealthContributor` with the name `primary` which is a component of the composite `test`.
Here, `primary` itself is a composite and the `HealthContributor` with the name `b` will be excluded from the `custom` group.
In the example above, the `custom` group will include the javadoc:org.springframework.boot.actuate.health.HealthContributor[] with the name `primary` which is a component of the composite `test`.
Here, `primary` itself is a composite and the javadoc:org.springframework.boot.actuate.health.HealthContributor[] with the name `b` will be excluded from the `custom` group.
Health groups can be made available at an additional path on either the main or management port.
@ -914,7 +914,7 @@ The path must be a single path segment.
[[actuator.endpoints.health.datasource]]
=== DataSource Health
The `DataSource` health indicator shows the health of both standard data sources and routing data source beans.
The javadoc:javax.sql.DataSource[] health indicator shows the health of both standard data sources and routing data source beans.
The health of a routing data source includes the health of each of its target data sources.
In the health endpoint's response, each of a routing data source's targets is named by using its routing key.
If you prefer not to include routing data sources in the indicator's output, set configprop:management.health.db.ignore-routing-data-sources[] to `true`.
@ -928,7 +928,7 @@ Applications deployed on Kubernetes can provide information about their internal
Depending on https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/[your Kubernetes configuration], the kubelet calls those probes and reacts to the result.
By default, Spring Boot manages your xref:features/spring-application.adoc#features.spring-application.application-availability[Application Availability] state.
If deployed in a Kubernetes environment, actuator gathers the "`Liveness`" and "`Readiness`" information from the `ApplicationAvailability` interface and uses that information in dedicated xref:actuator/endpoints.adoc#actuator.endpoints.health.auto-configured-health-indicators[health indicators]: `LivenessStateHealthIndicator` and `ReadinessStateHealthIndicator`.
If deployed in a Kubernetes environment, actuator gathers the "`Liveness`" and "`Readiness`" information from the javadoc:org.springframework.boot.availability.ApplicationAvailability[] interface and uses that information in dedicated xref:actuator/endpoints.adoc#actuator.endpoints.health.auto-configured-health-indicators[health indicators]: javadoc:org.springframework.boot.actuate.availability.LivenessStateHealthIndicator[] and javadoc:org.springframework.boot.actuate.availability.ReadinessStateHealthIndicator[].
These indicators are shown on the global health endpoint (`"/actuator/health"`).
They are also exposed as separate HTTP Probes by using xref:actuator/endpoints.adoc#actuator.endpoints.health.groups[health groups]: `"/actuator/health/liveness"` and `"/actuator/health/readiness"`.
@ -1022,14 +1022,14 @@ Also, if an application uses Kubernetes https://kubernetes.io/docs/tasks/run-app
=== Application Lifecycle and Probe States
An important aspect of the Kubernetes Probes support is its consistency with the application lifecycle.
There is a significant difference between the `AvailabilityState` (which is the in-memory, internal state of the application)
There is a significant difference between the javadoc:org.springframework.boot.availability.AvailabilityState[] (which is the in-memory, internal state of the application)
and the actual probe (which exposes that state).
Depending on the phase of application lifecycle, the probe might not be available.
Spring Boot publishes xref:features/spring-application.adoc#features.spring-application.application-events-and-listeners[application events during startup and shutdown],
and probes can listen to such events and expose the `AvailabilityState` information.
and probes can listen to such events and expose the javadoc:org.springframework.boot.availability.AvailabilityState[] information.
The following tables show the `AvailabilityState` and the state of HTTP connectors at different stages.
The following tables show the javadoc:org.springframework.boot.availability.AvailabilityState[] and the state of HTTP connectors at different stages.
When a Spring Boot application starts:
@ -1088,15 +1088,15 @@ TIP: See xref:how-to:deployment/cloud.adoc#howto.deployment.cloud.kubernetes.con
[[actuator.endpoints.info]]
== Application Information
Application information exposes various information collected from all javadoc:org.springframework.boot.actuate.info.InfoContributor[] beans defined in your `ApplicationContext`.
Spring Boot includes a number of auto-configured `InfoContributor` beans, and you can write your own.
Application information exposes various information collected from all javadoc:org.springframework.boot.actuate.info.InfoContributor[] beans defined in your javadoc:org.springframework.context.ApplicationContext[].
Spring Boot includes a number of auto-configured javadoc:org.springframework.boot.actuate.info.InfoContributor[] beans, and you can write your own.
[[actuator.endpoints.info.auto-configured-info-contributors]]
=== Auto-configured InfoContributors
When appropriate, Spring auto-configures the following `InfoContributor` beans:
When appropriate, Spring auto-configures the following javadoc:org.springframework.boot.actuate.info.InfoContributor[] beans:
[cols="1,4,8,4"]
|===
@ -1109,7 +1109,7 @@ When appropriate, Spring auto-configures the following `InfoContributor` beans:
| `env`
| javadoc:org.springframework.boot.actuate.info.EnvironmentInfoContributor[]
| Exposes any property from the `Environment` whose name starts with `info.`.
| Exposes any property from the javadoc:org.springframework.core.env.Environment[] whose name starts with `info.`.
| None.
| `git`
@ -1155,7 +1155,7 @@ Alternatively, to disable every contributor that is usually enabled by default,
=== Custom Application Information
When the `env` contributor is enabled, you can customize the data exposed by the `info` endpoint by setting `+info.*+` Spring properties.
All `Environment` properties under the `info` key are automatically exposed.
All javadoc:org.springframework.core.env.Environment[] properties under the `info` key are automatically exposed.
For example, you could add the following settings to your `application.properties` file:
[configprops,yaml]
@ -1191,9 +1191,9 @@ info:
=== Git Commit Information
Another useful feature of the `info` endpoint is its ability to publish information about the state of your `git` source code repository when the project was built.
If a `GitProperties` bean is available, you can use the `info` endpoint to expose these properties.
If a javadoc:org.springframework.boot.info.GitProperties[] bean is available, you can use the `info` endpoint to expose these properties.
TIP: A `GitProperties` bean is auto-configured if a `git.properties` file is available at the root of the classpath.
TIP: A javadoc:org.springframework.boot.info.GitProperties[] bean is auto-configured if a `git.properties` file is available at the root of the classpath.
See xref:how-to:build.adoc#howto.build.generate-git-info[] for more detail.
By default, the endpoint exposes `git.branch`, `git.commit.id`, and `git.commit.time` properties, if present.
@ -1223,7 +1223,7 @@ management:
[[actuator.endpoints.info.build-information]]
=== Build Information
If a `BuildProperties` bean is available, the `info` endpoint can also publish information about your build.
If a javadoc:org.springframework.boot.info.BuildProperties[] bean is available, the `info` endpoint can also publish information about your build.
This happens if a `META-INF/build-info.properties` file is available in the classpath.
TIP: The Maven and Gradle plugins can both generate that file.

View File

@ -1,13 +1,13 @@
[[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.
You can enable recording of HTTP exchanges by providing a bean of type javadoc:org.springframework.boot.actuate.web.exchanges.HttpExchangeRepository[] in your application's configuration.
For convenience, Spring Boot offers javadoc:org.springframework.boot.actuate.web.exchanges.InMemoryHttpExchangeRepository[], which, by default, stores the last 100 request-response exchanges.
javadoc:org.springframework.boot.actuate.web.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`.
Alternatively, you can create your own javadoc:org.springframework.boot.actuate.web.exchanges.HttpExchangeRepository[].
You can use the `httpexchanges` endpoint to obtain information about the request-response exchanges that are stored in the `HttpExchangeRepository`.
You can use the `httpexchanges` endpoint to obtain information about the request-response exchanges that are stored in the javadoc:org.springframework.boot.actuate.web.exchanges.HttpExchangeRepository[].

View File

@ -4,11 +4,11 @@
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 (`@org.springframework.jmx.export.annotation.ManagedResource`, `@org.springframework.jmx.export.annotation.ManagedAttribute`, or `@org.springframework.jmx.export.annotation.ManagedOperation`) are exposed to it.
Spring Boot exposes the most suitable javadoc:javax.management.MBeanServer[] as a bean with an ID of `mbeanServer`.
Any of your beans that are annotated with Spring JMX annotations (`@org.springframework.jmx.export.annotation.ManagedResource`, javadoc:org.springframework.jmx.export.annotation.ManagedAttribute[format=annotation], or javadoc:org.springframework.jmx.export.annotation.ManagedOperation[format=annotation]) 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.
If your platform provides a standard javadoc:javax.management.MBeanServer[], Spring Boot uses that and defaults to the VM javadoc:javax.management.MBeanServer[], if necessary.
If all that fails, a new javadoc:javax.management.MBeanServer[] is created.
NOTE: `spring.jmx.enabled` affects only the management beans provided by Spring.
Enabling management beans provided by other libraries (for example {url-log4j2-docs}/jmx.html[Log4j2] or {url-quartz-javadoc}/constant-values.html#org.quartz.impl.StdSchedulerFactory.PROP_SCHED_JMX_EXPORT[Quartz]) is independent.
@ -16,7 +16,7 @@ Enabling management beans provided by other libraries (for example {url-log4j2-d
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.
To take full control over endpoint registration in the JMX domain, consider registering your own javadoc:org.springframework.boot.actuate.endpoint.jmx.EndpointObjectNameFactory[] implementation.
@ -26,7 +26,7 @@ To take full control over endpoint registration in the JMX domain, consider regi
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.
If your application contains more than one Spring javadoc:org.springframework.context.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.

View File

@ -52,7 +52,7 @@ For more details, see the https://github.com/open-telemetry/opentelemetry-java-i
TIP: You have to configure the appender in your `logback-spring.xml` or `log4j2-spring.xml` configuration to get OpenTelemetry logging working.
The `+OpenTelemetryAppender+` for both Logback and Log4j requires access to an `OpenTelemetry` instance to function properly.
The `+OpenTelemetryAppender+` for both Logback and Log4j requires access to an javadoc:io.opentelemetry.api.OpenTelemetry[] instance to function properly.
This instance must be set programmatically during application startup, which can be done like this:
include-code::OpenTelemetryAppenderInitializer[]

View File

@ -30,7 +30,7 @@ TIP: To learn more about Micrometer's capabilities, see its {url-micrometer-docs
[[actuator.metrics.getting-started]]
== Getting Started
Spring Boot auto-configures a composite `MeterRegistry` and adds a registry to the composite for each of the supported implementations that it finds on the classpath.
Spring Boot auto-configures a composite javadoc:io.micrometer.core.instrument.MeterRegistry[] and adds a registry to the composite for each of the supported implementations that it finds on the classpath.
Having a dependency on `micrometer-registry-\{system}` in your runtime classpath is enough for Spring Boot to configure the registry.
Most registries share common features.
@ -57,7 +57,7 @@ management:
enabled: false
----
Spring Boot also adds any auto-configured registries to the global static composite registry on the `io.micrometer.core.instrument.Metrics` class, unless you explicitly tell it not to:
Spring Boot also adds any auto-configured registries to the global static composite registry on the javadoc:io.micrometer.core.instrument.Metrics[] class, unless you explicitly tell it not to:
[configprops,yaml]
----
@ -66,7 +66,7 @@ management:
use-global-registry: false
----
You can register any number of `MeterRegistryCustomizer` beans to further configure the registry, such as applying common tags, before any meters are registered with the registry:
You can register any number of javadoc:org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer[] beans to further configure the registry, such as applying common tags, before any meters are registered with the registry:
include-code::commontags/MyMeterRegistryConfiguration[]
@ -359,12 +359,12 @@ management:
port: 9004
----
Micrometer provides a default `HierarchicalNameMapper` that governs how a dimensional meter ID is {url-micrometer-docs-implementations}/graphite#_hierarchical_name_mapping[mapped to flat hierarchical names].
Micrometer provides a default javadoc:io.micrometer.core.instrument.util.HierarchicalNameMapper[] that governs how a dimensional meter ID is {url-micrometer-docs-implementations}/graphite#_hierarchical_name_mapping[mapped to flat hierarchical names].
[TIP]
====
To take control over this behavior, define your `GraphiteMeterRegistry` and supply your own `HierarchicalNameMapper`.
Auto-configured `GraphiteConfig` and `io.micrometer.core.instrument.Clock` beans are provided unless you define your own:
To take control over this behavior, define your javadoc:io.micrometer.graphite.GraphiteMeterRegistry[] and supply your own javadoc:io.micrometer.core.instrument.util.HierarchicalNameMapper[].
Auto-configured javadoc:io.micrometer.graphite.GraphiteConfig[] and javadoc:io.micrometer.core.instrument.Clock[] beans are provided unless you define your own:
include-code::MyGraphiteConfiguration[]
====
@ -435,12 +435,12 @@ management:
domain: "com.example.app.metrics"
----
Micrometer provides a default `HierarchicalNameMapper` that governs how a dimensional meter ID is {url-micrometer-docs-implementations}/jmx#_hierarchical_name_mapping[mapped to flat hierarchical names].
Micrometer provides a default javadoc:io.micrometer.core.instrument.util.HierarchicalNameMapper[] that governs how a dimensional meter ID is {url-micrometer-docs-implementations}/jmx#_hierarchical_name_mapping[mapped to flat hierarchical names].
[TIP]
====
To take control over this behavior, define your `JmxMeterRegistry` and supply your own `HierarchicalNameMapper`.
Auto-configured `JmxConfig` and `io.micrometer.core.instrument.Clock` beans are provided unless you define your own:
To take control over this behavior, define your javadoc:io.micrometer.jmx.JmxMeterRegistry[] and supply your own javadoc:io.micrometer.core.instrument.util.HierarchicalNameMapper[].
Auto-configured javadoc:io.micrometer.jmx.JmxConfig[] and javadoc:io.micrometer.core.instrument.Clock[] beans are provided unless you define your own:
include-code::MyJmxConfiguration[]
====
@ -502,7 +502,7 @@ management:
client-provider-type: "insights-agent"
----
Finally, you can take full control by defining your own `NewRelicClientProvider` bean.
Finally, you can take full control by defining your own javadoc:io.micrometer.newrelic.NewRelicClientProvider[] bean.
@ -543,8 +543,8 @@ scrape_configs:
----
https://prometheus.io/docs/prometheus/latest/feature_flags/#exemplars-storage[Prometheus Exemplars] are also supported.
To enable this feature, a `io.prometheus.metrics.tracer.common.SpanContext` bean should be present.
If you're using the deprecated Prometheus simpleclient support and want to enable that feature, a `SpanContextSupplier` bean should be present.
To enable this feature, a javadoc:io.prometheus.metrics.tracer.common.SpanContext[] bean should be present.
If you're using the deprecated Prometheus simpleclient support and want to enable that feature, a javadoc:io.prometheus.client.exemplars.tracer.common.SpanContextSupplier[] bean should be present.
If you use {url-micrometer-tracing-docs}[Micrometer Tracing], this will be auto-configured for you, but you can always create your own if you want.
Please check the https://prometheus.io/docs/prometheus/latest/feature_flags/#exemplars-storage[Prometheus Docs], since this feature needs to be explicitly enabled on Prometheus' side, and it is only supported using the https://github.com/OpenObservability/OpenMetrics/blob/v1.0.0/specification/OpenMetrics.md#exemplars[OpenMetrics] format.
@ -563,11 +563,11 @@ To enable Prometheus Pushgateway support, add the following dependency to your p
</dependency>
----
When the Prometheus Pushgateway dependency is present on the classpath and the configprop:management.prometheus.metrics.export.pushgateway.enabled[] property is set to `true`, a `PrometheusPushGatewayManager` bean is auto-configured.
When the Prometheus Pushgateway dependency is present on the classpath and the configprop:management.prometheus.metrics.export.pushgateway.enabled[] property is set to `true`, a javadoc:org.springframework.boot.actuate.metrics.export.prometheus.PrometheusPushGatewayManager[] bean is auto-configured.
This manages the pushing of metrics to a Prometheus Pushgateway.
You can tune the `PrometheusPushGatewayManager` by using properties under `management.prometheus.metrics.export.pushgateway`.
For advanced configuration, you can also provide your own `PrometheusPushGatewayManager` bean.
You can tune the javadoc:org.springframework.boot.actuate.metrics.export.prometheus.PrometheusPushGatewayManager[] by using properties under `management.prometheus.metrics.export.pushgateway`.
For advanced configuration, you can also provide your own javadoc:org.springframework.boot.actuate.metrics.export.prometheus.PrometheusPushGatewayManager[] bean.
@ -778,7 +778,7 @@ The details are published under the `log4j2.events.` or `logback.events.` meter
[[actuator.metrics.supported.tasks]]
=== Task Execution and Scheduling Metrics
Auto-configuration enables the instrumentation of all available `ThreadPoolTaskExecutor` and `ThreadPoolTaskScheduler` beans, as long as the underling `ThreadPoolExecutor` is available.
Auto-configuration enables the instrumentation of all available javadoc:org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor[] and javadoc:org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler[] beans, as long as the underling javadoc:java.util.concurrent.ThreadPoolExecutor[] is available.
Metrics are tagged by the name of the executor, which is derived from the bean name.
@ -786,7 +786,7 @@ Metrics are tagged by the name of the executor, which is derived from the bean n
[[actuator.metrics.supported.jms]]
=== JMS Metrics
Auto-configuration enables the instrumentation of all available `JmsTemplate` beans and `@JmsListener` annotated methods.
Auto-configuration enables the instrumentation of all available javadoc:org.springframework.jms.core.JmsTemplate[] beans and javadoc:org.springframework.jms.annotation.JmsListener[format=annotation] annotated methods.
This will produce `"jms.message.publish"` and `"jms.message.process"` metrics respectively.
See the {url-spring-framework-docs}/integration/observability.html#observability.jms[Spring Framework reference documentation for more information on produced observations].
@ -801,15 +801,15 @@ You can customize the name by setting the configprop:management.observations.htt
See the {url-spring-framework-docs}/integration/observability.html#observability.http-server.servlet[Spring Framework reference documentation for more information on produced observations].
To add to the default tags, provide a `@Bean` that extends `org.springframework.http.server.observation.DefaultServerRequestObservationConvention` from the `org.springframework.http.server.observation` package.
To replace the default tags, provide a `@Bean` that implements `org.springframework.http.server.observation.ServerRequestObservationConvention`.
To add to the default tags, provide a javadoc:org.springframework.context.annotation.Bean[format=annotation] that extends javadoc:org.springframework.http.server.observation.DefaultServerRequestObservationConvention[] from the `org.springframework.http.server.observation` package.
To replace the default tags, provide a javadoc:org.springframework.context.annotation.Bean[format=annotation] that implements javadoc:org.springframework.http.server.observation.ServerRequestObservationConvention[].
TIP: In some cases, exceptions handled in web controllers are not recorded as request metrics tags.
Applications can opt in and record exceptions by xref:web/servlet.adoc#web.servlet.spring-mvc.error-handling[setting handled exceptions as request attributes].
By default, all requests are handled.
To customize the filter, provide a `@Bean` that implements `FilterRegistrationBean<ServerHttpObservationFilter>`.
To customize the filter, provide a javadoc:org.springframework.context.annotation.Bean[format=annotation] that implements `FilterRegistrationBean<ServerHttpObservationFilter>`.
@ -822,8 +822,8 @@ You can customize the name by setting the configprop:management.observations.htt
See the {url-spring-framework-docs}/integration/observability.html#observability.http-server.reactive[Spring Framework reference documentation for more information on produced observations].
To add to the default tags, provide a `@Bean` that extends `org.springframework.http.server.reactive.observation.DefaultServerRequestObservationConvention` from the `org.springframework.http.server.reactive.observation` package.
To replace the default tags, provide a `@Bean` that implements `org.springframework.http.server.reactive.observation.ServerRequestObservationConvention`.
To add to the default tags, provide a javadoc:org.springframework.context.annotation.Bean[format=annotation] that extends javadoc:org.springframework.http.server.reactive.observation.DefaultServerRequestObservationConvention[] from the `org.springframework.http.server.reactive.observation` package.
To replace the default tags, provide a javadoc:org.springframework.context.annotation.Bean[format=annotation] that implements javadoc:org.springframework.http.server.reactive.observation.ServerRequestObservationConvention[].
TIP: In some cases, exceptions handled in controllers and handler functions are not recorded as request metrics tags.
Applications can opt in and record exceptions by xref:web/reactive.adoc#web.reactive.webflux.error-handling[setting handled exceptions as request attributes].
@ -859,36 +859,36 @@ By default, Jersey server metrics are tagged with the following information:
| The request's URI template prior to variable substitution, if possible (for example, `/api/person/\{id}`)
|===
To customize the tags, provide a `@Bean` that implements `JerseyObservationConvention`.
To customize the tags, provide a javadoc:org.springframework.context.annotation.Bean[format=annotation] that implements javadoc:io.micrometer.core.instrument.binder.jersey.server.JerseyObservationConvention[].
[[actuator.metrics.supported.http-clients]]
=== HTTP Client Metrics
Spring Boot Actuator manages the instrumentation of `RestTemplate`, `WebClient` and `RestClient`.
Spring Boot Actuator manages the instrumentation of javadoc:org.springframework.web.client.RestTemplate[], javadoc:org.springframework.web.reactive.function.client.WebClient[] and javadoc:org.springframework.web.client.RestClient[].
For that, you have to inject the auto-configured builder and use it to create instances:
* `RestTemplateBuilder` for `RestTemplate`
* `WebClient.Builder` for `WebClient`
* `RestClient.Builder` for `RestClient`
* javadoc:org.springframework.boot.web.client.RestTemplateBuilder[] for javadoc:org.springframework.web.client.RestTemplate[]
* javadoc:org.springframework.web.reactive.function.client.WebClient$Builder[] for javadoc:org.springframework.web.reactive.function.client.WebClient[]
* javadoc:org.springframework.web.client.RestClient$Builder[] for javadoc:org.springframework.web.client.RestClient[]
You can also manually apply the customizers responsible for this instrumentation, namely `ObservationRestTemplateCustomizer`, `ObservationWebClientCustomizer` and `ObservationRestClientCustomizer`.
You can also manually apply the customizers responsible for this instrumentation, namely javadoc:org.springframework.boot.actuate.metrics.web.client.ObservationRestTemplateCustomizer[], javadoc:org.springframework.boot.actuate.metrics.web.reactive.client.ObservationWebClientCustomizer[] and javadoc:org.springframework.boot.actuate.metrics.web.client.ObservationRestClientCustomizer[].
By default, metrics are generated with the name, `http.client.requests`.
You can customize the name by setting the configprop:management.observations.http.client.requests.name[] property.
See the {url-spring-framework-docs}/integration/observability.html#observability.http-client[Spring Framework reference documentation for more information on produced observations].
To customize the tags when using `RestTemplate` or `RestClient`, provide a `@Bean` that implements `org.springframework.http.client.observation.ClientRequestObservationConvention` from the `org.springframework.http.client.observation` package.
To customize the tags when using `WebClient`, provide a `@Bean` that implements `org.springframework.web.reactive.function.client.ClientRequestObservationConvention` from the `org.springframework.web.reactive.function.client` package.
To customize the tags when using javadoc:org.springframework.web.client.RestTemplate[] or javadoc:org.springframework.web.client.RestClient[], provide a javadoc:org.springframework.context.annotation.Bean[format=annotation] that implements javadoc:org.springframework.http.client.observation.ClientRequestObservationConvention[] from the `org.springframework.http.client.observation` package.
To customize the tags when using javadoc:org.springframework.web.reactive.function.client.WebClient[], provide a javadoc:org.springframework.context.annotation.Bean[format=annotation] that implements javadoc:org.springframework.web.reactive.function.client.ClientRequestObservationConvention[] from the `org.springframework.web.reactive.function.client` package.
[[actuator.metrics.supported.tomcat]]
=== Tomcat Metrics
Auto-configuration enables the instrumentation of Tomcat only when an MBean `org.apache.tomcat.util.modeler.Registry` is enabled.
Auto-configuration enables the instrumentation of Tomcat only when an MBean javadoc:org.apache.tomcat.util.modeler.Registry[] is enabled.
By default, the MBean registry is disabled, but you can enable it by setting configprop:server.tomcat.mbeanregistry.enabled[] to `true`.
Tomcat metrics are published under the `tomcat.` meter name.
@ -898,7 +898,7 @@ Tomcat metrics are published under the `tomcat.` meter name.
[[actuator.metrics.supported.cache]]
=== Cache Metrics
Auto-configuration enables the instrumentation of all available `org.springframework.cache.Cache` instances on startup, with metrics prefixed with `cache`.
Auto-configuration enables the instrumentation of all available javadoc:org.springframework.cache.Cache[] instances on startup, with metrics prefixed with `cache`.
Cache instrumentation is standardized for a basic set of metrics.
Additional, cache-specific metrics are also available.
@ -910,11 +910,11 @@ The following cache libraries are supported:
* Any compliant JCache (JSR-107) implementation
* Redis
Metrics are tagged by the name of the cache and by the name of the `org.springframework.cache.CacheManager`, which is derived from the bean name.
Metrics are tagged by the name of the cache and by the name of the javadoc:org.springframework.cache.CacheManager[], which is derived from the bean name.
NOTE: Only caches that are configured on startup are bound to the registry.
For caches not defined in the caches configuration, such as caches created on the fly or programmatically after the startup phase, an explicit registration is required.
A `CacheMetricsRegistrar` bean is made available to make that process easier.
A javadoc:org.springframework.boot.actuate.metrics.cache.CacheMetricsRegistrar[] bean is made available to make that process easier.
@ -935,14 +935,14 @@ See the {url-spring-graphql-docs}/observability.html[Spring GraphQL reference do
[[actuator.metrics.supported.jdbc]]
=== DataSource Metrics
Auto-configuration enables the instrumentation of all available `DataSource` objects with metrics prefixed with `jdbc.connections`.
Auto-configuration enables the instrumentation of all available javadoc:javax.sql.DataSource[] objects with metrics prefixed with `jdbc.connections`.
Data source instrumentation results in gauges that represent the currently active, idle, maximum allowed, and minimum allowed connections in the pool.
Metrics are also tagged by the name of the `DataSource` computed based on the bean name.
Metrics are also tagged by the name of the javadoc:javax.sql.DataSource[] computed based on the bean name.
TIP: By default, Spring Boot provides metadata for all supported data sources.
You can add additional `DataSourcePoolMetadataProvider` beans if your favorite data source is not supported.
See `DataSourcePoolMetadataProvidersConfiguration` for examples.
You can add additional javadoc:org.springframework.boot.jdbc.metadata.DataSourcePoolMetadataProvider[] beans if your favorite data source is not supported.
See javadoc:org.springframework.boot.autoconfigure.jdbc.metadata.DataSourcePoolMetadataProvidersConfiguration[] for examples.
Also, Hikari-specific metrics are exposed with a `hikaricp` prefix.
Each metric is tagged by the name of the pool (you can control it with `spring.datasource.name`).
@ -952,12 +952,12 @@ Each metric is tagged by the name of the pool (you can control it with `spring.d
[[actuator.metrics.supported.hibernate]]
=== Hibernate Metrics
If `org.hibernate.orm:hibernate-micrometer` is on the classpath, all available Hibernate `EntityManagerFactory` instances that have statistics enabled are instrumented with a metric named `hibernate`.
If `org.hibernate.orm:hibernate-micrometer` is on the classpath, all available Hibernate javadoc:jakarta.persistence.EntityManagerFactory[] instances that have statistics enabled are instrumented with a metric named `hibernate`.
Metrics are also tagged by the name of the `EntityManagerFactory`, which is derived from the bean name.
Metrics are also tagged by the name of the javadoc:jakarta.persistence.EntityManagerFactory[], which is derived from the bean name.
To enable statistics, the standard JPA property `hibernate.generate_statistics` must be set to `true`.
You can enable that on the auto-configured `EntityManagerFactory`:
You can enable that on the auto-configured javadoc:jakarta.persistence.EntityManagerFactory[]:
[configprops,yaml]
----
@ -972,14 +972,14 @@ spring:
[[actuator.metrics.supported.spring-data-repository]]
=== Spring Data Repository Metrics
Auto-configuration enables the instrumentation of all Spring Data `org.springframework.data.repository.Repository` method invocations.
Auto-configuration enables the instrumentation of all Spring Data javadoc:org.springframework.data.repository.Repository[] method invocations.
By default, metrics are generated with the name, `spring.data.repository.invocations`.
You can customize the name by setting the configprop:management.metrics.data.repository.metric-name[] property.
The `@io.micrometer.core.annotation.Timed` annotation from the `io.micrometer.core.annotation` package is supported on `org.springframework.data.repository.Repository` interfaces and methods.
If you do not want to record metrics for all `org.springframework.data.repository.Repository` invocations, you can set configprop:management.metrics.data.repository.autotime.enabled[] to `false` and exclusively use `@io.micrometer.core.annotation.Timed` annotations instead.
The javadoc:io.micrometer.core.annotation.Timed[format=annotation] annotation from the `io.micrometer.core.annotation` package is supported on javadoc:org.springframework.data.repository.Repository[] interfaces and methods.
If you do not want to record metrics for all javadoc:org.springframework.data.repository.Repository[] invocations, you can set configprop:management.metrics.data.repository.autotime.enabled[] to `false` and exclusively use javadoc:io.micrometer.core.annotation.Timed[format=annotation] annotations instead.
NOTE: A `@io.micrometer.core.annotation.Timed` annotation with `longTask = true` enables a long task timer for the method.
NOTE: A javadoc:io.micrometer.core.annotation.Timed[format=annotation] annotation with `longTask = true` enables a long task timer for the method.
Long task timers require a separate metric name and can be stacked with a short task timer.
By default, repository invocation related metrics are tagged with the following information:
@ -988,10 +988,10 @@ By default, repository invocation related metrics are tagged with the following
| Tag | Description
| `repository`
| The simple class name of the source `org.springframework.data.repository.Repository`.
| The simple class name of the source javadoc:org.springframework.data.repository.Repository[].
| `method`
| The name of the `org.springframework.data.repository.Repository` method that was invoked.
| The name of the javadoc:org.springframework.data.repository.Repository[] method that was invoked.
| `state`
| The result state (`SUCCESS`, `ERROR`, `CANCELED`, or `RUNNING`).
@ -1000,7 +1000,7 @@ By default, repository invocation related metrics are tagged with the following
| The simple class name of any exception that was thrown from the invocation.
|===
To replace the default tags, provide a `@Bean` that implements `RepositoryTagsProvider`.
To replace the default tags, provide a javadoc:org.springframework.context.annotation.Bean[format=annotation] that implements javadoc:org.springframework.boot.actuate.metrics.data.RepositoryTagsProvider[].
@ -1014,7 +1014,7 @@ Auto-configuration enables the instrumentation of all available RabbitMQ connect
[[actuator.metrics.supported.spring-integration]]
=== Spring Integration Metrics
Spring Integration automatically provides {url-spring-integration-docs}/metrics.html#micrometer-integration[Micrometer support] whenever a `MeterRegistry` bean is available.
Spring Integration automatically provides {url-spring-integration-docs}/metrics.html#micrometer-integration[Micrometer support] whenever a javadoc:io.micrometer.core.instrument.MeterRegistry[] bean is available.
Metrics are published under the `spring.integration.` meter name.
@ -1022,8 +1022,8 @@ Metrics are published under the `spring.integration.` meter name.
[[actuator.metrics.supported.kafka]]
=== Kafka Metrics
Auto-configuration registers a `MicrometerConsumerListener` and `MicrometerProducerListener` for the auto-configured consumer factory and producer factory, respectively.
It also registers a `KafkaStreamsMicrometerListener` for `StreamsBuilderFactoryBean`.
Auto-configuration registers a javadoc:org.springframework.kafka.core.MicrometerConsumerListener[] and javadoc:org.springframework.kafka.core.MicrometerProducerListener[] for the auto-configured consumer factory and producer factory, respectively.
It also registers a javadoc:org.springframework.kafka.streams.KafkaStreamsMicrometerListener[] for javadoc:org.springframework.kafka.config.StreamsBuilderFactoryBean[].
For more detail, see the {url-spring-kafka-docs}/kafka/micrometer.html#micrometer-native[Micrometer Native Metrics] section of the Spring Kafka documentation.
@ -1038,7 +1038,7 @@ This section briefly describes the available metrics for MongoDB.
[[actuator.metrics.supported.mongodb.command]]
==== MongoDB Command Metrics
Auto-configuration registers a `MongoMetricsCommandListener` with the auto-configured `MongoClient`.
Auto-configuration registers a javadoc:io.micrometer.core.instrument.binder.mongodb.MongoMetricsCommandListener[] with the auto-configured javadoc:{url-mongodb-driver-sync-javadoc}/com.mongodb.client.MongoClient[].
A timer metric named `mongodb.driver.commands` is created for each command issued to the underlying MongoDB driver.
Each metric is tagged with the following information by default:
@ -1058,7 +1058,7 @@ Each metric is tagged with the following information by default:
| The outcome of the command (`SUCCESS` or `FAILED`).
|===
To replace the default metric tags, define a `MongoCommandTagsProvider` bean, as the following example shows:
To replace the default metric tags, define a javadoc:io.micrometer.core.instrument.binder.mongodb.MongoCommandTagsProvider[] bean, as the following example shows:
include-code::MyCommandTagsProviderConfiguration[]
@ -1078,7 +1078,7 @@ management:
[[actuator.metrics.supported.mongodb.connection-pool]]
==== MongoDB Connection Pool Metrics
Auto-configuration registers a `MongoMetricsConnectionPoolListener` with the auto-configured `MongoClient`.
Auto-configuration registers a javadoc:io.micrometer.core.instrument.binder.mongodb.MongoMetricsConnectionPoolListener[] with the auto-configured javadoc:{url-mongodb-driver-sync-javadoc}/com.mongodb.client.MongoClient[].
The following gauge metrics are created for the connection pool:
@ -1097,7 +1097,7 @@ Each metric is tagged with the following information by default:
| The address of the server to which the connection pool corresponds.
|===
To replace the default metric tags, define a `MongoConnectionPoolTagsProvider` bean:
To replace the default metric tags, define a javadoc:io.micrometer.core.instrument.binder.mongodb.MongoConnectionPoolTagsProvider[] bean:
include-code::MyConnectionPoolTagsProviderConfiguration[]
@ -1117,15 +1117,15 @@ management:
[[actuator.metrics.supported.jetty]]
=== Jetty Metrics
Auto-configuration binds metrics for Jetty's `org.eclipse.jetty.util.thread.ThreadPool` by using Micrometer's `JettyServerThreadPoolMetrics`.
Metrics for Jetty's `org.eclipse.jetty.server.Connector` instances are bound by using Micrometer's `JettyConnectionMetrics` and, when configprop:server.ssl.enabled[] is set to `true`, Micrometer's `JettySslHandshakeMetrics`.
Auto-configuration binds metrics for Jetty's javadoc:org.eclipse.jetty.util.thread.ThreadPool[] by using Micrometer's javadoc:io.micrometer.core.instrument.binder.jetty.JettyServerThreadPoolMetrics[].
Metrics for Jetty's javadoc:org.eclipse.jetty.server.Connector[] instances are bound by using Micrometer's javadoc:io.micrometer.core.instrument.binder.jetty.JettyConnectionMetrics[] and, when configprop:server.ssl.enabled[] is set to `true`, Micrometer's javadoc:io.micrometer.core.instrument.binder.jetty.JettySslHandshakeMetrics[].
[[actuator.metrics.supported.timed-annotation]]
=== @Timed Annotation Support
To enable scanning of `@io.micrometer.core.annotation.Timed` annotations, you will need to set the configprop:management.observations.annotations.enabled[] property to `true`.
To enable scanning of javadoc:io.micrometer.core.annotation.Timed[format=annotation] annotations, you will need to set the configprop:management.observations.annotations.enabled[] property to `true`.
Please refer to the {url-micrometer-docs-concepts}/timers.html#_the_timed_annotation[Micrometer documentation].
@ -1133,7 +1133,7 @@ Please refer to the {url-micrometer-docs-concepts}/timers.html#_the_timed_annota
[[actuator.metrics.supported.redis]]
=== Redis Metrics
Auto-configuration registers a `MicrometerCommandLatencyRecorder` for the auto-configured `LettuceConnectionFactory`.
Auto-configuration registers a javadoc:io.lettuce.core.metrics.MicrometerCommandLatencyRecorder[] for the auto-configured javadoc:org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory[].
For more detail, see the {url-lettuce-docs}#command.latency.metrics.micrometer[Micrometer Metrics section] of the Lettuce documentation.
@ -1141,32 +1141,32 @@ For more detail, see the {url-lettuce-docs}#command.latency.metrics.micrometer[M
[[actuator.metrics.registering-custom]]
== Registering Custom Metrics
To register custom metrics, inject `MeterRegistry` into your component:
To register custom metrics, inject javadoc:io.micrometer.core.instrument.MeterRegistry[] into your component:
include-code::MyBean[]
If your metrics depend on other beans, we recommend that you use a `MeterBinder` to register them:
If your metrics depend on other beans, we recommend that you use a javadoc:io.micrometer.core.instrument.binder.MeterBinder[] to register them:
include-code::MyMeterBinderConfiguration[]
Using a `MeterBinder` ensures that the correct dependency relationships are set up and that the bean is available when the metric's value is retrieved.
A `MeterBinder` implementation can also be useful if you find that you repeatedly instrument a suite of metrics across components or applications.
Using a javadoc:io.micrometer.core.instrument.binder.MeterBinder[] ensures that the correct dependency relationships are set up and that the bean is available when the metric's value is retrieved.
A javadoc:io.micrometer.core.instrument.binder.MeterBinder[] implementation can also be useful if you find that you repeatedly instrument a suite of metrics across components or applications.
NOTE: By default, metrics from all `MeterBinder` beans are automatically bound to the Spring-managed `MeterRegistry`.
NOTE: By default, metrics from all javadoc:io.micrometer.core.instrument.binder.MeterBinder[] beans are automatically bound to the Spring-managed javadoc:io.micrometer.core.instrument.MeterRegistry[].
[[actuator.metrics.customizing]]
== Customizing Individual Metrics
If you need to apply customizations to specific `Meter` instances, you can use the `io.micrometer.core.instrument.config.MeterFilter` interface.
If you need to apply customizations to specific javadoc:io.micrometer.core.instrument.Meter[] instances, you can use the javadoc:io.micrometer.core.instrument.config.MeterFilter[] interface.
For example, if you want to rename the `mytag.region` tag to `mytag.area` for all meter IDs beginning with `com.example`, you can do the following:
include-code::MyMetricsFilterConfiguration[]
NOTE: By default, all `MeterFilter` beans are automatically bound to the Spring-managed `MeterRegistry`.
Make sure to register your metrics by using the Spring-managed `MeterRegistry` and not any of the static methods on `io.micrometer.core.instrument.Metrics`.
NOTE: By default, all javadoc:io.micrometer.core.instrument.config.MeterFilter[] beans are automatically bound to the Spring-managed javadoc:io.micrometer.core.instrument.MeterRegistry[].
Make sure to register your metrics by using the Spring-managed javadoc:io.micrometer.core.instrument.MeterRegistry[] and not any of the static methods on javadoc:io.micrometer.core.instrument.Metrics[].
These use the global registry that is not Spring-managed.
@ -1189,15 +1189,15 @@ management:
The preceding example adds `region` and `stack` tags to all meters with a value of `us-east-1` and `prod`, respectively.
NOTE: The order of common tags is important if you use Graphite.
As the order of common tags cannot be guaranteed by using this approach, Graphite users are advised to define a custom `MeterFilter` instead.
As the order of common tags cannot be guaranteed by using this approach, Graphite users are advised to define a custom javadoc:io.micrometer.core.instrument.config.MeterFilter[] instead.
[[actuator.metrics.customizing.per-meter-properties]]
=== Per-meter Properties
In addition to `MeterFilter` beans, you can apply a limited set of customization on a per-meter basis using properties.
Per-meter customizations are applied, using Spring Boot's `PropertiesMeterFilter`, to any meter IDs that start with the given name.
In addition to javadoc:io.micrometer.core.instrument.config.MeterFilter[] beans, you can apply a limited set of customization on a per-meter basis using properties.
Per-meter customizations are applied, using Spring Boot's javadoc:org.springframework.boot.actuate.autoconfigure.metrics.PropertiesMeterFilter[], to any meter IDs that start with the given name.
The following example filters out any meters that have an ID starting with `example.remote`.
[configprops,yaml]
@ -1217,7 +1217,7 @@ The following properties allow per-meter customization:
| configprop:management.metrics.enable[]
| Whether to accept meters with certain IDs.
Meters that are not accepted are filtered from the `MeterRegistry`.
Meters that are not accepted are filtered from the javadoc:io.micrometer.core.instrument.MeterRegistry[].
| configprop:management.metrics.distribution.percentiles-histogram[]
| Whether to publish a histogram suitable for computing aggregable (across dimension) percentile approximations.
@ -1270,4 +1270,4 @@ If you wanted to see only the maximum size for the "`Metaspace`", you could add
[[actuator.metrics.micrometer-observation]]
== Integration with Micrometer Observation
A `DefaultMeterObservationHandler` is automatically registered on the `ObservationRegistry`, which creates metrics for every completed observation.
A javadoc:io.micrometer.core.instrument.observation.DefaultMeterObservationHandler[] is automatically registered on the javadoc:io.micrometer.observation.ObservationRegistry[], which creates metrics for every completed observation.

View File

@ -5,14 +5,14 @@ Observability is the ability to observe the internal state of a running system f
It consists of the three pillars: logging, metrics and traces.
For metrics and traces, Spring Boot uses {url-micrometer-docs}/observation[Micrometer Observation].
To create your own observations (which will lead to metrics and traces), you can inject an `ObservationRegistry`.
To create your own observations (which will lead to metrics and traces), you can inject an javadoc:io.micrometer.observation.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.
Beans of type javadoc:io.micrometer.observation.ObservationPredicate[], javadoc:io.micrometer.observation.GlobalObservationConvention[], javadoc:io.micrometer.observation.ObservationFilter[] and javadoc:io.micrometer.observation.ObservationHandler[] will be automatically registered on the javadoc:io.micrometer.observation.ObservationRegistry[].
You can additionally register any number of javadoc:org.springframework.boot.actuate.autoconfigure.observation.ObservationRegistryCustomizer[] beans to further configure the registry.
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.
@ -26,7 +26,7 @@ To enable it, add the `io.r2dbc:r2dbc-proxy` dependency to your project.
[[actuator.observability.context-propagation]]
== Context Propagation
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.
By default, javadoc:java.lang.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 {url-micrometer-docs}/observation[Micrometer Observation documentation].
@ -73,8 +73,8 @@ The preceding example will prevent all observations with a name starting with `d
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.
If you need greater control over the prevention of observations, you can register beans of type javadoc:io.micrometer.observation.ObservationPredicate[].
Observations are only reported if all the javadoc:io.micrometer.observation.ObservationPredicate[] beans return `true` for that observation.
include-code::MyObservationPredicate[]
@ -93,10 +93,10 @@ the metrics and traces use the semantic conventions described in the Spring proj
Spring Boot's actuator module includes basic support for 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 `io.opentelemetry.sdk.resources.Resource` bean.
The attributes of the auto-configured `io.opentelemetry.sdk.resources.Resource` can be configured via the configprop:management.opentelemetry.resource-attributes[] configuration property.
If you have defined your own `io.opentelemetry.sdk.resources.Resource` bean, this will no longer be the case.
It provides a bean of type javadoc:io.opentelemetry.api.OpenTelemetry[], and if there are beans of type javadoc:io.opentelemetry.sdk.trace.SdkTracerProvider[], javadoc:io.opentelemetry.context.propagation.ContextPropagators[], javadoc:io.opentelemetry.sdk.logs.SdkLoggerProvider[] or javadoc:io.opentelemetry.sdk.metrics.SdkMeterProvider[] in the application context, they automatically get registered.
Additionally, it provides a javadoc:io.opentelemetry.sdk.resources.Resource[] bean.
The attributes of the auto-configured javadoc:io.opentelemetry.sdk.resources.Resource[] can be configured via the configprop:management.opentelemetry.resource-attributes[] configuration property.
If you have defined your own javadoc:io.opentelemetry.sdk.resources.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].
@ -108,5 +108,5 @@ 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 `@io.micrometer.core.annotation.Timed`, `@Counted`, `@MeterTag` and `@NewSpan` annotations, you will need to set the configprop:management.observations.annotations.enabled[] property to `true`.
To enable scanning of metrics and tracing annotations like javadoc:io.micrometer.core.annotation.Timed[format=annotation], javadoc:io.micrometer.core.annotation.Counted[format=annotation], javadoc:io.micrometer.core.aop.MeterTag[format=annotation] and javadoc:io.micrometer.tracing.annotation.NewSpan[format=annotation] 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}/timers.html#_the_timed_annotation[Micrometer] and {url-micrometer-tracing-docs}/api.html#_aspect_oriented_programming[Micrometer Tracing] reference docs.

View File

@ -3,8 +3,8 @@
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`).
* javadoc:org.springframework.boot.context.ApplicationPidFileWriter[] creates a file that contains the application PID (by default, in the application directory with a file name of `application.pid`).
* javadoc:org.springframework.boot.web.context.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:
@ -30,5 +30,5 @@ 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.
You can also activate a listener by invoking the `SpringApplication.addListeners(...)` method and passing the appropriate javadoc:java.io.Writer[] object.
This method also lets you customize the file name and path in the javadoc:java.io.Writer[] constructor.

View File

@ -103,7 +103,7 @@ Please read xref:reference:actuator/observability.adoc#actuator.observability.co
To automatically propagate traces over the network, use the auto-configured xref:io/rest-client.adoc#io.rest-client.resttemplate[`RestTemplateBuilder`], xref:io/rest-client.adoc#io.rest-client.restclient[`RestClient.Builder`] or xref:io/rest-client.adoc#io.rest-client.webclient[`WebClient.Builder`] to construct the client.
WARNING: If you create the `RestTemplate`, the `RestClient` or the `WebClient` without using the auto-configured builders, automatic trace propagation won't work!
WARNING: If you create the javadoc:org.springframework.web.client.RestTemplate[], the javadoc:org.springframework.web.client.RestClient[] or the javadoc:org.springframework.web.reactive.function.client.WebClient[] without using the auto-configured builders, automatic trace propagation won't work!
@ -179,7 +179,7 @@ Use the `management.wavefront.*` configuration properties to configure reporting
[[actuator.micrometer-tracing.micrometer-observation]]
== Integration with Micrometer Observation
A `TracingAwareMeterObservationHandler` is automatically registered on the `ObservationRegistry`, which creates spans for every completed observation.
A javadoc:io.micrometer.tracing.handler.TracingAwareMeterObservationHandler[] is automatically registered on the javadoc:io.micrometer.observation.ObservationRegistry[], which creates spans for every completed observation.
@ -187,7 +187,7 @@ A `TracingAwareMeterObservationHandler` is automatically registered on the `Obse
== Creating Custom Spans
You can create your own spans by starting an observation.
For this, inject `ObservationRegistry` into your component:
For this, inject javadoc:io.micrometer.observation.ObservationRegistry[] into your component:
include-code::CustomObservation[]
@ -200,7 +200,7 @@ TIP: If you want to create a span without creating a metric, you need to use the
[[actuator.micrometer-tracing.baggage]]
== Baggage
You can create baggage with the `io.micrometer.tracing.Tracer` API:
You can create baggage with the javadoc:io.micrometer.tracing.Tracer[] API:
include-code::CreatingBaggage[]
@ -218,5 +218,5 @@ For the example above, setting this property to `baggage1` results in an MDC ent
[[actuator.micrometer-tracing.tests]]
== Tests
Tracing components which are reporting data are not auto-configured when using `@SpringBootTest`.
Tracing components which are reporting data are not auto-configured when using javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation].
See xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.tracing[] for more details.

View File

@ -38,7 +38,7 @@ TIP: We also provide a `spring-boot-starter-data-redis-reactive` starter for con
[[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.
You can inject an auto-configured javadoc:org.springframework.data.redis.connection.RedisConnectionFactory[], javadoc:org.springframework.data.redis.core.StringRedisTemplate[], or vanilla javadoc:org.springframework.data.redis.core.RedisTemplate[] instance as you would any other Spring Bean.
The following listing shows an example of such a bean:
include-code::MyBean[]
@ -72,16 +72,16 @@ spring:
----
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.
TIP: You can also register an arbitrary number of beans that implement javadoc:org.springframework.boot.autoconfigure.data.redis.LettuceClientConfigurationBuilderCustomizer[] for more advanced customizations.
javadoc:io.lettuce.core.resource.ClientResources[] can also be customized using javadoc:org.springframework.boot.autoconfigure.data.redis.ClientResourcesBuilderCustomizer[].
If you use Jedis, javadoc:org.springframework.boot.autoconfigure.data.redis.JedisClientConfigurationBuilderCustomizer[] is also available.
Alternatively, you can register a bean of type javadoc:org.springframework.data.redis.connection.RedisStandaloneConfiguration[], javadoc:org.springframework.data.redis.connection.RedisSentinelConfiguration[], or javadoc:org.springframework.data.redis.connection.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).
If you add your own javadoc:org.springframework.context.annotation.Bean[format=annotation] of any of the auto-configured types, it replaces the default (except in the case of javadoc:org.springframework.data.redis.core.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:
The auto-configured javadoc:org.springframework.data.redis.connection.RedisConnectionFactory[] can be configured to use SSL for communication with the server by setting the properties as shown in this example:
[configprops,yaml]
----
@ -92,7 +92,7 @@ spring:
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:
Custom SSL trust material can be configured in an xref:features/ssl.adoc[SSL bundle] and applied to the javadoc:org.springframework.data.redis.connection.RedisConnectionFactory[] as shown in this example:
[configprops,yaml]
----
@ -116,19 +116,19 @@ Spring Boot offers several conveniences for working with MongoDB, including the
[[data.nosql.mongodb.connecting]]
=== Connecting to a MongoDB Database
To access MongoDB databases, you can inject an auto-configured `org.springframework.data.mongodb.MongoDatabaseFactory`.
To access MongoDB databases, you can inject an auto-configured javadoc: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`.
If you have defined your own javadoc:{url-mongodb-driver-sync-javadoc}/com.mongodb.client.MongoClient[], it will be used to auto-configure a suitable javadoc:org.springframework.data.mongodb.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`.
The auto-configured javadoc:{url-mongodb-driver-sync-javadoc}/com.mongodb.client.MongoClient[] is created using a javadoc:{url-mongodb-driver-core-javadoc}/com.mongodb.MongoClientSettings[] bean.
If you have defined your own javadoc:{url-mongodb-driver-core-javadoc}/com.mongodb.MongoClientSettings[], it will be used without modification and the `spring.data.mongodb` properties will be ignored.
Otherwise a javadoc:{url-mongodb-driver-core-javadoc}/com.mongodb.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 javadoc:org.springframework.boot.autoconfigure.mongo.MongoClientSettingsBuilderCustomizer[] beans to fine-tune the javadoc:{url-mongodb-driver-core-javadoc}/com.mongodb.MongoClientSettings[] configuration.
Each will be called in order with the javadoc:{url-mongodb-driver-core-javadoc}/com.mongodb.MongoClientSettings$Builder[] that is used to build the javadoc:{url-mongodb-driver-core-javadoc}/com.mongodb.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:
@ -157,7 +157,7 @@ spring:
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:
The auto-configured javadoc:{url-mongodb-driver-sync-javadoc}/com.mongodb.client.MongoClient[] can be configured to use SSL for communication with the server by setting the properties as shown in this example:
[configprops,yaml]
----
@ -169,7 +169,7 @@ spring:
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:
Custom SSL trust material can be configured in an xref:features/ssl.adoc[SSL bundle] and applied to the javadoc:{url-mongodb-driver-sync-javadoc}/com.mongodb.client.MongoClient[] as shown in this example:
[configprops,yaml]
----
@ -191,8 +191,8 @@ You can also specify the port as part of the host address by using the `host:por
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.
TIP: If you do not use Spring Data MongoDB, you can inject a javadoc:{url-mongodb-driver-sync-javadoc}/com.mongodb.client.MongoClient[] bean instead of using javadoc:org.springframework.data.mongodb.MongoDatabaseFactory[].
If you want to take complete control of establishing the MongoDB connection, you can also declare your own javadoc:org.springframework.data.mongodb.MongoDatabaseFactory[] or javadoc:{url-mongodb-driver-sync-javadoc}/com.mongodb.client.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.
@ -202,8 +202,8 @@ The auto-configuration configures this factory automatically if Netty is availab
[[data.nosql.mongodb.template]]
=== MongoTemplate
{url-spring-data-mongodb-site}[Spring Data MongoDB] provides a javadoc:{url-spring-data-mongodb-javadoc}/org.springframework.data.mongodb.core.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:
{url-spring-data-mongodb-site}[Spring Data MongoDB] provides a javadoc:{url-spring-data-mongodb-javadoc}/org.springframework.data.mongodb.core.MongoTemplate[] class that is very similar in its design to Spring's javadoc:org.springframework.jdbc.core.JdbcTemplate[].
As with javadoc:org.springframework.jdbc.core.JdbcTemplate[], Spring Boot auto-configures a bean for you to inject the template, as follows:
include-code::MyBean[]
@ -218,13 +218,13 @@ 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:
You could take the JPA example from earlier and, assuming that `+City+` is now a MongoDB data class rather than a JPA javadoc:jakarta.persistence.Entity[format=annotation], 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.
You can customize the locations to look for repositories and documents by using javadoc:org.springframework.data.mongodb.repository.config.EnableMongoRepositories[format=annotation] and javadoc:org.springframework.boot.autoconfigure.domain.EntityScan[format=annotation] respectively.
TIP: For complete details of Spring Data MongoDB, including its rich object mapping technologies, see its {url-spring-data-mongodb-docs}[reference documentation].
@ -241,9 +241,9 @@ Spring Boot offers several conveniences for working with Neo4j, including the `s
[[data.nosql.neo4j.connecting]]
=== Connecting to a Neo4j Database
To access a Neo4j server, you can inject an auto-configured `org.neo4j.driver.Driver`.
To access a Neo4j server, you can inject an auto-configured javadoc: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 `org.neo4j.driver.Driver` that gives you access, amongst other things, to a `org.neo4j.driver.Session`:
The following example shows how to inject a Neo4j javadoc:org.neo4j.driver.Driver[] that gives you access, amongst other things, to a javadoc:org.neo4j.driver.Session[]:
include-code::MyBean[]
@ -260,9 +260,9 @@ spring:
password: "secret"
----
The auto-configured `org.neo4j.driver.Driver` is created using `org.neo4j.driver.Config$ConfigBuilder`.
To fine-tune its configuration, declare one or more `ConfigBuilderCustomizer` beans.
Each will be called in order with the `org.neo4j.driver.Config$ConfigBuilder` that is used to build the `org.neo4j.driver.Driver`.
The auto-configured javadoc:org.neo4j.driver.Driver[] is created using `org.neo4j.driver.Config$ConfigBuilder`.
To fine-tune its configuration, declare one or more javadoc:org.springframework.boot.autoconfigure.neo4j.ConfigBuilderCustomizer[] beans.
Each will be called in order with the `org.neo4j.driver.Config$ConfigBuilder` that is used to build the javadoc:org.neo4j.driver.Driver[].
@ -273,21 +273,21 @@ 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 `@org.springframework.data.neo4j.core.schema.Node` rather than JPA `@Entity` and the repository abstraction works in the same way, as shown in the following example:
You could take the JPA example from earlier and define `+City+` as Spring Data Neo4j javadoc:org.springframework.data.neo4j.core.schema.Node[format=annotation] rather than JPA javadoc:jakarta.persistence.Entity[format=annotation] 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.
Spring Boot supports both classic and reactive Neo4j repositories, using the javadoc:org.springframework.data.neo4j.core.Neo4jTemplate[] or javadoc:org.springframework.data.neo4j.core.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.
You can customize the locations to look for repositories and entities by using javadoc:org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories[format=annotation] and javadoc:org.springframework.boot.autoconfigure.domain.EntityScan[format=annotation] respectively.
[NOTE]
====
In an application using the reactive style, a `ReactiveTransactionManager` is not auto-configured.
In an application using the reactive style, a javadoc:org.springframework.transaction.ReactiveTransactionManager[] is not auto-configured.
To enable transaction management, the following bean must be defined in your configuration:
include-code::MyNeo4jConfiguration[]
@ -305,7 +305,7 @@ Spring Boot supports several clients:
* The official low-level REST client
* The official Java API client
* The `ReactiveElasticsearchClient` provided by Spring Data Elasticsearch
* The javadoc:org.springframework.data.elasticsearch.client.elc.ReactiveElasticsearchClient[] provided by Spring Data Elasticsearch
Spring Boot provides a dedicated starter, `spring-boot-starter-data-elasticsearch`.
@ -334,14 +334,14 @@ spring:
[[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 `org.elasticsearch.client.RestClientBuilder` bean.
If you have `elasticsearch-rest-client` on the classpath, Spring Boot will auto-configure and register a javadoc:org.springframework.web.client.RestClient[] bean.
In addition to the properties described previously, to fine-tune the javadoc:org.springframework.web.client.RestClient[] you can register an arbitrary number of beans that implement javadoc:org.springframework.boot.autoconfigure.elasticsearch.RestClientBuilderCustomizer[] for more advanced customizations.
To take full control over the clients' configuration, define a javadoc:org.elasticsearch.client.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:
Additionally, if `elasticsearch-rest-client-sniffer` is on the classpath, a javadoc:org.elasticsearch.client.sniff.Sniffer[] is auto-configured to automatically discover nodes from a running Elasticsearch cluster and set them on the javadoc:org.springframework.web.client.RestClient[] bean.
You can further tune how javadoc:org.elasticsearch.client.sniff.Sniffer[] is configured, as shown in the following example:
[configprops,yaml]
----
@ -358,38 +358,38 @@ spring:
[[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.
If you have `co.elastic.clients:elasticsearch-java` on the classpath, Spring Boot will auto-configure and register an javadoc:co.elastic.clients.elasticsearch.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.
The javadoc:co.elastic.clients.elasticsearch.ElasticsearchClient[] uses a transport that depends upon the previously described javadoc:org.springframework.web.client.RestClient[].
Therefore, the properties described previously can be used to configure the javadoc:co.elastic.clients.elasticsearch.ElasticsearchClient[].
Furthermore, you can define a javadoc:co.elastic.clients.transport.rest_client.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`.
{url-spring-data-elasticsearch-site}[Spring Data Elasticsearch] ships javadoc:org.springframework.data.elasticsearch.client.elc.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 javadoc:org.springframework.data.elasticsearch.client.elc.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.
The javadoc:org.springframework.data.elasticsearch.client.elc.ReactiveElasticsearchClient[] uses a transport that depends upon the previously described javadoc:org.springframework.web.client.RestClient[].
Therefore, the properties described previously can be used to configure the javadoc:org.springframework.data.elasticsearch.client.elc.ReactiveElasticsearchClient[].
Furthermore, you can define a javadoc:co.elastic.clients.transport.rest_client.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,
To connect to Elasticsearch, an javadoc:co.elastic.clients.elasticsearch.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,
javadoc:org.springframework.data.elasticsearch.client.elc.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.
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 javadoc:org.springframework.data.elasticsearch.client.elc.ReactiveElasticsearchTemplate[] as beans.
They are the reactive equivalent of the other REST clients.
@ -401,19 +401,19 @@ 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 `@org.springframework.data.elasticsearch.annotations.Document` class rather than a JPA `@Entity`, it works in the same way.
You could take the JPA example from earlier and, assuming that `+City+` is now an Elasticsearch javadoc:org.springframework.data.elasticsearch.annotations.Document[format=annotation] class rather than a JPA javadoc:jakarta.persistence.Entity[format=annotation], 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.
You can customize the locations to look for repositories and documents by using javadoc:org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories[format=annotation] and javadoc:org.springframework.boot.autoconfigure.domain.EntityScan[format=annotation] 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 `ElasticsearchTemplate` or `ReactiveElasticsearchTemplate` beans.
Spring Boot supports both classic and reactive Elasticsearch repositories, using the javadoc:org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate[] or javadoc:org.springframework.data.elasticsearch.client.elc.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 `ElasticsearchTemplate` or `ElasticsearchOperations` `@Bean`, as long as it is named `"elasticsearchTemplate"`.
Same applies to `ReactiveElasticsearchTemplate` and `ReactiveElasticsearchOperations`, with the bean name `"reactiveElasticsearchTemplate"`.
If you wish to use your own template for backing the Elasticsearch repositories, you can add your own javadoc:org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate[] or javadoc:org.springframework.data.elasticsearch.core.ElasticsearchOperations[] javadoc:org.springframework.context.annotation.Bean[format=annotation], as long as it is named `"elasticsearchTemplate"`.
Same applies to javadoc:org.springframework.data.elasticsearch.client.elc.ReactiveElasticsearchTemplate[] and javadoc:org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations[], with the bean name `"reactiveElasticsearchTemplate"`.
You can choose to disable the repositories support with the following property:
@ -440,7 +440,7 @@ There is a `spring-boot-starter-data-cassandra` starter for collecting the depen
[[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.
You can inject an auto-configured javadoc:org.springframework.data.cassandra.core.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:
@ -501,8 +501,8 @@ The Cassandra driver has its own configuration infrastructure that loads an `app
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`.
For more advanced driver customizations, you can register an arbitrary number of beans that implement javadoc:org.springframework.boot.autoconfigure.cassandra.DriverConfigLoaderBuilderCustomizer[].
The `+CqlSession+` can be customized with a bean of type javadoc:org.springframework.boot.autoconfigure.cassandra.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.
@ -511,7 +511,7 @@ 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.
If you add your own javadoc:org.springframework.context.annotation.Bean[format=annotation] of type javadoc:org.springframework.data.cassandra.core.CassandraTemplate[], it replaces the default.
@ -519,11 +519,11 @@ If you add your own `@Bean` of type `CassandraTemplate`, it replaces the default
=== 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 `@org.springframework.data.cassandra.repository.Query` annotated finder methods.
Currently, this is more limited than the JPA repositories discussed earlier and needs javadoc:org.springframework.data.cassandra.repository.Query[format=annotation] 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.
You can customize the locations to look for repositories and entities by using javadoc:org.springframework.data.cassandra.repository.config.EnableCassandraRepositories[format=annotation] and javadoc:org.springframework.boot.autoconfigure.domain.EntityScan[format=annotation] respectively.
TIP: For complete details of Spring Data Cassandra, see the {url-spring-data-cassandra-docs}[reference documentation].
@ -541,7 +541,7 @@ There are `spring-boot-starter-data-couchbase` and `spring-boot-starter-data-cou
[[data.nosql.couchbase.connecting]]
=== Connecting to Couchbase
You can get a `com.couchbase.client.java.Cluster` by adding the Couchbase SDK and some configuration.
You can get a javadoc:com.couchbase.client.java.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://docs.couchbase.com/dotnet-sdk/current/howtos/managing-connections.html[connection string] and credentials for authentication. Basic authentication with username and password can be configured as shown in the following example:
@ -587,8 +587,8 @@ spring:
private-key: "classpath:client.key"
----
It is also possible to customize some of the `ClusterEnvironment` settings.
For instance, the following configuration changes the timeout to open a new `com.couchbase.client.java.Bucket` and enables SSL support with a reference to a configured xref:features/ssl.adoc[SSL bundle]:
It is also possible to customize some of the javadoc:com.couchbase.client.java.env.ClusterEnvironment[] settings.
For instance, the following configuration changes the timeout to open a new javadoc:com.couchbase.client.java.Bucket[] and enables SSL support with a reference to a configured xref:features/ssl.adoc[SSL bundle]:
[configprops,yaml]
----
@ -602,7 +602,7 @@ spring:
----
TIP: Check the `spring.couchbase.env.*` properties for more details.
To take more control, one or more `ClusterEnvironmentBuilderCustomizer` beans can be used.
To take more control, one or more javadoc:org.springframework.boot.autoconfigure.couchbase.ClusterEnvironmentBuilderCustomizer[] beans can be used.
@ -613,12 +613,12 @@ 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.
You can customize the locations to look for repositories and documents by using javadoc:org.springframework.data.couchbase.repository.config.EnableCouchbaseRepositories[format=annotation] and javadoc:org.springframework.boot.autoconfigure.domain.EntityScan[format=annotation] 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 `com.couchbase.client.java.Cluster` is available, as described above, and a bucket name has been specified:
You can inject an auto-configured javadoc:org.springframework.data.couchbase.core.CouchbaseTemplate[] instance as you would with any other Spring Bean, provided a javadoc:org.springframework.data.couchbase.CouchbaseClientFactory[] bean is available.
This happens when a javadoc:com.couchbase.client.java.Cluster[] is available, as described above, and a bucket name has been specified:
[configprops,yaml]
----
@ -628,17 +628,17 @@ spring:
bucket-name: "my-bucket"
----
The following examples shows how to inject a `CouchbaseTemplate` bean:
The following examples shows how to inject a javadoc:org.springframework.data.couchbase.core.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 `org.springframework.data.convert.CustomConversions` `@Bean` with a name of `couchbaseCustomConversions`.
* A `CouchbaseTemplate` `@Bean` with a name of `couchbaseTemplate`.
* A javadoc:org.springframework.data.couchbase.core.mapping.CouchbaseMappingContext[] javadoc:org.springframework.context.annotation.Bean[format=annotation] with a name of `couchbaseMappingContext`.
* A javadoc:org.springframework.data.convert.CustomConversions[] javadoc:org.springframework.context.annotation.Bean[format=annotation] with a name of `couchbaseCustomConversions`.
* A javadoc:org.springframework.data.couchbase.core.CouchbaseTemplate[] javadoc:org.springframework.context.annotation.Bean[format=annotation] with a name of `couchbaseTemplate`.
To avoid hard-coding those names in your own config, you can reuse `org.springframework.data.couchbase.config.BeanNames` provided by Spring Data Couchbase.
To avoid hard-coding those names in your own config, you can reuse javadoc:org.springframework.data.couchbase.config.BeanNames[] provided by Spring Data Couchbase.
For instance, you can customize the converters to use, as follows:
include-code::MyCouchbaseConfiguration[]
@ -672,10 +672,10 @@ spring:
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.
An javadoc:org.springframework.ldap.core.support.LdapContextSource[] is auto-configured based on these settings.
If a javadoc:org.springframework.ldap.core.support.DirContextAuthenticationStrategy[] bean is available, it is associated to the auto-configured javadoc:org.springframework.ldap.core.support.LdapContextSource[].
If you need to customize it, for instance to use a javadoc:org.springframework.ldap.pool2.factory.PooledContextSource[], you can still inject the auto-configured javadoc:org.springframework.ldap.core.support.LdapContextSource[].
Make sure to flag your customized javadoc:org.springframework.ldap.core.ContextSource[] as javadoc:org.springframework.context.annotation.Primary[format=annotation] so that the auto-configured javadoc:org.springframework.ldap.core.LdapTemplate[] uses it.
@ -686,11 +686,11 @@ 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.
You can customize the locations to look for repositories and documents by using javadoc:org.springframework.data.ldap.repository.config.EnableLdapRepositories[format=annotation] and javadoc:org.springframework.boot.autoconfigure.domain.EntityScan[format=annotation] respectively.
TIP: For complete details of Spring Data LDAP, see the {url-spring-data-ldap-docs}[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:
You can also inject an auto-configured javadoc:org.springframework.ldap.core.LdapTemplate[] instance as you would with any other Spring Bean, as shown in the following example:
include-code::MyBean[]

View File

@ -1,16 +1,16 @@
[[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 `org.springframework.data.repository.Repository` implementations directly from interfaces and using conventions to generate queries from your method names.
The {url-spring-framework-site}[Spring Framework] provides extensive support for working with SQL databases, from direct JDBC access using javadoc:org.springframework.jdbc.core.simple.JdbcClient[] or javadoc:org.springframework.jdbc.core.JdbcTemplate[] to complete "`object relational mapping`" technologies such as Hibernate.
{url-spring-data-site}[Spring Data] provides an additional level of functionality: creating javadoc:org.springframework.data.repository.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.
Java's javadoc:javax.sql.DataSource[] interface provides a standard method of working with database connections.
Traditionally, a javadoc:javax.sql.DataSource[] uses a `URL` along with some credentials to establish a database connection.
TIP: See the xref:how-to:data-access.adoc#howto.data-access.configure-custom-datasource[] section of the "`How-to Guides`" for more advanced examples, typically to take full control over the configuration of the DataSource.
@ -65,7 +65,7 @@ Disabling the database's automatic shutdown lets Spring Boot control when the da
[[data.sql.datasource.production]]
=== Connection to a Production Database
Production database connections can also be auto-configured by using a pooling `DataSource`.
Production database connections can also be auto-configured by using a pooling javadoc:javax.sql.DataSource[].
@ -90,7 +90,7 @@ 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 `java.sql.Driver` class is available, so we check for that before doing anything.
NOTE: For a pooling javadoc:javax.sql.DataSource[] to be created, we need to be able to verify that a valid javadoc:java.sql.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 javadoc:org.springframework.boot.autoconfigure.jdbc.DataSourceProperties[] API documentation for more of the supported options.
@ -121,7 +121,7 @@ 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 the Tomcat pooling javadoc:javax.sql.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.
@ -130,17 +130,17 @@ NOTE: If you use the `spring-boot-starter-jdbc` or `spring-boot-starter-data-jpa
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`:
Additional connection pools can always be configured manually, using javadoc:org.springframework.boot.jdbc.DataSourceBuilder[].
If you define your own javadoc:javax.sql.DataSource[] bean, auto-configuration does not occur.
The following connection pools are supported by javadoc:org.springframework.boot.jdbc.DataSourceBuilder[]:
* HikariCP
* Tomcat pooling `DataSource`
* Tomcat pooling javadoc:javax.sql.DataSource[]
* Commons DBCP2
* Oracle UCP & `+OracleDataSource+`
* Spring Framework's `SimpleDriverDataSource`
* H2 `JdbcDataSource`
* PostgreSQL `PGSimpleDataSource`
* Spring Framework's javadoc:org.springframework.jdbc.datasource.SimpleDriverDataSource[]
* H2 javadoc:org.h2.jdbcx.JdbcDataSource[]
* PostgreSQL javadoc:org.postgresql.ds.PGSimpleDataSource[]
* C3P0
@ -150,8 +150,8 @@ The following connection pools are supported by `DataSourceBuilder`:
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`:
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 javadoc:javax.sql.DataSource[] from a specific JNDI location.
For example, the following section in `application.properties` shows how you can access a JBoss AS defined javadoc:javax.sql.DataSource[]:
[configprops,yaml]
----
@ -165,7 +165,7 @@ spring:
[[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:
Spring's javadoc:org.springframework.jdbc.core.JdbcTemplate[] and javadoc:org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate[] classes are auto-configured, and you can autowire them directly into your own beans, as shown in the following example:
include-code::MyBean[]
@ -179,20 +179,20 @@ spring:
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.
NOTE: The javadoc:org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate[] reuses the same javadoc:org.springframework.jdbc.core.JdbcTemplate[] instance behind the scenes.
If more than one javadoc:org.springframework.jdbc.core.JdbcTemplate[] is defined and no primary candidate exists, the javadoc:org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate[] is not auto-configured.
[[data.sql.jdbc-client]]
== Using JdbcClient
Spring's `JdbcClient` is auto-configured based on the presence of a `NamedParameterJdbcTemplate`.
Spring's javadoc:org.springframework.jdbc.core.simple.JdbcClient[] is auto-configured based on the presence of a javadoc:org.springframework.jdbc.core.namedparam.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.
If you rely on auto-configuration to create the underlying javadoc:org.springframework.jdbc.core.JdbcTemplate[], any customization using `spring.jdbc.template.*` properties is taken into account in the client as well.
@ -219,12 +219,12 @@ 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 `@jakarta.persistence.Entity`, `@jakarta.persistence.Embeddable`, or `@jakarta.persistence.MappedSuperclass` are considered.
Any classes annotated with javadoc:jakarta.persistence.Entity[format=annotation], javadoc:jakarta.persistence.Embeddable[format=annotation], or javadoc:jakarta.persistence.MappedSuperclass[format=annotation] 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.
TIP: You can customize entity scanning locations by using the javadoc:org.springframework.boot.autoconfigure.domain.EntityScan[format=annotation] annotation.
See the xref:how-to:data-access.adoc#howto.data-access.separate-entity-definitions-from-spring-configuration[] section of the "`How-to Guides`".
@ -241,7 +241,7 @@ For more complex queries, you can annotate your method with Spring Data's javado
Spring Data repositories usually extend from the javadoc:{url-spring-data-commons-javadoc}/org.springframework.data.repository.Repository[] or javadoc:{url-spring-data-commons-javadoc}/org.springframework.data.repository.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`.
TIP: You can customize the locations to look for repositories using javadoc:org.springframework.data.jpa.repository.config.EnableJpaRepositories[format=annotation].
The following example shows a typical Spring Data repository interface definition:
@ -249,14 +249,14 @@ 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 `org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder` will use the context's `AsyncTaskExecutor`, if any, as the bootstrap executor.
When using deferred or lazy bootstrapping, the auto-configured javadoc:org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder[] will use the context's javadoc:org.springframework.core.task.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.
You can use javadoc:org.springframework.beans.factory.SmartInitializingSingleton[] to invoke any initialization that requires the JPA infrastructure.
For JPA components (such as converters) that are created as Spring beans, use javadoc:org.springframework.beans.factory.ObjectProvider[] to delay the resolution of dependencies, if any.
====
TIP: We have barely scratched the surface of Spring Data JPA.
@ -269,7 +269,7 @@ For complete details, see the {url-spring-data-jpa-docs}[Spring Data JPA referen
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:
To use Spring Data Envers, make sure your repository extends from javadoc:org.springframework.data.repository.history.RevisionRepository[] as shown in the following example:
include-code::CountryRepository[]
@ -306,7 +306,7 @@ spring:
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.
By default, the DDL execution (or validation) is deferred until the javadoc:org.springframework.context.ApplicationContext[] has started.
@ -321,12 +321,12 @@ If you do not want this behavior, you should set `spring.jpa.open-in-view` to `f
[[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 `@org.springframework.data.jdbc.repository.query.Query` annotation is provided.
Spring Data includes repository support for JDBC and will automatically generate SQL for the methods on javadoc:org.springframework.data.repository.CrudRepository[].
For more advanced queries, a javadoc:org.springframework.data.jdbc.repository.query.Query[format=annotation] 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.
If necessary, you can take control of Spring Data JDBC's configuration by adding the javadoc:org.springframework.data.jdbc.repository.config.EnableJdbcRepositories[format=annotation] annotation or an javadoc:org.springframework.data.jdbc.repository.config.AbstractJdbcConfiguration[] subclass to your application.
TIP: For complete details of Spring Data JDBC, see the {url-spring-data-jdbc-docs}[reference documentation].
@ -367,7 +367,7 @@ If your application uses Spring Security, you need to configure it to
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:
In simple setups, a javadoc:org.springframework.security.web.SecurityFilterChain[] like the following can be used:
include-code::DevProfileSecurityConfiguration[tag=!customizer]
@ -427,15 +427,15 @@ The following listing shows an example:
[[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:
The fluent API offered by jOOQ is initiated through the javadoc:org.jooq.DSLContext[] interface.
Spring Boot auto-configures a javadoc:org.jooq.DSLContext[] as a Spring Bean and connects it to your application javadoc:javax.sql.DataSource[].
To use the javadoc:org.jooq.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`.
TIP: The jOOQ manual tends to use a variable named `create` to hold the javadoc:org.jooq.DSLContext[].
You can then use the `DSLContext` to construct your queries, as shown in the following example:
You can then use the javadoc:org.jooq.DSLContext[] to construct your queries, as shown in the following example:
include-code::MyBean[tag=method]
@ -454,10 +454,10 @@ NOTE: Spring Boot can only auto-configure dialects supported by the open source
[[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`.
More advanced customizations can be achieved by defining your own javadoc:org.springframework.boot.autoconfigure.jooq.DefaultConfigurationCustomizer[] bean that will be invoked prior to creating the javadoc:org.jooq.Configuration[] javadoc:org.springframework.context.annotation.Bean[format=annotation].
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.
You can also create your own javadoc:org.jooq.Configuration[] javadoc:org.springframework.context.annotation.Bean[format=annotation] if you want to take complete control of the jOOQ configuration.
@ -465,10 +465,10 @@ You can also create your own `org.jooq.Configuration` `@Bean` if you want to tak
== 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 `io.r2dbc.spi.ConnectionFactory`, similar to a `DataSource` with jdbc.
R2DBC's javadoc:io.r2dbc.spi.Connection[] provides a standard method of working with non-blocking database connections.
Connections are provided by using a javadoc:io.r2dbc.spi.ConnectionFactory[], similar to a javadoc:javax.sql.DataSource[] with jdbc.
`io.r2dbc.spi.ConnectionFactory` configuration is controlled by external configuration properties in `+spring.r2dbc.*+`.
javadoc:io.r2dbc.spi.ConnectionFactory[] configuration is controlled by external configuration properties in `+spring.r2dbc.*+`.
For example, you might declare the following section in `application.properties`:
[configprops,yaml]
@ -487,7 +487,7 @@ Information specified in the URL takes precedence over individual properties, th
TIP: The "`How-to Guides`" 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 `io.r2dbc.spi.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`.
To customize the connections created by a javadoc:io.r2dbc.spi.ConnectionFactory[], that is, set specific parameters that you do not want (or cannot) configure in your central database configuration, you can use a javadoc:org.springframework.boot.autoconfigure.r2dbc.ConnectionFactoryOptionsBuilderCustomizer[] javadoc:org.springframework.context.annotation.Bean[format=annotation].
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[]
@ -496,8 +496,8 @@ The following examples show how to set some PostgreSQL connection options:
include-code::MyPostgresR2dbcConfiguration[]
When a `io.r2dbc.spi.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.
When a javadoc:io.r2dbc.spi.ConnectionFactory[] bean is available, the regular JDBC javadoc:javax.sql.DataSource[] auto-configuration backs off.
If you want to retain the JDBC javadoc:javax.sql.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 javadoc:org.springframework.context.annotation.Configuration[format=annotation] class in your application to re-enable it.
@ -528,7 +528,7 @@ If you want to make sure that each context has a separate embedded database, you
[[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:
A javadoc:org.springframework.r2dbc.core.DatabaseClient[] bean is auto-configured, and you can autowire it directly into your own beans, as shown in the following example:
include-code::MyBean[]

View File

@ -7,4 +7,4 @@ You can learn more about AOP with Spring in the {url-spring-framework-docs}/core
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.
If AspectJ is on the classpath, Spring Boot's auto-configuration will automatically enable AspectJ auto proxy such that javadoc:org.springframework.context.annotation.EnableAspectJAutoProxy[format=annotation] is not required.

View File

@ -83,55 +83,55 @@ The following service connections are currently supported:
|===
| Connection Details | Matched on
| `ActiveMQConnectionDetails`
| javadoc:org.springframework.boot.autoconfigure.jms.activemq.ActiveMQConnectionDetails[]
| Containers named "symptoma/activemq" or "apache/activemq-classic"
| `ArtemisConnectionDetails`
| javadoc:org.springframework.boot.autoconfigure.jms.artemis.ArtemisConnectionDetails[]
| Containers named "apache/activemq-artemis"
| `CassandraConnectionDetails`
| javadoc:org.springframework.boot.autoconfigure.cassandra.CassandraConnectionDetails[]
| Containers named "cassandra" or "bitnami/cassandra"
| `ElasticsearchConnectionDetails`
| javadoc:org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchConnectionDetails[]
| Containers named "elasticsearch" or "bitnami/elasticsearch"
| `HazelcastConnectionDetails`
| javadoc:org.springframework.boot.autoconfigure.hazelcast.HazelcastConnectionDetails[]
| Containers named "hazelcast/hazelcast".
| `JdbcConnectionDetails`
| javadoc:org.springframework.boot.autoconfigure.jdbc.JdbcConnectionDetails[]
| Containers named "clickhouse/clickhouse-server", "bitnami/clickhouse", "gvenzl/oracle-free", "gvenzl/oracle-xe", "mariadb", "bitnami/mariadb", "mssql/server", "mysql", "bitnami/mysql", "postgres", or "bitnami/postgresql"
| `LdapConnectionDetails`
| javadoc:org.springframework.boot.autoconfigure.ldap.LdapConnectionDetails[]
| Containers named "osixia/openldap"
| `MongoConnectionDetails`
| javadoc:org.springframework.boot.autoconfigure.mongo.MongoConnectionDetails[]
| Containers named "mongo" or "bitnami/mongodb"
| `Neo4jConnectionDetails`
| javadoc:org.springframework.boot.autoconfigure.neo4j.Neo4jConnectionDetails[]
| Containers named "neo4j" or "bitnami/neo4j"
| `org.springframework.boot.actuate.autoconfigure.logging.otlp.OtlpLoggingConnectionDetails`
| javadoc:org.springframework.boot.actuate.autoconfigure.logging.otlp.OtlpLoggingConnectionDetails[]
| Containers named "otel/opentelemetry-collector-contrib", "grafana/otel-lgtm"
| `OtlpMetricsConnectionDetails`
| javadoc:org.springframework.boot.actuate.autoconfigure.metrics.export.otlp.OtlpMetricsConnectionDetails[]
| Containers named "otel/opentelemetry-collector-contrib", "grafana/otel-lgtm"
| `OtlpTracingConnectionDetails`
| javadoc:org.springframework.boot.actuate.autoconfigure.tracing.otlp.OtlpTracingConnectionDetails[]
| Containers named "otel/opentelemetry-collector-contrib", "grafana/otel-lgtm"
| `PulsarConnectionDetails`
| javadoc:org.springframework.boot.autoconfigure.pulsar.PulsarConnectionDetails[]
| Containers named "apachepulsar/pulsar"
| `R2dbcConnectionDetails`
| javadoc:org.springframework.boot.autoconfigure.r2dbc.R2dbcConnectionDetails[]
| Containers named "clickhouse/clickhouse-server", "bitnami/clickhouse", "gvenzl/oracle-free", "gvenzl/oracle-xe", "mariadb", "bitnami/mariadb", "mssql/server", "mysql", "bitnami/mysql", "postgres", or "bitnami/postgresql"
| `RabbitConnectionDetails`
| javadoc:org.springframework.boot.autoconfigure.amqp.RabbitConnectionDetails[]
| Containers named "rabbitmq" or "bitnami/rabbitmq"
| `RedisConnectionDetails`
| javadoc:org.springframework.boot.autoconfigure.data.redis.RedisConnectionDetails[]
| Containers named "redis", "bitnami/redis", "redis/redis-stack" or "redis/redis-stack-server"
| `ZipkinConnectionDetails`
| javadoc:org.springframework.boot.actuate.autoconfigure.tracing.zipkin.ZipkinConnectionDetails[]
| Containers named "openzipkin/zipkin".
|===
@ -334,18 +334,18 @@ The `+TestMyApplication+` class can use the `SpringApplication.from(...)` method
include-code::launch/TestMyApplication[]
You'll also need to define the `org.testcontainers.containers.Container` instances that you want to start along with your application.
You'll also need to define the javadoc:org.testcontainers.containers.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.
Once that has been done, you can create a javadoc:org.springframework.boot.test.context.TestConfiguration[format=annotation] class that declares javadoc:org.springframework.context.annotation.Bean[format=annotation] methods for the containers you want to start.
You can also annotate your `@Bean` methods with `@ServiceConnection` in order to create `ConnectionDetails` beans.
You can also annotate your javadoc:org.springframework.context.annotation.Bean[format=annotation] methods with javadoc:org.springframework.boot.testcontainers.service.connection.ServiceConnection[format=annotation] in order to create javadoc:org.springframework.boot.autoconfigure.service.connection.ConnectionDetails[] beans.
See xref:testing/testcontainers.adoc#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 `org.testcontainers.containers.Container` beans is automatically managed by Spring Boot.
NOTE: The lifecycle of javadoc:org.testcontainers.containers.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.
@ -364,22 +364,22 @@ TIP: You can use the Maven goal `spring-boot:test-run` or the Gradle task `bootT
[[features.dev-services.testcontainers.at-development-time.dynamic-properties]]
==== Contributing Dynamic Properties at Development Time
If you want to contribute dynamic properties at development time from your `org.testcontainers.containers.Container` `@Bean` methods, define an additional `DynamicPropertyRegistrar` bean.
The registrar should be defined using a `@Bean` method that injects the container from which the properties will be sourced as a parameter.
If you want to contribute dynamic properties at development time from your javadoc:org.testcontainers.containers.Container[] javadoc:org.springframework.context.annotation.Bean[format=annotation] methods, define an additional javadoc:org.springframework.test.context.DynamicPropertyRegistrar[] bean.
The registrar should be defined using a javadoc:org.springframework.context.annotation.Bean[format=annotation] method that injects the container from which the properties will be sourced as a parameter.
This arrangement ensures that container has been started before the properties are used.
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.
NOTE: Using a javadoc:org.springframework.boot.testcontainers.service.connection.ServiceConnection[format=annotation] is recommended whenever possible, however, dynamic properties can be a useful fallback for technologies that don't yet have javadoc:org.springframework.boot.testcontainers.service.connection.ServiceConnection[format=annotation] support.
[[features.dev-services.testcontainers.at-development-time.importing-container-declarations]]
==== Importing Testcontainer Declaration Classes
A common pattern when using Testcontainers is to declare `org.testcontainers.containers.Container` instances as static fields.
A common pattern when using Testcontainers is to declare javadoc:org.testcontainers.containers.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.
@ -387,22 +387,22 @@ For example, the following `MyContainers` interface declares `mongo` and `neo4j`
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 your containers as `@Bean` methods.
To do so, add the `@ImportTestcontainers` annotation to your test configuration class:
If you already have containers defined in this way, or you just prefer this style, you can import these declaration classes rather than defining your containers as javadoc:org.springframework.context.annotation.Bean[format=annotation] methods.
To do so, add the javadoc:org.springframework.boot.testcontainers.context.ImportTestcontainers[format=annotation] annotation to your test configuration class:
include-code::MyContainersConfiguration[]
TIP: If you don't intend to use the xref:testing/testcontainers.adoc#testing.testcontainers.service-connections[service connections feature] but want to use xref:testing/testcontainers.adoc#testing.testcontainers.dynamic-properties[`@DynamicPropertySource`] instead, remove the `@ServiceConnection` annotation from the `org.testcontainers.containers.Container` fields.
You can also add `@DynamicPropertySource` annotated methods to your declaration class.
TIP: If you don't intend to use the xref:testing/testcontainers.adoc#testing.testcontainers.service-connections[service connections feature] but want to use xref:testing/testcontainers.adoc#testing.testcontainers.dynamic-properties[`@DynamicPropertySource`] instead, remove the javadoc:org.springframework.boot.testcontainers.service.connection.ServiceConnection[format=annotation] annotation from the javadoc:org.testcontainers.containers.Container[] fields.
You can also add javadoc:org.springframework.test.context.DynamicPropertySource[format=annotation] annotated methods to your declaration class.
[[features.dev-services.testcontainers.at-development-time.devtools]]
==== Using DevTools with Testcontainers at Development Time
When using devtools, you can annotate beans and bean methods with `@RestartScope`.
When using devtools, you can annotate beans and bean methods with javadoc:org.springframework.boot.devtools.restart.RestartScope[format=annotation].
Such beans won't be recreated when the devtools restart the application.
This is especially useful for Testcontainer `org.testcontainers.containers.Container` beans, as they keep their state despite the application restart.
This is especially useful for Testcontainer javadoc:org.testcontainers.containers.Container[] beans, as they keep their state despite the application restart.
include-code::MyContainersConfiguration[]

View File

@ -12,13 +12,13 @@ We first cover what you need to know to build your own auto-configuration and th
[[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`.
Classes that implement auto-configuration are annotated with javadoc:org.springframework.boot.autoconfigure.AutoConfiguration[format=annotation].
This annotation itself is meta-annotated with javadoc:org.springframework.context.annotation.Configuration[format=annotation], making auto-configurations standard javadoc:org.springframework.context.annotation.Configuration[format=annotation] classes.
Additional javadoc:org.springframework.context.annotation.Conditional[format=annotation] annotations are used to constrain when the auto-configuration should apply.
Usually, auto-configuration classes use javadoc:org.springframework.boot.autoconfigure.condition.ConditionalOnClass[format=annotation] and javadoc:org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean[format=annotation] annotations.
This ensures that auto-configuration applies only when relevant classes are found and when you have not declared your own javadoc:org.springframework.context.annotation.Configuration[format=annotation].
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).
You can browse the source code of {code-spring-boot-autoconfigure-src}[`spring-boot-autoconfigure`] to see the javadoc:org.springframework.boot.autoconfigure.AutoConfiguration[format=annotation] 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).
@ -39,16 +39,16 @@ 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.
Specific javadoc:org.springframework.context.annotation.Import[format=annotation] 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 javadoc:org.springframework.boot.autoconfigure.AutoConfiguration[format=annotation] annotation or the dedicated javadoc:org.springframework.boot.autoconfigure.AutoConfigureBefore[format=annotation] and javadoc:org.springframework.boot.autoconfigure.AutoConfigureAfter[format=annotation] annotations.
For example, if you provide web-specific configuration, your class may need to be applied after `WebMvcAutoConfiguration`.
For example, if you provide web-specific configuration, your class may need to be applied after javadoc:org.springframework.boot.autoconfigure.web.servlet.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.
If you want to order certain auto-configurations that should not have any direct knowledge of each other, you can also use javadoc:org.springframework.boot.autoconfigure.AutoConfigureOrder[format=annotation].
That annotation has the same semantic as the regular javadoc:org.springframework.core.annotation.Order[format=annotation] 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.
As with standard javadoc:org.springframework.context.annotation.Configuration[format=annotation] 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 javadoc:org.springframework.context.annotation.DependsOn[format=annotation] relationships.
@ -75,10 +75,10 @@ NOTE: The `+AutoConfiguration.imports+` file should also be updated to _only_ re
[[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.
You almost always want to include one or more javadoc:org.springframework.context.annotation.Conditional[format=annotation] annotations on your auto-configuration class.
The javadoc:org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean[format=annotation] 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.
Spring Boot includes a number of javadoc:org.springframework.context.annotation.Conditional[format=annotation] annotations that you can reuse in your own code by annotating javadoc:org.springframework.context.annotation.Configuration[format=annotation] classes or individual javadoc:org.springframework.context.annotation.Bean[format=annotation] methods.
These annotations include:
* xref:features/developing-auto-configuration.adoc#features.developing-auto-configuration.condition-annotations.class-conditions[]
@ -93,49 +93,49 @@ These annotations include:
[[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.
The javadoc:org.springframework.boot.autoconfigure.condition.ConditionalOnClass[format=annotation] and javadoc:org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass[format=annotation] annotations let javadoc:org.springframework.context.annotation.Configuration[format=annotation] 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.
You can also use the `name` attribute if you prefer to specify the class name by using a javadoc:java.lang.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.
This mechanism does not apply the same way to javadoc:org.springframework.context.annotation.Bean[format=annotation] 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:
To handle this scenario, a separate javadoc:org.springframework.context.annotation.Configuration[format=annotation] 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.
TIP: If you use javadoc:org.springframework.boot.autoconfigure.condition.ConditionalOnClass[format=annotation] or javadoc:org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass[format=annotation] 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.
The javadoc:org.springframework.boot.autoconfigure.condition.ConditionalOnBean[format=annotation] and javadoc:org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean[format=annotation] 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.
The `search` attribute lets you limit the javadoc:org.springframework.context.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:
When placed on a javadoc:org.springframework.context.annotation.Bean[format=annotation] 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`.
In the preceding example, the `someService` bean is going to be created if no bean of type `+SomeService+` is already contained in the javadoc:org.springframework.context.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).
For this reason, we recommend using only javadoc:org.springframework.boot.autoconfigure.condition.ConditionalOnBean[format=annotation] and javadoc:org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean[format=annotation] 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.
NOTE: javadoc:org.springframework.boot.autoconfigure.condition.ConditionalOnBean[format=annotation] and javadoc:org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean[format=annotation] do not prevent javadoc:org.springframework.context.annotation.Configuration[format=annotation] classes from being created.
The only difference between using these conditions at the class level and marking each contained javadoc:org.springframework.context.annotation.Bean[format=annotation] method with the annotation is that the former prevents registration of the javadoc:org.springframework.context.annotation.Configuration[format=annotation] 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.
TIP: When declaring a javadoc:org.springframework.context.annotation.Bean[format=annotation] 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.
Providing as much type information as possible in javadoc:org.springframework.context.annotation.Bean[format=annotation] 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.
The javadoc:org.springframework.boot.autoconfigure.condition.ConditionalOnProperty[format=annotation] 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.
@ -147,7 +147,7 @@ If multiple names are given in the `name` attribute, all of the properties have
[[features.developing-auto-configuration.condition-annotations.resource-conditions]]
=== Resource Conditions
The `@ConditionalOnResource` annotation lets configuration be included only when a specific resource is present.
The javadoc:org.springframework.boot.autoconfigure.condition.ConditionalOnResource[format=annotation] 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`.
@ -155,11 +155,11 @@ Resources can be specified by using the usual Spring conventions, as shown in th
[[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 javadoc:org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication[format=annotation] and javadoc:org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication[format=annotation] 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 javadoc:org.springframework.web.context.WebApplicationContext[], defines a `session` scope, or has a javadoc:org.springframework.web.context.ConfigurableWebEnvironment[].
A reactive web application is any application that uses a javadoc:org.springframework.boot.web.reactive.context.ReactiveWebApplicationContext[], or has a javadoc:org.springframework.boot.web.reactive.context.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.
The javadoc:org.springframework.boot.autoconfigure.condition.ConditionalOnWarDeployment[format=annotation] and javadoc:org.springframework.boot.autoconfigure.condition.ConditionalOnNotWarDeployment[format=annotation] 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.
@ -167,7 +167,7 @@ This condition will not match for applications that are run with an embedded web
[[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].
The javadoc:org.springframework.boot.autoconfigure.condition.ConditionalOnExpression[format=annotation] 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.
@ -177,13 +177,13 @@ As a result, the bean won't be eligible for post-processing (such as configurati
[[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.
An auto-configuration can be affected by many factors: user configuration (`@Bean` definition and javadoc:org.springframework.core.env.Environment[] customization), condition evaluation (presence of a particular library), and others.
Concretely, each test should create a well defined javadoc:org.springframework.context.ApplicationContext[] that represents a combination of those customizations.
javadoc:org.springframework.boot.test.context.runner.ApplicationContextRunner[] provides a great way to achieve that.
WARNING: `ApplicationContextRunner` doesn't work when running the tests in a native image.
WARNING: javadoc:org.springframework.boot.test.context.runner.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.
javadoc:org.springframework.boot.test.context.runner.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]
@ -196,13 +196,13 @@ 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:
It is also possible to easily customize the javadoc:org.springframework.core.env.Environment[], as shown in the following example:
include-code::MyServiceAutoConfigurationTests[tag=test-env]
The runner can also be used to display the `ConditionEvaluationReport`.
The runner can also be used to display the javadoc:org.springframework.boot.autoconfigure.condition.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.
The following example shows how to use the javadoc:org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener[] to print the report in auto-configuration tests.
include-code::MyConditionEvaluationReportingTests[]
@ -211,7 +211,7 @@ 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.
If you need to test an auto-configuration that only operates in a servlet or reactive web application context, use the javadoc:org.springframework.boot.test.context.runner.WebApplicationContextRunner[] or javadoc:org.springframework.boot.test.context.runner.ReactiveWebApplicationContextRunner[] respectively.
@ -219,7 +219,7 @@ If you need to test an auto-configuration that only operates in a servlet or rea
=== 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.
Spring Boot ships with a javadoc:org.springframework.boot.test.context.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]
@ -273,16 +273,16 @@ Make sure that configuration keys are documented by adding field Javadoc for eac
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.
NOTE: You should only use plain text with javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] field Javadoc, since they are not processed before being added to the JSON.
If you use `@ConfigurationProperties` with record class then record components' descriptions should be provided via class-level Javadoc tag `@param` (there are no explicit instance fields in record classes to put regular field-level Javadocs on).
If you use javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] with record class then record components' descriptions should be provided via class-level Javadoc tag `@param` (there are no explicit instance fields in record classes to put regular field-level Javadocs on).
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".
* Use javadoc: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.
@ -295,7 +295,7 @@ Using your own starter in a compatible IDE is also a good idea to validate that
=== 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.
It may also contain configuration key definitions (such as javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation]) 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.

View File

@ -4,23 +4,23 @@
Spring Boot lets you externalize your configuration so that you can work with the same application code in different environments.
You can use a variety of external configuration sources including Java properties files, YAML files, environment variables, and command-line arguments.
Property values can be injected directly into your beans by using the `@Value` annotation, accessed through Spring's `Environment` abstraction, or be xref:features/external-config.adoc#features.external-config.typesafe-configuration-properties[bound to structured objects] through `@ConfigurationProperties`.
Property values can be injected directly into your beans by using the javadoc:org.springframework.beans.factory.annotation.Value[format=annotation] annotation, accessed through Spring's javadoc:org.springframework.core.env.Environment[] abstraction, or be xref:features/external-config.adoc#features.external-config.typesafe-configuration-properties[bound to structured objects] through javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation].
Spring Boot uses a very particular `PropertySource` order that is designed to allow sensible overriding of values.
Spring Boot uses a very particular javadoc:org.springframework.core.env.PropertySource[] order that is designed to allow sensible overriding of values.
Later property sources can override the values defined in earlier ones.
Sources are considered in the following order:
. Default properties (specified by setting javadoc:org.springframework.boot.SpringApplication#setDefaultProperties(java.util.Map)[]).
. javadoc:{url-spring-framework-javadoc}/org.springframework.context.annotation.PropertySource[format=annotation] annotations on your `@Configuration` classes.
Please note that such property sources are not added to the `Environment` until the application context is being refreshed.
. javadoc:{url-spring-framework-javadoc}/org.springframework.context.annotation.PropertySource[format=annotation] annotations on your javadoc:org.springframework.context.annotation.Configuration[format=annotation] classes.
Please note that such property sources are not added to the javadoc:org.springframework.core.env.Environment[] until the application context is being refreshed.
This is too late to configure certain properties such as `+logging.*+` and `+spring.main.*+` which are read before refresh begins.
. Config data (such as `application.properties` files).
. A `RandomValuePropertySource` that has properties only in `+random.*+`.
. A javadoc:org.springframework.boot.env.RandomValuePropertySource[] that has properties only in `+random.*+`.
. OS environment variables.
. Java System properties (`System.getProperties()`).
. JNDI attributes from `java:comp/env`.
. `ServletContext` init parameters.
. `ServletConfig` init parameters.
. javadoc:jakarta.servlet.ServletContext[] init parameters.
. javadoc:jakarta.servlet.ServletConfig[] init parameters.
. Properties from `SPRING_APPLICATION_JSON` (inline JSON embedded in an environment variable or system property).
. Command line arguments.
. `properties` attribute on your tests.
@ -44,7 +44,7 @@ See xref:features/external-config.adoc#features.external-config.typesafe-configu
NOTE: If your application runs in a servlet container or application server, then JNDI properties (in `java:comp/env`) or servlet context initialization parameters can be used instead of, or as well as, environment variables or system properties.
To provide a concrete example, suppose you develop a `@Component` that uses a `name` property, as shown in the following example:
To provide a concrete example, suppose you develop a javadoc:org.springframework.stereotype.Component[format=annotation] that uses a `name` property, as shown in the following example:
include-code::MyBean[]
@ -61,10 +61,10 @@ See the xref:actuator/endpoints.adoc[Production ready features] section for deta
[[features.external-config.command-line-args]]
== Accessing Command Line Properties
By default, `SpringApplication` converts any command line option arguments (that is, arguments starting with `--`, such as `--server.port=9000`) to a `property` and adds them to the Spring `Environment`.
By default, javadoc:org.springframework.boot.SpringApplication[] converts any command line option arguments (that is, arguments starting with `--`, such as `--server.port=9000`) to a `property` and adds them to the Spring javadoc:org.springframework.core.env.Environment[].
As mentioned previously, command line properties always take precedence over file-based property sources.
If you do not want command line properties to be added to the `Environment`, you can disable them by using `SpringApplication.setAddCommandLineProperties(false)`.
If you do not want command line properties to be added to the javadoc:org.springframework.core.env.Environment[], you can disable them by using `SpringApplication.setAddCommandLineProperties(false)`.
@ -74,7 +74,7 @@ If you do not want command line properties to be added to the `Environment`, you
Environment variables and system properties often have restrictions that mean some property names cannot be used.
To help with this, Spring Boot allows you to encode a block of properties into a single JSON structure.
When your application starts, any `spring.application.json` or `SPRING_APPLICATION_JSON` properties will be parsed and added to the `Environment`.
When your application starts, any `spring.application.json` or `SPRING_APPLICATION_JSON` properties will be parsed and added to the javadoc:org.springframework.core.env.Environment[].
For example, the `SPRING_APPLICATION_JSON` property can be supplied on the command line in a UN{asterisk}X shell as an environment variable:
@ -83,7 +83,7 @@ For example, the `SPRING_APPLICATION_JSON` property can be supplied on the comma
$ SPRING_APPLICATION_JSON='{"my":{"name":"test"}}' java -jar myapp.jar
----
In the preceding example, you end up with `my.name=test` in the Spring `Environment`.
In the preceding example, you end up with `my.name=test` in the Spring javadoc:org.springframework.core.env.Environment[].
The same JSON can also be provided as a system property:
@ -101,7 +101,7 @@ $ java -jar myapp.jar --spring.application.json='{"my":{"name":"test"}}'
If you are deploying to a classic Application Server, you could also use a JNDI variable named `java:comp/env/spring.application.json`.
NOTE: Although `null` values from the JSON will be added to the resulting property source, the `PropertySourcesPropertyResolver` treats `null` properties as missing values.
NOTE: Although `null` values from the JSON will be added to the resulting property source, the javadoc:org.springframework.core.env.PropertySourcesPropertyResolver[] treats `null` properties as missing values.
This means that the JSON cannot override properties from lower order property sources with a `null` value.
@ -120,7 +120,7 @@ Spring Boot will automatically find and load `application.properties` and `appli
.. Immediate child directories of the `config/` subdirectory
The list is ordered by precedence (with values from lower items overriding earlier ones).
Documents from the loaded files are added as `PropertySource` instances to the Spring `Environment`.
Documents from the loaded files are added as javadoc:org.springframework.core.env.PropertySource[] instances to the Spring javadoc:org.springframework.core.env.Environment[].
If you do not like `application` as the configuration file name, you can switch to another file name by specifying a configprop:spring.config.name[] environment property.
For example, to look for `myproject.properties` and `myproject.yaml` files you can run your application as follows:
@ -188,14 +188,14 @@ These default values can then be overridden at runtime with a different file loc
[[features.external-config.files.optional-prefix]]
=== Optional Locations
By default, when a specified config data location does not exist, Spring Boot will throw a `ConfigDataLocationNotFoundException` and your application will not start.
By default, when a specified config data location does not exist, Spring Boot will throw a javadoc:org.springframework.boot.context.config.ConfigDataLocationNotFoundException[] and your application will not start.
If you want to specify a location, but you do not mind if it does not always exist, you can use the `optional:` prefix.
You can use this prefix with the `spring.config.location` and `spring.config.additional-location` properties, as well as with xref:features/external-config.adoc#features.external-config.files.importing[`spring.config.import`] declarations.
For example, a `spring.config.import` value of `optional:file:./myconfig.properties` allows your application to start, even if the `myconfig.properties` file is missing.
If you want to ignore all `ConfigDataLocationNotFoundException` errors and always continue to start your application, you can use the `spring.config.on-not-found` property.
If you want to ignore all javadoc:org.springframework.boot.context.config.ConfigDataLocationNotFoundException[] errors and always continue to start your application, you can use the `spring.config.on-not-found` property.
Set the value to `ignore` using `SpringApplication.setDefaultProperties(...)` or with a system/environment variable.
@ -263,7 +263,7 @@ When we have `classpath:/cfg/;classpath:/ext/` instead (with a `;` delimiter) we
. `/ext/application-live.properties`
====
The `Environment` has a set of default profiles (by default, `[default]`) that are used if no active profiles are set.
The javadoc:org.springframework.core.env.Environment[] has a set of default profiles (by default, `[default]`) that are used if no active profiles are set.
In other words, if no profiles are explicitly activated, then properties from `application-default` are considered.
NOTE: Properties files are only ever loaded once.
@ -330,7 +330,7 @@ By default you can import Java Properties, YAML and xref:features/external-confi
Third-party jars can offer support for additional technologies (there is no requirement for files to be local).
For example, you can imagine config data being from external stores such as Consul, Apache ZooKeeper or Netflix Archaius.
If you want to support your own locations, see the `ConfigDataLocationResolver` and `ConfigDataLoader` classes in the `+org.springframework.boot.context.config+` package.
If you want to support your own locations, see the javadoc:org.springframework.boot.context.config.ConfigDataLocationResolver[] and javadoc:org.springframework.boot.context.config.ConfigDataLoader[] classes in the `+org.springframework.boot.context.config+` package.
====
@ -393,15 +393,15 @@ spring:
import: "optional:configtree:/etc/config/"
----
You can then access or inject `myapp.username` and `myapp.password` properties from the `Environment` in the usual way.
You can then access or inject `myapp.username` and `myapp.password` properties from the javadoc:org.springframework.core.env.Environment[] in the usual way.
TIP: The names of the folders and files under the config tree form the property name.
In the above example, to access the properties as `username` and `password`, you can set `spring.config.import` to `optional:configtree:/etc/config/myapp`.
NOTE: Filenames with dot notation are also correctly mapped.
For example, in the above example, a file named `myapp.username` in `/etc/config` would result in a `myapp.username` property in the `Environment`.
For example, in the above example, a file named `myapp.username` in `/etc/config` would result in a `myapp.username` property in the javadoc:org.springframework.core.env.Environment[].
TIP: Configuration tree values can be bound to both string `String` and `byte[]` types depending on the contents expected.
TIP: Configuration tree values can be bound to both string javadoc:java.lang.String[] and `byte[]` types depending on the contents expected.
If you have multiple config trees to import from the same parent folder you can use a wildcard shortcut.
Any `configtree:` location that ends with `/*/` will import all immediate children as config trees.
@ -454,7 +454,7 @@ spring:
[[features.external-config.files.property-placeholders]]
=== Property Placeholders
The values in `application.properties` and `application.yaml` are filtered through the existing `Environment` when they are used, so you can refer back to previously defined values (for example, from System properties or environment variables).
The values in `application.properties` and `application.yaml` are filtered through the existing javadoc:org.springframework.core.env.Environment[] when they are used, so you can refer back to previously defined values (for example, from System properties or environment variables).
The standard `$\{name}` property-placeholder syntax can be used anywhere within a value.
Property placeholders can also specify a default value using a `:` to separate the default value from the property name, for example `${name:default}`.
@ -472,7 +472,7 @@ Assuming that the `username` property has not been set elsewhere, `app.descripti
[NOTE]
====
You should always refer to property names in the placeholder using their canonical form (kebab-case using only lowercase letters).
This will allow Spring Boot to use the same logic as it does when xref:features/external-config.adoc#features.external-config.typesafe-configuration-properties.relaxed-binding[relaxed binding] `@ConfigurationProperties`.
This will allow Spring Boot to use the same logic as it does when xref:features/external-config.adoc#features.external-config.typesafe-configuration-properties.relaxed-binding[relaxed binding] javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation].
For example, `${demo.item-price}` will pick up `demo.item-price` and `demo.itemPrice` forms from the `application.properties` file, as well as `DEMO_ITEMPRICE` from the system environment.
If you used `${demo.itemPrice}` instead, `demo.item-price` and `DEMO_ITEMPRICE` would not be considered.
@ -525,7 +525,7 @@ The lines immediately before and after the separator must not be same comment pr
TIP: Multi-document property files are often used in conjunction with activation properties such as `spring.config.activate.on-profile`.
See the xref:features/external-config.adoc#features.external-config.files.activation-properties[next section] for details.
WARNING: Multi-document property files cannot be loaded by using the `@PropertySource` or `@TestPropertySource` annotations.
WARNING: Multi-document property files cannot be loaded by using the javadoc:org.springframework.context.annotation.PropertySource[format=annotation] or javadoc:org.springframework.test.context.TestPropertySource[format=annotation] annotations.
@ -548,7 +548,7 @@ The following activation properties are available:
| A profile expression that must match for the document to be active.
| `on-cloud-platform`
| The `CloudPlatform` that must be detected for the document to be active.
| The javadoc:org.springframework.boot.cloud.CloudPlatform[] that must be detected for the document to be active.
|===
For example, the following specifies that the second document is only active when running on Kubernetes, and only when either the "`prod`" or "`staging`" profiles are active:
@ -571,8 +571,8 @@ myotherprop: "sometimes-set"
[[features.external-config.encrypting]]
== Encrypting Properties
Spring Boot does not provide any built-in support for encrypting property values, however, it does provide the hook points necessary to modify values contained in the Spring `Environment`.
The `EnvironmentPostProcessor` interface allows you to manipulate the `Environment` before the application starts.
Spring Boot does not provide any built-in support for encrypting property values, however, it does provide the hook points necessary to modify values contained in the Spring javadoc:org.springframework.core.env.Environment[].
The javadoc:org.springframework.boot.env.EnvironmentPostProcessor[] interface allows you to manipulate the javadoc:org.springframework.core.env.Environment[] before the application starts.
See xref:how-to:application.adoc#howto.application.customize-the-environment-or-application-context[] for details.
If you need a secure way to store credentials and passwords, the https://cloud.spring.io/spring-cloud-vault/[Spring Cloud Vault] project provides support for storing externalized configuration in https://www.vaultproject.io/[HashiCorp Vault].
@ -583,7 +583,7 @@ If you need a secure way to store credentials and passwords, the https://cloud.s
== Working With YAML
https://yaml.org[YAML] is a superset of JSON and, as such, is a convenient format for specifying hierarchical configuration data.
The `SpringApplication` class automatically supports YAML as an alternative to properties whenever you have the https://github.com/snakeyaml/snakeyaml[SnakeYAML] library on your classpath.
The javadoc:org.springframework.boot.SpringApplication[] class automatically supports YAML as an alternative to properties whenever you have the https://github.com/snakeyaml/snakeyaml[SnakeYAML] library on your classpath.
NOTE: If you use starters, SnakeYAML is automatically provided by `spring-boot-starter`.
@ -592,7 +592,7 @@ NOTE: If you use starters, SnakeYAML is automatically provided by `spring-boot-s
[[features.external-config.yaml.mapping-to-properties]]
=== Mapping YAML to Properties
YAML documents need to be converted from their hierarchical format to a flat structure that can be used with the Spring `Environment`.
YAML documents need to be converted from their hierarchical format to a flat structure that can be used with the Spring javadoc:org.springframework.core.env.Environment[].
For example, consider the following YAML document:
[source,yaml]
@ -606,7 +606,7 @@ environments:
name: "My Cool App"
----
In order to access these properties from the `Environment`, they would be flattened as follows:
In order to access these properties from the javadoc:org.springframework.core.env.Environment[], they would be flattened as follows:
[source,properties]
----
@ -636,10 +636,10 @@ my.servers[0]=dev.example.com
my.servers[1]=another.example.com
----
TIP: Properties that use the `[index]` notation can be bound to Java `java.util.List` or `java.util.Set` objects using Spring Boot's `Binder` class.
TIP: Properties that use the `[index]` notation can be bound to Java javadoc:java.util.List[] or javadoc:java.util.Set[] objects using Spring Boot's javadoc:org.springframework.boot.context.properties.bind.Binder[] class.
For more details see the xref:features/external-config.adoc#features.external-config.typesafe-configuration-properties[] section below.
WARNING: YAML files cannot be loaded by using the `@PropertySource` or `@TestPropertySource` annotations.
WARNING: YAML files cannot be loaded by using the javadoc:org.springframework.context.annotation.PropertySource[format=annotation] or javadoc:org.springframework.test.context.TestPropertySource[format=annotation] annotations.
So, in the case that you need to load values that way, you need to use a properties file.
@ -648,16 +648,16 @@ So, in the case that you need to load values that way, you need to use a propert
=== Directly Loading YAML
Spring Framework provides two convenient classes that can be used to load YAML documents.
The `YamlPropertiesFactoryBean` loads YAML as `Properties` and the `YamlMapFactoryBean` loads YAML as a `java.util.Map`.
The javadoc:org.springframework.beans.factory.config.YamlPropertiesFactoryBean[] loads YAML as javadoc:java.util.Properties[] and the javadoc:org.springframework.beans.factory.config.YamlMapFactoryBean[] loads YAML as a javadoc:java.util.Map[].
You can also use the `YamlPropertySourceLoader` class if you want to load YAML as a Spring `PropertySource`.
You can also use the javadoc:org.springframework.boot.env.YamlPropertySourceLoader[] class if you want to load YAML as a Spring javadoc:org.springframework.core.env.PropertySource[].
[[features.external-config.random-values]]
== Configuring Random Values
The `RandomValuePropertySource` is useful for injecting random values (for example, into secrets or test cases).
The javadoc:org.springframework.boot.env.RandomValuePropertySource[] is useful for injecting random values (for example, into secrets or test cases).
It can produce integers, longs, uuids, or strings, as shown in the following example:
[configprops%novalidate,yaml]
@ -681,7 +681,7 @@ If `max` is provided, then `value` is the minimum value and `max` is the maximum
Spring Boot supports setting a prefix for environment properties.
This is useful if the system environment is shared by multiple Spring Boot applications with different configuration requirements.
The prefix for system environment properties can be set directly on `SpringApplication`.
The prefix for system environment properties can be set directly on javadoc:org.springframework.boot.SpringApplication[].
For example, if you set the prefix to `input`, a property such as `remote.timeout` will also be resolved as `input.remote.timeout` in the system environment.
@ -693,7 +693,7 @@ For example, if you set the prefix to `input`, a property such as `remote.timeou
Using the `@Value("$\{property}")` annotation to inject configuration properties can sometimes be cumbersome, especially if you are working with multiple properties or your data is hierarchical in nature.
Spring Boot provides an alternative method of working with properties that lets strongly typed beans govern and validate the configuration of your application.
TIP: See also the xref:features/external-config.adoc#features.external-config.typesafe-configuration-properties.vs-value-annotation[differences between `@Value` and type-safe configuration properties].
TIP: See also the xref:features/external-config.adoc#features.external-config.typesafe-configuration-properties.vs-value-annotation[differences between javadoc:org.springframework.beans.factory.annotation.Value[format=annotation] and type-safe configuration properties].
@ -707,15 +707,15 @@ include-code::MyProperties[]
The preceding POJO defines the following properties:
* `my.service.enabled`, with a value of `false` by default.
* `my.service.remote-address`, with a type that can be coerced from `String`.
* `my.service.remote-address`, with a type that can be coerced from javadoc:java.lang.String[].
* `my.service.security.username`, with a nested "security" object whose name is determined by the name of the property.
In particular, the type is not used at all there and could have been `SecurityProperties`.
In particular, the type is not used at all there and could have been javadoc:org.springframework.boot.autoconfigure.security.SecurityProperties[].
* `my.service.security.password`.
* `my.service.security.roles`, with a collection of `String` that defaults to `USER`.
* `my.service.security.roles`, with a collection of javadoc:java.lang.String[] that defaults to `USER`.
TIP: To use a reserved keyword in the name of a property, such as `my.service.import`, use the `@org.springframework.boot.context.properties.bind.Name` annotation on the property's field.
TIP: To use a reserved keyword in the name of a property, such as `my.service.import`, use the javadoc:org.springframework.boot.context.properties.bind.Name[format=annotation] annotation on the property's field.
NOTE: The properties that map to `@ConfigurationProperties` classes available in Spring Boot, which are configured through properties files, YAML files, environment variables, and other mechanisms, are public API but the accessors (getters/setters) of the class itself are not meant to be used directly.
NOTE: The properties that map to javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] classes available in Spring Boot, which are configured through properties files, YAML files, environment variables, and other mechanisms, are public API but the accessors (getters/setters) of the class itself are not meant to be used directly.
[NOTE]
====
@ -747,50 +747,50 @@ include-code::MyProperties[]
In this setup, the presence of a single parameterized constructor implies that constructor binding should be used.
This means that the binder will find a constructor with the parameters that you wish to have bound.
If your class has multiple constructors, the `@ConstructorBinding` annotation can be used to specify which constructor to use for constructor binding.
To opt out of constructor binding for a class with a single parameterized constructor, the constructor must be annotated with `@Autowired` or made `private`.
If your class has multiple constructors, the javadoc:org.springframework.boot.context.properties.bind.ConstructorBinding[format=annotation] annotation can be used to specify which constructor to use for constructor binding.
To opt out of constructor binding for a class with a single parameterized constructor, the constructor must be annotated with javadoc:org.springframework.beans.factory.annotation.Autowired[format=annotation] or made `private`.
Constructor binding can be used with records.
Unless your record has multiple constructors, there is no need to use `@ConstructorBinding`.
Unless your record has multiple constructors, there is no need to use javadoc:org.springframework.boot.context.properties.bind.ConstructorBinding[format=annotation].
Nested members of a constructor bound class (such as `+Security+` in the example above) will also be bound through their constructor.
Default values can be specified using `@org.springframework.boot.context.properties.bind.DefaultValue` on constructor parameters and record components.
The conversion service will be applied to coerce the annotation's `String` value to the target type of a missing property.
Default values can be specified using javadoc:org.springframework.boot.context.properties.bind.DefaultValue[format=annotation] on constructor parameters and record components.
The conversion service will be applied to coerce the annotation's javadoc:java.lang.String[] value to the target type of a missing property.
Referring to the previous example, if no properties are bound to `+Security+`, the `MyProperties` instance will contain a `null` value for `security`.
To make it contain a non-null instance of `+Security+` even when no properties are bound to it (when using Kotlin, this will require the `username` and `password` parameters of `+Security+` to be declared as nullable as they do not have default values), use an empty `@org.springframework.boot.context.properties.bind.DefaultValue` annotation:
To make it contain a non-null instance of `+Security+` even when no properties are bound to it (when using Kotlin, this will require the `username` and `password` parameters of `+Security+` to be declared as nullable as they do not have default values), use an empty javadoc:org.springframework.boot.context.properties.bind.DefaultValue[format=annotation] annotation:
include-code::nonnull/MyProperties[tag=*]
NOTE: To use constructor binding the class must be enabled using `@EnableConfigurationProperties` or configuration property scanning.
You cannot use constructor binding with beans that are created by the regular Spring mechanisms (for example `@Component` beans, beans created by using `@Bean` methods or beans loaded by using `@Import`)
NOTE: To use constructor binding the class must be enabled using javadoc:org.springframework.boot.context.properties.EnableConfigurationProperties[format=annotation] or configuration property scanning.
You cannot use constructor binding with beans that are created by the regular Spring mechanisms (for example javadoc:org.springframework.stereotype.Component[format=annotation] beans, beans created by using javadoc:org.springframework.context.annotation.Bean[format=annotation] methods or beans loaded by using javadoc:org.springframework.context.annotation.Import[format=annotation])
NOTE: To use constructor binding the class must be compiled with `-parameters`.
This will happen automatically if you use Spring Boot's Gradle plugin or if you use Maven and `spring-boot-starter-parent`.
NOTE: The use of `java.util.Optional` with `@ConfigurationProperties` is not recommended as it is primarily intended for use as a return type.
NOTE: The use of javadoc:java.util.Optional[] with javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] is not recommended as it is primarily intended for use as a return type.
As such, it is not well-suited to configuration property injection.
For consistency with properties of other types, if you do declare an `java.util.Optional` property and it has no value, `null` rather than an empty `java.util.Optional` will be bound.
For consistency with properties of other types, if you do declare an javadoc:java.util.Optional[] property and it has no value, `null` rather than an empty javadoc:java.util.Optional[] will be bound.
TIP: To use a reserved keyword in the name of a property, such as `my.service.import`, use the `@org.springframework.boot.context.properties.bind.Name` annotation on the constructor parameter.
TIP: To use a reserved keyword in the name of a property, such as `my.service.import`, use the javadoc:org.springframework.boot.context.properties.bind.Name[format=annotation] annotation on the constructor parameter.
[[features.external-config.typesafe-configuration-properties.enabling-annotated-types]]
=== Enabling @ConfigurationProperties-annotated Types
Spring Boot provides infrastructure to bind `@ConfigurationProperties` types and register them as beans.
Spring Boot provides infrastructure to bind javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] types and register them as beans.
You can either enable configuration properties on a class-by-class basis or enable configuration property scanning that works in a similar manner to component scanning.
Sometimes, classes annotated with `@ConfigurationProperties` might not be suitable for scanning, for example, if you're developing your own auto-configuration or you want to enable them conditionally.
In these cases, specify the list of types to process using the `@EnableConfigurationProperties` annotation.
This can be done on any `@Configuration` class, as shown in the following example:
Sometimes, classes annotated with javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] might not be suitable for scanning, for example, if you're developing your own auto-configuration or you want to enable them conditionally.
In these cases, specify the list of types to process using the javadoc:org.springframework.boot.context.properties.EnableConfigurationProperties[format=annotation] annotation.
This can be done on any javadoc:org.springframework.context.annotation.Configuration[format=annotation] class, as shown in the following example:
include-code::MyConfiguration[]
include-code::SomeProperties[]
To use configuration property scanning, add the `@ConfigurationPropertiesScan` annotation to your application.
Typically, it is added to the main application class that is annotated with `@SpringBootApplication` but it can be added to any `@Configuration` class.
To use configuration property scanning, add the javadoc:org.springframework.boot.context.properties.ConfigurationPropertiesScan[format=annotation] annotation to your application.
Typically, it is added to the main application class that is annotated with javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation] but it can be added to any javadoc:org.springframework.context.annotation.Configuration[format=annotation] class.
By default, scanning will occur from the package of the class that declares the annotation.
If you want to define specific packages to scan, you can do so as shown in the following example:
@ -798,22 +798,22 @@ include-code::MyApplication[]
[NOTE]
====
When the `@ConfigurationProperties` bean is registered using configuration property scanning or through `@EnableConfigurationProperties`, the bean has a conventional name: `<prefix>-<fqn>`, where `<prefix>` is the environment key prefix specified in the `@ConfigurationProperties` annotation and `<fqn>` is the fully qualified name of the bean.
When the javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] bean is registered using configuration property scanning or through javadoc:org.springframework.boot.context.properties.EnableConfigurationProperties[format=annotation], the bean has a conventional name: `<prefix>-<fqn>`, where `<prefix>` is the environment key prefix specified in the javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] annotation and `<fqn>` is the fully qualified name of the bean.
If the annotation does not provide any prefix, only the fully qualified name of the bean is used.
Assuming that it is in the `com.example.app` package, the bean name of the `+SomeProperties+` example above is `some.properties-com.example.app.SomeProperties`.
====
We recommend that `@ConfigurationProperties` only deal with the environment and, in particular, does not inject other beans from the context.
For corner cases, setter injection can be used or any of the `*Aware` interfaces provided by the framework (such as `EnvironmentAware` if you need access to the `Environment`).
If you still want to inject other beans using the constructor, the configuration properties bean must be annotated with `@Component` and use JavaBean-based property binding.
We recommend that javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] only deal with the environment and, in particular, does not inject other beans from the context.
For corner cases, setter injection can be used or any of the `*Aware` interfaces provided by the framework (such as javadoc:org.springframework.context.EnvironmentAware[] if you need access to the javadoc:org.springframework.core.env.Environment[]).
If you still want to inject other beans using the constructor, the configuration properties bean must be annotated with javadoc:org.springframework.stereotype.Component[format=annotation] and use JavaBean-based property binding.
[[features.external-config.typesafe-configuration-properties.using-annotated-types]]
=== Using @ConfigurationProperties-annotated Types
This style of configuration works particularly well with the `SpringApplication` external YAML configuration, as shown in the following example:
This style of configuration works particularly well with the javadoc:org.springframework.boot.SpringApplication[] external YAML configuration, as shown in the following example:
[source,yaml]
----
@ -827,11 +827,11 @@ my:
- "ADMIN"
----
To work with `@ConfigurationProperties` beans, you can inject them in the same way as any other bean, as shown in the following example:
To work with javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans, you can inject them in the same way as any other bean, as shown in the following example:
include-code::MyService[]
TIP: Using `@ConfigurationProperties` also lets you generate metadata files that can be used by IDEs to offer auto-completion for your own keys.
TIP: Using javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] also lets you generate metadata files that can be used by IDEs to offer auto-completion for your own keys.
See the xref:specification:configuration-metadata/index.adoc[appendix] for details.
@ -839,10 +839,10 @@ See the xref:specification:configuration-metadata/index.adoc[appendix] for detai
[[features.external-config.typesafe-configuration-properties.third-party-configuration]]
=== Third-party Configuration
As well as using `@ConfigurationProperties` to annotate a class, you can also use it on public `@Bean` methods.
As well as using javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] to annotate a class, you can also use it on public javadoc:org.springframework.context.annotation.Bean[format=annotation] methods.
Doing so can be particularly useful when you want to bind properties to third-party components that are outside of your control.
To configure a bean from the `Environment` properties, add `@ConfigurationProperties` to its bean registration, as shown in the following example:
To configure a bean from the javadoc:org.springframework.core.env.Environment[] properties, add javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] to its bean registration, as shown in the following example:
include-code::ThirdPartyConfiguration[]
@ -853,10 +853,10 @@ Any JavaBean property defined with the `another` prefix is mapped onto that `+An
[[features.external-config.typesafe-configuration-properties.relaxed-binding]]
=== Relaxed Binding
Spring Boot uses some relaxed rules for binding `Environment` properties to `@ConfigurationProperties` beans, so there does not need to be an exact match between the `Environment` property name and the bean property name.
Spring Boot uses some relaxed rules for binding javadoc:org.springframework.core.env.Environment[] properties to javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans, so there does not need to be an exact match between the javadoc:org.springframework.core.env.Environment[] property name and the bean property name.
Common examples where this is useful include dash-separated environment properties (for example, `context-path` binds to `contextPath`), and capitalized environment properties (for example, `PORT` binds to `port`).
As an example, consider the following `@ConfigurationProperties` class:
As an example, consider the following javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] class:
include-code::MyPersonProperties[]
@ -911,7 +911,7 @@ TIP: We recommend that, when possible, properties are stored in lower-case kebab
[[features.external-config.typesafe-configuration-properties.relaxed-binding.maps]]
==== Binding Maps
When binding to `java.util.Map` properties you may need to use a special bracket notation so that the original `key` value is preserved.
When binding to javadoc:java.util.Map[] properties you may need to use a special bracket notation so that the original `key` value is preserved.
If the key is not surrounded by `[]`, any characters that are not alpha-numeric, `-` or `.` are removed.
For example, consider binding the following properties to a `Map<String,String>`:
@ -927,11 +927,11 @@ my:
NOTE: For YAML files, the brackets need to be surrounded by quotes for the keys to be parsed properly.
The properties above will bind to a `java.util.Map` with `/key1`, `/key2` and `key3` as the keys in the map.
The properties above will bind to a javadoc:java.util.Map[] with `/key1`, `/key2` and `key3` as the keys in the map.
The slash has been removed from `key3` because it was not surrounded by square brackets.
When binding to scalar values, keys with `.` in them do not need to be surrounded by `[]`.
Scalar values include enums and all types in the `java.lang` package except for `Object`.
Scalar values include enums and all types in the `java.lang` package except for javadoc:java.lang.Object[].
Binding `a.b=c` to `Map<String, String>` will preserve the `.` in the key and return a Map with the entry `{"a.b"="c"}`.
For any other types you need to use the bracket notation if your `key` contains a `.`.
For example, binding `a.b=c` to `Map<String, Object>` will return a Map with the entry `{"a"={"b"="c"}}` whereas `[a.b]=c` will return a Map with the entry `{"a.b"="c"}`.
@ -956,7 +956,7 @@ To convert a property name in the canonical-form to an environment variable name
For example, the configuration property `spring.main.log-startup-info` would be an environment variable named `SPRING_MAIN_LOGSTARTUPINFO`.
Environment variables can also be used when binding to object lists.
To bind to a `java.util.List`, the element number should be surrounded with underscores in the variable name.
To bind to a javadoc:java.util.List[], the element number should be surrounded with underscores in the variable name.
For example, the configuration property `my.service[0].other` would use an environment variable named `MY_SERVICE_0_OTHER`.
@ -968,16 +968,16 @@ Support for binding from environment variables is applied to the `systemEnvironm
==== Binding Maps From Environment Variables
When Spring Boot binds an environment variable to a property class, it lowercases the environment variable name before binding.
Most of the time this detail isn't important, except when binding to `Map` properties.
Most of the time this detail isn't important, except when binding to javadoc:java.util.Map[] properties.
The keys in the `Map` are always in lowercase, as seen in the following example:
The keys in the javadoc:java.util.Map[] are always in lowercase, as seen in the following example:
include-code::MyMapsProperties[]
When setting `MY_PROPS_VALUES_KEY=value`, the `values` `Map` contains a `{"key"="value"}` entry.
When setting `MY_PROPS_VALUES_KEY=value`, the `values` javadoc:java.util.Map[] contains a `{"key"="value"}` entry.
Only the environment variable *name* is lower-cased, not the value.
When setting `MY_PROPS_VALUES_KEY=VALUE`, the `values` `Map` contains a `{"key"="VALUE"}` entry.
When setting `MY_PROPS_VALUES_KEY=VALUE`, the `values` javadoc:java.util.Map[] contains a `{"key"="VALUE"}` entry.
@ -985,7 +985,7 @@ When setting `MY_PROPS_VALUES_KEY=VALUE`, the `values` `Map` contains a `{"key"=
==== Caching
Relaxed binding uses a cache to improve performance. By default, this caching is only applied to immutable property sources.
To customize this behavior, for example to enable caching for mutable property sources, use `ConfigurationPropertyCaching`.
To customize this behavior, for example to enable caching for mutable property sources, use javadoc:org.springframework.boot.context.properties.source.ConfigurationPropertyCaching[].
@ -1021,7 +1021,7 @@ If the `dev` profile is not active, `MyProperties.list` contains one `MyPojo` en
If the `dev` profile is enabled, however, the `list` _still_ contains only one entry (with a name of `my another name` and a description of `null`).
This configuration _does not_ add a second `MyPojo` instance to the list, and it does not merge the items.
When a `java.util.List` is specified in multiple profiles, the one with the highest priority (and only that one) is used.
When a javadoc:java.util.List[] is specified in multiple profiles, the one with the highest priority (and only that one) is used.
Consider the following example:
[configprops%novalidate,yaml]
@ -1045,7 +1045,7 @@ my:
In the preceding example, if the `dev` profile is active, `MyProperties.list` contains _one_ `MyPojo` entry (with a name of `my another name` and a description of `null`).
For YAML, both comma-separated lists and YAML lists can be used for completely overriding the contents of the list.
For `java.util.Map` properties, you can bind with property values drawn from multiple sources.
For javadoc:java.util.Map[] properties, you can bind with property values drawn from multiple sources.
However, for the same property in multiple sources, the one with the highest priority is used.
The following example exposes a `Map<String, MyPojo>` from `MyProperties`:
@ -1084,12 +1084,12 @@ NOTE: The preceding merging rules apply to properties from all property sources,
[[features.external-config.typesafe-configuration-properties.conversion]]
=== Properties Conversion
Spring Boot attempts to coerce the external application properties to the right type when it binds to the `@ConfigurationProperties` beans.
If you need custom type conversion, you can provide a `ConversionService` bean (with a bean named `conversionService`) or custom property editors (through a `CustomEditorConfigurer` bean) or custom converters (with bean definitions annotated as `@ConfigurationPropertiesBinding`).
Spring Boot attempts to coerce the external application properties to the right type when it binds to the javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans.
If you need custom type conversion, you can provide a javadoc:org.springframework.core.convert.ConversionService[] bean (with a bean named `conversionService`) or custom property editors (through a javadoc:org.springframework.beans.factory.config.CustomEditorConfigurer[] bean) or custom converters (with bean definitions annotated as javadoc:org.springframework.boot.context.properties.ConfigurationPropertiesBinding[format=annotation]).
NOTE: As this bean is requested very early during the application lifecycle, make sure to limit the dependencies that your `ConversionService` is using.
NOTE: As this bean is requested very early during the application lifecycle, make sure to limit the dependencies that your javadoc:org.springframework.core.convert.ConversionService[] is using.
Typically, any dependency that you require may not be fully initialized at creation time.
You may want to rename your custom `ConversionService` if it is not required for configuration keys coercion and only rely on custom converters qualified with `@ConfigurationPropertiesBinding`.
You may want to rename your custom javadoc:org.springframework.core.convert.ConversionService[] if it is not required for configuration keys coercion and only rely on custom converters qualified with javadoc:org.springframework.boot.context.properties.ConfigurationPropertiesBinding[format=annotation].
@ -1097,10 +1097,10 @@ You may want to rename your custom `ConversionService` if it is not required for
==== Converting Durations
Spring Boot has dedicated support for expressing durations.
If you expose a `java.time.Duration` property, the following formats in application properties are available:
If you expose a javadoc:java.time.Duration[] property, the following formats in application properties are available:
* A regular `long` representation (using milliseconds as the default unit unless a `@DurationUnit` has been specified)
* The standard ISO-8601 format {apiref-openjdk}/java.base/java/time/Duration.html#parse(java.lang.CharSequence)[used by `java.time.Duration`]
* A regular `long` representation (using milliseconds as the default unit unless a javadoc:org.springframework.boot.convert.DurationUnit[format=annotation] has been specified)
* The standard ISO-8601 format {apiref-openjdk}/java.base/java/time/Duration.html#parse(java.lang.CharSequence)[used by javadoc:java.time.Duration[]]
* A more readable format where the value and the unit are coupled (`10s` means 10 seconds)
Consider the following example:
@ -1121,14 +1121,14 @@ These are:
* `h` for hours
* `d` for days
The default unit is milliseconds and can be overridden using `@DurationUnit` as illustrated in the sample above.
The default unit is milliseconds and can be overridden using javadoc:org.springframework.boot.convert.DurationUnit[format=annotation] as illustrated in the sample above.
If you prefer to use constructor binding, the same properties can be exposed, as shown in the following example:
include-code::constructorbinding/MyProperties[]
TIP: If you are upgrading a `Long` property, make sure to define the unit (using `@DurationUnit`) if it is not milliseconds.
TIP: If you are upgrading a javadoc:java.lang.Long[] property, make sure to define the unit (using javadoc:org.springframework.boot.convert.DurationUnit[format=annotation]) if it is not milliseconds.
Doing so gives a transparent upgrade path while supporting a much richer format.
@ -1136,11 +1136,11 @@ Doing so gives a transparent upgrade path while supporting a much richer format.
[[features.external-config.typesafe-configuration-properties.conversion.periods]]
==== Converting Periods
In addition to durations, Spring Boot can also work with `java.time.Period` type.
In addition to durations, Spring Boot can also work with javadoc:java.time.Period[] type.
The following formats can be used in application properties:
* An regular `int` representation (using days as the default unit unless a `@PeriodUnit` has been specified)
* The standard ISO-8601 format {apiref-openjdk}/java.base/java/time/Period.html#parse(java.lang.CharSequence)[used by `java.time.Period`]
* An regular `int` representation (using days as the default unit unless a javadoc:org.springframework.boot.convert.PeriodUnit[format=annotation] has been specified)
* The standard ISO-8601 format {apiref-openjdk}/java.base/java/time/Period.html#parse(java.lang.CharSequence)[used by javadoc:java.time.Period[]]
* A simpler format where the value and the unit pairs are coupled (`1y3d` means 1 year and 3 days)
The following units are supported with the simple format:
@ -1150,17 +1150,17 @@ The following units are supported with the simple format:
* `w` for weeks
* `d` for days
NOTE: The `java.time.Period` type never actually stores the number of weeks, it is a shortcut that means "`7 days`".
NOTE: The javadoc:java.time.Period[] type never actually stores the number of weeks, it is a shortcut that means "`7 days`".
[[features.external-config.typesafe-configuration-properties.conversion.data-sizes]]
==== Converting Data Sizes
Spring Framework has a `DataSize` value type that expresses a size in bytes.
If you expose a `DataSize` property, the following formats in application properties are available:
Spring Framework has a javadoc:org.springframework.util.unit.DataSize[] value type that expresses a size in bytes.
If you expose a javadoc:org.springframework.util.unit.DataSize[] property, the following formats in application properties are available:
* A regular `long` representation (using bytes as the default unit unless a `@DataSizeUnit` has been specified)
* A regular `long` representation (using bytes as the default unit unless a javadoc:org.springframework.boot.convert.DataSizeUnit[format=annotation] has been specified)
* A more readable format where the value and the unit are coupled (`10MB` means 10 megabytes)
Consider the following example:
@ -1179,13 +1179,13 @@ These are:
* `GB` for gigabytes
* `TB` for terabytes
The default unit is bytes and can be overridden using `@DataSizeUnit` as illustrated in the sample above.
The default unit is bytes and can be overridden using javadoc:org.springframework.boot.convert.DataSizeUnit[format=annotation] as illustrated in the sample above.
If you prefer to use constructor binding, the same properties can be exposed, as shown in the following example:
include-code::constructorbinding/MyProperties[]
TIP: If you are upgrading a `Long` property, make sure to define the unit (using `@DataSizeUnit`) if it is not bytes.
TIP: If you are upgrading a javadoc:java.lang.Long[] property, make sure to define the unit (using javadoc:org.springframework.boot.convert.DataSizeUnit[format=annotation]) if it is not bytes.
Doing so gives a transparent upgrade path while supporting a much richer format.
@ -1193,25 +1193,25 @@ Doing so gives a transparent upgrade path while supporting a much richer format.
[[features.external-config.typesafe-configuration-properties.validation]]
=== @ConfigurationProperties Validation
Spring Boot attempts to validate `@ConfigurationProperties` classes whenever they are annotated with Spring's `@org.springframework.validation.annotation.Validated` annotation.
Spring Boot attempts to validate javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] classes whenever they are annotated with Spring's javadoc:org.springframework.validation.annotation.Validated[format=annotation] annotation.
You can use JSR-303 `jakarta.validation` constraint annotations directly on your configuration class.
To do so, ensure that a compliant JSR-303 implementation is on your classpath and then add constraint annotations to your fields, as shown in the following example:
include-code::MyProperties[]
TIP: You can also trigger validation by annotating the `@Bean` method that creates the configuration properties with `@org.springframework.validation.annotation.Validated`.
TIP: You can also trigger validation by annotating the javadoc:org.springframework.context.annotation.Bean[format=annotation] method that creates the configuration properties with javadoc:org.springframework.validation.annotation.Validated[format=annotation].
To cascade validation to nested properties the associated field must be annotated with `@Valid`.
To cascade validation to nested properties the associated field must be annotated with javadoc:jakarta.validation.Valid[format=annotation].
The following example builds on the preceding `MyProperties` example:
include-code::nested/MyProperties[]
You can also add a custom Spring `org.springframework.validation.Validator` by creating a bean definition called `configurationPropertiesValidator`.
The `@Bean` method should be declared `static`.
The configuration properties validator is created very early in the application's lifecycle, and declaring the `@Bean` method as static lets the bean be created without having to instantiate the `@Configuration` class.
You can also add a custom Spring javadoc:org.springframework.validation.Validator[] by creating a bean definition called `configurationPropertiesValidator`.
The javadoc:org.springframework.context.annotation.Bean[format=annotation] method should be declared `static`.
The configuration properties validator is created very early in the application's lifecycle, and declaring the javadoc:org.springframework.context.annotation.Bean[format=annotation] method as static lets the bean be created without having to instantiate the javadoc:org.springframework.context.annotation.Configuration[format=annotation] class.
Doing so avoids any problems that may be caused by early instantiation.
TIP: The `spring-boot-actuator` module includes an endpoint that exposes all `@ConfigurationProperties` beans.
TIP: The `spring-boot-actuator` module includes an endpoint that exposes all javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans.
Point your web browser to `/actuator/configprops` or use the equivalent JMX endpoint.
See the xref:actuator/endpoints.adoc[Production ready features] section for details.
@ -1220,8 +1220,8 @@ See the xref:actuator/endpoints.adoc[Production ready features] section for deta
[[features.external-config.typesafe-configuration-properties.vs-value-annotation]]
=== @ConfigurationProperties vs. @Value
The `@Value` annotation is a core container feature, and it does not provide the same features as type-safe configuration properties.
The following table summarizes the features that are supported by `@ConfigurationProperties` and `@Value`:
The javadoc:org.springframework.beans.factory.annotation.Value[format=annotation] annotation is a core container feature, and it does not provide the same features as type-safe configuration properties.
The following table summarizes the features that are supported by javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] and javadoc:org.springframework.beans.factory.annotation.Value[format=annotation]:
[cols="4,2,2"]
|===
@ -1243,16 +1243,16 @@ The following table summarizes the features that are supported by `@Configuratio
[[features.external-config.typesafe-configuration-properties.vs-value-annotation.note]]
[NOTE]
====
If you do want to use `@Value`, we recommend that you refer to property names using their canonical form (kebab-case using only lowercase letters).
This will allow Spring Boot to use the same logic as it does when xref:features/external-config.adoc#features.external-config.typesafe-configuration-properties.relaxed-binding[relaxed binding] `@ConfigurationProperties`.
If you do want to use javadoc:org.springframework.beans.factory.annotation.Value[format=annotation], we recommend that you refer to property names using their canonical form (kebab-case using only lowercase letters).
This will allow Spring Boot to use the same logic as it does when xref:features/external-config.adoc#features.external-config.typesafe-configuration-properties.relaxed-binding[relaxed binding] javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation].
For example, `@Value("${demo.item-price}")` will pick up `demo.item-price` and `demo.itemPrice` forms from the `application.properties` file, as well as `DEMO_ITEMPRICE` from the system environment.
If you used `@Value("${demo.itemPrice}")` instead, `demo.item-price` and `DEMO_ITEMPRICE` would not be considered.
====
If you define a set of configuration keys for your own components, we recommend you group them in a POJO annotated with `@ConfigurationProperties`.
If you define a set of configuration keys for your own components, we recommend you group them in a POJO annotated with javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation].
Doing so will provide you with structured, type-safe object that you can inject into your own beans.
`SpEL` expressions from xref:features/external-config.adoc#features.external-config.files[application property files] are not processed at time of parsing these files and populating the environment.
However, it is possible to write a `SpEL` expression in `@Value`.
If the value of a property from an application property file is a `SpEL` expression, it will be evaluated when consumed through `@Value`.
However, it is possible to write a `SpEL` expression in javadoc:org.springframework.beans.factory.annotation.Value[format=annotation].
If the value of a property from an application property file is a `SpEL` expression, it will be evaluated when consumed through javadoc:org.springframework.beans.factory.annotation.Value[format=annotation].

View File

@ -6,7 +6,7 @@ By default, Spring Boot looks for the presence of a `messages` resource bundle a
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 `org.springframework.context.MessageSource`.
If no properties file is found that matches any of the configured base names, there will be no auto-configured javadoc:org.springframework.context.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:

View File

@ -15,29 +15,29 @@ Jackson is the preferred and default library.
== 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`].
When Jackson is on the classpath an javadoc:com.fasterxml.jackson.databind.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 javadoc:com.fasterxml.jackson.databind.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 `com.fasterxml.jackson.databind.JsonSerializer` and `com.fasterxml.jackson.databind.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.
If you use Jackson to serialize and deserialize JSON data, you might want to write your own javadoc:com.fasterxml.jackson.databind.JsonSerializer[] and javadoc:com.fasterxml.jackson.databind.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 javadoc:org.springframework.boot.jackson.JsonComponent[format=annotation] annotation that makes it easier to directly register Spring Beans.
You can use the `@JsonComponent` annotation directly on `com.fasterxml.jackson.databind.JsonSerializer`, `com.fasterxml.jackson.databind.JsonDeserializer` or `com.fasterxml.jackson.databind.KeyDeserializer` implementations.
You can use the javadoc:org.springframework.boot.jackson.JsonComponent[format=annotation] annotation directly on javadoc:com.fasterxml.jackson.databind.JsonSerializer[], javadoc:com.fasterxml.jackson.databind.JsonDeserializer[] or javadoc:com.fasterxml.jackson.databind.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.
All javadoc:org.springframework.boot.jackson.JsonComponent[format=annotation] beans in the javadoc:org.springframework.context.ApplicationContext[] are automatically registered with Jackson.
Because javadoc:org.springframework.boot.jackson.JsonComponent[format=annotation] is meta-annotated with javadoc:org.springframework.stereotype.Component[format=annotation], the usual component-scanning rules apply.
Spring Boot also provides javadoc:org.springframework.boot.jackson.JsonObjectSerializer[] and javadoc:org.springframework.boot.jackson.JsonObjectDeserializer[] base classes that provide useful alternatives to the standard Jackson versions when serializing objects.
See javadoc:org.springframework.boot.jackson.JsonObjectSerializer[] and javadoc:org.springframework.boot.jackson.JsonObjectDeserializer[] in the API documentation for details.
The example above can be rewritten to use `JsonObjectSerializer`/`JsonObjectDeserializer` as follows:
The example above can be rewritten to use javadoc:org.springframework.boot.jackson.JsonObjectSerializer[]/`JsonObjectDeserializer` as follows:
include-code::object/MyJsonComponent[]
@ -47,8 +47,8 @@ include-code::object/MyJsonComponent[]
=== 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`.
Spring Boot's Jackson auto-configuration will scan your application's packages for classes annotated with javadoc:org.springframework.boot.jackson.JsonMixin[format=annotation] and register them with the auto-configured javadoc:com.fasterxml.jackson.databind.ObjectMapper[].
The registration is performed by Spring Boot's javadoc:org.springframework.boot.jackson.JsonMixinModule[].
@ -56,9 +56,9 @@ The registration is performed by Spring Boot's `JsonMixinModule`.
== Gson
Auto-configuration for Gson is provided.
When Gson is on the classpath a `Gson` bean is automatically configured.
When Gson is on the classpath a javadoc:com.google.gson.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.
To take more control, one or more javadoc:org.springframework.boot.autoconfigure.gson.GsonBuilderCustomizer[] beans can be used.
@ -66,5 +66,5 @@ To take more control, one or more `GsonBuilderCustomizer` beans can be used.
== 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.
When the JSON-B API and an implementation are on the classpath a javadoc:jakarta.json.bind.Jsonb[] bean will be automatically configured.
The preferred JSON-B implementation is Eclipse Yasson for which dependency management is provided.

View File

@ -33,8 +33,8 @@ TIP: These dependencies and plugins are provided by default if one bootstraps a
== 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 `java.util.Optional`.
It deals with `null` values at compile time rather than deferring the problem to runtime and encountering a javadoc:java.lang.NullPointerException[].
This helps to eliminate a common source of bugs without paying the cost of wrappers like javadoc:java.util.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.
@ -92,7 +92,7 @@ runApplication<MyApplication>(*args) {
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.
javadoc:org.springframework.boot.test.web.client.TestRestTemplate[] extensions, similar to those provided by Spring Framework for javadoc:org.springframework.web.client.RestOperations[] in Spring Framework, are provided.
Among other things, the extensions make it possible to take advantage of Kotlin reified type parameters.
@ -114,7 +114,7 @@ TIP: `org.jetbrains.kotlinx:kotlinx-coroutines-reactor` dependency is provided b
[[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 data classes with immutable `val` properties as shown in the following example:
javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] when used in combination with xref:features/external-config.adoc#features.external-config.typesafe-configuration-properties.constructor-binding[constructor binding] supports data classes with immutable `val` properties as shown in the following example:
[source,kotlin]
----
@ -145,10 +145,10 @@ Note that some features (such as detecting the default value or deprecated items
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.
This makes it possible to use javadoc:org.junit.jupiter.api.BeforeAll[format=annotation] and javadoc:org.junit.jupiter.api.AfterAll[format=annotation] 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:testing/spring-boot-applications.adoc#testing.spring-boot-applications.mocking-beans[`@MockitoBean` and `@MockitoSpyBean` annotations], you can use https://github.com/Ninja-Squad/springmockk[SpringMockK] which provides similar `+@MockkBean+` and `+@SpykBean+` annotations.
If you need the `MockK` equivalent of the Mockito specific xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.mocking-beans[`@MockitoBean` and javadoc:org.springframework.test.context.bean.override.mockito.MockitoSpyBean[format=annotation] annotations], you can use https://github.com/Ninja-Squad/springmockk[SpringMockK] which provides similar `+@MockkBean+` and `+@SpykBean+` annotations.

View File

@ -204,7 +204,7 @@ The following rotation policy properties are supported:
[[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.
All the supported logging systems can have the logger levels set in the Spring javadoc:org.springframework.core.env.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`:
@ -233,7 +233,7 @@ If you need to configure logging for a class, you can use xref:features/external
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`.
To help with this, Spring Boot allows you to define logging groups in your Spring javadoc:org.springframework.core.env.Environment[].
For example, here is how you could define a "`tomcat`" group by adding it to your `application.properties`:
[configprops,yaml]
@ -262,7 +262,7 @@ Spring Boot includes the following pre-defined logging groups that can be used o
| `+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`
| `org.springframework.jdbc.core`, `org.hibernate.SQL`, javadoc:org.jooq.tools.LoggerListener[]
|===
@ -290,13 +290,13 @@ logging:
[[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[].
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 javadoc:org.springframework.core.env.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 force Spring Boot to use a particular logging system by using the javadoc:org.springframework.boot.logging.LoggingSystem[] system property.
The value should be the fully qualified class name of a javadoc:org.springframework.boot.logging.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 `@org.springframework.context.annotation.PropertySources` in Spring `@Configuration` files.
NOTE: Since logging is initialized *before* the javadoc:org.springframework.context.ApplicationContext[] is created, it is not possible to control logging from javadoc:org.springframework.context.annotation.PropertySources[format=annotation] in Spring javadoc:org.springframework.context.annotation.Configuration[format=annotation] 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:
@ -320,7 +320,7 @@ If you use standard configuration locations, Spring cannot completely control lo
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.
To help with the customization, some other properties are transferred from the Spring javadoc:org.springframework.core.env.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:
@ -618,8 +618,8 @@ You can also declare implementations by listing them in a `META-INF/spring.facto
=== Supporting Other Structured Logging Formats
The structured logging support in Spring Boot is extensible, allowing you to define your own custom format.
To do this, implement the `StructuredLogFormatter` interface. The generic type argument has to be `ILoggingEvent` when using Logback and `org.apache.logging.log4j.core.LogEvent` when using Log4j2 (that means your implementation is tied to a specific logging system).
Your implementation is then called with the log event and returns the `String` to be logged, as seen in this example:
To do this, implement the javadoc:org.springframework.boot.logging.structured.StructuredLogFormatter[] interface. The generic type argument has to be javadoc:ch.qos.logback.classic.spi.ILoggingEvent[] when using Logback and javadoc:org.apache.logging.log4j.core.LogEvent[] when using Log4j2 (that means your implementation is tied to a specific logging system).
Your implementation is then called with the log event and returns the javadoc:java.lang.String[] to be logged, as seen in this example:
include-code::MyCustomFormat[]
@ -683,12 +683,12 @@ The following listing shows three sample profiles:
[[features.logging.logback-extensions.environment-properties]]
=== Environment Properties
The `<springProperty>` tag lets you expose properties from the Spring `Environment` for use within Logback.
The `<springProperty>` tag lets you expose properties from the Spring javadoc:org.springframework.core.env.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`).
However, rather than specifying a direct `value`, you specify the `source` of the property (from the javadoc:org.springframework.core.env.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.
If you need a fallback value (in case the property is not set in the javadoc:org.springframework.core.env.Environment[]), you can use the `defaultValue` attribute.
The following example shows how to expose properties for use within Logback:
[source,xml]
@ -702,7 +702,7 @@ The following example shows how to expose properties for use within Logback:
----
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.
However, properties can be added to the javadoc:org.springframework.core.env.Environment[] by using the relaxed rules.
@ -751,10 +751,10 @@ The following listing shows three sample profiles:
[[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].
If you want to refer to properties from your Spring javadoc:org.springframework.core.env.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 Log4j2 properties named `applicationName` and `applicationGroup` that read `spring.application.name` and `spring.application.group` from the Spring `Environment`:
The following example shows how to set Log4j2 properties named `applicationName` and `applicationGroup` that read `spring.application.name` and `spring.application.group` from the Spring javadoc:org.springframework.core.env.Environment[]:
[source,xml]
----
@ -772,12 +772,12 @@ NOTE: The lookup key should be specified in kebab case (such as `my.property-nam
=== Log4j2 System Properties
Log4j2 supports a number of https://logging.apache.org/log4j/2.x/manual/systemproperties.html[System Properties] that can be used to configure various items.
For example, the `log4j2.skipJansi` system property can be used to configure if the `org.apache.logging.log4j.core.appender.ConsoleAppender` will try to use a https://github.com/fusesource/jansi[Jansi] output stream on Windows.
For example, the `log4j2.skipJansi` system property can be used to configure if the javadoc:org.apache.logging.log4j.core.appender.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 `org.apache.logging.log4j.core.appender.ConsoleAppender` use Jansi on Windows.
All system properties that are loaded after the Log4j2 initialization can be obtained from the Spring javadoc:org.springframework.core.env.Environment[].
For example, you could add `log4j2.skipJansi=false` to your `application.properties` file to have the javadoc:org.apache.logging.log4j.core.appender.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.
NOTE: The Spring javadoc:org.springframework.core.env.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`.
WARNING: System properties that are loaded during early Log4j2 initialization cannot reference the Spring javadoc:org.springframework.core.env.Environment[].
For example, the property Log4j2 uses to allow the default Log4j2 implementation to be chosen is used before the Spring Environment is available.

View File

@ -2,14 +2,14 @@
= 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:
Any javadoc:org.springframework.stereotype.Component[format=annotation], javadoc:org.springframework.context.annotation.Configuration[format=annotation] or javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] can be marked with javadoc:org.springframework.context.annotation.Profile[format=annotation] 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.
NOTE: If javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans are registered through javadoc:org.springframework.boot.context.properties.EnableConfigurationProperties[format=annotation] instead of automatic scanning, the javadoc:org.springframework.context.annotation.Profile[format=annotation] annotation needs to be specified on the javadoc:org.springframework.context.annotation.Configuration[format=annotation] class that has the javadoc:org.springframework.boot.context.properties.EnableConfigurationProperties[format=annotation] annotation.
In the case where javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] are scanned, javadoc:org.springframework.context.annotation.Profile[format=annotation] can be specified on the javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] class itself.
You can use a configprop:spring.profiles.active[] `Environment` property to specify which profiles are active.
You can use a configprop:spring.profiles.active[] javadoc:org.springframework.core.env.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:
@ -23,7 +23,7 @@ spring:
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:
The name of the default profile is `default` and it can be tuned using the configprop:spring.profiles.default[] javadoc:org.springframework.core.env.Environment[] property, as shown in the following example:
[configprops,yaml]
----
@ -58,12 +58,12 @@ spring:
[[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.
The configprop:spring.profiles.active[] property follows the same ordering rules as other properties: The highest javadoc:org.springframework.core.env.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.
The javadoc:org.springframework.boot.SpringApplication[] entry point also has a Java API for setting additional profiles.
See the `setAdditionalProfiles()` method in javadoc:org.springframework.boot.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:
@ -115,12 +115,12 @@ This means it cannot be included in xref:features/external-config.adoc#features.
== 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.
It is also possible to activate profiles by using Spring's javadoc:org.springframework.core.env.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.
Profile-specific variants of both `application.properties` (or `application.yaml`) and files referenced through javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] are considered as files and loaded.
See xref:features/external-config.adoc#features.external-config.files.profile-specific[] for details.

View File

@ -1,7 +1,7 @@
[[features.spring-application]]
= SpringApplication
The `SpringApplication` class provides a convenient way to bootstrap a Spring application that is started from a `main()` method.
The javadoc:org.springframework.boot.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 javadoc:org.springframework.boot.SpringApplication#run(java.lang.Class,java.lang.String...)[] method, as shown in the following example:
include-code::MyApplication[]
@ -21,14 +21,14 @@ The application version is determined using the implementation version from the
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`.
TIP: To add additional logging during startup, you can override `logStartupInfo(boolean)` in a subclass of javadoc:org.springframework.boot.SpringApplication[].
[[features.spring-application.startup-failure]]
== Startup Failure
If your application fails to start, registered `FailureAnalyzer` beans get a chance to provide a dedicated error message and a concrete action to fix the problem.
If your application fails to start, registered javadoc:org.springframework.boot.diagnostics.FailureAnalyzer[] beans 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]
@ -46,10 +46,10 @@ 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].
NOTE: Spring Boot provides numerous javadoc:org.springframework.boot.diagnostics.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`.
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 javadoc: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:
@ -63,7 +63,7 @@ $ java -jar myproject-0.0.1-SNAPSHOT.jar --debug
[[features.spring-application.lazy-initialization]]
== Lazy Initialization
`SpringApplication` allows an application to be initialized lazily.
javadoc:org.springframework.boot.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.
@ -73,7 +73,7 @@ If a misconfigured bean is initialized lazily, a failure will no longer occur du
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`.
Lazy initialization can be enabled programmatically using the `lazyInitialization` method on javadoc:org.springframework.boot.builder.SpringApplicationBuilder[] or the `setLazyInitialization` method on javadoc:org.springframework.boot.SpringApplication[].
Alternatively, it can be enabled using the configprop:spring.main.lazy-initialization[] property as shown in the following example:
[configprops,yaml]
@ -93,7 +93,7 @@ TIP: If you want to disable lazy initialization for certain beans while using la
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:
Inside your `banner.txt` file, you can use any key available in the javadoc:org.springframework.core.env.Environment[] as well as any of the following placeholders:
.Banner variables
|===
@ -125,7 +125,7 @@ Inside your `banner.txt` file, you can use any key available in the `Environment
|===
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.
Use the javadoc: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 javadoc:java.lang.System#out[] (`console`), sent to the configured logger (`log`), or not produced at all (`off`).
@ -146,15 +146,15 @@ This will initialize the `application.*` banner properties before building the c
[[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.
If the javadoc:org.springframework.boot.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.
NOTE: The constructor arguments passed to javadoc:org.springframework.boot.SpringApplication[] are configuration sources for Spring beans.
In most cases, these are references to javadoc:org.springframework.context.annotation.Configuration[format=annotation] classes, but they could also be direct references javadoc:org.springframework.stereotype.Component[format=annotation] classes.
It is also possible to configure the `SpringApplication` by using an `application.properties` file.
It is also possible to configure the javadoc:org.springframework.boot.SpringApplication[] by using an `application.properties` file.
See xref:features/external-config.adoc[] for details.
For a complete list of the configuration options, see the javadoc:org.springframework.boot.SpringApplication[] API documentation.
@ -164,14 +164,14 @@ For a complete list of the configuration options, see the javadoc:org.springfram
[[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`.
If you need to build an javadoc:org.springframework.context.ApplicationContext[] hierarchy (multiple contexts with a parent/child relationship) or if you prefer using a fluent builder API, you can use the javadoc:org.springframework.boot.builder.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:
The javadoc:org.springframework.boot.builder.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.
NOTE: There are some restrictions when creating an javadoc:org.springframework.context.ApplicationContext[] hierarchy.
For example, Web components *must* be contained within the child context, and the same javadoc:org.springframework.core.env.Environment[] is used for both parent and child contexts.
See the javadoc:org.springframework.boot.builder.SpringApplicationBuilder[] API documentation for full details.
@ -183,7 +183,7 @@ When deployed on platforms, applications can provide information about their ava
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.
In addition, you can also obtain availability states by injecting the javadoc:org.springframework.boot.availability.ApplicationAvailability[] interface into your own beans.
@ -196,7 +196,7 @@ A broken "`Liveness`" state means that the application is in a state that it can
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`.
The internal state of Spring Boot applications is mostly represented by the Spring javadoc:org.springframework.context.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].
@ -207,18 +207,18 @@ An application is considered live as soon as the context has been refreshed, see
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.
This typically happens during startup, while javadoc:org.springframework.boot.CommandLineRunner[] and javadoc:org.springframework.boot.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`.
TIP: Tasks expected to run during startup should be executed by javadoc:org.springframework.boot.CommandLineRunner[] and javadoc:org.springframework.boot.ApplicationRunner[] components instead of using Spring component lifecycle callbacks such as javadoc:jakarta.annotation.PostConstruct[format=annotation].
[[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.
Application components can retrieve the current availability state at any time, by injecting the javadoc:org.springframework.boot.availability.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:
@ -237,14 +237,14 @@ You can get more guidance about xref:how-to:deployment/cloud.adoc#howto.deployme
[[features.spring-application.application-events-and-listeners]]
== Application Events and Listeners
In addition to the usual Spring Framework events, such as javadoc:{url-spring-framework-javadoc}/org.springframework.context.event.ContextRefreshedEvent[], a `SpringApplication` sends some additional application events.
In addition to the usual Spring Framework events, such as javadoc:{url-spring-framework-javadoc}/org.springframework.context.event.ContextRefreshedEvent[], a javadoc:org.springframework.boot.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`.
Some events are actually triggered before the javadoc:org.springframework.context.ApplicationContext[] is created, so you cannot register a listener on those as a javadoc:org.springframework.context.annotation.Bean[format=annotation].
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:
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 javadoc:org.springframework.context.ApplicationListener[] key, as shown in the following example:
[source]
----
@ -255,22 +255,22 @@ 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 javadoc:org.springframework.boot.availability.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 javadoc:org.springframework.boot.availability.ReadinessState#ACCEPTING_TRAFFIC[] to indicate that the application is ready to service requests.
. An `ApplicationFailedEvent` is sent if there is an exception on startup.
. An javadoc:org.springframework.boot.context.event.ApplicationStartingEvent[] is sent at the start of a run but before any processing, except for the registration of listeners and initializers.
. An javadoc:org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent[] is sent when the javadoc:org.springframework.core.env.Environment[] to be used in the context is known but before the context is created.
. An javadoc:org.springframework.boot.context.event.ApplicationContextInitializedEvent[] is sent when the javadoc:org.springframework.context.ApplicationContext[] is prepared and ApplicationContextInitializers have been called but before any bean definitions are loaded.
. An javadoc:org.springframework.boot.context.event.ApplicationPreparedEvent[] is sent just before the refresh is started but after bean definitions have been loaded.
. An javadoc:org.springframework.boot.context.event.ApplicationStartedEvent[] is sent after the context has been refreshed but before any application and command-line runners have been called.
. An javadoc:org.springframework.boot.availability.AvailabilityChangeEvent[] is sent right after with javadoc:org.springframework.boot.availability.LivenessState#CORRECT[] to indicate that the application is considered as live.
. An javadoc:org.springframework.boot.context.event.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 javadoc:org.springframework.boot.availability.AvailabilityChangeEvent[] is sent right after with javadoc:org.springframework.boot.availability.ReadinessState#ACCEPTING_TRAFFIC[] to indicate that the application is ready to service requests.
. An javadoc:org.springframework.boot.context.event.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`:
The above list only includes ``SpringApplicationEvent``s that are tied to a javadoc:org.springframework.boot.SpringApplication[].
In addition to these, the following events are also published after javadoc:org.springframework.boot.context.event.ApplicationPreparedEvent[] and before javadoc:org.springframework.boot.context.event.ApplicationStartedEvent[]:
- A `WebServerInitializedEvent` is sent after the `org.springframework.boot.web.server.WebServer` is ready.
`ServletWebServerInitializedEvent` and `ReactiveWebServerInitializedEvent` are the servlet and reactive variants respectively.
- A `ContextRefreshedEvent` is sent when an `ApplicationContext` is refreshed.
- A javadoc:org.springframework.boot.web.context.WebServerInitializedEvent[] is sent after the javadoc:org.springframework.boot.web.server.WebServer[] is ready.
javadoc:org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent[] and javadoc:org.springframework.boot.web.reactive.context.ReactiveWebServerInitializedEvent[] are the servlet and reactive variants respectively.
- A javadoc:org.springframework.context.event.ContextRefreshedEvent[] is sent when an javadoc:org.springframework.context.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.
@ -280,79 +280,79 @@ Consider using xref:features/spring-application.adoc#features.spring-application
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.
As a result of this, if your application uses a hierarchy of javadoc:org.springframework.boot.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`.
The context can be injected by implementing javadoc:org.springframework.context.ApplicationContextAware[] or, if the listener is a bean, by using javadoc:org.springframework.beans.factory.annotation.Autowired[format=annotation].
[[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:
A javadoc:org.springframework.boot.SpringApplication[] attempts to create the right type of javadoc:org.springframework.context.ApplicationContext[] on your behalf.
The algorithm used to determine a javadoc:org.springframework.boot.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
* If Spring MVC is present, an javadoc:org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext[] is used
* If Spring MVC is not present and Spring WebFlux is present, an javadoc:org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext[] is used
* Otherwise, javadoc:org.springframework.context.annotation.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.
This means that if you are using Spring MVC and the new javadoc:org.springframework.web.reactive.function.client.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(...)`.
It is also possible to take complete control of the javadoc:org.springframework.context.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.
TIP: It is often desirable to call `setWebApplicationType(WebApplicationType.NONE)` when using javadoc:org.springframework.boot.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:
If you need to access the application arguments that were passed to `SpringApplication.run(...)`, you can inject a javadoc:org.springframework.boot.ApplicationArguments[] bean.
The javadoc:org.springframework.boot.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.
TIP: Spring Boot also registers a javadoc:org.springframework.core.env.CommandLinePropertySource[] with the Spring javadoc:org.springframework.core.env.Environment[].
This lets you also inject single application arguments by using the javadoc:org.springframework.beans.factory.annotation.Value[format=annotation] 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.
If you need to run some specific code once the javadoc:org.springframework.boot.SpringApplication[] has started, you can implement the javadoc:org.springframework.boot.ApplicationRunner[] or javadoc:org.springframework.boot.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:
The javadoc:org.springframework.boot.CommandLineRunner[] interfaces provides access to application arguments as a string array, whereas the javadoc:org.springframework.boot.ApplicationRunner[] uses the javadoc:org.springframework.boot.ApplicationArguments[] interface discussed earlier.
The following example shows a javadoc:org.springframework.boot.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.
If several javadoc:org.springframework.boot.CommandLineRunner[] or javadoc:org.springframework.boot.ApplicationRunner[] beans are defined that must be called in a specific order, you can additionally implement the javadoc:org.springframework.core.Ordered[] interface or use the javadoc: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.
Each javadoc:org.springframework.boot.SpringApplication[] registers a shutdown hook with the JVM to ensure that the javadoc:org.springframework.context.ApplicationContext[] closes gracefully on exit.
All the standard Spring lifecycle callbacks (such as the javadoc:org.springframework.beans.factory.DisposableBean[] interface or the javadoc:jakarta.annotation.PreDestroy[format=annotation] 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.
In addition, beans may implement the javadoc: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.
Also, the javadoc:org.springframework.boot.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.
If there is more than one javadoc:org.springframework.boot.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 javadoc:org.springframework.core.Ordered[] interface or use the javadoc:org.springframework.core.annotation.Order[] annotation.
@ -360,7 +360,7 @@ To control the order in which the generators are called, additionally implement
== 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 javadoc:org.springframework.boot.admin.SpringApplicationAdminMXBean[] on the platform `MBeanServer`.
This exposes the javadoc:org.springframework.boot.admin.SpringApplicationAdminMXBean[] on the platform javadoc:javax.management.MBeanServer[].
You could use this feature to administer your Spring Boot application remotely.
This feature could also be useful for any service wrapper implementation.
@ -371,17 +371,17 @@ TIP: If you want to know on which HTTP port the application is running, get the
[[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,
During the application startup, the javadoc:org.springframework.boot.SpringApplication[] and the javadoc:org.springframework.context.ApplicationContext[] perform many tasks related to the application lifecycle,
the beans lifecycle or even processing application events.
With javadoc:{url-spring-framework-javadoc}/org.springframework.core.metrics.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].
With javadoc:{url-spring-framework-javadoc}/org.springframework.core.metrics.ApplicationStartup[], Spring Framework {url-spring-framework-docs}/core/beans/context-introduction.html#context-functionality-startup[allows you to track the application startup sequence with javadoc:org.springframework.core.metrics.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:
You can choose an javadoc:org.springframework.core.metrics.ApplicationStartup[] implementation when setting up the javadoc:org.springframework.boot.SpringApplication[] instance.
For example, to use the javadoc:org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup[], you could write:
include-code::MyApplication[]
The first available implementation, `FlightRecorderApplicationStartup` is provided by Spring Framework.
The first available implementation, javadoc:org.springframework.core.metrics.jfr.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:
@ -390,8 +390,8 @@ Once configured, you can record data by running the application with the Flight
$ 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 ships with the javadoc:org.springframework.boot.context.metrics.buffering.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 javadoc:org.springframework.boot.context.metrics.buffering.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.
@ -410,7 +410,7 @@ That's because virtual threads are scheduled on a JVM wide platform thread pool
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 `@org.springframework.scheduling.annotation.Scheduled` beans, for example, to keep your application alive.
This behavior can be a problem when you rely on javadoc:org.springframework.scheduling.annotation.Scheduled[format=annotation] 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`.

View File

@ -126,18 +126,18 @@ See the sections on xref:how-to:webserver.adoc#howto.webserver.configure-ssl[emb
[[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.
Spring Boot auto-configures a bean of type javadoc:org.springframework.boot.ssl.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:
An javadoc:org.springframework.boot.ssl.SslBundle[] can be retrieved from the auto-configured javadoc:org.springframework.boot.ssl.SslBundles[] bean and used to create objects that are used to configure SSL connectivity in client libraries.
The javadoc:org.springframework.boot.ssl.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 `javax.net.ssl.KeyManagerFactory` and `javax.net.ssl.TrustManagerFactory` instances as well as the `javax.net.ssl.KeyManager` and `javax.net.ssl.TrustManager` arrays that they create.
- `createSslContext()` provides a convenient way to obtain a new `javax.net.ssl.SSLContext` instance.
- `getStores()` provides access to the key store and trust store javadoc:java.security.KeyStore[] instances as well as any required key store password.
- `getManagers()` provides access to the javadoc:javax.net.ssl.KeyManagerFactory[] and javadoc:javax.net.ssl.TrustManagerFactory[] instances as well as the javadoc:javax.net.ssl.KeyManager[] and javadoc:javax.net.ssl.TrustManager[] arrays that they create.
- `createSslContext()` provides a convenient way to obtain a new javadoc:javax.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.
In addition, the javadoc:org.springframework.boot.ssl.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`:
The following example shows retrieving an javadoc:org.springframework.boot.ssl.SslBundle[] and using it to create an javadoc:javax.net.ssl.SSLContext[]:
include-code::MyComponent[]

View File

@ -1,26 +1,26 @@
[[features.task-execution-and-scheduling]]
= Task Execution and Scheduling
In the absence of an `java.util.concurrent.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 the absence of an javadoc:java.util.concurrent.Executor[] bean in the context, Spring Boot auto-configures an javadoc:org.springframework.core.task.AsyncTaskExecutor[].
When virtual threads are enabled (using Java 21+ and configprop:spring.threads.virtual.enabled[] set to `true`) this will be a javadoc:org.springframework.core.task.SimpleAsyncTaskExecutor[] that uses virtual threads.
Otherwise, it will be a javadoc:org.springframework.scheduling.concurrent.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 for GraphQL's asynchronous handling of javadoc:java.util.concurrent.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 `java.util.concurrent.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 `java.util.concurrent.Executor` into an `AsyncTaskExecutor` or define both an `AsyncTaskExecutor` and an `AsyncConfigurer` wrapping your custom `java.util.concurrent.Executor`.
If you have defined a custom javadoc:java.util.concurrent.Executor[] in the context, both regular task execution (that is javadoc:org.springframework.scheduling.annotation.EnableAsync[format=annotation]) and Spring for GraphQL will use it.
However, the Spring MVC and Spring WebFlux support will only use it if it is an javadoc:org.springframework.core.task.AsyncTaskExecutor[] implementation (named `applicationTaskExecutor`).
Depending on your target arrangement, you could change your javadoc:java.util.concurrent.Executor[] into an javadoc:org.springframework.core.task.AsyncTaskExecutor[] or define both an javadoc:org.springframework.core.task.AsyncTaskExecutor[] and an javadoc:org.springframework.scheduling.annotation.AsyncConfigurer[] wrapping your custom javadoc:java.util.concurrent.Executor[].
The auto-configured `ThreadPoolTaskExecutorBuilder` allows you to easily create instances that reproduce what the auto-configuration does by default.
The auto-configured javadoc:org.springframework.boot.task.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.
When a javadoc:org.springframework.scheduling.concurrent.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]
@ -37,13 +37,13 @@ spring:
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).
A scheduler can also be auto-configured if it needs to be associated with scheduled task execution (using javadoc:org.springframework.scheduling.annotation.EnableScheduling[format=annotation] 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 enabled (using Java 21+ and configprop:spring.threads.virtual.enabled[] set to `true`) this will be a javadoc:org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler[] that uses virtual threads.
This javadoc:org.springframework.scheduling.concurrent.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:
If virtual threads are not enabled, it will be a javadoc:org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler[] with sensible defaults.
The javadoc:org.springframework.scheduling.concurrent.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]
----
@ -55,5 +55,5 @@ spring:
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`).
A javadoc:org.springframework.boot.task.ThreadPoolTaskExecutorBuilder[] bean, a javadoc:org.springframework.boot.task.SimpleAsyncTaskExecutorBuilder[] bean, a javadoc:org.springframework.boot.task.ThreadPoolTaskSchedulerBuilder[] bean and a javadoc:org.springframework.boot.task.SimpleAsyncTaskSchedulerBuilder[] are made available in the context if a custom executor or scheduler needs to be created.
The javadoc:org.springframework.boot.task.SimpleAsyncTaskExecutorBuilder[] and javadoc:org.springframework.boot.task.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`).

View File

@ -4,7 +4,7 @@
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.
Spring Boot auto-configures the cache infrastructure as long as caching support is enabled by using the javadoc:org.springframework.cache.annotation.EnableCaching[format=annotation] annotation.
NOTE: Check the {url-spring-framework-docs}/integration/cache.html[relevant section] of the Spring Framework reference for more details.
@ -17,7 +17,7 @@ Before invoking `computePiDecimal`, the abstraction looks for an entry in the `p
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.
CAUTION: You can also use the standard JSR-107 (JCache) annotations (such as javadoc:javax.cache.annotation.CacheResult[format=annotation]) 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.
@ -34,9 +34,9 @@ TIP: It is also possible to transparently {url-spring-framework-docs}/integratio
[[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.
The cache abstraction does not provide an actual store and relies on abstraction materialized by the javadoc:org.springframework.cache.Cache[] and javadoc:org.springframework.cache.CacheManager[] interfaces.
If you have not defined a bean of type `org.springframework.cache.CacheManager` or a `org.springframework.cache.interceptor.CacheResolver` named `cacheResolver` (see javadoc:{url-spring-framework-javadoc}/org.springframework.cache.annotation.CachingConfigurer[]), Spring Boot tries to detect the following providers (in the indicated order):
If you have not defined a bean of type javadoc:org.springframework.cache.CacheManager[] or a javadoc:org.springframework.cache.interceptor.CacheResolver[] named `cacheResolver` (see javadoc:{url-spring-framework-javadoc}/org.springframework.cache.annotation.CachingConfigurer[]), Spring Boot tries to detect the following providers (in the indicated order):
. xref:io/caching.adoc#io.caching.provider.generic[]
. xref:io/caching.adoc#io.caching.provider.jcache[] (EhCache 3, Hazelcast, Infinispan, and others)
@ -50,36 +50,36 @@ If you have not defined a bean of type `org.springframework.cache.CacheManager`
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 `org.springframework.cache.CacheManager` is auto-configured by Spring Boot, it is possible to _force_ a particular cache provider by setting the configprop:spring.cache.type[] property.
TIP: If the javadoc:org.springframework.cache.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 `org.springframework.cache.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.
If the javadoc:org.springframework.cache.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 javadoc:org.springframework.boot.autoconfigure.cache.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.
NOTE: In the preceding example, an auto-configured javadoc:org.springframework.cache.concurrent.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`.
You can have as many customizers as you want, and you can also order them by using javadoc:org.springframework.core.annotation.Order[format=annotation] or javadoc:org.springframework.core.Ordered[].
[[io.caching.provider.generic]]
=== Generic
Generic caching is used if the context defines _at least_ one `org.springframework.cache.Cache` bean.
A `org.springframework.cache.CacheManager` wrapping all beans of that type is created.
Generic caching is used if the context defines _at least_ one javadoc:org.springframework.cache.Cache[] bean.
A javadoc:org.springframework.cache.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.
https://jcp.org/en/jsr/detail?id=107[JCache] is bootstrapped through the presence of a javadoc:javax.cache.spi.CachingProvider[] on the classpath (that is, a JSR-107 compliant caching library exists on the classpath), and the javadoc:org.springframework.cache.jcache.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.
@ -99,15 +99,15 @@ Even if the JSR-107 standard does not enforce a standardized way to define the l
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 `javax.cache.CacheManager` as well, unless the configprop:spring.cache.jcache.config[] property is specified.
If a single javadoc:com.hazelcast.core.HazelcastInstance[] is available, it is automatically reused for the javadoc:javax.cache.CacheManager[] as well, unless the configprop:spring.cache.jcache.config[] property is specified.
There are two ways to customize the underlying `javax.cache.CacheManager`:
There are two ways to customize the underlying javadoc: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 `javax.cache.CacheManager` for full customization.
If a custom javadoc:javax.cache.configuration.Configuration[] bean is defined, it is used to customize them.
* javadoc:org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer[] beans are invoked with the reference of the javadoc:javax.cache.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.
TIP: If a standard javadoc:javax.cache.CacheManager[] bean is defined, it is wrapped automatically in an javadoc:org.springframework.cache.CacheManager[] implementation that the abstraction expects.
No further customization is applied to it.
@ -116,10 +116,10 @@ No further customization is applied to it.
=== 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 `org.springframework.cache.CacheManager`.
If a javadoc:com.hazelcast.core.HazelcastInstance[] has been auto-configured and `com.hazelcast:hazelcast-spring` is on the classpath, it is automatically wrapped in a javadoc:org.springframework.cache.CacheManager[].
NOTE: Hazelcast can be used as a JCache compliant cache or as a Spring `org.springframework.cache.CacheManager` compliant cache.
When setting configprop:spring.cache.type[] to `hazelcast`, Spring Boot will use the `org.springframework.cache.CacheManager` based implementation.
NOTE: Hazelcast can be used as a JCache compliant cache or as a Spring javadoc:org.springframework.cache.CacheManager[] compliant cache.
When setting configprop:spring.cache.type[] to `hazelcast`, Spring Boot will use the javadoc:org.springframework.cache.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].
@ -140,7 +140,7 @@ spring:
----
Caches can be created on startup by setting the configprop:spring.cache.cache-names[] property.
If a custom `org.infinispan.configuration.cache.ConfigurationBuilder` bean is defined, it is used to customize the caches.
If a custom javadoc:org.infinispan.configuration.cache.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.
@ -151,7 +151,7 @@ For example, `infinispan-core-jakarta` and `infinispan-commons-jakarta` must be
[[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.
If Spring Data Couchbase is available and Couchbase is xref:data/nosql.adoc#data.nosql.couchbase[configured], a javadoc:org.springframework.data.couchbase.cache.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:
@ -164,7 +164,7 @@ spring:
expiration: "10m"
----
If you need more control over the configuration, consider registering a `CouchbaseCacheManagerBuilderCustomizer` bean.
If you need more control over the configuration, consider registering a javadoc:org.springframework.boot.autoconfigure.cache.CouchbaseCacheManagerBuilderCustomizer[] bean.
The following example shows a customizer that configures a specific entry expiration for `cache1` and `cache2`:
include-code::MyCouchbaseCacheManagerConfiguration[]
@ -174,7 +174,7 @@ include-code::MyCouchbaseCacheManagerConfiguration[]
[[io.caching.provider.redis]]
=== Redis
If https://redis.io/[Redis] is available and configured, a `RedisCacheManager` is auto-configured.
If https://redis.io/[Redis] is available and configured, a javadoc:org.springframework.data.redis.cache.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:
@ -188,12 +188,12 @@ spring:
----
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`.
We strongly recommend keeping this setting enabled if you create your own javadoc:org.springframework.data.redis.cache.RedisCacheManager[].
TIP: You can take full control of the default configuration by adding a `RedisCacheConfiguration` `@Bean` of your own.
TIP: You can take full control of the default configuration by adding a javadoc:org.springframework.data.redis.cache.RedisCacheConfiguration[] javadoc:org.springframework.context.annotation.Bean[format=annotation] 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.
If you need more control over the configuration, consider registering a javadoc:org.springframework.boot.autoconfigure.cache.RedisCacheManagerBuilderCustomizer[] bean.
The following example shows a customizer that configures a specific time to live for `cache1` and `cache2`:
include-code::MyRedisCacheManagerConfiguration[]
@ -204,12 +204,12 @@ include-code::MyRedisCacheManagerConfiguration[]
=== 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.
If Caffeine is present, a javadoc:org.springframework.cache.caffeine.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
. A javadoc:com.github.benmanes.caffeine.cache.CaffeineSpec[] bean is defined
. A javadoc: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
@ -222,8 +222,8 @@ spring:
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 `com.github.benmanes.caffeine.cache.CacheLoader` is going to be associated with _all_ caches managed by the cache manager, it must be defined as `CacheLoader<Object, Object>`.
If a javadoc:com.github.benmanes.caffeine.cache.CacheLoader[] bean is defined, it is automatically associated to the javadoc:org.springframework.cache.caffeine.CaffeineCacheManager[].
Since the javadoc:com.github.benmanes.caffeine.cache.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.
@ -235,7 +235,7 @@ 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.
Cache defaults can be customized using a javadoc:org.springframework.boot.autoconfigure.cache.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[]
@ -245,7 +245,7 @@ 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.
If none of the other providers can be found, a simple implementation using a javadoc:java.util.concurrent.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:
@ -265,9 +265,9 @@ This is similar to the way the "real" cache providers behave if you use an undec
[[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 ` org.springframework.cache.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`.
When javadoc:org.springframework.cache.annotation.EnableCaching[format=annotation] is present in your configuration, a suitable cache configuration is expected as well.
If you have a custom ` org.springframework.cache.CacheManager`, consider defining it in a separate javadoc:org.springframework.context.annotation.Configuration[format=annotation] 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 javadoc:org.springframework.boot.test.autoconfigure.core.AutoConfigureCache[format=annotation].
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:

View File

@ -1,11 +1,11 @@
[[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.
The Spring Framework provides an abstraction for sending email by using the javadoc:org.springframework.mail.javamail.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`.
TIP: See the {url-spring-framework-docs}/integration/email.html[reference documentation] for a detailed explanation of how you can use javadoc:org.springframework.mail.javamail.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.
If `spring.mail.host` and the relevant libraries (as defined by `spring-boot-starter-mail`) are available, a default javadoc:org.springframework.mail.javamail.JavaMailSender[] is created if none exists.
The sender can be further customized by configuration items from the `spring.mail` namespace.
See javadoc:org.springframework.boot.autoconfigure.mail.MailProperties[] for more details.
@ -21,7 +21,7 @@ spring:
"[mail.smtp.writetimeout]": 5000
----
It is also possible to configure a `JavaMailSender` with an existing `jakarta.mail.Session` from JNDI:
It is also possible to configure a javadoc:org.springframework.mail.javamail.JavaMailSender[] with an existing javadoc:jakarta.mail.Session[] from JNDI:
[configprops,yaml]
----

View File

@ -1,18 +1,18 @@
[[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.
If https://hazelcast.com/[Hazelcast] is on the classpath and a suitable configuration is found, Spring Boot auto-configures a javadoc:com.hazelcast.core.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.
* The presence of a javadoc: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 you define a javadoc: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:
@ -28,8 +28,8 @@ Otherwise, Spring Boot tries to find the Hazelcast configuration from the defaul
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 `ManagedContext` can be overridden by declaring a `HazelcastConfigCustomizer` bean with an `@Order` higher than zero.
TIP: By default, javadoc:com.hazelcast.spring.context.SpringAware[format=annotation] on Hazelcast components is supported.
The javadoc:com.hazelcast.core.ManagedContext[] can be overridden by declaring a javadoc:org.springframework.boot.autoconfigure.hazelcast.HazelcastConfigCustomizer[] bean with an javadoc:org.springframework.core.annotation.Order[format=annotation] 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 `org.springframework.cache.CacheManager` implementation.
If caching is enabled, the javadoc:com.hazelcast.core.HazelcastInstance[] is automatically wrapped in a javadoc:org.springframework.cache.CacheManager[] implementation.

View File

@ -3,9 +3,9 @@
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.
When a JTA environment is detected, Spring's javadoc:org.springframework.transaction.jta.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 `@org.springframework.transaction.annotation.Transactional`, to participate in a distributed transaction.
You can use standard Spring idioms, such as javadoc:org.springframework.transaction.annotation.Transactional[format=annotation], 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.
@ -16,22 +16,22 @@ If you are within a JTA environment and still want to use local transactions, yo
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 `jakarta.jms.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`.
Spring Boot tries to auto-configure JMS by looking for a javadoc:jakarta.jms.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 javadoc:javax.sql.DataSource[].
[[io.jta.mixing-xa-and-non-xa-connections]]
== Mixing XA and Non-XA JMS Connections
When using JTA, the primary JMS `jakarta.jms.ConnectionFactory` bean is XA-aware and participates in distributed transactions.
You can inject into your bean without needing to use any `@org.springframework.beans.factory.annotation.Qualifier`:
When using JTA, the primary JMS javadoc:jakarta.jms.ConnectionFactory[] bean is XA-aware and participates in distributed transactions.
You can inject into your bean without needing to use any javadoc:org.springframework.beans.factory.annotation.Qualifier[format=annotation]:
include-code::primary/MyBean[]
In some situations, you might want to process certain JMS messages by using a non-XA `jakarta.jms.ConnectionFactory`.
In some situations, you might want to process certain JMS messages by using a non-XA javadoc:jakarta.jms.ConnectionFactory[].
For example, your JMS processing logic might take longer than the XA timeout.
If you want to use a non-XA `jakarta.jms.ConnectionFactory`, you can the `nonXaJmsConnectionFactory` bean:
If you want to use a non-XA javadoc:jakarta.jms.ConnectionFactory[], you can the `nonXaJmsConnectionFactory` bean:
include-code::nonxa/MyBean[]
@ -45,5 +45,5 @@ include-code::xa/MyBean[]
== Supporting an Embedded Transaction Manager
The javadoc:org.springframework.boot.jms.XAConnectionFactoryWrapper[] and javadoc:org.springframework.boot.jdbc.XADataSourceWrapper[] interfaces can be used to support embedded transaction managers.
The interfaces are responsible for wrapping `jakarta.jms.XAConnectionFactory` and `javax.sql.XADataSource` beans and exposing them as regular `jakarta.jms.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`.
The interfaces are responsible for wrapping javadoc:jakarta.jms.XAConnectionFactory[] and javadoc:javax.sql.XADataSource[] beans and exposing them as regular javadoc:jakarta.jms.ConnectionFactory[] and javadoc:javax.sql.DataSource[] beans, which transparently enroll in the distributed transaction.
DataSource and JMS auto-configuration use JTA variants, provided you have a javadoc:org.springframework.transaction.jta.JtaTransactionManager[] bean and appropriate XA wrapper beans registered within your javadoc:org.springframework.context.ApplicationContext[].

View File

@ -2,17 +2,17 @@
= 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 `org.quartz.Scheduler` is auto-configured (through the `org.springframework.scheduling.quartz.SchedulerFactoryBean` abstraction).
If Quartz is available, a javadoc:org.quartz.Scheduler[] is auto-configured (through the javadoc:org.springframework.scheduling.quartz.SchedulerFactoryBean[] abstraction).
Beans of the following types are automatically picked up and associated with the `org.quartz.Scheduler`:
Beans of the following types are automatically picked up and associated with the javadoc:org.quartz.Scheduler[]:
* `org.quartz.JobDetail`: defines a particular Job.
`org.quartz.JobDetail` instances can be built with the `org.quartz.JobBuilder` API.
* `org.quartz.Calendar`.
* `org.quartz.Trigger`: defines when a particular job is triggered.
* javadoc:org.quartz.JobDetail[]: defines a particular Job.
javadoc:org.quartz.JobDetail[] instances can be built with the javadoc:org.quartz.JobBuilder[] API.
* javadoc:org.quartz.Calendar[].
* javadoc:org.quartz.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:
By default, an in-memory javadoc:org.quartz.spi.JobStore[] is used.
However, it is possible to configure a JDBC-based store if a javadoc:javax.sql.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]
----
@ -35,18 +35,18 @@ WARNING: By default, the database is detected and initialized by using the stand
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 `org.springframework.transaction.TransactionManager` other than the application's main `org.springframework.transaction.TransactionManager` declare a `org.springframework.transaction.TransactionManager` bean, annotating its `@Bean` method with `@QuartzTransactionManager`.
To have Quartz use a javadoc:javax.sql.DataSource[] other than the application's main javadoc:javax.sql.DataSource[], declare a javadoc:javax.sql.DataSource[] bean, annotating its javadoc:org.springframework.context.annotation.Bean[format=annotation] method with javadoc:org.springframework.boot.autoconfigure.quartz.QuartzDataSource[format=annotation].
Doing so ensures that the Quartz-specific javadoc:javax.sql.DataSource[] is used by both the javadoc:org.springframework.scheduling.quartz.SchedulerFactoryBean[] and for schema initialization.
Similarly, to have Quartz use a javadoc:org.springframework.transaction.TransactionManager[] other than the application's main javadoc:org.springframework.transaction.TransactionManager[] declare a javadoc:org.springframework.transaction.TransactionManager[] bean, annotating its javadoc:org.springframework.context.annotation.Bean[format=annotation] method with javadoc:org.springframework.boot.autoconfigure.quartz.QuartzTransactionManager[format=annotation].
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.
Quartz Scheduler configuration can be customized using `spring.quartz` properties and javadoc:org.springframework.boot.autoconfigure.quartz.SchedulerFactoryBeanCustomizer[] beans, which allow programmatic javadoc:org.springframework.scheduling.quartz.SchedulerFactoryBean[] customization.
Advanced Quartz configuration properties can be customized using `spring.quartz.properties.*`.
NOTE: In particular, an `java.util.concurrent.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`.
NOTE: In particular, an javadoc:java.util.concurrent.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 javadoc:org.springframework.boot.autoconfigure.quartz.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:

View File

@ -2,23 +2,23 @@
= 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`.
If you are developing a non-blocking reactive application and you're using Spring WebFlux, then you can use javadoc:org.springframework.web.reactive.function.client.WebClient[].
If you prefer blocking APIs then you can use javadoc:org.springframework.web.client.RestClient[] or javadoc:org.springframework.web.client.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].
If you have Spring WebFlux on your classpath we recommend that you use javadoc:org.springframework.web.reactive.function.client.WebClient[] to call remote REST services.
The javadoc:org.springframework.web.reactive.function.client.WebClient[] interface provides a functional style API and is fully reactive.
You can learn more about the javadoc:org.springframework.web.reactive.function.client.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`.
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 javadoc:org.springframework.web.reactive.function.client.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 creates and pre-configures a prototype javadoc:org.springframework.web.reactive.function.client.WebClient$Builder[] bean for you.
It is strongly advised to inject it in your components and use it to create javadoc:org.springframework.web.reactive.function.client.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:
@ -30,7 +30,7 @@ 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.
Spring Boot will auto-detect which javadoc:org.springframework.http.client.reactive.ClientHttpConnector[] to use to drive javadoc:org.springframework.web.reactive.function.client.WebClient[] depending on the libraries available on the application classpath.
In order of preference, the following clients are supported:
. Reactor Netty
@ -44,9 +44,9 @@ The `spring-boot-starter-webflux` starter depends on `io.projectreactor.netty:re
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.
Developers can override the resource configuration for Jetty and Reactor Netty by providing a custom javadoc:org.springframework.http.client.ReactorResourceFactory[] or javadoc:org.springframework.http.client.reactive.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.
If you wish to override that choice for the client, you can define your own javadoc:org.springframework.http.client.reactive.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].
@ -55,25 +55,25 @@ You can learn more about the {url-spring-framework-docs}/web/webflux-webclient/c
[[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.
There are three main approaches to javadoc:org.springframework.web.reactive.function.client.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.
To make the scope of any customizations as narrow as possible, inject the auto-configured javadoc:org.springframework.web.reactive.function.client.WebClient$Builder[] and then call its methods as required.
javadoc:org.springframework.web.reactive.function.client.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.
To make an application-wide, additive customization to all javadoc:org.springframework.web.reactive.function.client.WebClient$Builder[] instances, you can declare javadoc:org.springframework.boot.web.reactive.function.client.WebClientCustomizer[] beans and change the javadoc:org.springframework.web.reactive.function.client.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.
In that case, no auto-configuration or javadoc:org.springframework.boot.web.reactive.function.client.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.
If you need custom SSL configuration on the javadoc:org.springframework.http.client.reactive.ClientHttpConnector[] used by the javadoc:org.springframework.web.reactive.function.client.WebClient[], you can inject a javadoc:org.springframework.boot.autoconfigure.web.reactive.function.client.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 javadoc:org.springframework.boot.autoconfigure.web.reactive.function.client.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:
@ -84,13 +84,13 @@ 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.
If you are not using Spring WebFlux or Project Reactor in your application we recommend that you use javadoc:org.springframework.web.client.RestClient[] to call remote REST services.
The `RestClient` interface provides a functional style blocking API.
The javadoc:org.springframework.web.client.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`.
Spring Boot creates and pre-configures a prototype javadoc:org.springframework.web.client.RestClient$Builder[] bean for you.
It is strongly advised to inject it in your components and use it to create javadoc:org.springframework.web.client.RestClient[] instances.
Spring Boot is configuring that builder with javadoc:org.springframework.boot.autoconfigure.http.HttpMessageConverters[] and an appropriate javadoc:org.springframework.http.client.ClientHttpRequestFactory[].
The following code shows a typical example:
@ -101,16 +101,16 @@ 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.
There are three main approaches to javadoc:org.springframework.web.client.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.
To make the scope of any customizations as narrow as possible, inject the auto-configured javadoc:org.springframework.web.client.RestClient$Builder[] and then call its methods as required.
javadoc:org.springframework.web.client.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.
To make an application-wide, additive customization to all javadoc:org.springframework.web.client.RestClient$Builder[] instances, you can declare javadoc:org.springframework.boot.web.client.RestClientCustomizer[] beans and change the javadoc:org.springframework.web.client.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.
In that case, no auto-configuration or javadoc:org.springframework.boot.web.client.RestClientCustomizer[] is applied.
TIP: You can also change the xref:io/rest-client.adoc#io.rest-client.clienthttprequestfactory.configuration[global HTTP client configuration].
@ -119,15 +119,15 @@ TIP: You can also change the xref:io/rest-client.adoc#io.rest-client.clienthttpr
[[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.
If you need custom SSL configuration on the javadoc:org.springframework.http.client.ClientHttpRequestFactory[] used by the javadoc:org.springframework.web.client.RestClient[], you can inject a javadoc:org.springframework.boot.autoconfigure.web.client.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 javadoc:org.springframework.boot.autoconfigure.web.client.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 `org.springframework.boot.http.client.ClientHttpRequestFactorySettings` class with `ClientHttpRequestFactoryBuilder`:
If you need to apply other customization in addition to an SSL bundle, you can use the javadoc:org.springframework.boot.http.client.ClientHttpRequestFactorySettings[] class with javadoc:org.springframework.boot.http.client.ClientHttpRequestFactoryBuilder[]:
include-code::settings/MyService[]
@ -136,18 +136,18 @@ include-code::settings/MyService[]
[[io.rest-client.resttemplate]]
== RestTemplate
Spring Framework's javadoc:{url-spring-framework-javadoc}/org.springframework.web.client.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.
Spring Framework's javadoc:{url-spring-framework-javadoc}/org.springframework.web.client.RestTemplate[] class predates javadoc:org.springframework.web.client.RestClient[] and is the classic way that many applications use to call remote REST services.
You might choose to use javadoc:org.springframework.web.client.RestTemplate[] when you have existing code that you don't want to migrate to javadoc:org.springframework.web.client.RestClient[], or because you're already familiar with the javadoc:org.springframework.web.client.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.
Since javadoc:org.springframework.web.client.RestTemplate[] instances often need to be customized before being used, Spring Boot does not provide any single auto-configured javadoc:org.springframework.web.client.RestTemplate[] bean.
It does, however, auto-configure a javadoc:org.springframework.boot.web.client.RestTemplateBuilder[], which can be used to create javadoc:org.springframework.web.client.RestTemplate[] instances when needed.
The auto-configured javadoc:org.springframework.boot.web.client.RestTemplateBuilder[] ensures that sensible javadoc:org.springframework.boot.autoconfigure.http.HttpMessageConverters[] and an appropriate javadoc:org.springframework.http.client.ClientHttpRequestFactory[] are applied to javadoc:org.springframework.web.client.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`.
javadoc:org.springframework.boot.web.client.RestTemplateBuilder[] includes a number of useful methods that can be used to quickly configure a javadoc:org.springframework.web.client.RestTemplate[].
For example, to add BASIC authentication support, you can use `builder.basicAuthentication("user", "password").build()`.
@ -155,27 +155,27 @@ For example, to add BASIC authentication support, you can use `builder.basicAuth
[[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.
There are three main approaches to javadoc:org.springframework.web.client.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 the scope of any customizations as narrow as possible, inject the auto-configured javadoc:org.springframework.boot.web.client.RestTemplateBuilder[] and then call its methods as required.
Each method call returns a new javadoc:org.springframework.boot.web.client.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.
To make an application-wide, additive customization, use a javadoc:org.springframework.boot.web.client.RestTemplateCustomizer[] bean.
All such beans are automatically registered with the auto-configured javadoc:org.springframework.boot.web.client.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.
Finally, you can define your own javadoc:org.springframework.boot.web.client.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:
If you want any javadoc:org.springframework.boot.web.client.RestTemplateCustomizer[] beans to be applied to your custom builder, as the auto-configuration would have done, configure it using a javadoc:org.springframework.boot.autoconfigure.web.client.RestTemplateBuilderConfigurer[].
The following example exposes a javadoc:org.springframework.boot.web.client.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.
The most extreme (and rarely used) option is to create your own javadoc:org.springframework.boot.web.client.RestTemplateBuilder[] bean without using a configurer.
In addition to replacing the auto-configured builder, this also prevents any javadoc:org.springframework.boot.web.client.RestTemplateCustomizer[] beans from being used.
TIP: You can also change the xref:io/rest-client.adoc#io.rest-client.clienthttprequestfactory.configuration[global HTTP client configuration].
@ -184,7 +184,7 @@ TIP: You can also change the xref:io/rest-client.adoc#io.rest-client.clienthttpr
[[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:
If you need custom SSL configuration on the javadoc:org.springframework.web.client.RestTemplate[], you can apply an xref:features/ssl.adoc#features.ssl.bundles[SSL bundle] to the javadoc:org.springframework.boot.web.client.RestTemplateBuilder[] as shown in this example:
include-code::MyService[]
@ -193,7 +193,7 @@ 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.
Spring Boot will auto-detect which HTTP client to use with javadoc:org.springframework.web.client.RestClient[] and javadoc:org.springframework.web.client.RestTemplate[] depending on the libraries available on the application classpath.
In order of preference, the following clients are supported:
. Apache HttpClient
@ -210,7 +210,7 @@ If multiple clients are available on the classpath, and not global configuration
=== Global HTTP Client Configuration
If the the auto-detected HTTP client does not meet your needs, you can use the configprop:spring.http.client.factory[] property to pick a specific factory.
For example, if you have Apache HttpClient on your classpath, but you prefer Jetty's `org.eclipse.jetty.client.HttpClient` you can add use the following:
For example, if you have Apache HttpClient on your classpath, but you prefer Jetty's javadoc:org.eclipse.jetty.client.HttpClient[] you can add use the following:
[configprops,yaml]
----
@ -233,10 +233,10 @@ spring:
redirects: dont-follow
----
For more complex customizations, you can declare your own `ClientHttpRequestFactoryBuilder` bean which will cause auto-configuration to back off.
For more complex customizations, you can declare your own javadoc:org.springframework.boot.http.client.ClientHttpRequestFactoryBuilder[] bean which will cause auto-configuration to back off.
This can be useful when you need to customize some of the internals of the underlying HTTP library.
For example, the following will use a JDK client configured with a specific `java.net.ProxySelector`:
For example, the following will use a JDK client configured with a specific javadoc:java.net.ProxySelector[]:
include-code::MyClientHttpConfiguration[]

View File

@ -3,15 +3,15 @@
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 `@org.springframework.validation.annotation.Validated` annotation at the type level for their methods to be searched for inline constraint annotations.
Target classes with such annotated methods need to be annotated with the javadoc:org.springframework.validation.annotation.Validated[format=annotation] 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 `org.springframework.context.MessageSource` is used when resolving `+{parameters}+` in constraint messages.
The application's javadoc:org.springframework.context.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 `jakarta.validation.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.
To customize the javadoc:jakarta.validation.Configuration[] used to build the javadoc:jakarta.validation.ValidatorFactory[], define a javadoc:org.springframework.boot.autoconfigure.validation.ValidationConfigurationCustomizer[] bean.
When multiple customizer beans are defined, they are called in order based on their javadoc:org.springframework.core.annotation.Order[format=annotation] annotation or javadoc:org.springframework.core.Ordered[] implementation.

View File

@ -1,11 +1,11 @@
[[io.webservices]]
= Web Services
Spring Boot provides Web Services auto-configuration so that all you must do is define your `@org.springframework.ws.server.endpoint.annotation.Endpoint` beans.
Spring Boot provides Web Services auto-configuration so that all you must do is define your javadoc:org.springframework.ws.server.endpoint.annotation.Endpoint[format=annotation] beans.
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.
javadoc:org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition[] and javadoc:org.springframework.xml.xsd.SimpleXsdSchema[] beans can be automatically created for your WSDLs and XSDs respectively.
To do so, configure their location, as shown in the following example:
@ -22,14 +22,14 @@ spring:
== 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.
Since javadoc:org.springframework.ws.client.core.WebServiceTemplate[] instances often need to be customized before being used, Spring Boot does not provide any single auto-configured javadoc:org.springframework.ws.client.core.WebServiceTemplate[] bean.
It does, however, auto-configure a javadoc:org.springframework.boot.webservices.client.WebServiceTemplateBuilder[], which can be used to create javadoc:org.springframework.ws.client.core.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.
By default, javadoc:org.springframework.boot.webservices.client.WebServiceTemplateBuilder[] detects a suitable HTTP-based javadoc:org.springframework.ws.transport.WebServiceMessageSender[] using the available HTTP client libraries on the classpath.
You can also customize read and connection timeouts for an individual builder as follows:
include-code::MyWebServiceTemplateConfiguration[]

View File

@ -39,11 +39,11 @@ NOTE: When specifying addresses that way, the `host` and `port` properties are i
If the address uses the `amqps` protocol, SSL support is enabled automatically.
See javadoc:org.springframework.boot.autoconfigure.amqp.RabbitProperties[] for more of the supported property-based configuration options.
To configure lower-level details of the RabbitMQ `com.rabbitmq.client.ConnectionFactory` that is used by Spring AMQP, define a `ConnectionFactoryCustomizer` bean.
To configure lower-level details of the RabbitMQ javadoc:com.rabbitmq.client.ConnectionFactory[] that is used by Spring AMQP, define a javadoc:org.springframework.boot.autoconfigure.amqp.ConnectionFactoryCustomizer[] bean.
If a `ConnectionNameStrategy` bean exists in the context, it will be automatically used to name connections created by the auto-configured `org.springframework.amqp.rabbit.connection.CachingConnectionFactory`.
If a javadoc:org.springframework.amqp.rabbit.connection.ConnectionNameStrategy[] bean exists in the context, it will be automatically used to name connections created by the auto-configured javadoc:org.springframework.amqp.rabbit.connection.CachingConnectionFactory[].
To make an application-wide, additive customization to the `RabbitTemplate`, use a `RabbitTemplateCustomizer` bean.
To make an application-wide, additive customization to the javadoc:org.springframework.amqp.rabbit.core.RabbitTemplate[], use a javadoc:org.springframework.boot.autoconfigure.amqp.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.
@ -52,16 +52,16 @@ TIP: See https://spring.io/blog/2010/06/14/understanding-amqp-the-protocol-used-
[[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:
Spring's javadoc:org.springframework.amqp.core.AmqpTemplate[] and javadoc:org.springframework.amqp.core.AmqpAdmin[] are auto-configured, and you can autowire them directly into your own beans, as shown in the following example:
include-code::MyBean[]
NOTE: javadoc:{url-spring-amqp-javadoc}/org.springframework.amqp.rabbit.core.RabbitMessagingTemplate[] can be injected in a similar manner.
If a `org.springframework.amqp.support.converter.MessageConverter` bean is defined, it is associated automatically to the auto-configured `AmqpTemplate`.
If a javadoc:org.springframework.amqp.support.converter.MessageConverter[] bean is defined, it is associated automatically to the auto-configured javadoc:org.springframework.amqp.core.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.
If necessary, any javadoc: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):
To retry operations, you can enable retries on the javadoc:org.springframework.amqp.core.AmqpTemplate[] (for example, in the event that the broker connection is lost):
[configprops,yaml]
----
@ -74,9 +74,9 @@ spring:
----
Retries are disabled by default.
You can also customize the `RetryTemplate` programmatically by declaring a `RabbitRetryTemplateCustomizer` bean.
You can also customize the javadoc:org.springframework.retry.support.RetryTemplate[] programmatically by declaring a javadoc:org.springframework.boot.autoconfigure.amqp.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.
If you need to create more javadoc:org.springframework.amqp.rabbit.core.RabbitTemplate[] instances or if you want to override the default, Spring Boot provides a javadoc:org.springframework.boot.autoconfigure.amqp.RabbitTemplateConfigurer[] bean that you can use to initialize a javadoc:org.springframework.amqp.rabbit.core.RabbitTemplate[] with the same settings as the factories used by the auto-configuration.
@ -93,18 +93,18 @@ spring:
name: "my-stream"
----
If a `org.springframework.amqp.support.converter.MessageConverter`, `org.springframework.rabbit.stream.support.converter.StreamMessageConverter`, or `org.springframework.rabbit.stream.producer.ProducerCustomizer` bean is defined, it is associated automatically to the auto-configured `RabbitStreamTemplate`.
If a javadoc:org.springframework.amqp.support.converter.MessageConverter[], javadoc:org.springframework.rabbit.stream.support.converter.StreamMessageConverter[], or javadoc:org.springframework.rabbit.stream.producer.ProducerCustomizer[] bean is defined, it is associated automatically to the auto-configured javadoc:org.springframework.rabbit.stream.producer.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.
If you need to create more javadoc:org.springframework.rabbit.stream.producer.RabbitStreamTemplate[] instances or if you want to override the default, Spring Boot provides a javadoc:org.springframework.boot.autoconfigure.amqp.RabbitStreamTemplateConfigurer[] bean that you can use to initialize a javadoc:org.springframework.rabbit.stream.producer.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 `org.springframework.amqp.support.converter.MessageConverter` or a `org.springframework.amqp.rabbit.retry.MessageRecoverer` bean is defined, it is automatically associated with the default factory.
When the Rabbit infrastructure is present, any bean can be annotated with javadoc:org.springframework.amqp.rabbit.annotation.RabbitListener[format=annotation] to create a listener endpoint.
If no javadoc:org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory[] has been defined, a default javadoc:org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory[] is automatically configured and you can switch to a direct container using the configprop:spring.rabbitmq.listener.type[] property.
If a javadoc:org.springframework.amqp.support.converter.MessageConverter[] or a javadoc:org.springframework.amqp.rabbit.retry.MessageRecoverer[] bean is defined, it is automatically associated with the default factory.
The following sample component creates a listener endpoint on the `someQueue` queue:
@ -112,25 +112,25 @@ include-code::MyBean[]
TIP: See javadoc:{url-spring-amqp-javadoc}/org.springframework.amqp.rabbit.annotation.EnableRabbit[format=annotation] 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.
If you need to create more javadoc:org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory[] instances or if you want to override the default, Spring Boot provides a javadoc:org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer[] and a javadoc:org.springframework.boot.autoconfigure.amqp.DirectRabbitListenerContainerFactoryConfigurer[] that you can use to initialize a javadoc:org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory[] and a javadoc:org.springframework.amqp.rabbit.config.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 `org.springframework.amqp.support.converter.MessageConverter`:
For instance, the following configuration class exposes another factory that uses a specific javadoc:org.springframework.amqp.support.converter.MessageConverter[]:
include-code::custom/MyRabbitConfiguration[]
Then you can use the factory in any `@RabbitListener`-annotated method, as follows:
Then you can use the factory in any javadoc:org.springframework.amqp.rabbit.annotation.RabbitListener[format=annotation]-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.
By default, javadoc:org.springframework.amqp.rabbit.retry.RejectAndDontRequeueRecoverer[] is used, but you can define a javadoc:org.springframework.amqp.rabbit.retry.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.
You can also customize the javadoc:org.springframework.retry.support.RetryTemplate[] programmatically by declaring a javadoc:org.springframework.boot.autoconfigure.amqp.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.
You can modify this behavior in two ways: Set the `defaultRequeueRejected` property to `false` so that zero re-deliveries are attempted or throw an javadoc:org.springframework.amqp.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.

View File

@ -1,8 +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.
The Spring Framework provides extensive support for integrating with messaging systems, from simplified use of the JMS API using javadoc:org.springframework.jms.core.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 Boot also provides auto-configuration options for javadoc:org.springframework.amqp.rabbit.core.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.

View File

@ -1,8 +1,8 @@
[[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 `jakarta.jms.ConnectionFactory` to work with JMS, you generally need not use it directly yourself and can instead rely on higher level messaging abstractions.
The javadoc:jakarta.jms.ConnectionFactory[] interface provides a standard method of creating a javadoc:jakarta.jms.Connection[] for interacting with a JMS broker.
Although Spring needs a javadoc:jakarta.jms.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.
@ -11,7 +11,7 @@ Spring Boot also auto-configures the necessary infrastructure to send and receiv
[[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 `jakarta.jms.ConnectionFactory`.
When https://activemq.apache.org/components/classic[ActiveMQ "Classic"] is available on the classpath, Spring Boot can configure a javadoc:jakarta.jms.ConnectionFactory[].
If the broker is present, an embedded broker is automatically started and configured (provided no broker URL is specified through configuration and the embedded broker is not disabled in the configuration).
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.
@ -44,7 +44,7 @@ spring:
If you want to take full control over the embedded broker, see https://activemq.apache.org/how-do-i-embed-a-broker-inside-a-connection.html[the ActiveMQ "Classic" documentation] for further information.
By default, a `org.springframework.jms.connection.CachingConnectionFactory` wraps the native `jakarta.jms.ConnectionFactory` with sensible settings that you can control by external configuration properties in `+spring.jms.*+`:
By default, a javadoc:org.springframework.jms.connection.CachingConnectionFactory[] wraps the native javadoc:jakarta.jms.ConnectionFactory[] with sensible settings that you can control by external configuration properties in `+spring.jms.*+`:
[configprops,yaml]
----
@ -54,7 +54,7 @@ spring:
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:
If you'd rather use native pooling, you can do so by adding a dependency to `org.messaginghub:pooled-jms` and configuring the javadoc:org.messaginghub.pooled.jms.JmsPoolConnectionFactory[] accordingly, as shown in the following example:
[configprops,yaml]
----
@ -66,7 +66,7 @@ spring:
----
TIP: See javadoc:org.springframework.boot.autoconfigure.jms.activemq.ActiveMQProperties[] for more of the supported options.
You can also register an arbitrary number of beans that implement `ActiveMQConnectionFactoryCustomizer` for more advanced customizations.
You can also register an arbitrary number of beans that implement javadoc:org.springframework.boot.autoconfigure.jms.activemq.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.
@ -75,10 +75,10 @@ By default, ActiveMQ "Classic" creates a destination if it does not yet exist so
[[messaging.jms.artemis]]
== ActiveMQ Artemis Support
Spring Boot can auto-configure a `jakarta.jms.ConnectionFactory` when it detects that https://activemq.apache.org/components/artemis/[ActiveMQ Artemis] is available on the classpath.
Spring Boot can auto-configure a javadoc:jakarta.jms.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 `jakarta.jms.ConnectionFactory` that connects to a broker running on the local machine with the default settings.
When the latter is configured, Spring Boot configures a javadoc:jakarta.jms.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.
@ -97,9 +97,9 @@ spring:
----
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.
These can be specified as a comma-separated list to create them with the default options, or you can define bean(s) of type javadoc:org.apache.activemq.artemis.jms.server.config.JMSQueueConfiguration[] or javadoc:org.apache.activemq.artemis.jms.server.config.TopicConfiguration[], for advanced queue and topic configurations, respectively.
By default, a `org.springframework.jms.connection.CachingConnectionFactory` wraps the native `jakarta.jms.ConnectionFactory` with sensible settings that you can control by external configuration properties in `+spring.jms.*+`:
By default, a javadoc:org.springframework.jms.connection.CachingConnectionFactory[] wraps the native javadoc:jakarta.jms.ConnectionFactory[] with sensible settings that you can control by external configuration properties in `+spring.jms.*+`:
[configprops,yaml]
----
@ -109,7 +109,7 @@ spring:
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:
If you'd rather use native pooling, you can do so by adding a dependency on `org.messaginghub:pooled-jms` and configuring the javadoc:org.messaginghub.pooled.jms.JmsPoolConnectionFactory[] accordingly, as shown in the following example:
[configprops,yaml]
----
@ -129,7 +129,7 @@ No JNDI lookup is involved, and destinations are resolved against their names, u
[[messaging.jms.jndi]]
== Using a JNDI ConnectionFactory
If you are running your application in an application server, Spring Boot tries to locate a JMS `jakarta.jms.ConnectionFactory` by using JNDI.
If you are running your application in an application server, Spring Boot tries to locate a JMS javadoc:jakarta.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:
@ -145,30 +145,30 @@ spring:
[[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:
Spring's javadoc:org.springframework.jms.core.JmsTemplate[] is auto-configured, and you can autowire it directly into your own beans, as shown in the following example:
include-code::MyBean[]
NOTE: javadoc:{url-spring-framework-javadoc}/org.springframework.jms.core.JmsMessagingTemplate[] can be injected in a similar manner.
If a `org.springframework.jms.support.destination.DestinationResolver` or a `org.springframework.jms.support.converter.MessageConverter` bean is defined, it is associated automatically to the auto-configured `JmsTemplate`.
If a javadoc:org.springframework.jms.support.destination.DestinationResolver[] or a javadoc:org.springframework.jms.support.converter.MessageConverter[] bean is defined, it is associated automatically to the auto-configured javadoc:org.springframework.jms.core.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 `org.springframework.jms.support.destination.DestinationResolver`, a `org.springframework.jms.support.converter.MessageConverter`, or a `jakarta.jms.ExceptionListener` beans are defined, they are associated automatically with the default factory.
When the JMS infrastructure is present, any bean can be annotated with javadoc:org.springframework.jms.annotation.JmsListener[format=annotation] to create a listener endpoint.
If no javadoc:org.springframework.jms.config.JmsListenerContainerFactory[] has been defined, a default one is configured automatically.
If a javadoc:org.springframework.jms.support.destination.DestinationResolver[], a javadoc:org.springframework.jms.support.converter.MessageConverter[], or a javadoc:jakarta.jms.ExceptionListener[] beans are defined, they are associated automatically with the default factory.
In most scenarios, message listener containers should be configured against the native `jakarta.jms.ConnectionFactory`.
In most scenarios, message listener containers should be configured against the native javadoc:jakarta.jms.ConnectionFactory[].
This way each listener container has its own connection and this gives full responsibility to it in terms of local recovery.
The auto-configuration uses `ConnectionFactoryUnwrapper` to unwrap the native connection factory from the auto-configured one.
The auto-configuration uses javadoc:org.springframework.boot.jms.ConnectionFactoryUnwrapper[] to unwrap the native connection factory from the auto-configured one.
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 you run in an infrastructure where a javadoc:org.springframework.transaction.jta.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 `@org.springframework.transaction.annotation.Transactional` on your listener method (or a delegate thereof).
In that latter scenario, you can associate your local data store transaction to the processing of an incoming message by adding javadoc:org.springframework.transaction.annotation.Transactional[format=annotation] 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.
@ -178,14 +178,14 @@ include-code::MyBean[]
TIP: See the javadoc:{url-spring-framework-javadoc}/org.springframework.jms.annotation.EnableJms[format=annotation] API documentation 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.
If you need to create more javadoc:org.springframework.jms.config.JmsListenerContainerFactory[] instances or if you want to override the default, Spring Boot provides a javadoc:org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer[] that you can use to initialize a javadoc:org.springframework.jms.config.DefaultJmsListenerContainerFactory[] with the same settings as the one that is auto-configured.
For instance, the following example exposes another factory that uses a specific `org.springframework.jms.support.converter.MessageConverter`:
For instance, the following example exposes another factory that uses a specific javadoc:org.springframework.jms.support.converter.MessageConverter[]:
include-code::custom/MyJmsConfiguration[]
NOTE: In the example above, the customization uses `ConnectionFactoryUnwrapper` to associate the native connection factory to the message listener container the same way the auto-configured factory does.
NOTE: In the example above, the customization uses javadoc:org.springframework.boot.jms.ConnectionFactoryUnwrapper[] to associate the native connection factory to the message listener container the same way the auto-configured factory does.
Then you can use the factory in any `@JmsListener`-annotated method as follows:
Then you can use the factory in any javadoc:org.springframework.jms.annotation.JmsListener[format=annotation]-annotated method as follows:
include-code::custom/MyBean[]

View File

@ -15,7 +15,7 @@ spring:
group-id: "myGroup"
----
TIP: To create a topic on startup, add a bean of type `NewTopic`.
TIP: To create a topic on startup, add a bean of type javadoc:org.apache.kafka.clients.admin.NewTopic[].
If the topic already exists, the bean is ignored.
See javadoc:org.springframework.boot.autoconfigure.kafka.KafkaProperties[] for more supported options.
@ -25,40 +25,40 @@ See javadoc:org.springframework.boot.autoconfigure.kafka.KafkaProperties[] for m
[[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:
Spring's javadoc:org.springframework.kafka.core.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`.
NOTE: If the property configprop:spring.kafka.producer.transaction-id-prefix[] is defined, a javadoc:org.springframework.kafka.transaction.KafkaTransactionManager[] is automatically configured.
Also, if a javadoc:org.springframework.kafka.support.converter.RecordMessageConverter[] bean is defined, it is automatically associated to the auto-configured javadoc:org.springframework.kafka.core.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.*`.
When the Apache Kafka infrastructure is present, any bean can be annotated with javadoc:org.springframework.kafka.annotation.KafkaListener[format=annotation] to create a listener endpoint.
If no javadoc:org.springframework.kafka.config.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.
If a javadoc:org.springframework.kafka.transaction.KafkaTransactionManager[] bean is defined, it is automatically associated to the container factory.
Similarly, if a javadoc:org.springframework.kafka.listener.adapter.RecordFilterStrategy[], javadoc:org.springframework.kafka.listener.CommonErrorHandler[], javadoc:org.springframework.kafka.listener.AfterRollbackProcessor[] or javadoc:org.springframework.kafka.listener.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`.
Depending on the listener type, a javadoc:org.springframework.kafka.support.converter.RecordMessageConverter[] or javadoc:org.springframework.kafka.support.converter.BatchMessageConverter[] bean is associated to the default factory.
If only a javadoc:org.springframework.kafka.support.converter.RecordMessageConverter[] bean is present for a batch listener, it is wrapped in a javadoc:org.springframework.kafka.support.converter.BatchMessageConverter[].
TIP: A custom `ChainedKafkaTransactionManager` must be marked `@Primary` as it usually references the auto-configured `KafkaTransactionManager` bean.
TIP: A custom javadoc:org.springframework.kafka.transaction.ChainedKafkaTransactionManager[] must be marked javadoc:org.springframework.context.annotation.Primary[format=annotation] as it usually references the auto-configured javadoc:org.springframework.kafka.transaction.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.
Spring for Apache Kafka provides a factory bean to create a javadoc:org.apache.kafka.streams.StreamsBuilder[] object and manage the lifecycle of its streams.
Spring Boot auto-configures the required javadoc:org.springframework.kafka.config.KafkaStreamsConfiguration[] bean as long as `kafka-streams` is on the classpath and Kafka Streams is enabled by the javadoc:org.springframework.kafka.annotation.EnableKafkaStreams[format=annotation] 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.
@ -67,11 +67,11 @@ 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[] for more information.
To use the factory bean, wire `StreamsBuilder` into your `@Bean` as shown in the following example:
To use the factory bean, wire javadoc:org.apache.kafka.streams.StreamsBuilder[] into your javadoc:org.springframework.context.annotation.Bean[format=annotation] as shown in the following example:
include-code::MyKafkaStreamsConfiguration[]
By default, the streams managed by the `StreamsBuilder` object are started automatically.
By default, the streams managed by the javadoc:org.apache.kafka.streams.StreamsBuilder[] object are started automatically.
You can customize this behavior using the configprop:spring.kafka.streams.auto-startup[] property.
@ -89,7 +89,7 @@ Most of these common properties can be overridden for one or more of the client
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.
Only a subset of the properties supported by Kafka are available directly through the javadoc:org.springframework.boot.autoconfigure.kafka.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]
@ -114,7 +114,7 @@ spring:
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 `org.springframework.kafka.support.serializer.JsonDeserializer` as follows:
You can also configure the Spring Kafka javadoc:org.springframework.kafka.support.serializer.JsonDeserializer[] as follows:
[configprops,yaml]
----
@ -127,7 +127,7 @@ spring:
"[spring.json.trusted.packages]": "com.example.main,com.example.another"
----
Similarly, you can disable the `org.springframework.kafka.support.serializer.JsonSerializer` default behavior of sending type information in headers:
Similarly, you can disable the javadoc:org.springframework.kafka.support.serializer.JsonSerializer[] default behavior of sending type information in headers:
[configprops,yaml]
----
@ -147,17 +147,17 @@ IMPORTANT: Properties set in this way override any configuration item that Sprin
== 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.
To use this feature, annotate a test class with javadoc:org.springframework.kafka.test.context.EmbeddedKafka[format=annotation] 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.
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 javadoc:org.springframework.kafka.test.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:
* Configure a property name on the javadoc:org.springframework.kafka.test.context.EmbeddedKafka[format=annotation] annotation:
include-code::annotation/MyTest[]

View File

@ -13,7 +13,7 @@ There are `spring-boot-starter-pulsar` and `spring-boot-starter-pulsar-reactive`
[[messaging.pulsar.connecting]]
== Connecting to Pulsar
When you use the Pulsar starter, Spring Boot will auto-configure and register a `PulsarClient` bean.
When you use the Pulsar starter, Spring Boot will auto-configure and register a javadoc:org.apache.pulsar.client.api.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.
@ -22,7 +22,7 @@ NOTE: The value must be a valid https://pulsar.apache.org/docs/client-libraries-
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.
If you need more control over the configuration, consider registering one or more javadoc:org.springframework.pulsar.core.PulsarClientBuilderCustomizer[] beans.
@ -71,22 +71,22 @@ For complete details on the client and authentication see the Spring for Apache
[[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.
When the Reactive auto-configuration is activated, Spring Boot will auto-configure and register a javadoc:org.apache.pulsar.reactive.client.api.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`.
The javadoc:org.apache.pulsar.reactive.client.api.ReactivePulsarClient[] adapts an instance of the previously described javadoc:org.apache.pulsar.client.api.PulsarClient[].
Therefore, follow the previous section to configure the javadoc:org.apache.pulsar.client.api.PulsarClient[] used by the javadoc:org.apache.pulsar.reactive.client.api.ReactivePulsarClient[].
[[messaging.pulsar.admin]]
== Connecting to Pulsar Administration
Spring for Apache Pulsar's `PulsarAdministration` client is also auto-configured.
Spring for Apache Pulsar's javadoc:org.springframework.pulsar.core.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.
If you need more control over the configuration, consider registering one or more javadoc:org.springframework.pulsar.core.PulsarAdminBuilderCustomizer[] beans.
@ -96,7 +96,7 @@ If you need more control over the configuration, consider registering one or mor
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`.
TIP: To create a topic on startup, add a bean of type javadoc:org.springframework.pulsar.core.PulsarTopic[].
If the topic already exists, the bean is ignored.
@ -104,72 +104,72 @@ 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:
Spring's javadoc:org.springframework.pulsar.core.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.
The javadoc:org.springframework.pulsar.core.PulsarTemplate[] relies on a javadoc:org.springframework.pulsar.core.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.
If you need more control over the producer factory configuration, consider registering one or more javadoc:org.springframework.pulsar.core.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.
You can also pass in a javadoc:org.springframework.pulsar.core.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.
If you need more control over the message being sent, you can pass in a javadoc:org.springframework.pulsar.core.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:
When the Reactive auto-configuration is activated, Spring's javadoc:org.springframework.pulsar.reactive.core.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.
The javadoc:org.springframework.pulsar.reactive.core.ReactivePulsarTemplate[] relies on a javadoc:org.springframework.pulsar.reactive.core.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.
If you need more control over the sender factory configuration, consider registering one or more javadoc:org.springframework.pulsar.reactive.core.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.
You can also pass in a javadoc:org.springframework.pulsar.reactive.core.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.
If you need more control over the message being sent, you can pass in a javadoc:org.springframework.pulsar.reactive.core.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.
When the Apache Pulsar infrastructure is present, any bean can be annotated with javadoc:org.springframework.pulsar.annotation.PulsarListener[format=annotation] 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.
Spring Boot auto-configuration provides all the components necessary for javadoc:org.springframework.pulsar.annotation.PulsarListener[], such as the javadoc:org.springframework.pulsar.config.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 configuration of the consumer factory, 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.
If you need more control over the configuration of the consumer factory, consider registering one or more javadoc:org.springframework.pulsar.core.ConsumerBuilderCustomizer[] beans.
These customizers are applied to all consumers created by the factory, and therefore all javadoc:org.springframework.pulsar.annotation.PulsarListener[format=annotation] instances.
You can also customize a single listener by setting the `consumerCustomizer` attribute of the javadoc:org.springframework.pulsar.annotation.PulsarListener[format=annotation] annotation.
If you need more control over the actual container factory configuration, consider registering one or more `PulsarContainerFactoryCustomizer<ConcurrentPulsarListenerContainerFactory<?>>` beans.
[[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.
When the Apache Pulsar infrastructure is present and the Reactive auto-configuration is activated, any bean can be annotated with javadoc:org.springframework.pulsar.reactive.config.annotation.ReactivePulsarListener[format=annotation] 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.
Spring Boot auto-configuration provides all the components necessary for javadoc:org.springframework.pulsar.reactive.config.annotation.ReactivePulsarListener[], such as the javadoc:org.springframework.pulsar.reactive.config.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 configuration of the consumer factory, 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.
If you need more control over the configuration of the consumer factory, consider registering one or more javadoc:org.springframework.pulsar.reactive.core.ReactiveMessageConsumerBuilderCustomizer[] beans.
These customizers are applied to all consumers created by the factory, and therefore all javadoc:org.springframework.pulsar.reactive.config.annotation.ReactivePulsarListener[format=annotation] instances.
You can also customize a single listener by setting the `consumerCustomizer` attribute of the javadoc:org.springframework.pulsar.reactive.config.annotation.ReactivePulsarListener[format=annotation] annotation.
If you need more control over the actual container factory configuration, consider registering one or more `PulsarContainerFactoryCustomizer<DefaultReactivePulsarListenerContainerFactory<?>>` beans.
@ -179,17 +179,17 @@ If you need more control over the actual container factory configuration, consid
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.
When the Apache Pulsar infrastructure is present, any bean can be annotated with javadoc:org.springframework.pulsar.annotation.PulsarReader[format=annotation] 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.
The javadoc:org.springframework.pulsar.annotation.PulsarReader[format=annotation] relies on a javadoc:org.springframework.pulsar.core.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 configuration of the reader factory, 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.
If you need more control over the configuration of the reader factory, consider registering one or more javadoc:org.springframework.pulsar.core.ReaderBuilderCustomizer[] beans.
These customizers are applied to all readers created by the factory, and therefore all javadoc:org.springframework.pulsar.annotation.PulsarReader[format=annotation] instances.
You can also customize a single listener by setting the `readerCustomizer` attribute of the javadoc:org.springframework.pulsar.annotation.PulsarReader[format=annotation] annotation.
If you need more control over the actual container factory configuration, consider registering one or more `PulsarContainerFactoryCustomizer<DefaultPulsarReaderContainerFactory<?>>` beans.
@ -197,18 +197,18 @@ If you need more control over the actual container factory configuration, consid
[[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.
When the Apache Pulsar infrastructure is present and the Reactive auto-configuration is activated, Spring's javadoc:org.springframework.pulsar.reactive.core.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 passing in one or more javadoc:org.springframework.pulsar.reactive.core.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.
If you need more control over the reader factory configuration, consider registering one or more javadoc:org.springframework.pulsar.reactive.core.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.
You can also pass one or more javadoc:org.springframework.pulsar.reactive.core.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].
@ -217,20 +217,20 @@ TIP: For more details on any of the above components and to discover other avail
[[messaging.pulsar.transactions]]
== Transaction Support
Spring for Apache Pulsar supports transactions when using `PulsarTemplate` and `@PulsarListener`.
Spring for Apache Pulsar supports transactions when using javadoc:org.springframework.pulsar.core.PulsarTemplate[] and javadoc:org.springframework.pulsar.annotation.PulsarListener[format=annotation].
NOTE: Transactions are not currently supported when using the reactive variants.
Setting the configprop:spring.pulsar.transaction.enabled[] property to `true` will:
* Configure a `PulsarTransactionManager` bean
* Enable transaction support for `PulsarTemplate`
* Enable transaction support for `@PulsarListener` methods
* Configure a javadoc:org.springframework.pulsar.transaction.PulsarTransactionManager[] bean
* Enable transaction support for javadoc:org.springframework.pulsar.core.PulsarTemplate[]
* Enable transaction support for javadoc:org.springframework.pulsar.annotation.PulsarListener[format=annotation] methods
The `transactional` attribute of `@PulsarListener` can be used to fine-tune when transactions should be used with listeners.
The `transactional` attribute of javadoc:org.springframework.pulsar.annotation.PulsarListener[format=annotation] can be used to fine-tune when transactions should be used with listeners.
For more control of the Spring for Apache Pulsar transaction features you should define your own `PulsarTemplate` and/or `ConcurrentPulsarListenerContainerFactory` beans.
You can also define a `PulsarAwareTransactionManager` bean if the default auto-configured `PulsarTransactionManager` is not suitable.
For more control of the Spring for Apache Pulsar transaction features you should define your own javadoc:org.springframework.pulsar.core.PulsarTemplate[] and/or javadoc:org.springframework.pulsar.config.ConcurrentPulsarListenerContainerFactory[] beans.
You can also define a javadoc:org.springframework.pulsar.transaction.PulsarAwareTransactionManager[] bean if the default auto-configured javadoc:org.springframework.pulsar.transaction.PulsarTransactionManager[] is not suitable.
@ -241,5 +241,5 @@ The properties supported by auto-configuration are shown in the xref:appendix:ap
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.
Only a subset of the properties supported by Pulsar are available directly through the javadoc:org.springframework.boot.autoconfigure.pulsar.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.

View File

@ -13,7 +13,7 @@ See the {url-spring-framework-docs}/rsocket.html#rsocket-spring[RSocket section]
[[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.
Spring Boot auto-configures an javadoc:org.springframework.messaging.rsocket.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
@ -22,8 +22,8 @@ By default, the auto-configuration will try to configure the following (in order
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.
Developers can customize the javadoc:org.springframework.messaging.rsocket.RSocketStrategies[] component by creating beans that implement the javadoc:org.springframework.boot.rsocket.messaging.RSocketStrategiesCustomizer[] interface.
Note that their javadoc:org.springframework.core.annotation.Order[format=annotation] is important, as it determines the order of codecs.
@ -67,20 +67,20 @@ spring:
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.
This means that Spring Boot will create a javadoc:org.springframework.messaging.rsocket.annotation.support.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.
Once the javadoc:io.rsocket.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 server, you can get injected with an javadoc:org.springframework.messaging.rsocket.RSocketRequester[] instance on any handler method of an RSocket javadoc:org.springframework.stereotype.Controller[format=annotation].
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.
Spring Boot auto-configures an javadoc:org.springframework.messaging.rsocket.RSocketRequester$Builder[] for such cases with the expected codecs and applies any javadoc:org.springframework.messaging.rsocket.RSocketConnectorConfigurer[] bean.
The `RSocketRequester.Builder` instance is a prototype bean, meaning each injection point will provide you with a new instance .
The javadoc:org.springframework.messaging.rsocket.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:

View File

@ -3,10 +3,10 @@
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.
If Spring Integration is available on your classpath, it is initialized through the javadoc:org.springframework.integration.config.EnableIntegration[format=annotation] 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 Integration polling logic relies xref:features/task-execution-and-scheduling.adoc[on the auto-configured javadoc:org.springframework.scheduling.TaskScheduler[]].
The default javadoc:org.springframework.integration.scheduling.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.
@ -20,10 +20,10 @@ spring:
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).
If `spring-integration-rsocket` is available, developers can configure an RSocket server using `spring.rsocket.server.*` properties and let it use javadoc:org.springframework.integration.rsocket.IntegrationRSocketEndpoint[] or javadoc:org.springframework.integration.rsocket.outbound.RSocketOutboundGateway[] components to handle incoming RSocket messages.
This infrastructure can handle Spring Integration RSocket channel adapters and javadoc:org.springframework.messaging.handler.annotation.MessageMapping[format=annotation] handlers (given `spring.integration.rsocket.server.message-mapping-enabled` is configured).
Spring Boot can also auto-configure an `ClientRSocketConnector` using configuration properties:
Spring Boot can also auto-configure an javadoc:org.springframework.integration.rsocket.ClientRSocketConnector[] using configuration properties:
[configprops,yaml]
----

View File

@ -29,7 +29,7 @@ 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).
- The Spring javadoc:org.springframework.context.annotation.Profile[format=annotation] 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, javadoc:org.springframework.boot.autoconfigure.condition.ConditionalOnProperty[format=annotation] and `.enable` properties).
To learn more about ahead-of-time processing, please see the xref:packaging/native-image/introducing-graalvm-native-images.adoc#packaging.native-image.introducing-graalvm-native-images.understanding-aot-processing[] section.

View File

@ -7,7 +7,7 @@
== 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.
Nested configuration properties which are not inner classes, however, *must* be annotated with javadoc:org.springframework.boot.context.properties.NestedConfigurationProperty[format=annotation], otherwise they won't be detected and will not be bindable.
include-code::MyProperties[]
@ -16,18 +16,18 @@ 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.
Without the javadoc:org.springframework.boot.context.properties.NestedConfigurationProperty[format=annotation] annotation on the `nested` field, the `my.properties.nested.number` property would not be bindable in a native image.
You can also annotate the getter method.
When using constructor binding, you have to annotate the field with `@NestedConfigurationProperty`:
When using constructor binding, you have to annotate the field with javadoc:org.springframework.boot.context.properties.NestedConfigurationProperty[format=annotation]:
include-code::MyPropertiesCtor[]
When using records, you have to annotate the parameter with `@NestedConfigurationProperty`:
When using records, you have to annotate the parameter with javadoc:org.springframework.boot.context.properties.NestedConfigurationProperty[format=annotation]:
include-code::MyPropertiesRecord[]
When using Kotlin, you need to annotate the parameter of a data class with `@NestedConfigurationProperty`:
When using Kotlin, you need to annotate the parameter of a data class with javadoc:org.springframework.boot.context.properties.NestedConfigurationProperty[format=annotation]:
include-code::MyPropertiesKotlin[]
@ -158,24 +158,24 @@ For further reading, please see {url-graal-docs-native-image}/metadata/Automatic
[[packaging.native-image.advanced.custom-hints]]
== Custom Hints
If you need to provide your own hints for reflection, resources, serialization, proxy usage and so on, you can use the `RuntimeHintsRegistrar` API.
Create a class that implements the `RuntimeHintsRegistrar` interface, and then make appropriate calls to the provided `RuntimeHints` instance:
If you need to provide your own hints for reflection, resources, serialization, proxy usage and so on, you can use the javadoc:org.springframework.aot.hint.RuntimeHintsRegistrar[] API.
Create a class that implements the javadoc:org.springframework.aot.hint.RuntimeHintsRegistrar[] interface, and then make appropriate calls to the provided javadoc:org.springframework.aot.hint.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.
You can then use javadoc:org.springframework.context.annotation.ImportRuntimeHints[format=annotation] on any javadoc:org.springframework.context.annotation.Configuration[format=annotation] class (for example your javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation] 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`.
Most of the hints are automatically inferred, for example when accepting or returning data from a javadoc:org.springframework.web.bind.annotation.RestController[format=annotation] method.
But when you work with javadoc:org.springframework.web.reactive.function.client.WebClient[], javadoc:org.springframework.web.client.RestClient[] or javadoc:org.springframework.web.client.RestTemplate[] directly, you might need to use javadoc:org.springframework.aot.hint.annotation.RegisterReflectionForBinding[format=annotation].
[[packaging.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 `java.util.function.Predicate` that can be used to test a `RuntimeHints` instance.
The javadoc:org.springframework.aot.hint.predicate.RuntimeHintsPredicates[] API can be used to test your hints.
The API provides methods that build a javadoc:java.util.function.Predicate[] that can be used to test a javadoc:org.springframework.aot.hint.RuntimeHints[] instance.
If you're using AssertJ, your test would look like this:

View File

@ -48,8 +48,8 @@ So instead, when using Spring Boot to create native images, a closed-world is as
A closed-world assumption implies, besides xref:packaging/native-image/introducing-graalvm-native-images.adoc#packaging.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).
- The Spring javadoc:org.springframework.context.annotation.Profile[format=annotation] 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, javadoc:org.springframework.boot.autoconfigure.condition.ConditionalOnProperty[format=annotation] 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:
@ -75,19 +75,19 @@ 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:
If we take a typical javadoc:org.springframework.context.annotation.Configuration[format=annotation] 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.
The bean definition is created by parsing the javadoc:org.springframework.context.annotation.Configuration[format=annotation] class and finding the javadoc:org.springframework.context.annotation.Bean[format=annotation] methods.
In the above example, we're defining a javadoc:org.springframework.beans.factory.config.BeanDefinition[] for a singleton bean named `myBean`.
We're also creating a javadoc:org.springframework.beans.factory.config.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 running on the JVM, javadoc:org.springframework.context.annotation.Configuration[format=annotation] class parsing happens when your application starts and javadoc:org.springframework.context.annotation.Bean[format=annotation] 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.
Rather than parsing javadoc:org.springframework.context.annotation.Configuration[format=annotation] 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:
@ -96,18 +96,18 @@ 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.
You can see above that the generated code creates equivalent bean definitions to the javadoc:org.springframework.context.annotation.Configuration[format=annotation] 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.
When a `myBean` instance is required, a javadoc:org.springframework.beans.factory.aot.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.
It will also generate code when bean post-processing is required (for example, to call javadoc:org.springframework.beans.factory.annotation.Autowired[format=annotation] methods).
An javadoc:org.springframework.context.ApplicationContextInitializer[] will also be generated which will be used by Spring Boot to initialize the javadoc:org.springframework.context.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.

View File

@ -5,7 +5,7 @@ One of the major advantages of dependency injection is that it should make your
You can instantiate objects by using the `new` operator without even involving Spring.
You can also use _mock objects_ instead of real dependencies.
Often, you need to move beyond unit testing and start integration testing (with a Spring `ApplicationContext`).
Often, you need to move beyond unit testing and start integration testing (with a Spring javadoc:org.springframework.context.ApplicationContext[]).
It is useful to be able to perform integration testing without requiring deployment of your application or needing to connect to other infrastructure.
The Spring Framework includes a dedicated test module for such integration testing.

View File

@ -1,35 +1,35 @@
[[testing.spring-boot-applications]]
= Testing Spring Boot Applications
A Spring Boot application is a Spring `ApplicationContext`, so nothing very special has to be done to test it beyond what you would normally do with a vanilla Spring context.
A Spring Boot application is a Spring javadoc:org.springframework.context.ApplicationContext[], so nothing very special has to be done to test it beyond what you would normally do with a vanilla Spring context.
NOTE: External properties, logging, and other features of Spring Boot are installed in the context by default only if you use `SpringApplication` to create it.
NOTE: External properties, logging, and other features of Spring Boot are installed in the context by default only if you use javadoc:org.springframework.boot.SpringApplication[] to create it.
Spring Boot provides a `@SpringBootTest` annotation, which can be used as an alternative to the standard `spring-test` `@ContextConfiguration` annotation when you need Spring Boot features.
The annotation works by xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.detecting-configuration[creating the `ApplicationContext` used in your tests through `SpringApplication`].
In addition to `@SpringBootTest` a number of other annotations are also provided for xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.autoconfigured-tests[testing more specific slices] of an application.
Spring Boot provides a javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation] annotation, which can be used as an alternative to the standard `spring-test` javadoc:org.springframework.test.context.ContextConfiguration[format=annotation] annotation when you need Spring Boot features.
The annotation works by xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.detecting-configuration[creating the javadoc:org.springframework.context.ApplicationContext[] used in your tests through javadoc:org.springframework.boot.SpringApplication[]].
In addition to javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation] a number of other annotations are also provided for xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.autoconfigured-tests[testing more specific slices] of an application.
TIP: If you are using JUnit 4, do not forget to also add `@RunWith(SpringRunner.class)` to your test, otherwise the annotations will be ignored.
If you are using JUnit 5, there is no need to add the equivalent `@ExtendWith(SpringExtension.class)` as `@SpringBootTest` and the other `+@...Test+` annotations are already annotated with it.
If you are using JUnit 5, there is no need to add the equivalent `@ExtendWith(SpringExtension.class)` as javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation] and the other `+@...Test+` annotations are already annotated with it.
By default, `@SpringBootTest` will not start a server.
You can use the `webEnvironment` attribute of `@SpringBootTest` to further refine how your tests run:
By default, javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation] will not start a server.
You can use the `webEnvironment` attribute of javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation] to further refine how your tests run:
* `MOCK`(Default) : Loads a web `ApplicationContext` and provides a mock web environment.
* `MOCK`(Default) : Loads a web javadoc:org.springframework.context.ApplicationContext[] and provides a mock web environment.
Embedded servers are not started when using this annotation.
If a web environment is not available on your classpath, this mode transparently falls back to creating a regular non-web `ApplicationContext`.
It can be used in conjunction with xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.with-mock-environment[`@AutoConfigureMockMvc` or `@AutoConfigureWebTestClient`] for mock-based testing of your web application.
* `RANDOM_PORT`: Loads a `WebServerApplicationContext` and provides a real web environment.
If a web environment is not available on your classpath, this mode transparently falls back to creating a regular non-web javadoc:org.springframework.context.ApplicationContext[].
It can be used in conjunction with xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.with-mock-environment[`@AutoConfigureMockMvc` or javadoc:org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient[format=annotation]] for mock-based testing of your web application.
* `RANDOM_PORT`: Loads a javadoc:org.springframework.boot.web.context.WebServerApplicationContext[] and provides a real web environment.
Embedded servers are started and listen on a random port.
* `DEFINED_PORT`: Loads a `WebServerApplicationContext` and provides a real web environment.
* `DEFINED_PORT`: Loads a javadoc:org.springframework.boot.web.context.WebServerApplicationContext[] and provides a real web environment.
Embedded servers are started and listen on a defined port (from your `application.properties`) or on the default port of `8080`.
* `NONE`: Loads an `ApplicationContext` by using `SpringApplication` but does not provide _any_ web environment (mock or otherwise).
* `NONE`: Loads an javadoc:org.springframework.context.ApplicationContext[] by using javadoc:org.springframework.boot.SpringApplication[] but does not provide _any_ web environment (mock or otherwise).
NOTE: If your test is `@org.springframework.transaction.annotation.Transactional`, it rolls back the transaction at the end of each test method by default.
NOTE: If your test is javadoc:org.springframework.transaction.annotation.Transactional[format=annotation], it rolls back the transaction at the end of each test method by default.
However, as using this arrangement with either `RANDOM_PORT` or `DEFINED_PORT` implicitly provides a real servlet environment, the HTTP client and server run in separate threads and, thus, in separate transactions.
Any transaction initiated on the server does not roll back in this case.
NOTE: `@SpringBootTest` with `webEnvironment = WebEnvironment.RANDOM_PORT` will also start the management server on a separate random port if your application uses a different port for the management server.
NOTE: javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation] with `webEnvironment = WebEnvironment.RANDOM_PORT` will also start the management server on a separate random port if your application uses a different port for the management server.
@ -49,26 +49,26 @@ include-code::MyWebFluxTests[]
[[testing.spring-boot-applications.detecting-configuration]]
== Detecting Test Configuration
If you are familiar with the Spring Test Framework, you may be used to using `@ContextConfiguration(classes=...)` in order to specify which Spring `@Configuration` to load.
Alternatively, you might have often used nested `@Configuration` classes within your test.
If you are familiar with the Spring Test Framework, you may be used to using `@ContextConfiguration(classes=...)` in order to specify which Spring javadoc:org.springframework.context.annotation.Configuration[format=annotation] to load.
Alternatively, you might have often used nested javadoc:org.springframework.context.annotation.Configuration[format=annotation] classes within your test.
When testing Spring Boot applications, this is often not required.
Spring Boot's `@*Test` annotations search for your primary configuration automatically whenever you do not explicitly define one.
The search algorithm works up from the package that contains the test until it finds a class annotated with `@SpringBootApplication` or `@SpringBootConfiguration`.
The search algorithm works up from the package that contains the test until it finds a class annotated with javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation] or javadoc:org.springframework.boot.SpringBootConfiguration[format=annotation].
As long as you xref:using/structuring-your-code.adoc[structured your code] in a sensible way, your main configuration is usually found.
[NOTE]
====
If you use a xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.autoconfigured-tests[test annotation to test a more specific slice of your application], you should avoid adding configuration settings that are specific to a particular area on the xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.user-configuration-and-slicing[main method's application class].
The underlying component scan configuration of `@SpringBootApplication` defines exclude filters that are used to make sure slicing works as expected.
If you are using an explicit `@ComponentScan` directive on your `@SpringBootApplication`-annotated class, be aware that those filters will be disabled.
The underlying component scan configuration of javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation] defines exclude filters that are used to make sure slicing works as expected.
If you are using an explicit javadoc:org.springframework.context.annotation.ComponentScan[format=annotation] directive on your javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation]-annotated class, be aware that those filters will be disabled.
If you are using slicing, you should define them again.
====
If you want to customize the primary configuration, you can use a nested `@TestConfiguration` class.
Unlike a nested `@Configuration` class, which would be used instead of your application's primary configuration, a nested `@TestConfiguration` class is used in addition to your application's primary configuration.
If you want to customize the primary configuration, you can use a nested javadoc:org.springframework.boot.test.context.TestConfiguration[format=annotation] class.
Unlike a nested javadoc:org.springframework.context.annotation.Configuration[format=annotation] class, which would be used instead of your application's primary configuration, a nested javadoc:org.springframework.boot.test.context.TestConfiguration[format=annotation] class is used in addition to your application's primary configuration.
NOTE: Spring's test framework caches application contexts between tests.
Therefore, as long as your tests share the same configuration (no matter how it is discovered), the potentially time-consuming process of loading the context happens only once.
@ -78,7 +78,7 @@ Therefore, as long as your tests share the same configuration (no matter how it
[[testing.spring-boot-applications.using-main]]
== Using the Test Configuration Main Method
Typically the test configuration discovered by `@SpringBootTest` will be your main `@SpringBootApplication`.
Typically the test configuration discovered by javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation] will be your main javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation].
In most well structured applications, this configuration class will also include the `main` method used to launch the application.
For example, the following is a very common code pattern for a typical Spring Boot application:
@ -92,15 +92,15 @@ For example, here is an application that changes the banner mode and sets additi
include-code::custom/MyApplication[]
Since customizations in the `main` method can affect the resulting `ApplicationContext`, it's possible that you might also want to use the `main` method to create the `ApplicationContext` used in your tests.
By default, `@SpringBootTest` will not call your `main` method, and instead the class itself is used directly to create the `ApplicationContext`
Since customizations in the `main` method can affect the resulting javadoc:org.springframework.context.ApplicationContext[], it's possible that you might also want to use the `main` method to create the javadoc:org.springframework.context.ApplicationContext[] used in your tests.
By default, javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation] will not call your `main` method, and instead the class itself is used directly to create the javadoc:org.springframework.context.ApplicationContext[]
If you want to change this behavior, you can change the `useMainMethod` attribute of `@SpringBootTest` to javadoc:org.springframework.boot.test.context.SpringBootTest$UseMainMethod#ALWAYS[] or javadoc:org.springframework.boot.test.context.SpringBootTest$UseMainMethod#WHEN_AVAILABLE[].
If you want to change this behavior, you can change the `useMainMethod` attribute of javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation] to javadoc:org.springframework.boot.test.context.SpringBootTest$UseMainMethod#ALWAYS[] or javadoc:org.springframework.boot.test.context.SpringBootTest$UseMainMethod#WHEN_AVAILABLE[].
When set to `ALWAYS`, the test will fail if no `main` method can be found.
When set to `WHEN_AVAILABLE` the `main` method will be used if it is available, otherwise the standard loading mechanism will be used.
For example, the following test will invoke the `main` method of `MyApplication` in order to create the `ApplicationContext`.
If the main method sets additional profiles then those will be active when the `ApplicationContext` starts.
For example, the following test will invoke the `main` method of `MyApplication` in order to create the javadoc:org.springframework.context.ApplicationContext[].
If the main method sets additional profiles then those will be active when the javadoc:org.springframework.context.ApplicationContext[] starts.
include-code::always/MyApplicationTests[]
@ -109,18 +109,18 @@ include-code::always/MyApplicationTests[]
[[testing.spring-boot-applications.excluding-configuration]]
== Excluding Test Configuration
If your application uses component scanning (for example, if you use `@SpringBootApplication` or `@ComponentScan`), you may find top-level configuration classes that you created only for specific tests accidentally get picked up everywhere.
If your application uses component scanning (for example, if you use javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation] or javadoc:org.springframework.context.annotation.ComponentScan[format=annotation]), you may find top-level configuration classes that you created only for specific tests accidentally get picked up everywhere.
As we xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.detecting-configuration[have seen earlier], `@TestConfiguration` can be used on an inner class of a test to customize the primary configuration.
`@TestConfiguration` can also be used on a top-level class. Doing so indicates that the class should not be picked up by scanning.
As we xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.detecting-configuration[have seen earlier], javadoc:org.springframework.boot.test.context.TestConfiguration[format=annotation] can be used on an inner class of a test to customize the primary configuration.
javadoc:org.springframework.boot.test.context.TestConfiguration[format=annotation] can also be used on a top-level class. Doing so indicates that the class should not be picked up by scanning.
You can then import the class explicitly where it is required, as shown in the following example:
include-code::MyTests[]
NOTE: If you directly use `@ComponentScan` (that is, not through `@SpringBootApplication`) you need to register the `TypeExcludeFilter` with it.
NOTE: If you directly use javadoc:org.springframework.context.annotation.ComponentScan[format=annotation] (that is, not through javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation]) you need to register the javadoc:org.springframework.boot.context.TypeExcludeFilter[] with it.
See the javadoc:org.springframework.boot.context.TypeExcludeFilter[] API documentation for details.
NOTE: An imported `@TestConfiguration` is processed earlier than an inner-class `@TestConfiguration` and an imported `@TestConfiguration` will be processed before any configuration found through component scanning.
NOTE: An imported javadoc:org.springframework.boot.test.context.TestConfiguration[format=annotation] is processed earlier than an inner-class javadoc:org.springframework.boot.test.context.TestConfiguration[format=annotation] and an imported javadoc:org.springframework.boot.test.context.TestConfiguration[format=annotation] will be processed before any configuration found through component scanning.
Generally speaking, this difference in ordering has no noticeable effect but it is something to be aware of if you're relying on bean overriding.
@ -129,7 +129,7 @@ Generally speaking, this difference in ordering has no noticeable effect but it
== Using Application Arguments
If your application expects xref:features/spring-application.adoc#features.spring-application.application-arguments[arguments], you can
have `@SpringBootTest` inject them using the `args` attribute.
have javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation] inject them using the `args` attribute.
include-code::MyApplicationArgumentTests[]
@ -138,20 +138,20 @@ include-code::MyApplicationArgumentTests[]
[[testing.spring-boot-applications.with-mock-environment]]
== Testing With a Mock Environment
By default, `@SpringBootTest` does not start the server but instead sets up a mock environment for testing web endpoints.
By default, javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation] does not start the server but instead sets up a mock environment for testing web endpoints.
With Spring MVC, we can query our web endpoints using {url-spring-framework-docs}/testing/mockmvc.html[`MockMvc`].
Three integrations are available:
* The regular {url-spring-framework-docs}/testing/mockmvc/hamcrest.html[`MockMvc`] that uses Hamcrest.
* {url-spring-framework-docs}/testing/mockmvc/assertj.html[`MockMvcTester`] that wraps `MockMvc` and uses AssertJ.
* {url-spring-framework-docs}/testing/webtestclient.html[`WebTestClient`] where `MockMvc` is plugged in as the server to handle requests with.
* {url-spring-framework-docs}/testing/mockmvc/assertj.html[`MockMvcTester`] that wraps javadoc:org.springframework.test.web.servlet.MockMvc[] and uses AssertJ.
* {url-spring-framework-docs}/testing/webtestclient.html[`WebTestClient`] where javadoc:org.springframework.test.web.servlet.MockMvc[] is plugged in as the server to handle requests with.
The following example showcases the available integrations:
include-code::MyMockMvcTests[]
TIP: If you want to focus only on the web layer and not start a complete `ApplicationContext`, consider xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.spring-mvc-tests[using `@WebMvcTest` instead].
TIP: If you want to focus only on the web layer and not start a complete javadoc:org.springframework.context.ApplicationContext[], consider xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.spring-mvc-tests[using javadoc:org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest[format=annotation] instead].
With Spring WebFlux endpoints, you can use {url-spring-framework-docs}/testing/webtestclient.html[`WebTestClient`] as shown in the following example:
@ -175,15 +175,15 @@ If you need to test these lower-level concerns, you can start a fully running se
If you need to start a full running server, we recommend that you use random ports.
If you use `@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)`, an available port is picked at random each time your test runs.
The `@LocalServerPort` annotation can be used to xref:how-to:webserver.adoc#howto.webserver.discover-port[inject the actual port used] into your test.
The javadoc:org.springframework.boot.test.web.server.LocalServerPort[format=annotation] annotation can be used to xref:how-to:webserver.adoc#howto.webserver.discover-port[inject the actual port used] into your test.
For convenience, tests that need to make REST calls to the started server can additionally autowire a {url-spring-framework-docs}/testing/webtestclient.html[`WebTestClient`], which resolves relative links to the running server and comes with a dedicated API for verifying responses, as shown in the following example:
include-code::MyRandomPortWebTestClientTests[]
TIP: `WebTestClient` can also used with a xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.with-mock-environment[mock environment], removing the need for a running server, by annotating your test class with `@AutoConfigureWebTestClient`.
TIP: javadoc:org.springframework.test.web.reactive.server.WebTestClient[] can also used with a xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.with-mock-environment[mock environment], removing the need for a running server, by annotating your test class with javadoc:org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient[format=annotation].
This setup requires `spring-webflux` on the classpath.
If you can not or will not add webflux, Spring Boot also provides a `TestRestTemplate` facility:
If you can not or will not add webflux, Spring Boot also provides a javadoc:org.springframework.boot.test.web.client.TestRestTemplate[] facility:
include-code::MyRandomPortTestRestTemplateTests[]
@ -192,8 +192,8 @@ include-code::MyRandomPortTestRestTemplateTests[]
[[testing.spring-boot-applications.customizing-web-test-client]]
== Customizing WebTestClient
To customize the `WebTestClient` bean, configure a `WebTestClientBuilderCustomizer` bean.
Any such beans are called with the `WebTestClient.Builder` that is used to create the `WebTestClient`.
To customize the javadoc:org.springframework.test.web.reactive.server.WebTestClient[] bean, configure a javadoc:org.springframework.boot.test.web.reactive.server.WebTestClientBuilderCustomizer[] bean.
Any such beans are called with the javadoc:org.springframework.test.web.reactive.server.WebTestClient$Builder[] that is used to create the javadoc:org.springframework.test.web.reactive.server.WebTestClient[].
@ -201,7 +201,7 @@ Any such beans are called with the `WebTestClient.Builder` that is used to creat
== Using JMX
As the test context framework caches context, JMX is disabled by default to prevent identical components to register on the same domain.
If such test needs access to an `MBeanServer`, consider marking it dirty as well:
If such test needs access to an javadoc:javax.management.MBeanServer[], consider marking it dirty as well:
include-code::MyJmxTests[]
@ -210,33 +210,33 @@ include-code::MyJmxTests[]
[[testing.spring-boot-applications.observations]]
== Using Observations
If you annotate xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.autoconfigured-tests[a sliced test] with `@AutoConfigureObservability`, it auto-configures an `ObservationRegistry`.
If you annotate xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.autoconfigured-tests[a sliced test] with javadoc:org.springframework.boot.test.autoconfigure.actuate.observability.AutoConfigureObservability[format=annotation], it auto-configures an javadoc:io.micrometer.observation.ObservationRegistry[].
[[testing.spring-boot-applications.metrics]]
== Using Metrics
Regardless of your classpath, meter registries, except the in-memory backed, are not auto-configured when using `@SpringBootTest`.
Regardless of your classpath, meter registries, except the in-memory backed, are not auto-configured when using javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation].
If you need to export metrics to a different backend as part of an integration test, annotate it with `@AutoConfigureObservability`.
If you need to export metrics to a different backend as part of an integration test, annotate it with javadoc:org.springframework.boot.test.autoconfigure.actuate.observability.AutoConfigureObservability[format=annotation].
If you annotate xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.autoconfigured-tests[a sliced test] with `@AutoConfigureObservability`, it auto-configures an in-memory `MeterRegistry`.
Data exporting in sliced tests is not supported with the `@AutoConfigureObservability` annotation.
If you annotate xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.autoconfigured-tests[a sliced test] with javadoc:org.springframework.boot.test.autoconfigure.actuate.observability.AutoConfigureObservability[format=annotation], it auto-configures an in-memory javadoc:io.micrometer.core.instrument.MeterRegistry[].
Data exporting in sliced tests is not supported with the javadoc:org.springframework.boot.test.autoconfigure.actuate.observability.AutoConfigureObservability[format=annotation] annotation.
[[testing.spring-boot-applications.tracing]]
== Using Tracing
Regardless of your classpath, tracing components which are reporting data are not auto-configured when using `@SpringBootTest`.
Regardless of your classpath, tracing components which are reporting data are not auto-configured when using javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation].
If you need those components as part of an integration test, annotate the test with `@AutoConfigureObservability`.
If you need those components as part of an integration test, annotate the test with javadoc:org.springframework.boot.test.autoconfigure.actuate.observability.AutoConfigureObservability[format=annotation].
If you have created your own reporting components (e.g. a custom `SpanExporter` or `+brave.handler.SpanHandler+`) and you don't want them to be active in tests, you can use the `@ConditionalOnEnabledTracing` annotation to disable them.
If you have created your own reporting components (e.g. a custom javadoc:io.opentelemetry.sdk.trace.export.SpanExporter[] or `+brave.handler.SpanHandler+`) and you don't want them to be active in tests, you can use the javadoc:org.springframework.boot.actuate.autoconfigure.tracing.ConditionalOnEnabledTracing[format=annotation] annotation to disable them.
If you annotate xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.autoconfigured-tests[a sliced test] with `@AutoConfigureObservability`, it auto-configures a no-op `io.micrometer.tracing.Tracer`.
Data exporting in sliced tests is not supported with the `@AutoConfigureObservability` annotation.
If you annotate xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.autoconfigured-tests[a sliced test] with javadoc:org.springframework.boot.test.autoconfigure.actuate.observability.AutoConfigureObservability[format=annotation], it auto-configures a no-op javadoc:io.micrometer.tracing.Tracer[].
Data exporting in sliced tests is not supported with the javadoc:org.springframework.boot.test.autoconfigure.actuate.observability.AutoConfigureObservability[format=annotation] annotation.
@ -247,8 +247,8 @@ When running tests, it is sometimes necessary to mock certain components within
For example, you may have a facade over some remote service that is unavailable during development.
Mocking can also be useful when you want to simulate failures that might be hard to trigger in a real environment.
Spring Framework includes a `@MockitoBean` annotation that can be used to define a Mockito mock for a bean inside your `ApplicationContext`.
Additionally, `@MockitoSpyBean` can be used to define a Mockito spy.
Spring Framework includes a javadoc:org.springframework.test.context.bean.override.mockito.MockitoBean[format=annotation] annotation that can be used to define a Mockito mock for a bean inside your javadoc:org.springframework.context.ApplicationContext[].
Additionally, javadoc:org.springframework.test.context.bean.override.mockito.MockitoSpyBean[format=annotation] can be used to define a Mockito spy.
Learn more about these features in the {url-spring-framework-docs}/testing/annotations/integration-spring/annotation-mockitobean.html[Spring Framework documentation].
@ -261,7 +261,7 @@ It often helps to load only the parts of the configuration that are required to
For example, you might want to test that Spring MVC controllers are mapping URLs correctly, and you do not want to involve database calls in those tests, or you might want to test JPA entities, and you are not interested in the web layer when those tests run.
The `spring-boot-test-autoconfigure` module includes a number of annotations that can be used to automatically configure such "`slices`".
Each of them works in a similar way, providing a `+@...Test+` annotation that loads the `ApplicationContext` and one or more `+@AutoConfigure...+` annotations that can be used to customize auto-configuration settings.
Each of them works in a similar way, providing a `+@...Test+` annotation that loads the javadoc:org.springframework.context.ApplicationContext[] and one or more `+@AutoConfigure...+` annotations that can be used to customize auto-configuration settings.
NOTE: Each slice restricts component scan to appropriate components and loads a very restricted set of auto-configuration classes.
If you need to exclude one of them, most `+@...Test+` annotations provide an `excludeAutoConfiguration` attribute.
@ -270,7 +270,7 @@ Alternatively, you can use `@ImportAutoConfiguration#exclude`.
NOTE: Including multiple "`slices`" by using several `+@...Test+` annotations in one test is not supported.
If you need multiple "`slices`", pick one of the `+@...Test+` annotations and include the `+@AutoConfigure...+` annotations of the other "`slices`" by hand.
TIP: It is also possible to use the `+@AutoConfigure...+` annotations with the standard `@SpringBootTest` annotation.
TIP: It is also possible to use the `+@AutoConfigure...+` annotations with the standard javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation] annotation.
You can use this combination if you are not interested in "`slicing`" your application but you want some of the auto-configured test beans.
@ -278,26 +278,26 @@ You can use this combination if you are not interested in "`slicing`" your appli
[[testing.spring-boot-applications.json-tests]]
== Auto-configured JSON Tests
To test that object JSON serialization and deserialization is working as expected, you can use the `@JsonTest` annotation.
`@JsonTest` auto-configures the available supported JSON mapper, which can be one of the following libraries:
To test that object JSON serialization and deserialization is working as expected, you can use the javadoc:org.springframework.boot.test.autoconfigure.json.JsonTest[format=annotation] annotation.
javadoc:org.springframework.boot.test.autoconfigure.json.JsonTest[format=annotation] auto-configures the available supported JSON mapper, which can be one of the following libraries:
* Jackson `ObjectMapper`, any `@JsonComponent` beans and any Jackson `com.fasterxml.jackson.databind.Module`
* Jackson javadoc:com.fasterxml.jackson.databind.ObjectMapper[], any javadoc:org.springframework.boot.jackson.JsonComponent[format=annotation] beans and any Jackson javadoc:com.fasterxml.jackson.databind.Module[]
* `+Gson+`
* `+Jsonb+`
TIP: A list of the auto-configurations that are enabled by `@JsonTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
TIP: A list of the auto-configurations that are enabled by javadoc:org.springframework.boot.test.autoconfigure.json.JsonTest[format=annotation] can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
If you need to configure elements of the auto-configuration, you can use the `@AutoConfigureJsonTesters` annotation.
If you need to configure elements of the auto-configuration, you can use the javadoc:org.springframework.boot.test.autoconfigure.json.AutoConfigureJsonTesters[format=annotation] annotation.
Spring Boot includes AssertJ-based helpers that work with the JSONAssert and JsonPath libraries to check that JSON appears as expected.
The `JacksonTester`, `GsonTester`, `JsonbTester`, and `BasicJsonTester` classes can be used for Jackson, Gson, Jsonb, and Strings respectively.
Any helper fields on the test class can be `@Autowired` when using `@JsonTest`.
The javadoc:org.springframework.boot.test.json.JacksonTester[], javadoc:org.springframework.boot.test.json.GsonTester[], javadoc:org.springframework.boot.test.json.JsonbTester[], and javadoc:org.springframework.boot.test.json.BasicJsonTester[] classes can be used for Jackson, Gson, Jsonb, and Strings respectively.
Any helper fields on the test class can be javadoc:org.springframework.beans.factory.annotation.Autowired[format=annotation] when using javadoc:org.springframework.boot.test.autoconfigure.json.JsonTest[format=annotation].
The following example shows a test class for Jackson:
include-code::MyJsonTests[]
NOTE: JSON helper classes can also be used directly in standard unit tests.
To do so, call the `initFields` method of the helper in your `@BeforeEach` method if you do not use `@JsonTest`.
To do so, call the `initFields` method of the helper in your javadoc:org.junit.jupiter.api.BeforeEach[format=annotation] method if you do not use javadoc:org.springframework.boot.test.autoconfigure.json.JsonTest[format=annotation].
If you use Spring Boot's AssertJ-based helpers to assert on a number value at a given JSON path, you might not be able to use `isEqualTo` depending on the type.
Instead, you can use AssertJ's `satisfies` to assert that the value matches the given condition.
@ -310,42 +310,42 @@ include-code::MyJsonAssertJTests[tag=*]
[[testing.spring-boot-applications.spring-mvc-tests]]
== Auto-configured Spring MVC Tests
To test whether Spring MVC controllers are working as expected, use the `@WebMvcTest` annotation.
`@WebMvcTest` auto-configures the Spring MVC infrastructure and limits scanned beans to `@Controller`, `@ControllerAdvice`, `@JsonComponent`, `org.springframework.core.convert.converter.Converter`, `org.springframework.core.convert.converter.GenericConverter`, `Filter`, `HandlerInterceptor`, `WebMvcConfigurer`, `WebMvcRegistrations`, and `org.springframework.web.method.support.HandlerMethodArgumentResolver`.
Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@WebMvcTest` annotation is used.
`@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans.
To test whether Spring MVC controllers are working as expected, use the javadoc:org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest[format=annotation] annotation.
javadoc:org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest[format=annotation] auto-configures the Spring MVC infrastructure and limits scanned beans to javadoc:org.springframework.stereotype.Controller[format=annotation], javadoc:org.springframework.web.bind.annotation.ControllerAdvice[format=annotation], javadoc:org.springframework.boot.jackson.JsonComponent[format=annotation], javadoc:org.springframework.core.convert.converter.Converter[], javadoc:org.springframework.core.convert.converter.GenericConverter[], javadoc:jakarta.servlet.Filter[], javadoc:org.springframework.web.servlet.HandlerInterceptor[], javadoc:org.springframework.web.servlet.config.annotation.WebMvcConfigurer[], javadoc:org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations[], and javadoc:org.springframework.web.method.support.HandlerMethodArgumentResolver[].
Regular javadoc:org.springframework.stereotype.Component[format=annotation] and javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans are not scanned when the javadoc:org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest[format=annotation] annotation is used.
javadoc:org.springframework.boot.context.properties.EnableConfigurationProperties[format=annotation] can be used to include javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans.
TIP: A list of the auto-configuration settings that are enabled by `@WebMvcTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
TIP: A list of the auto-configuration settings that are enabled by javadoc:org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest[format=annotation] can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
TIP: If you need to register extra components, such as the Jackson `com.fasterxml.jackson.databind.Module`, you can import additional configuration classes by using `@Import` on your test.
TIP: If you need to register extra components, such as the Jackson javadoc:com.fasterxml.jackson.databind.Module[], you can import additional configuration classes by using javadoc:org.springframework.context.annotation.Import[format=annotation] on your test.
Often, `@WebMvcTest` is limited to a single controller and is used in combination with `@MockBean` to provide mock implementations for required collaborators.
Often, javadoc:org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest[format=annotation] is limited to a single controller and is used in combination with javadoc:org.springframework.boot.test.mock.mockito.MockBean[format=annotation] to provide mock implementations for required collaborators.
`@WebMvcTest` also auto-configures `MockMvc`.
javadoc:org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest[format=annotation] also auto-configures javadoc:org.springframework.test.web.servlet.MockMvc[].
Mock MVC offers a powerful way to quickly test MVC controllers without needing to start a full HTTP server.
If AssertJ is available, the AssertJ support provided by `MockMvcTester` is auto-configured as well.
If AssertJ is available, the AssertJ support provided by javadoc:org.springframework.test.web.servlet.assertj.MockMvcTester[] is auto-configured as well.
TIP: You can also auto-configure `MockMvc` and `MockMvcTester` in a non-`@WebMvcTest` (such as `@SpringBootTest`) by annotating it with `@AutoConfigureMockMvc`.
The following example uses `MockMvcTester`:
TIP: You can also auto-configure javadoc:org.springframework.test.web.servlet.MockMvc[] and javadoc:org.springframework.test.web.servlet.assertj.MockMvcTester[] in a non-`@WebMvcTest` (such as javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation]) by annotating it with javadoc:org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc[format=annotation].
The following example uses javadoc:org.springframework.test.web.servlet.assertj.MockMvcTester[]:
include-code::MyControllerTests[]
TIP: If you need to configure elements of the auto-configuration (for example, when servlet filters should be applied) you can use attributes in the `@AutoConfigureMockMvc` annotation.
TIP: If you need to configure elements of the auto-configuration (for example, when servlet filters should be applied) you can use attributes in the javadoc:org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc[format=annotation] annotation.
If you use HtmlUnit and Selenium, auto-configuration also provides an HtmlUnit `WebClient` bean and/or a Selenium `WebDriver` bean.
If you use HtmlUnit and Selenium, auto-configuration also provides an HtmlUnit javadoc:org.springframework.web.reactive.function.client.WebClient[] bean and/or a Selenium javadoc:org.openqa.selenium.WebDriver[] bean.
The following example uses HtmlUnit:
include-code::MyHtmlUnitTests[]
NOTE: By default, Spring Boot puts `WebDriver` beans in a special "`scope`" to ensure that the driver exits after each test and that a new instance is injected.
If you do not want this behavior, you can add `@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)` to your `WebDriver` `@Bean` definition.
NOTE: By default, Spring Boot puts javadoc:org.openqa.selenium.WebDriver[] beans in a special "`scope`" to ensure that the driver exits after each test and that a new instance is injected.
If you do not want this behavior, you can add `@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)` to your javadoc:org.openqa.selenium.WebDriver[] javadoc:org.springframework.context.annotation.Bean[format=annotation] definition.
WARNING: The `webDriver` scope created by Spring Boot will replace any user defined scope of the same name.
If you define your own `webDriver` scope you may find it stops working when you use `@WebMvcTest`.
If you define your own `webDriver` scope you may find it stops working when you use javadoc:org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest[format=annotation].
If you have Spring Security on the classpath, `@WebMvcTest` will also scan `WebSecurityConfigurer` beans.
If you have Spring Security on the classpath, javadoc:org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest[format=annotation] will also scan javadoc:org.springframework.security.config.annotation.web.WebSecurityConfigurer[] beans.
Instead of disabling security completely for such tests, you can use Spring Security's test support.
More details on how to use Spring Security's `MockMvc` support can be found in this xref:how-to:testing.adoc#howto.testing.with-spring-security[] "`How-to Guides`" section.
More details on how to use Spring Security's javadoc:org.springframework.test.web.servlet.MockMvc[] support can be found in this xref:how-to:testing.adoc#howto.testing.with-spring-security[] "`How-to Guides`" section.
TIP: Sometimes writing Spring MVC tests is not enough; Spring Boot can help you run xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.with-running-server[full end-to-end tests with an actual server].
@ -354,31 +354,31 @@ TIP: Sometimes writing Spring MVC tests is not enough; Spring Boot can help you
[[testing.spring-boot-applications.spring-webflux-tests]]
== Auto-configured Spring WebFlux Tests
To test that {url-spring-framework-docs}/web-reactive.html[Spring WebFlux] controllers are working as expected, you can use the `@WebFluxTest` annotation.
`@WebFluxTest` auto-configures the Spring WebFlux infrastructure and limits scanned beans to `@Controller`, `@ControllerAdvice`, `@JsonComponent`, `org.springframework.core.convert.converter.Converter`, `org.springframework.core.convert.converter.GenericConverter` and `WebFluxConfigurer`.
Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@WebFluxTest` annotation is used.
`@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans.
To test that {url-spring-framework-docs}/web-reactive.html[Spring WebFlux] controllers are working as expected, you can use the javadoc:org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest[format=annotation] annotation.
javadoc:org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest[format=annotation] auto-configures the Spring WebFlux infrastructure and limits scanned beans to javadoc:org.springframework.stereotype.Controller[format=annotation], javadoc:org.springframework.web.bind.annotation.ControllerAdvice[format=annotation], javadoc:org.springframework.boot.jackson.JsonComponent[format=annotation], javadoc:org.springframework.core.convert.converter.Converter[], javadoc:org.springframework.core.convert.converter.GenericConverter[] and javadoc:org.springframework.web.reactive.config.WebFluxConfigurer[].
Regular javadoc:org.springframework.stereotype.Component[format=annotation] and javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans are not scanned when the javadoc:org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest[format=annotation] annotation is used.
javadoc:org.springframework.boot.context.properties.EnableConfigurationProperties[format=annotation] can be used to include javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans.
TIP: A list of the auto-configurations that are enabled by `@WebFluxTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
TIP: A list of the auto-configurations that are enabled by javadoc:org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest[format=annotation] can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
TIP: If you need to register extra components, such as Jackson `com.fasterxml.jackson.databind.Module`, you can import additional configuration classes using `@Import` on your test.
TIP: If you need to register extra components, such as Jackson javadoc:com.fasterxml.jackson.databind.Module[], you can import additional configuration classes using javadoc:org.springframework.context.annotation.Import[format=annotation] on your test.
Often, `@WebFluxTest` is limited to a single controller and used in combination with the `@MockBean` annotation to provide mock implementations for required collaborators.
Often, javadoc:org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest[format=annotation] is limited to a single controller and used in combination with the javadoc:org.springframework.boot.test.mock.mockito.MockBean[format=annotation] annotation to provide mock implementations for required collaborators.
`@WebFluxTest` also auto-configures {url-spring-framework-docs}/testing/webtestclient.html[`WebTestClient`], which offers a powerful way to quickly test WebFlux controllers without needing to start a full HTTP server.
javadoc:org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest[format=annotation] also auto-configures {url-spring-framework-docs}/testing/webtestclient.html[`WebTestClient`], which offers a powerful way to quickly test WebFlux controllers without needing to start a full HTTP server.
TIP: You can also auto-configure `WebTestClient` in a non-`@WebFluxTest` (such as `@SpringBootTest`) by annotating it with `@AutoConfigureWebTestClient`.
The following example shows a class that uses both `@WebFluxTest` and a `WebTestClient`:
TIP: You can also auto-configure javadoc:org.springframework.test.web.reactive.server.WebTestClient[] in a non-`@WebFluxTest` (such as javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation]) by annotating it with javadoc:org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient[format=annotation].
The following example shows a class that uses both javadoc:org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest[format=annotation] and a javadoc:org.springframework.test.web.reactive.server.WebTestClient[]:
include-code::MyControllerTests[]
TIP: This setup is only supported by WebFlux applications as using `WebTestClient` in a mocked web application only works with WebFlux at the moment.
TIP: This setup is only supported by WebFlux applications as using javadoc:org.springframework.test.web.reactive.server.WebTestClient[] in a mocked web application only works with WebFlux at the moment.
NOTE: `@WebFluxTest` cannot detect routes registered through the functional web framework.
For testing `org.springframework.web.reactive.function.server.RouterFunction` beans in the context, consider importing your `org.springframework.web.reactive.function.server.RouterFunction` yourself by using `@Import` or by using `@SpringBootTest`.
NOTE: javadoc:org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest[format=annotation] cannot detect routes registered through the functional web framework.
For testing javadoc:org.springframework.web.reactive.function.server.RouterFunction[] beans in the context, consider importing your javadoc:org.springframework.web.reactive.function.server.RouterFunction[] yourself by using javadoc:org.springframework.context.annotation.Import[format=annotation] or by using javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation].
NOTE: `@WebFluxTest` cannot detect custom security configuration registered as a `@Bean` of type `SecurityWebFilterChain`.
To include that in your test, you will need to import the configuration that registers the bean by using `@Import` or by using `@SpringBootTest`.
NOTE: javadoc:org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest[format=annotation] cannot detect custom security configuration registered as a javadoc:org.springframework.context.annotation.Bean[format=annotation] of type javadoc:org.springframework.security.web.server.SecurityWebFilterChain[].
To include that in your test, you will need to import the configuration that registers the bean by using javadoc:org.springframework.context.annotation.Import[format=annotation] or by using javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation].
TIP: Sometimes writing Spring WebFlux tests is not enough; Spring Boot can help you run xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.with-running-server[full end-to-end tests with an actual server].
@ -419,26 +419,26 @@ dependencies {
This testing module ships the {url-spring-graphql-docs}/testing.html#testing.graphqltester[GraphQlTester].
The tester is heavily used in test, so be sure to become familiar with using it.
There are `GraphQlTester` variants and Spring Boot will auto-configure them depending on the type of tests:
There are javadoc:org.springframework.graphql.test.tester.GraphQlTester[] variants and Spring Boot will auto-configure them depending on the type of tests:
* the `ExecutionGraphQlServiceTester` performs tests on the server side, without a client nor a transport
* the `HttpGraphQlTester` performs tests with a client that connects to a server, with or without a live server
* the javadoc:org.springframework.graphql.test.tester.ExecutionGraphQlServiceTester[] performs tests on the server side, without a client nor a transport
* the javadoc:org.springframework.graphql.test.tester.HttpGraphQlTester[] performs tests with a client that connects to a server, with or without a live server
Spring Boot helps you to test your {url-spring-graphql-docs}/controllers.html[Spring GraphQL Controllers] with the `@GraphQlTest` annotation.
`@GraphQlTest` auto-configures the Spring GraphQL infrastructure, without any transport nor server being involved.
This limits scanned beans to `@Controller`, `RuntimeWiringConfigurer`, `JsonComponent`, `org.springframework.core.convert.converter.Converter`, `org.springframework.core.convert.converter.GenericConverter`, `DataFetcherExceptionResolver`, `graphql.execution.instrumentation.Instrumentation` and `GraphQlSourceBuilderCustomizer`.
Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@GraphQlTest` annotation is used.
`@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans.
Spring Boot helps you to test your {url-spring-graphql-docs}/controllers.html[Spring GraphQL Controllers] with the javadoc:org.springframework.boot.test.autoconfigure.graphql.GraphQlTest[format=annotation] annotation.
javadoc:org.springframework.boot.test.autoconfigure.graphql.GraphQlTest[format=annotation] auto-configures the Spring GraphQL infrastructure, without any transport nor server being involved.
This limits scanned beans to javadoc:org.springframework.stereotype.Controller[format=annotation], javadoc:org.springframework.graphql.execution.RuntimeWiringConfigurer[], javadoc:org.springframework.boot.jackson.JsonComponent[], javadoc:org.springframework.core.convert.converter.Converter[], javadoc:org.springframework.core.convert.converter.GenericConverter[], javadoc:org.springframework.graphql.execution.DataFetcherExceptionResolver[], javadoc:graphql.execution.instrumentation.Instrumentation[] and javadoc:org.springframework.boot.autoconfigure.graphql.GraphQlSourceBuilderCustomizer[].
Regular javadoc:org.springframework.stereotype.Component[format=annotation] and javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans are not scanned when the javadoc:org.springframework.boot.test.autoconfigure.graphql.GraphQlTest[format=annotation] annotation is used.
javadoc:org.springframework.boot.context.properties.EnableConfigurationProperties[format=annotation] can be used to include javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans.
TIP: A list of the auto-configurations that are enabled by `@GraphQlTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
TIP: A list of the auto-configurations that are enabled by javadoc:org.springframework.boot.test.autoconfigure.graphql.GraphQlTest[format=annotation] can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
Often, `@GraphQlTest` is limited to a set of controllers and used in combination with the `@MockBean` annotation to provide mock implementations for required collaborators.
Often, javadoc:org.springframework.boot.test.autoconfigure.graphql.GraphQlTest[format=annotation] is limited to a set of controllers and used in combination with the javadoc:org.springframework.boot.test.mock.mockito.MockBean[format=annotation] annotation to provide mock implementations for required collaborators.
include-code::GreetingControllerTests[]
`@SpringBootTest` tests are full integration tests and involve the entire application.
When using a random or defined port, a live server is configured and an `HttpGraphQlTester` bean is contributed automatically so you can use it to test your server.
When a MOCK environment is configured, you can also request an `HttpGraphQlTester` bean by annotating your test class with `@AutoConfigureHttpGraphQlTester`:
javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation] tests are full integration tests and involve the entire application.
When using a random or defined port, a live server is configured and an javadoc:org.springframework.graphql.test.tester.HttpGraphQlTester[] bean is contributed automatically so you can use it to test your server.
When a MOCK environment is configured, you can also request an javadoc:org.springframework.graphql.test.tester.HttpGraphQlTester[] bean by annotating your test class with javadoc:org.springframework.boot.test.autoconfigure.graphql.tester.AutoConfigureHttpGraphQlTester[format=annotation]:
include-code::GraphQlIntegrationTests[]
@ -447,13 +447,13 @@ include-code::GraphQlIntegrationTests[]
[[testing.spring-boot-applications.autoconfigured-spring-data-cassandra]]
== Auto-configured Data Cassandra Tests
You can use `@DataCassandraTest` to test Cassandra applications.
By default, it configures a `CassandraTemplate`, scans for `@org.springframework.data.cassandra.core.mapping.Table` classes, and configures Spring Data Cassandra repositories.
Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataCassandraTest` annotation is used.
`@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans.
You can use javadoc:org.springframework.boot.test.autoconfigure.data.cassandra.DataCassandraTest[format=annotation] to test Cassandra applications.
By default, it configures a javadoc:org.springframework.data.cassandra.core.CassandraTemplate[], scans for javadoc:org.springframework.data.cassandra.core.mapping.Table[format=annotation] classes, and configures Spring Data Cassandra repositories.
Regular javadoc:org.springframework.stereotype.Component[format=annotation] and javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans are not scanned when the javadoc:org.springframework.boot.test.autoconfigure.data.cassandra.DataCassandraTest[format=annotation] annotation is used.
javadoc:org.springframework.boot.context.properties.EnableConfigurationProperties[format=annotation] can be used to include javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans.
(For more about using Cassandra with Spring Boot, see xref:data/nosql.adoc#data.nosql.cassandra[].)
TIP: A list of the auto-configuration settings that are enabled by `@DataCassandraTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
TIP: A list of the auto-configuration settings that are enabled by javadoc:org.springframework.boot.test.autoconfigure.data.cassandra.DataCassandraTest[format=annotation] can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
The following example shows a typical setup for using Cassandra tests in Spring Boot:
@ -464,13 +464,13 @@ include-code::MyDataCassandraTests[]
[[testing.spring-boot-applications.autoconfigured-spring-data-couchbase]]
== Auto-configured Data Couchbase Tests
You can use `@DataCouchbaseTest` to test Couchbase applications.
By default, it configures a `CouchbaseTemplate` or `ReactiveCouchbaseTemplate`, scans for `@org.springframework.data.couchbase.core.mapping.Document` classes, and configures Spring Data Couchbase repositories.
Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataCouchbaseTest` annotation is used.
`@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans.
You can use javadoc:org.springframework.boot.test.autoconfigure.data.couchbase.DataCouchbaseTest[format=annotation] to test Couchbase applications.
By default, it configures a javadoc:org.springframework.data.couchbase.core.CouchbaseTemplate[] or javadoc:org.springframework.data.couchbase.core.ReactiveCouchbaseTemplate[], scans for javadoc:org.springframework.data.couchbase.core.mapping.Document[format=annotation] classes, and configures Spring Data Couchbase repositories.
Regular javadoc:org.springframework.stereotype.Component[format=annotation] and javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans are not scanned when the javadoc:org.springframework.boot.test.autoconfigure.data.couchbase.DataCouchbaseTest[format=annotation] annotation is used.
javadoc:org.springframework.boot.context.properties.EnableConfigurationProperties[format=annotation] can be used to include javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans.
(For more about using Couchbase with Spring Boot, see xref:data/nosql.adoc#data.nosql.couchbase[], earlier in this chapter.)
TIP: A list of the auto-configuration settings that are enabled by `@DataCouchbaseTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
TIP: A list of the auto-configuration settings that are enabled by javadoc:org.springframework.boot.test.autoconfigure.data.couchbase.DataCouchbaseTest[format=annotation] can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
The following example shows a typical setup for using Couchbase tests in Spring Boot:
@ -481,13 +481,13 @@ include-code::MyDataCouchbaseTests[]
[[testing.spring-boot-applications.autoconfigured-spring-data-elasticsearch]]
== Auto-configured Data Elasticsearch Tests
You can use `@DataElasticsearchTest` to test Elasticsearch applications.
By default, it configures an `ElasticsearchTemplate`, scans for `@org.springframework.data.elasticsearch.annotations.Document` classes, and configures Spring Data Elasticsearch repositories.
Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataElasticsearchTest` annotation is used.
`@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans.
You can use javadoc:org.springframework.boot.test.autoconfigure.data.elasticsearch.DataElasticsearchTest[format=annotation] to test Elasticsearch applications.
By default, it configures an javadoc:org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate[], scans for javadoc:org.springframework.data.elasticsearch.annotations.Document[format=annotation] classes, and configures Spring Data Elasticsearch repositories.
Regular javadoc:org.springframework.stereotype.Component[format=annotation] and javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans are not scanned when the javadoc:org.springframework.boot.test.autoconfigure.data.elasticsearch.DataElasticsearchTest[format=annotation] annotation is used.
javadoc:org.springframework.boot.context.properties.EnableConfigurationProperties[format=annotation] can be used to include javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans.
(For more about using Elasticsearch with Spring Boot, see xref:data/nosql.adoc#data.nosql.elasticsearch[], earlier in this chapter.)
TIP: A list of the auto-configuration settings that are enabled by `@DataElasticsearchTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
TIP: A list of the auto-configuration settings that are enabled by javadoc:org.springframework.boot.test.autoconfigure.data.elasticsearch.DataElasticsearchTest[format=annotation] can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
The following example shows a typical setup for using Elasticsearch tests in Spring Boot:
@ -498,16 +498,16 @@ include-code::MyDataElasticsearchTests[]
[[testing.spring-boot-applications.autoconfigured-spring-data-jpa]]
== Auto-configured Data JPA Tests
You can use the `@DataJpaTest` annotation to test JPA applications.
By default, it scans for `@Entity` classes and configures Spring Data JPA repositories.
You can use the javadoc:org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest[format=annotation] annotation to test JPA applications.
By default, it scans for javadoc:jakarta.persistence.Entity[format=annotation] classes and configures Spring Data JPA repositories.
If an embedded database is available on the classpath, it configures one as well.
SQL queries are logged by default by setting the `spring.jpa.show-sql` property to `true`.
This can be disabled using the `showSql` attribute of the annotation.
Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataJpaTest` annotation is used.
`@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans.
Regular javadoc:org.springframework.stereotype.Component[format=annotation] and javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans are not scanned when the javadoc:org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest[format=annotation] annotation is used.
javadoc:org.springframework.boot.context.properties.EnableConfigurationProperties[format=annotation] can be used to include javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans.
TIP: A list of the auto-configuration settings that are enabled by `@DataJpaTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
TIP: A list of the auto-configuration settings that are enabled by javadoc:org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest[format=annotation] can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
By default, data JPA tests are transactional and roll back at the end of each test.
See the {url-spring-framework-docs}/testing/testcontext-framework/tx.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details.
@ -515,18 +515,18 @@ If that is not what you want, you can disable transaction management for a test
include-code::MyNonTransactionalTests[]
Data JPA tests may also inject a javadoc:org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager[] bean, which provides an alternative to the standard JPA `EntityManager` that is specifically designed for tests.
Data JPA tests may also inject a javadoc:org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager[] bean, which provides an alternative to the standard JPA javadoc:jakarta.persistence.EntityManager[] that is specifically designed for tests.
TIP: `TestEntityManager` can also be auto-configured to any of your Spring-based test class by adding `@AutoConfigureTestEntityManager`.
When doing so, make sure that your test is running in a transaction, for instance by adding `@org.springframework.transaction.annotation.Transactional` on your test class or method.
TIP: javadoc:org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager[] can also be auto-configured to any of your Spring-based test class by adding javadoc:org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestEntityManager[format=annotation].
When doing so, make sure that your test is running in a transaction, for instance by adding javadoc:org.springframework.transaction.annotation.Transactional[format=annotation] on your test class or method.
A `JdbcTemplate` is also available if you need that.
The following example shows the `@DataJpaTest` annotation in use:
A javadoc:org.springframework.jdbc.core.JdbcTemplate[] is also available if you need that.
The following example shows the javadoc:org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest[format=annotation] annotation in use:
include-code::withoutdb/MyRepositoryTests[]
In-memory embedded databases generally work well for tests, since they are fast and do not require any installation.
If, however, you prefer to run tests against a real database you can use the `@AutoConfigureTestDatabase` annotation, as shown in the following example:
If, however, you prefer to run tests against a real database you can use the javadoc:org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase[format=annotation] annotation, as shown in the following example:
include-code::withdb/MyRepositoryTests[]
@ -535,12 +535,12 @@ include-code::withdb/MyRepositoryTests[]
[[testing.spring-boot-applications.autoconfigured-jdbc]]
== Auto-configured JDBC Tests
`@JdbcTest` is similar to `@DataJpaTest` but is for tests that only require a `DataSource` and do not use Spring Data JDBC.
By default, it configures an in-memory embedded database and a `JdbcTemplate`.
Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@JdbcTest` annotation is used.
`@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans.
javadoc:org.springframework.boot.test.autoconfigure.jdbc.JdbcTest[format=annotation] is similar to javadoc:org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest[format=annotation] but is for tests that only require a javadoc:javax.sql.DataSource[] and do not use Spring Data JDBC.
By default, it configures an in-memory embedded database and a javadoc:org.springframework.jdbc.core.JdbcTemplate[].
Regular javadoc:org.springframework.stereotype.Component[format=annotation] and javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans are not scanned when the javadoc:org.springframework.boot.test.autoconfigure.jdbc.JdbcTest[format=annotation] annotation is used.
javadoc:org.springframework.boot.context.properties.EnableConfigurationProperties[format=annotation] can be used to include javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans.
TIP: A list of the auto-configurations that are enabled by `@JdbcTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
TIP: A list of the auto-configurations that are enabled by javadoc:org.springframework.boot.test.autoconfigure.jdbc.JdbcTest[format=annotation] can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
By default, JDBC tests are transactional and roll back at the end of each test.
See the {url-spring-framework-docs}/testing/testcontext-framework/tx.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details.
@ -548,7 +548,7 @@ If that is not what you want, you can disable transaction management for a test
include-code::MyTransactionalTests[]
If you prefer your test to run against a real database, you can use the `@AutoConfigureTestDatabase` annotation in the same way as for `@DataJpaTest`.
If you prefer your test to run against a real database, you can use the javadoc:org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase[format=annotation] annotation in the same way as for javadoc:org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest[format=annotation].
(See xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.autoconfigured-spring-data-jpa[].)
@ -556,18 +556,18 @@ If you prefer your test to run against a real database, you can use the `@AutoCo
[[testing.spring-boot-applications.autoconfigured-spring-data-jdbc]]
== Auto-configured Data JDBC Tests
`@DataJdbcTest` is similar to `@JdbcTest` but is for tests that use Spring Data JDBC repositories.
By default, it configures an in-memory embedded database, a `JdbcTemplate`, and Spring Data JDBC repositories.
Only `AbstractJdbcConfiguration` subclasses are scanned when the `@DataJdbcTest` annotation is used, regular `@Component` and `@ConfigurationProperties` beans are not scanned.
`@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans.
javadoc:org.springframework.boot.test.autoconfigure.data.jdbc.DataJdbcTest[format=annotation] is similar to javadoc:org.springframework.boot.test.autoconfigure.jdbc.JdbcTest[format=annotation] but is for tests that use Spring Data JDBC repositories.
By default, it configures an in-memory embedded database, a javadoc:org.springframework.jdbc.core.JdbcTemplate[], and Spring Data JDBC repositories.
Only javadoc:org.springframework.data.jdbc.repository.config.AbstractJdbcConfiguration[] subclasses are scanned when the javadoc:org.springframework.boot.test.autoconfigure.data.jdbc.DataJdbcTest[format=annotation] annotation is used, regular javadoc:org.springframework.stereotype.Component[format=annotation] and javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans are not scanned.
javadoc:org.springframework.boot.context.properties.EnableConfigurationProperties[format=annotation] can be used to include javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans.
TIP: A list of the auto-configurations that are enabled by `@DataJdbcTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
TIP: A list of the auto-configurations that are enabled by javadoc:org.springframework.boot.test.autoconfigure.data.jdbc.DataJdbcTest[format=annotation] can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
By default, Data JDBC tests are transactional and roll back at the end of each test.
See the {url-spring-framework-docs}/testing/testcontext-framework/tx.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details.
If that is not what you want, you can disable transaction management for a test or for the whole test class as xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.autoconfigured-jdbc[shown in the JDBC example].
If you prefer your test to run against a real database, you can use the `@AutoConfigureTestDatabase` annotation in the same way as for `@DataJpaTest`.
If you prefer your test to run against a real database, you can use the javadoc:org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase[format=annotation] annotation in the same way as for javadoc:org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest[format=annotation].
(See xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.autoconfigured-spring-data-jpa[].)
@ -575,16 +575,16 @@ If you prefer your test to run against a real database, you can use the `@AutoCo
[[testing.spring-boot-applications.autoconfigured-spring-data-r2dbc]]
== Auto-configured Data R2DBC Tests
`@DataR2dbcTest` is similar to `@DataJdbcTest` but is for tests that use Spring Data R2DBC repositories.
By default, it configures an in-memory embedded database, an `R2dbcEntityTemplate`, and Spring Data R2DBC repositories.
Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataR2dbcTest` annotation is used.
`@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans.
javadoc:org.springframework.boot.test.autoconfigure.data.r2dbc.DataR2dbcTest[format=annotation] is similar to javadoc:org.springframework.boot.test.autoconfigure.data.jdbc.DataJdbcTest[format=annotation] but is for tests that use Spring Data R2DBC repositories.
By default, it configures an in-memory embedded database, an javadoc:org.springframework.data.r2dbc.core.R2dbcEntityTemplate[], and Spring Data R2DBC repositories.
Regular javadoc:org.springframework.stereotype.Component[format=annotation] and javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans are not scanned when the javadoc:org.springframework.boot.test.autoconfigure.data.r2dbc.DataR2dbcTest[format=annotation] annotation is used.
javadoc:org.springframework.boot.context.properties.EnableConfigurationProperties[format=annotation] can be used to include javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans.
TIP: A list of the auto-configurations that are enabled by `@DataR2dbcTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
TIP: A list of the auto-configurations that are enabled by javadoc:org.springframework.boot.test.autoconfigure.data.r2dbc.DataR2dbcTest[format=annotation] can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
By default, Data R2DBC tests are not transactional.
If you prefer your test to run against a real database, you can use the `@AutoConfigureTestDatabase` annotation in the same way as for `@DataJpaTest`.
If you prefer your test to run against a real database, you can use the javadoc:org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase[format=annotation] annotation in the same way as for javadoc:org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest[format=annotation].
(See xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.autoconfigured-spring-data-jpa[].)
@ -592,17 +592,17 @@ If you prefer your test to run against a real database, you can use the `@AutoCo
[[testing.spring-boot-applications.autoconfigured-jooq]]
== Auto-configured jOOQ Tests
You can use `@JooqTest` in a similar fashion as `@JdbcTest` but for jOOQ-related tests.
As jOOQ relies heavily on a Java-based schema that corresponds with the database schema, the existing `DataSource` is used.
If you want to replace it with an in-memory database, you can use `@AutoConfigureTestDatabase` to override those settings.
You can use javadoc:org.springframework.boot.test.autoconfigure.jooq.JooqTest[format=annotation] in a similar fashion as javadoc:org.springframework.boot.test.autoconfigure.jdbc.JdbcTest[format=annotation] but for jOOQ-related tests.
As jOOQ relies heavily on a Java-based schema that corresponds with the database schema, the existing javadoc:javax.sql.DataSource[] is used.
If you want to replace it with an in-memory database, you can use javadoc:org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase[format=annotation] to override those settings.
(For more about using jOOQ with Spring Boot, see xref:data/sql.adoc#data.sql.jooq[].)
Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@JooqTest` annotation is used.
`@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans.
Regular javadoc:org.springframework.stereotype.Component[format=annotation] and javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans are not scanned when the javadoc:org.springframework.boot.test.autoconfigure.jooq.JooqTest[format=annotation] annotation is used.
javadoc:org.springframework.boot.context.properties.EnableConfigurationProperties[format=annotation] can be used to include javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans.
TIP: A list of the auto-configurations that are enabled by `@JooqTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
TIP: A list of the auto-configurations that are enabled by javadoc:org.springframework.boot.test.autoconfigure.jooq.JooqTest[format=annotation] can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
`@JooqTest` configures a `DSLContext`.
The following example shows the `@JooqTest` annotation in use:
javadoc:org.springframework.boot.test.autoconfigure.jooq.JooqTest[format=annotation] configures a javadoc:org.jooq.DSLContext[].
The following example shows the javadoc:org.springframework.boot.test.autoconfigure.jooq.JooqTest[format=annotation] annotation in use:
include-code::MyJooqTests[]
@ -614,15 +614,15 @@ If that is not what you want, you can disable transaction management for a test
[[testing.spring-boot-applications.autoconfigured-spring-data-mongodb]]
== Auto-configured Data MongoDB Tests
You can use `@DataMongoTest` to test MongoDB applications.
By default, it configures a `MongoTemplate`, scans for `@org.springframework.data.mongodb.core.mapping.Document` classes, and configures Spring Data MongoDB repositories.
Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataMongoTest` annotation is used.
`@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans.
You can use javadoc:org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest[format=annotation] to test MongoDB applications.
By default, it configures a javadoc:org.springframework.data.mongodb.core.MongoTemplate[], scans for javadoc:org.springframework.data.mongodb.core.mapping.Document[format=annotation] classes, and configures Spring Data MongoDB repositories.
Regular javadoc:org.springframework.stereotype.Component[format=annotation] and javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans are not scanned when the javadoc:org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest[format=annotation] annotation is used.
javadoc:org.springframework.boot.context.properties.EnableConfigurationProperties[format=annotation] can be used to include javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans.
(For more about using MongoDB with Spring Boot, see xref:data/nosql.adoc#data.nosql.mongodb[].)
TIP: A list of the auto-configuration settings that are enabled by `@DataMongoTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
TIP: A list of the auto-configuration settings that are enabled by javadoc:org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest[format=annotation] can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
The following class shows the `@DataMongoTest` annotation in use:
The following class shows the javadoc:org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest[format=annotation] annotation in use:
include-code::MyDataMongoDbTests[]
@ -631,13 +631,13 @@ include-code::MyDataMongoDbTests[]
[[testing.spring-boot-applications.autoconfigured-spring-data-neo4j]]
== Auto-configured Data Neo4j Tests
You can use `@DataNeo4jTest` to test Neo4j applications.
By default, it scans for `@org.springframework.data.neo4j.core.schema.Node` classes, and configures Spring Data Neo4j repositories.
Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataNeo4jTest` annotation is used.
`@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans.
You can use javadoc:org.springframework.boot.test.autoconfigure.data.neo4j.DataNeo4jTest[format=annotation] to test Neo4j applications.
By default, it scans for javadoc:org.springframework.data.neo4j.core.schema.Node[format=annotation] classes, and configures Spring Data Neo4j repositories.
Regular javadoc:org.springframework.stereotype.Component[format=annotation] and javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans are not scanned when the javadoc:org.springframework.boot.test.autoconfigure.data.neo4j.DataNeo4jTest[format=annotation] annotation is used.
javadoc:org.springframework.boot.context.properties.EnableConfigurationProperties[format=annotation] can be used to include javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans.
(For more about using Neo4J with Spring Boot, see xref:data/nosql.adoc#data.nosql.neo4j[].)
TIP: A list of the auto-configuration settings that are enabled by `@DataNeo4jTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
TIP: A list of the auto-configuration settings that are enabled by javadoc:org.springframework.boot.test.autoconfigure.data.neo4j.DataNeo4jTest[format=annotation] can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
The following example shows a typical setup for using Neo4J tests in Spring Boot:
@ -650,22 +650,22 @@ If that is not what you want, you can disable transaction management for a test
include-code::nopropagation/MyDataNeo4jTests[]
NOTE: Transactional tests are not supported with reactive access.
If you are using this style, you must configure `@DataNeo4jTest` tests as described above.
If you are using this style, you must configure javadoc:org.springframework.boot.test.autoconfigure.data.neo4j.DataNeo4jTest[format=annotation] tests as described above.
[[testing.spring-boot-applications.autoconfigured-spring-data-redis]]
== Auto-configured Data Redis Tests
You can use `@DataRedisTest` to test Redis applications.
By default, it scans for `@RedisHash` classes and configures Spring Data Redis repositories.
Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataRedisTest` annotation is used.
`@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans.
You can use javadoc:org.springframework.boot.test.autoconfigure.data.redis.DataRedisTest[format=annotation] to test Redis applications.
By default, it scans for javadoc:org.springframework.data.redis.core.RedisHash[format=annotation] classes and configures Spring Data Redis repositories.
Regular javadoc:org.springframework.stereotype.Component[format=annotation] and javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans are not scanned when the javadoc:org.springframework.boot.test.autoconfigure.data.redis.DataRedisTest[format=annotation] annotation is used.
javadoc:org.springframework.boot.context.properties.EnableConfigurationProperties[format=annotation] can be used to include javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans.
(For more about using Redis with Spring Boot, see xref:data/nosql.adoc#data.nosql.redis[].)
TIP: A list of the auto-configuration settings that are enabled by `@DataRedisTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
TIP: A list of the auto-configuration settings that are enabled by javadoc:org.springframework.boot.test.autoconfigure.data.redis.DataRedisTest[format=annotation] can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
The following example shows the `@DataRedisTest` annotation in use:
The following example shows the javadoc:org.springframework.boot.test.autoconfigure.data.redis.DataRedisTest[format=annotation] annotation in use:
include-code::MyDataRedisTests[]
@ -674,15 +674,15 @@ include-code::MyDataRedisTests[]
[[testing.spring-boot-applications.autoconfigured-spring-data-ldap]]
== Auto-configured Data LDAP Tests
You can use `@DataLdapTest` to test LDAP applications.
By default, it configures an in-memory embedded LDAP (if available), configures an `LdapTemplate`, scans for `@Entry` classes, and configures Spring Data LDAP repositories.
Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataLdapTest` annotation is used.
`@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans.
You can use javadoc:org.springframework.boot.test.autoconfigure.data.ldap.DataLdapTest[format=annotation] to test LDAP applications.
By default, it configures an in-memory embedded LDAP (if available), configures an javadoc:org.springframework.ldap.core.LdapTemplate[], scans for javadoc:org.springframework.ldap.odm.annotations.Entry[format=annotation] classes, and configures Spring Data LDAP repositories.
Regular javadoc:org.springframework.stereotype.Component[format=annotation] and javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans are not scanned when the javadoc:org.springframework.boot.test.autoconfigure.data.ldap.DataLdapTest[format=annotation] annotation is used.
javadoc:org.springframework.boot.context.properties.EnableConfigurationProperties[format=annotation] can be used to include javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans.
(For more about using LDAP with Spring Boot, see xref:data/nosql.adoc#data.nosql.ldap[].)
TIP: A list of the auto-configuration settings that are enabled by `@DataLdapTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
TIP: A list of the auto-configuration settings that are enabled by javadoc:org.springframework.boot.test.autoconfigure.data.ldap.DataLdapTest[format=annotation] can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
The following example shows the `@DataLdapTest` annotation in use:
The following example shows the javadoc:org.springframework.boot.test.autoconfigure.data.ldap.DataLdapTest[format=annotation] annotation in use:
include-code::inmemory/MyDataLdapTests[]
@ -696,20 +696,20 @@ include-code::server/MyDataLdapTests[]
[[testing.spring-boot-applications.autoconfigured-rest-client]]
== Auto-configured REST Clients
You can use the `@RestClientTest` annotation to test REST clients.
By default, it auto-configures Jackson, GSON, and Jsonb support, configures a `RestTemplateBuilder` and a `RestClient.Builder`, and adds support for `MockRestServiceServer`.
Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@RestClientTest` annotation is used.
`@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans.
You can use the javadoc:org.springframework.boot.test.autoconfigure.web.client.RestClientTest[format=annotation] annotation to test REST clients.
By default, it auto-configures Jackson, GSON, and Jsonb support, configures a javadoc:org.springframework.boot.web.client.RestTemplateBuilder[] and a javadoc:org.springframework.web.client.RestClient$Builder[], and adds support for javadoc:org.springframework.test.web.client.MockRestServiceServer[].
Regular javadoc:org.springframework.stereotype.Component[format=annotation] and javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans are not scanned when the javadoc:org.springframework.boot.test.autoconfigure.web.client.RestClientTest[format=annotation] annotation is used.
javadoc:org.springframework.boot.context.properties.EnableConfigurationProperties[format=annotation] can be used to include javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] beans.
TIP: A list of the auto-configuration settings that are enabled by `@RestClientTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
TIP: A list of the auto-configuration settings that are enabled by javadoc:org.springframework.boot.test.autoconfigure.web.client.RestClientTest[format=annotation] can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
The specific beans that you want to test should be specified by using the `value` or `components` attribute of `@RestClientTest`.
The specific beans that you want to test should be specified by using the `value` or `components` attribute of javadoc:org.springframework.boot.test.autoconfigure.web.client.RestClientTest[format=annotation].
When using a `RestTemplateBuilder` in the beans under test and `RestTemplateBuilder.rootUri(String rootUri)` has been called when building the `RestTemplate`, then the root URI should be omitted from the `MockRestServiceServer` expectations as shown in the following example:
When using a javadoc:org.springframework.boot.web.client.RestTemplateBuilder[] in the beans under test and `RestTemplateBuilder.rootUri(String rootUri)` has been called when building the javadoc:org.springframework.web.client.RestTemplate[], then the root URI should be omitted from the javadoc:org.springframework.test.web.client.MockRestServiceServer[] expectations as shown in the following example:
include-code::MyRestTemplateServiceTests[]
When using a `RestClient.Builder` in the beans under test, or when using a `RestTemplateBuilder` without calling `rootUri(String rootURI)`, the full URI must be used in the `MockRestServiceServer` expectations as shown in the following example:
When using a javadoc:org.springframework.web.client.RestClient$Builder[] in the beans under test, or when using a javadoc:org.springframework.boot.web.client.RestTemplateBuilder[] without calling `rootUri(String rootURI)`, the full URI must be used in the javadoc:org.springframework.test.web.client.MockRestServiceServer[] expectations as shown in the following example:
include-code::MyRestClientServiceTests[]
@ -718,10 +718,10 @@ include-code::MyRestClientServiceTests[]
[[testing.spring-boot-applications.autoconfigured-spring-restdocs]]
== Auto-configured Spring REST Docs Tests
You can use the `@AutoConfigureRestDocs` annotation to use {url-spring-restdocs-site}[Spring REST Docs] in your tests with Mock MVC, REST Assured, or WebTestClient.
You can use the javadoc:org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs[format=annotation] annotation to use {url-spring-restdocs-site}[Spring REST Docs] in your tests with Mock MVC, REST Assured, or WebTestClient.
It removes the need for the JUnit extension in Spring REST Docs.
`@AutoConfigureRestDocs` can be used to override the default output directory (`target/generated-snippets` if you are using Maven or `build/generated-snippets` if you are using Gradle).
javadoc:org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs[format=annotation] can be used to override the default output directory (`target/generated-snippets` if you are using Maven or `build/generated-snippets` if you are using Gradle).
It can also be used to configure the host, scheme, and port that appears in any documented URIs.
@ -729,24 +729,24 @@ It can also be used to configure the host, scheme, and port that appears in any
[[testing.spring-boot-applications.autoconfigured-spring-restdocs.with-mock-mvc]]
=== Auto-configured Spring REST Docs Tests With Mock MVC
`@AutoConfigureRestDocs` customizes the `MockMvc` bean to use Spring REST Docs when testing servlet-based web applications.
You can inject it by using `@Autowired` and use it in your tests as you normally would when using Mock MVC and Spring REST Docs, as shown in the following example:
javadoc:org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs[format=annotation] customizes the javadoc:org.springframework.test.web.servlet.MockMvc[] bean to use Spring REST Docs when testing servlet-based web applications.
You can inject it by using javadoc:org.springframework.beans.factory.annotation.Autowired[format=annotation] and use it in your tests as you normally would when using Mock MVC and Spring REST Docs, as shown in the following example:
include-code::hamcrest/MyUserDocumentationTests[]
If you prefer to use the AssertJ integration, `MockMvcTester` is available as well, as shown in the following example:
If you prefer to use the AssertJ integration, javadoc:org.springframework.test.web.servlet.assertj.MockMvcTester[] is available as well, as shown in the following example:
include-code::assertj/MyUserDocumentationTests[]
Both reuses the same `MockMvc` instance behind the scenes so any configuration to it applies to both.
Both reuses the same javadoc:org.springframework.test.web.servlet.MockMvc[] instance behind the scenes so any configuration to it applies to both.
If you require more control over Spring REST Docs configuration than offered by the attributes of `@AutoConfigureRestDocs`, you can use a `RestDocsMockMvcConfigurationCustomizer` bean, as shown in the following example:
If you require more control over Spring REST Docs configuration than offered by the attributes of javadoc:org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs[format=annotation], you can use a javadoc:org.springframework.boot.test.autoconfigure.restdocs.RestDocsMockMvcConfigurationCustomizer[] bean, as shown in the following example:
include-code::MyRestDocsConfiguration[]
If you want to make use of Spring REST Docs support for a parameterized output directory, you can create a `RestDocumentationResultHandler` bean.
The auto-configuration calls `alwaysDo` with this result handler, thereby causing each `MockMvc` call to automatically generate the default snippets.
The following example shows a `RestDocumentationResultHandler` being defined:
If you want to make use of Spring REST Docs support for a parameterized output directory, you can create a javadoc:org.springframework.restdocs.mockmvc.RestDocumentationResultHandler[] bean.
The auto-configuration calls `alwaysDo` with this result handler, thereby causing each javadoc:org.springframework.test.web.servlet.MockMvc[] call to automatically generate the default snippets.
The following example shows a javadoc:org.springframework.restdocs.mockmvc.RestDocumentationResultHandler[] being defined:
include-code::MyResultHandlerConfiguration[]
@ -755,17 +755,17 @@ include-code::MyResultHandlerConfiguration[]
[[testing.spring-boot-applications.autoconfigured-spring-restdocs.with-web-test-client]]
=== Auto-configured Spring REST Docs Tests With WebTestClient
`@AutoConfigureRestDocs` can also be used with `WebTestClient` when testing reactive web applications.
You can inject it by using `@Autowired` and use it in your tests as you normally would when using `@WebFluxTest` and Spring REST Docs, as shown in the following example:
javadoc:org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs[format=annotation] can also be used with javadoc:org.springframework.test.web.reactive.server.WebTestClient[] when testing reactive web applications.
You can inject it by using javadoc:org.springframework.beans.factory.annotation.Autowired[format=annotation] and use it in your tests as you normally would when using javadoc:org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest[format=annotation] and Spring REST Docs, as shown in the following example:
include-code::MyUsersDocumentationTests[]
If you require more control over Spring REST Docs configuration than offered by the attributes of `@AutoConfigureRestDocs`, you can use a `RestDocsWebTestClientConfigurationCustomizer` bean, as shown in the following example:
If you require more control over Spring REST Docs configuration than offered by the attributes of javadoc:org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs[format=annotation], you can use a javadoc:org.springframework.boot.test.autoconfigure.restdocs.RestDocsWebTestClientConfigurationCustomizer[] bean, as shown in the following example:
include-code::MyRestDocsConfiguration[]
If you want to make use of Spring REST Docs support for a parameterized output directory, you can use a `WebTestClientBuilderCustomizer` to configure a consumer for every entity exchange result.
The following example shows such a `WebTestClientBuilderCustomizer` being defined:
If you want to make use of Spring REST Docs support for a parameterized output directory, you can use a javadoc:org.springframework.boot.test.web.reactive.server.WebTestClientBuilderCustomizer[] to configure a consumer for every entity exchange result.
The following example shows such a javadoc:org.springframework.boot.test.web.reactive.server.WebTestClientBuilderCustomizer[] being defined:
include-code::MyWebTestClientBuilderCustomizerConfiguration[]
@ -774,12 +774,12 @@ include-code::MyWebTestClientBuilderCustomizerConfiguration[]
[[testing.spring-boot-applications.autoconfigured-spring-restdocs.with-rest-assured]]
=== Auto-configured Spring REST Docs Tests With REST Assured
`@AutoConfigureRestDocs` makes a `RequestSpecification` bean, preconfigured to use Spring REST Docs, available to your tests.
You can inject it by using `@Autowired` and use it in your tests as you normally would when using REST Assured and Spring REST Docs, as shown in the following example:
javadoc:org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs[format=annotation] makes a javadoc:io.restassured.specification.RequestSpecification[] bean, preconfigured to use Spring REST Docs, available to your tests.
You can inject it by using javadoc:org.springframework.beans.factory.annotation.Autowired[format=annotation] and use it in your tests as you normally would when using REST Assured and Spring REST Docs, as shown in the following example:
include-code::MyUserDocumentationTests[]
If you require more control over Spring REST Docs configuration than offered by the attributes of `@AutoConfigureRestDocs`, a `RestDocsRestAssuredConfigurationCustomizer` bean can be used, as shown in the following example:
If you require more control over Spring REST Docs configuration than offered by the attributes of javadoc:org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs[format=annotation], a javadoc:org.springframework.boot.test.autoconfigure.restdocs.RestDocsRestAssuredConfigurationCustomizer[] bean can be used, as shown in the following example:
include-code::MyRestDocsConfiguration[]
@ -793,14 +793,14 @@ include-code::MyRestDocsConfiguration[]
[[testing.spring-boot-applications.autoconfigured-webservices.client]]
=== Auto-configured Spring Web Services Client Tests
You can use `@WebServiceClientTest` to test applications that call web services using the Spring Web Services project.
By default, it configures a `MockWebServiceServer` bean and automatically customizes your `WebServiceTemplateBuilder`.
You can use javadoc:org.springframework.boot.test.autoconfigure.webservices.client.WebServiceClientTest[format=annotation] to test applications that call web services using the Spring Web Services project.
By default, it configures a javadoc:org.springframework.ws.test.client.MockWebServiceServer[] bean and automatically customizes your javadoc:org.springframework.boot.webservices.client.WebServiceTemplateBuilder[].
(For more about using Web Services with Spring Boot, see xref:io/webservices.adoc[].)
TIP: A list of the auto-configuration settings that are enabled by `@WebServiceClientTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
TIP: A list of the auto-configuration settings that are enabled by javadoc:org.springframework.boot.test.autoconfigure.webservices.client.WebServiceClientTest[format=annotation] can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
The following example shows the `@WebServiceClientTest` annotation in use:
The following example shows the javadoc:org.springframework.boot.test.autoconfigure.webservices.client.WebServiceClientTest[format=annotation] annotation in use:
include-code::MyWebServiceClientTests[]
@ -809,14 +809,14 @@ include-code::MyWebServiceClientTests[]
[[testing.spring-boot-applications.autoconfigured-webservices.server]]
=== Auto-configured Spring Web Services Server Tests
You can use `@WebServiceServerTest` to test applications that implement web services using the Spring Web Services project.
By default, it configures a `MockWebServiceClient` bean that can be used to call your web service endpoints.
You can use javadoc:org.springframework.boot.test.autoconfigure.webservices.server.WebServiceServerTest[format=annotation] to test applications that implement web services using the Spring Web Services project.
By default, it configures a javadoc:org.springframework.ws.test.server.MockWebServiceClient[] bean that can be used to call your web service endpoints.
(For more about using Web Services with Spring Boot, see xref:io/webservices.adoc[].)
TIP: A list of the auto-configuration settings that are enabled by `@WebServiceServerTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
TIP: A list of the auto-configuration settings that are enabled by javadoc:org.springframework.boot.test.autoconfigure.webservices.server.WebServiceServerTest[format=annotation] can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix].
The following example shows the `@WebServiceServerTest` annotation in use:
The following example shows the javadoc:org.springframework.boot.test.autoconfigure.webservices.server.WebServiceServerTest[format=annotation] annotation in use:
include-code::MyWebServiceServerTests[]
@ -826,11 +826,11 @@ include-code::MyWebServiceServerTests[]
== Additional Auto-configuration and Slicing
Each slice provides one or more `+@AutoConfigure...+` annotations that namely defines the auto-configurations that should be included as part of a slice.
Additional auto-configurations can be added on a test-by-test basis by creating a custom `+@AutoConfigure...+` annotation or by adding `@ImportAutoConfiguration` to the test as shown in the following example:
Additional auto-configurations can be added on a test-by-test basis by creating a custom `+@AutoConfigure...+` annotation or by adding javadoc:org.springframework.boot.autoconfigure.ImportAutoConfiguration[format=annotation] to the test as shown in the following example:
include-code::MyJdbcTests[]
NOTE: Make sure to not use the regular `@Import` annotation to import auto-configurations as they are handled in a specific way by Spring Boot.
NOTE: Make sure to not use the regular javadoc:org.springframework.context.annotation.Import[format=annotation] annotation to import auto-configurations as they are handled in a specific way by Spring Boot.
Alternatively, additional auto-configurations can be added for any use of a slice annotation by registering them in a file stored in `META-INF/spring` as shown in the following example:
@ -840,41 +840,41 @@ Alternatively, additional auto-configurations can be added for any use of a slic
com.example.IntegrationAutoConfiguration
----
In this example, the `+com.example.IntegrationAutoConfiguration+` is enabled on every test annotated with `@JdbcTest`.
In this example, the `+com.example.IntegrationAutoConfiguration+` is enabled on every test annotated with javadoc:org.springframework.boot.test.autoconfigure.jdbc.JdbcTest[format=annotation].
TIP: You can use comments with `#` in this file.
TIP: A slice or `+@AutoConfigure...+` annotation can be customized this way as long as it is meta-annotated with `@ImportAutoConfiguration`.
TIP: A slice or `+@AutoConfigure...+` annotation can be customized this way as long as it is meta-annotated with javadoc:org.springframework.boot.autoconfigure.ImportAutoConfiguration[format=annotation].
[[testing.spring-boot-applications.user-configuration-and-slicing]]
== User Configuration and Slicing
If you xref:using/structuring-your-code.adoc[structure your code] in a sensible way, your `@SpringBootApplication` class is xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.detecting-configuration[used by default] as the configuration of your tests.
If you xref:using/structuring-your-code.adoc[structure your code] in a sensible way, your javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation] class is xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.detecting-configuration[used by default] as the configuration of your tests.
It then becomes important not to litter the application's main class with configuration settings that are specific to a particular area of its functionality.
Assume that you are using Spring Data MongoDB, you rely on the auto-configuration for it, and you have enabled auditing.
You could define your `@SpringBootApplication` as follows:
You could define your javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation] as follows:
include-code::MyApplication[]
Because this class is the source configuration for the test, any slice test actually tries to enable Mongo auditing, which is definitely not what you want to do.
A recommended approach is to move that area-specific configuration to a separate `@Configuration` class at the same level as your application, as shown in the following example:
A recommended approach is to move that area-specific configuration to a separate javadoc:org.springframework.context.annotation.Configuration[format=annotation] class at the same level as your application, as shown in the following example:
include-code::MyMongoConfiguration[]
NOTE: Depending on the complexity of your application, you may either have a single `@Configuration` class for your customizations or one class per domain area.
The latter approach lets you enable it in one of your tests, if necessary, with the `@Import` annotation.
See xref:how-to:testing.adoc#howto.testing.slice-tests[this how-to section] for more details on when you might want to enable specific `@Configuration` classes for slice tests.
NOTE: Depending on the complexity of your application, you may either have a single javadoc:org.springframework.context.annotation.Configuration[format=annotation] class for your customizations or one class per domain area.
The latter approach lets you enable it in one of your tests, if necessary, with the javadoc:org.springframework.context.annotation.Import[format=annotation] annotation.
See xref:how-to:testing.adoc#howto.testing.slice-tests[this how-to section] for more details on when you might want to enable specific javadoc:org.springframework.context.annotation.Configuration[format=annotation] classes for slice tests.
Test slices exclude `@Configuration` classes from scanning.
For example, for a `@WebMvcTest`, the following configuration will not include the given `WebMvcConfigurer` bean in the application context loaded by the test slice:
Test slices exclude javadoc:org.springframework.context.annotation.Configuration[format=annotation] classes from scanning.
For example, for a javadoc:org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest[format=annotation], the following configuration will not include the given javadoc:org.springframework.web.servlet.config.annotation.WebMvcConfigurer[] bean in the application context loaded by the test slice:
include-code::MyWebConfiguration[]
The configuration below will, however, cause the custom `WebMvcConfigurer` to be loaded by the test slice.
The configuration below will, however, cause the custom javadoc:org.springframework.web.servlet.config.annotation.WebMvcConfigurer[] to be loaded by the test slice.
include-code::MyWebMvcConfigurer[]
@ -885,10 +885,10 @@ Your application may resemble the following code:
include-code::scan/MyApplication[]
Doing so effectively overrides the default component scan directive with the side effect of scanning those two packages regardless of the slice that you chose.
For instance, a `@DataJpaTest` seems to suddenly scan components and user configurations of your application.
For instance, a javadoc:org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest[format=annotation] seems to suddenly scan components and user configurations of your application.
Again, moving the custom directive to a separate class is a good way to fix this issue.
TIP: If this is not an option for you, you can create a `@SpringBootConfiguration` somewhere in the hierarchy of your test so that it is used instead.
TIP: If this is not an option for you, you can create a javadoc:org.springframework.boot.SpringBootConfiguration[format=annotation] somewhere in the hierarchy of your test so that it is used instead.
Alternatively, you can specify a source for your test, which disables the behavior of finding a default one.

View File

@ -8,21 +8,21 @@ A few test utility classes that are generally useful when testing your applicati
[[testing.utilities.config-data-application-context-initializer]]
== ConfigDataApplicationContextInitializer
`ConfigDataApplicationContextInitializer` is an `ApplicationContextInitializer` that you can apply to your tests to load Spring Boot `application.properties` files.
You can use it when you do not need the full set of features provided by `@SpringBootTest`, as shown in the following example:
javadoc:org.springframework.boot.test.context.ConfigDataApplicationContextInitializer[] is an javadoc:org.springframework.context.ApplicationContextInitializer[] that you can apply to your tests to load Spring Boot `application.properties` files.
You can use it when you do not need the full set of features provided by javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation], as shown in the following example:
include-code::MyConfigFileTests[]
NOTE: Using `ConfigDataApplicationContextInitializer` alone does not provide support for `@Value("${...}")` injection.
Its only job is to ensure that `application.properties` files are loaded into Spring's `Environment`.
For `@Value` support, you need to either additionally configure a `PropertySourcesPlaceholderConfigurer` or use `@SpringBootTest`, which auto-configures one for you.
NOTE: Using javadoc:org.springframework.boot.test.context.ConfigDataApplicationContextInitializer[] alone does not provide support for `@Value("${...}")` injection.
Its only job is to ensure that `application.properties` files are loaded into Spring's javadoc:org.springframework.core.env.Environment[].
For javadoc:org.springframework.beans.factory.annotation.Value[format=annotation] support, you need to either additionally configure a javadoc:org.springframework.context.support.PropertySourcesPlaceholderConfigurer[] or use javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation], which auto-configures one for you.
[[testing.utilities.test-property-values]]
== TestPropertyValues
`TestPropertyValues` lets you quickly add properties to a `ConfigurableEnvironment` or `ConfigurableApplicationContext`.
javadoc:org.springframework.boot.test.util.TestPropertyValues[] lets you quickly add properties to a javadoc:org.springframework.core.env.ConfigurableEnvironment[] or javadoc:org.springframework.context.ConfigurableApplicationContext[].
You can call it with `key=value` strings, as follows:
include-code::MyEnvironmentTests[]
@ -32,8 +32,8 @@ include-code::MyEnvironmentTests[]
[[testing.utilities.output-capture]]
== OutputCaptureExtension
`OutputCaptureExtension` is a JUnit `org.junit.jupiter.api.extension.Extension` that you can use to capture javadoc:java.lang.System#out[] and javadoc:java.lang.System#err[] output.
To use it, add `@ExtendWith(OutputCaptureExtension.class)` and inject `CapturedOutput` as an argument to your test class constructor or test method as follows:
javadoc:org.springframework.boot.test.system.OutputCaptureExtension[] is a JUnit javadoc:org.junit.jupiter.api.extension.Extension[] that you can use to capture javadoc:java.lang.System#out[] and javadoc:java.lang.System#err[] output.
To use it, add `@ExtendWith(OutputCaptureExtension.class)` and inject javadoc:org.springframework.boot.test.system.CapturedOutput[] as an argument to your test class constructor or test method as follows:
include-code::MyOutputCaptureTests[]
@ -42,28 +42,28 @@ include-code::MyOutputCaptureTests[]
[[testing.utilities.test-rest-template]]
== TestRestTemplate
`TestRestTemplate` is a convenience alternative to Spring's `RestTemplate` that is useful in integration tests.
javadoc:org.springframework.boot.test.web.client.TestRestTemplate[] is a convenience alternative to Spring's javadoc:org.springframework.web.client.RestTemplate[] that is useful in integration tests.
You can get a vanilla template or one that sends Basic HTTP authentication (with a username and password).
In either case, the template is fault tolerant.
This means that it behaves in a test-friendly way by not throwing exceptions on 4xx and 5xx errors.
Instead, such errors can be detected through the returned `ResponseEntity` and its status code.
Instead, such errors can be detected through the returned javadoc:org.springframework.http.ResponseEntity[] and its status code.
TIP: Spring Framework 5.0 provides a new `WebTestClient` that works for xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.spring-webflux-tests[WebFlux integration tests] and both xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.with-running-server[WebFlux and MVC end-to-end testing].
It provides a fluent API for assertions, unlike `TestRestTemplate`.
TIP: Spring Framework 5.0 provides a new javadoc:org.springframework.test.web.reactive.server.WebTestClient[] that works for xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.spring-webflux-tests[WebFlux integration tests] and both xref:testing/spring-boot-applications.adoc#testing.spring-boot-applications.with-running-server[WebFlux and MVC end-to-end testing].
It provides a fluent API for assertions, unlike javadoc:org.springframework.boot.test.web.client.TestRestTemplate[].
It is recommended, but not mandatory, to use the Apache HTTP Client (version 5.1 or better).
If you have that on your classpath, the `TestRestTemplate` responds by configuring the client appropriately.
If you have that on your classpath, the javadoc:org.springframework.boot.test.web.client.TestRestTemplate[] responds by configuring the client appropriately.
If you do use Apache's HTTP client, some additional test-friendly features are enabled:
* Redirects are not followed (so you can assert the response location).
* Cookies are ignored (so the template is stateless).
`TestRestTemplate` can be instantiated directly in your integration tests, as shown in the following example:
javadoc:org.springframework.boot.test.web.client.TestRestTemplate[] can be instantiated directly in your integration tests, as shown in the following example:
include-code::MyTests[]
Alternatively, if you use the `@SpringBootTest` annotation with `WebEnvironment.RANDOM_PORT` or `WebEnvironment.DEFINED_PORT`, you can inject a fully configured `TestRestTemplate` and start using it.
If necessary, additional customizations can be applied through the `RestTemplateBuilder` bean.
Alternatively, if you use the javadoc:org.springframework.boot.test.context.SpringBootTest[format=annotation] annotation with `WebEnvironment.RANDOM_PORT` or `WebEnvironment.DEFINED_PORT`, you can inject a fully configured javadoc:org.springframework.boot.test.web.client.TestRestTemplate[] and start using it.
If necessary, additional customizations can be applied through the javadoc:org.springframework.boot.web.client.RestTemplateBuilder[] bean.
Any URLs that do not specify a host and port automatically connect to the embedded server, as shown in the following example:
include-code::MySpringBootTests[]

View File

@ -25,108 +25,108 @@ When using Testcontainers, connection details can be automatically created for a
include-code::MyIntegrationTests[]
Thanks to `@ServiceConnection`, the above configuration allows Neo4j-related beans in the application to communicate with Neo4j running inside the Testcontainers-managed Docker container.
This is done by automatically defining a `Neo4jConnectionDetails` bean which is then used by the Neo4j auto-configuration, overriding any connection-related configuration properties.
Thanks to javadoc:org.springframework.boot.testcontainers.service.connection.ServiceConnection[format=annotation], the above configuration allows Neo4j-related beans in the application to communicate with Neo4j running inside the Testcontainers-managed Docker container.
This is done by automatically defining a javadoc:org.springframework.boot.autoconfigure.neo4j.Neo4jConnectionDetails[] bean which is then used by the Neo4j auto-configuration, overriding any connection-related configuration properties.
NOTE: You'll need to add the `spring-boot-testcontainers` module as a test dependency in order to use service connections with Testcontainers.
Service connection annotations are processed by `ContainerConnectionDetailsFactory` classes registered with `spring.factories`.
A `ContainerConnectionDetailsFactory` can create a `ConnectionDetails` bean based on a specific `org.testcontainers.containers.Container` subclass, or the Docker image name.
Service connection annotations are processed by javadoc:org.springframework.boot.testcontainers.service.connection.ContainerConnectionDetailsFactory[] classes registered with `spring.factories`.
A javadoc:org.springframework.boot.testcontainers.service.connection.ContainerConnectionDetailsFactory[] can create a javadoc:org.springframework.boot.autoconfigure.service.connection.ConnectionDetails[] bean based on a specific javadoc:org.testcontainers.containers.Container[] subclass, or the Docker image name.
The following service connection factories are provided in the `spring-boot-testcontainers` jar:
|===
| Connection Details | Matched on
| `ActiveMQConnectionDetails`
| Containers named "symptoma/activemq" or `ActiveMQContainer`
| javadoc:org.springframework.boot.autoconfigure.jms.activemq.ActiveMQConnectionDetails[]
| Containers named "symptoma/activemq" or javadoc:org.testcontainers.activemq.ActiveMQContainer[]
| `ArtemisConnectionDetails`
| Containers of type `ArtemisContainer`
| javadoc:org.springframework.boot.autoconfigure.jms.artemis.ArtemisConnectionDetails[]
| Containers of type javadoc:org.testcontainers.activemq.ArtemisContainer[]
| `CassandraConnectionDetails`
| Containers of type `org.testcontainers.cassandra.CassandraContainer`
| javadoc:org.springframework.boot.autoconfigure.cassandra.CassandraConnectionDetails[]
| Containers of type javadoc:org.testcontainers.cassandra.CassandraContainer[]
| `CouchbaseConnectionDetails`
| Containers of type `CouchbaseContainer`
| javadoc:org.springframework.boot.autoconfigure.couchbase.CouchbaseConnectionDetails[]
| Containers of type javadoc:org.testcontainers.couchbase.CouchbaseContainer[]
| `ElasticsearchConnectionDetails`
| Containers of type `ElasticsearchContainer`
| javadoc:org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchConnectionDetails[]
| Containers of type javadoc:org.testcontainers.elasticsearch.ElasticsearchContainer[]
| `FlywayConnectionDetails`
| Containers of type `JdbcDatabaseContainer`
| javadoc:org.springframework.boot.autoconfigure.flyway.FlywayConnectionDetails[]
| Containers of type javadoc:{url-testcontainers-jdbc-javadoc}/org.testcontainers.containers.JdbcDatabaseContainer[]
| `JdbcConnectionDetails`
| Containers of type `JdbcDatabaseContainer`
| javadoc:org.springframework.boot.autoconfigure.jdbc.JdbcConnectionDetails[]
| Containers of type javadoc:{url-testcontainers-jdbc-javadoc}/org.testcontainers.containers.JdbcDatabaseContainer[]
| `KafkaConnectionDetails`
| Containers of type `org.testcontainers.kafka.KafkaContainer`, `org.testcontainers.kafka.ConfluentKafkaContainer` or `RedpandaContainer`
| javadoc:org.springframework.boot.autoconfigure.kafka.KafkaConnectionDetails[]
| Containers of type javadoc:org.testcontainers.kafka.KafkaContainer[], javadoc:org.testcontainers.kafka.ConfluentKafkaContainer[] or javadoc:org.testcontainers.redpanda.RedpandaContainer[]
| `LiquibaseConnectionDetails`
| Containers of type `JdbcDatabaseContainer`
| javadoc:org.springframework.boot.autoconfigure.liquibase.LiquibaseConnectionDetails[]
| Containers of type javadoc:{url-testcontainers-jdbc-javadoc}/org.testcontainers.containers.JdbcDatabaseContainer[]
| `MongoConnectionDetails`
| Containers of type `MongoDBContainer`
| javadoc:org.springframework.boot.autoconfigure.mongo.MongoConnectionDetails[]
| Containers of type javadoc:{url-testcontainers-mongodb-javadoc}/org.testcontainers.containers.MongoDBContainer[]
| `Neo4jConnectionDetails`
| Containers of type `Neo4jContainer`
| javadoc:org.springframework.boot.autoconfigure.neo4j.Neo4jConnectionDetails[]
| Containers of type javadoc:{url-testcontainers-neo4j-javadoc}/org.testcontainers.containers.Neo4jContainer[]
| `OtlpLoggingConnectionDetails`
| javadoc:org.springframework.boot.actuate.autoconfigure.logging.otlp.OtlpLoggingConnectionDetails[]
| Containers named "otel/opentelemetry-collector-contrib" or of type `LgtmStackContainer`
| `OtlpMetricsConnectionDetails`
| javadoc:org.springframework.boot.actuate.autoconfigure.metrics.export.otlp.OtlpMetricsConnectionDetails[]
| Containers named "otel/opentelemetry-collector-contrib" or of type `LgtmStackContainer`
| `OtlpTracingConnectionDetails`
| javadoc:org.springframework.boot.actuate.autoconfigure.tracing.otlp.OtlpTracingConnectionDetails[]
| Containers named "otel/opentelemetry-collector-contrib" or of type `LgtmStackContainer`
| `PulsarConnectionDetails`
| Containers of type `PulsarContainer`
| javadoc:org.springframework.boot.autoconfigure.pulsar.PulsarConnectionDetails[]
| Containers of type javadoc:{url-testcontainers-pulsar-javadoc}/org.testcontainers.containers.PulsarContainer[]
| `R2dbcConnectionDetails`
| Containers of type `ClickHouseContainer`, `MariaDBContainer`, `MSSQLServerContainer`, `MySQLContainer`, javadoc:{url-testcontainers-oracle-free-javadoc}/org.testcontainers.OracleContainer[OracleContainer (free)], javadoc:{url-testcontainers-oracle-xe-javadoc}/org.testcontainers.oracle.OracleContainer[OracleContainer (XE)] or `PostgreSQLContainer`
| javadoc:org.springframework.boot.autoconfigure.r2dbc.R2dbcConnectionDetails[]
| Containers of type `ClickHouseContainer`, javadoc:{url-testcontainers-mariadb-javadoc}/org.testcontainers.containers.MariaDBContainer[], javadoc:{url-testcontainers-mssqlserver-javadoc}/org.testcontainers.containers.MSSQLServerContainer[], javadoc:{url-testcontainers-mysql-javadoc}/org.testcontainers.containers.MySQLContainer[], javadoc:{url-testcontainers-oracle-free-javadoc}/org.testcontainers.OracleContainer[OracleContainer (free)], javadoc:{url-testcontainers-oracle-xe-javadoc}/org.testcontainers.oracle.OracleContainer[OracleContainer (XE)] or javadoc:{url-testcontainers-postgresql-javadoc}/org.testcontainers.containers.PostgreSQLContainer[]
| `RabbitConnectionDetails`
| Containers of type `RabbitMQContainer`
| javadoc:org.springframework.boot.autoconfigure.amqp.RabbitConnectionDetails[]
| Containers of type javadoc:{url-testcontainers-rabbitmq-javadoc}/org.testcontainers.containers.RabbitMQContainer[]
| `RedisConnectionDetails`
| Containers of type `com.redis.testcontainers.RedisContainer` or `com.redis.testcontainers.RedisStackContainer`, or containers named "redis", "redis/redis-stack" or "redis/redis-stack-server"
| javadoc:org.springframework.boot.autoconfigure.data.redis.RedisConnectionDetails[]
| Containers of type javadoc:com.redis.testcontainers.RedisContainer[] or javadoc:com.redis.testcontainers.RedisStackContainer[], or containers named "redis", "redis/redis-stack" or "redis/redis-stack-server"
| `ZipkinConnectionDetails`
| javadoc:org.springframework.boot.actuate.autoconfigure.tracing.zipkin.ZipkinConnectionDetails[]
| Containers named "openzipkin/zipkin"
|===
[TIP]
====
By default all applicable connection details beans will be created for a given `org.testcontainers.containers.Container`.
For example, a `PostgreSQLContainer` will create both `JdbcConnectionDetails` and `R2dbcConnectionDetails`.
By default all applicable connection details beans will be created for a given javadoc:org.testcontainers.containers.Container[].
For example, a javadoc:{url-testcontainers-postgresql-javadoc}/org.testcontainers.containers.PostgreSQLContainer[] will create both javadoc:org.springframework.boot.autoconfigure.jdbc.JdbcConnectionDetails[] and javadoc:org.springframework.boot.autoconfigure.r2dbc.R2dbcConnectionDetails[].
If you want to create only a subset of the applicable types, you can use the `type` attribute of `@ServiceConnection`.
If you want to create only a subset of the applicable types, you can use the `type` attribute of javadoc:org.springframework.boot.testcontainers.service.connection.ServiceConnection[format=annotation].
====
By default `Container.getDockerImageName().getRepository()` is used to obtain the name used to find connection details.
The repository portion of the Docker image name ignores any registry and the version.
This works as long as Spring Boot is able to get the instance of the `org.testcontainers.containers.Container`, which is the case when using a `static` field like in the example above.
This works as long as Spring Boot is able to get the instance of the javadoc:org.testcontainers.containers.Container[], which is the case when using a `static` field like in the example above.
If you're using a `@Bean` method, Spring Boot won't call the bean method to get the Docker image name, because this would cause eager initialization issues.
If you're using a javadoc:org.springframework.context.annotation.Bean[format=annotation] method, Spring Boot won't call the bean method to get the Docker image name, because this would cause eager initialization issues.
Instead, the return type of the bean method is used to find out which connection detail should be used.
This works as long as you're using typed containers such as `Neo4jContainer` or `RabbitMQContainer`.
This stops working if you're using `GenericContainer`, for example with Redis as shown in the following example:
This works as long as you're using typed containers such as javadoc:{url-testcontainers-neo4j-javadoc}/org.testcontainers.containers.Neo4jContainer[] or javadoc:{url-testcontainers-rabbitmq-javadoc}/org.testcontainers.containers.RabbitMQContainer[].
This stops working if you're using javadoc:org.testcontainers.containers.GenericContainer[], for example with Redis as shown in the following example:
include-code::MyRedisConfiguration[]
Spring Boot can't tell from `GenericContainer` which container image is used, so the `name` attribute from `@ServiceConnection` must be used to provide that hint.
Spring Boot can't tell from javadoc:org.testcontainers.containers.GenericContainer[] which container image is used, so the `name` attribute from javadoc:org.springframework.boot.testcontainers.service.connection.ServiceConnection[format=annotation] must be used to provide that hint.
You can also use the `name` attribute of `@ServiceConnection` to override which connection detail will be used, for example when using custom images.
If you are using the Docker image `registry.mycompany.com/mirror/myredis`, you'd use `@ServiceConnection(name="redis")` to ensure `RedisConnectionDetails` are created.
You can also use the `name` attribute of javadoc:org.springframework.boot.testcontainers.service.connection.ServiceConnection[format=annotation] to override which connection detail will be used, for example when using custom images.
If you are using the Docker image `registry.mycompany.com/mirror/myredis`, you'd use `@ServiceConnection(name="redis")` to ensure javadoc:org.springframework.boot.autoconfigure.data.redis.RedisConnectionDetails[] are created.
[[testing.testcontainers.dynamic-properties]]
== Dynamic Properties
A slightly more verbose but also more flexible alternative to service connections is `@DynamicPropertySource`.
A static `@DynamicPropertySource` method allows adding dynamic property values to the Spring Environment.
A slightly more verbose but also more flexible alternative to service connections is javadoc:org.springframework.test.context.DynamicPropertySource[format=annotation].
A static javadoc:org.springframework.test.context.DynamicPropertySource[format=annotation] method allows adding dynamic property values to the Spring Environment.
include-code::MyIntegrationTests[]

View File

@ -4,10 +4,10 @@
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.
You need to opt-in to auto-configuration by adding the javadoc:org.springframework.boot.autoconfigure.EnableAutoConfiguration[format=annotation] or javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation] annotations to one of your javadoc:org.springframework.context.annotation.Configuration[format=annotation] 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.
TIP: You should only ever add one javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation] or javadoc:org.springframework.boot.autoconfigure.EnableAutoConfiguration[format=annotation] annotation.
We generally recommend that you add one or the other to your primary javadoc:org.springframework.context.annotation.Configuration[format=annotation] class only.
@ -16,7 +16,7 @@ We generally recommend that you add one or the other to your primary `@Configura
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.
For example, if you add your own javadoc:javax.sql.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.
@ -26,12 +26,12 @@ Doing so enables debug logs for a selection of core loggers and logs a condition
[[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:
If you find that specific auto-configuration classes that you do not want are being applied, you can use the exclude attribute of javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation] 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.
If you prefer to use javadoc:org.springframework.boot.autoconfigure.EnableAutoConfiguration[format=annotation] rather than javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation], `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.
@ -45,5 +45,5 @@ The actual contents of those classes, such as nested configuration classes or be
== 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.
The javadoc:org.springframework.boot.autoconfigure.EnableAutoConfiguration[format=annotation] annotation (either directly or through its presence on javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation]) determines the default auto-configuration package.
Additional packages can be configured using the javadoc:org.springframework.boot.autoconfigure.AutoConfigurationPackage[format=annotation] annotation.

View File

@ -2,8 +2,8 @@
= 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`.
Although it is possible to use javadoc:org.springframework.boot.SpringApplication[] with XML sources, we generally recommend that your primary source be a single javadoc:org.springframework.context.annotation.Configuration[format=annotation] class.
Usually the class that defines the `main` method is a good candidate as the primary javadoc:org.springframework.context.annotation.Configuration[format=annotation].
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.
@ -14,14 +14,14 @@ 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.
You need not put all your javadoc:org.springframework.context.annotation.Configuration[format=annotation] into a single class.
The javadoc:org.springframework.context.annotation.Import[format=annotation] annotation can be used to import additional configuration classes.
Alternatively, you can use javadoc:org.springframework.context.annotation.ComponentScan[format=annotation] to automatically pick up all Spring components, including javadoc:org.springframework.context.annotation.Configuration[format=annotation] 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.
If you absolutely must use XML based configuration, we recommend that you still start with a javadoc:org.springframework.context.annotation.Configuration[format=annotation] class.
You can then use an javadoc:org.springframework.context.annotation.ImportResource[format=annotation] annotation to load XML configuration files.

View File

@ -112,9 +112,9 @@ Other devtools features (such as LiveReload and property overrides) can still be
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`.
NOTE: DevTools needs to customize the javadoc:org.springframework.core.io.ResourceLoader[] used by the javadoc:org.springframework.context.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.
Direct override of the `getResource` method on the javadoc:org.springframework.context.ApplicationContext[] is not supported.
CAUTION: Automatic restart is not supported when using AspectJ weaving.
@ -187,7 +187,7 @@ You can use the configprop:spring.devtools.restart.exclude[] property xref:using
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:
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[] javadoc:java.lang.System[] property to `false` before calling `SpringApplication.run(...)`, as shown in the following example:
include-code::MyApplication[]
@ -241,7 +241,7 @@ As described earlier in the xref:#using.devtools.restart.restart-vs-reload[] sec
If this causes issues, you can diagnose the problem by using the `spring.devtools.restart.enabled` system property, and if the app works with restart switched off, 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.
The same is true if you use `mvn spring-boot:run` or `gradle bootRun`: the project containing your javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation] is loaded with the "`restart`" classloader, and everything else with the "`base`" classloader.
The classpath is printed on the console when you start the app, which can help to identify any problematic entries.
Classes used reflectively, especially annotations, can be loaded into the parent (fixed) classloader on startup before the application classes which use them, and this might lead to them not being detected by Spring in the application.
@ -272,8 +272,8 @@ System properties can not be used, only the properties file.
[[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()`.
Restart functionality does not work well with objects that are deserialized by using a standard javadoc:java.io.ObjectInputStream[].
If you need to deserialize data, you may need to use Spring's javadoc:org.springframework.core.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.
@ -395,7 +395,7 @@ NOTE: Remote devtools is not supported for Spring WebFlux applications.
=== 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.
You need to run javadoc: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:
@ -403,7 +403,7 @@ For example, if you are using Eclipse or Spring Tools and you have a project nam
* 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.
* Use javadoc: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:
@ -434,7 +434,7 @@ On a slower development environment, it may happen that the quiet period is not
The server is restarted after the first batch of class changes is uploaded.
The next batch cant 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.
This is typically manifested by a warning in the javadoc:org.springframework.boot.devtools.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[] section for configuring these properties.

View File

@ -2,16 +2,16 @@
= 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.
We generally recommend using constructor injection to wire up dependencies and javadoc:org.springframework.context.annotation.ComponentScan[format=annotation] 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.
If you structure your code as suggested above (locating your application class in a top package), you can add javadoc:org.springframework.context.annotation.ComponentScan[format=annotation] without any arguments or use the javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation] annotation which implicitly includes it.
All of your application components (`@Component`, javadoc:org.springframework.stereotype.Service[format=annotation], javadoc:org.springframework.stereotype.Repository[format=annotation], javadoc:org.springframework.stereotype.Controller[format=annotation], 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:
The following example shows a javadoc:org.springframework.stereotype.Service[format=annotation] 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`:
If a bean has more than one constructor, you will need to mark the one you want Spring to use with javadoc:org.springframework.beans.factory.annotation.Autowired[format=annotation]:
include-code::multipleconstructors/MyAccountService[]

View File

@ -13,7 +13,7 @@ TIP: If you wish to enforce a structure based on domains, take a look at https:/
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.
It can cause particular problems for Spring Boot applications that use the javadoc:org.springframework.context.annotation.ComponentScan[format=annotation], javadoc:org.springframework.boot.context.properties.ConfigurationPropertiesScan[format=annotation], javadoc:org.springframework.boot.autoconfigure.domain.EntityScan[format=annotation], or javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation] 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`).
@ -24,10 +24,10 @@ TIP: We recommend that you follow Java's recommended package naming conventions
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.
For example, if you are writing a JPA application, the package of the javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation] annotated class is used to search for javadoc:jakarta.persistence.Entity[format=annotation] 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.
TIP: If you do not want to use javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation], the javadoc:org.springframework.boot.autoconfigure.EnableAutoConfiguration[format=annotation] and javadoc:org.springframework.context.annotation.ComponentScan[format=annotation] annotations that it imports defines that behavior so you can also use those instead.
The following listing shows a typical layout:
@ -51,6 +51,6 @@ com
+- OrderRepository.java
----
The `MyApplication.java` file would declare the `main` method, along with the basic `@SpringBootApplication`, as follows:
The `MyApplication.java` file would declare the `main` method, along with the basic javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation], as follows:
include-code::MyApplication[]

View File

@ -2,16 +2,16 @@
= 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:
A single javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation] 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:testing/spring-boot-applications.adoc#testing.spring-boot-applications.detecting-configuration[configuration detection] in your integration tests.
* javadoc:org.springframework.boot.autoconfigure.EnableAutoConfiguration[format=annotation]: enable xref:using/auto-configuration.adoc[Spring Boot's auto-configuration mechanism]
* javadoc:org.springframework.context.annotation.ComponentScan[format=annotation]: enable javadoc:org.springframework.stereotype.Component[format=annotation] scan on the package where the application is located (see xref:using/structuring-your-code.adoc[the best practices])
* javadoc:org.springframework.boot.SpringBootConfiguration[format=annotation]: enable registration of extra beans in the context or the import of additional configuration classes.
An alternative to Spring's standard javadoc:org.springframework.context.annotation.Configuration[format=annotation] that aids xref:testing/spring-boot-applications.adoc#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: javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation] also provides aliases to customize the attributes of javadoc:org.springframework.boot.autoconfigure.EnableAutoConfiguration[format=annotation] and javadoc:org.springframework.context.annotation.ComponentScan[format=annotation].
[NOTE]
====
@ -20,5 +20,5 @@ For instance, you may not want to use component scan or configuration properties
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`).
In this example, `MyApplication` is just like any other Spring Boot application except that javadoc:org.springframework.stereotype.Component[format=annotation]-annotated classes and javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation]-annotated classes are not detected automatically and the user-defined beans are imported explicitly (see javadoc:org.springframework.context.annotation.Import[format=annotation]).
====

View File

@ -2,7 +2,7 @@
= Graceful Shutdown
Graceful shutdown is enabled by default 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.
It occurs as part of closing the application context and is performed in the earliest phase of stopping javadoc:org.springframework.context.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.
To configure the timeout period, configure the configprop:spring.lifecycle.timeout-per-shutdown-phase[] property, as shown in the following example:

View File

@ -26,13 +26,13 @@ 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 `org.springframework.web.reactive.function.server.RouterFunction` beans as you like to modularize the definition of the router.
TIP: You can define as many javadoc:org.springframework.web.reactive.function.server.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`.
This behavior has been chosen because many Spring developers add `spring-boot-starter-webflux` to their Spring MVC application to use the reactive javadoc:org.springframework.web.reactive.function.client.WebClient[].
You can still enforce your choice by setting the chosen application type to `SpringApplication.setWebApplicationType(WebApplicationType.REACTIVE)`.
@ -44,21 +44,21 @@ Spring Boot provides auto-configuration for Spring WebFlux that works well with
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]).
* Configuring codecs for javadoc:org.springframework.http.codec.HttpMessageReader[] and javadoc:org.springframework.http.codec.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 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 javadoc:org.springframework.context.annotation.Configuration[format=annotation] class of type javadoc:org.springframework.web.reactive.config.WebFluxConfigurer[] but *without* javadoc:org.springframework.web.reactive.config.EnableWebFlux[format=annotation].
If you want to add additional customization to the auto-configured `org.springframework.http.server.reactive.HttpHandler`, you can define beans of type `WebHttpHandlerBuilderCustomizer` and use them to modify the `WebHttpHandlerBuilder`.
If you want to add additional customization to the auto-configured javadoc:org.springframework.http.server.reactive.HttpHandler[], you can define beans of type javadoc:org.springframework.boot.autoconfigure.web.reactive.WebHttpHandlerBuilderCustomizer[] and use them to modify the javadoc:org.springframework.web.server.adapter.WebHttpHandlerBuilder[].
If you want to take complete control of Spring WebFlux, you can add your own `@Configuration` annotated with `@EnableWebFlux`.
If you want to take complete control of Spring WebFlux, you can add your own javadoc:org.springframework.context.annotation.Configuration[format=annotation] annotated with javadoc:org.springframework.web.reactive.config.EnableWebFlux[format=annotation].
[[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.
If you want to customize the javadoc:org.springframework.core.convert.ConversionService[] used by Spring WebFlux, you can provide a javadoc:org.springframework.web.reactive.config.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:
@ -68,15 +68,15 @@ When not configured, the following defaults are used:
|configprop:spring.webflux.format.date[]
|`ofLocalizedDate(FormatStyle.SHORT)`
|`java.util.Date` and `java.time.LocalDate`
|`java.util.Date` and javadoc:java.time.LocalDate[]
|configprop:spring.webflux.format.time[]
|`ofLocalizedTime(FormatStyle.SHORT)`
|java.time's `LocalTime` and `OffsetTime`
|java.time's javadoc:java.time.LocalTime[] and javadoc:java.time.OffsetTime[]
|configprop:spring.webflux.format.date-time[]
|`ofLocalizedDateTime(FormatStyle.SHORT)`
|java.time's `LocalDateTime`, `OffsetDateTime`, and `ZonedDateTime`
|java.time's javadoc:java.time.LocalDateTime[], javadoc:java.time.OffsetDateTime[], and javadoc:java.time.ZonedDateTime[]
|===
@ -84,14 +84,14 @@ When not configured, the following defaults are used:
[[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 WebFlux uses the javadoc:org.springframework.http.codec.HttpMessageReader[] and javadoc:org.springframework.http.codec.HttpMessageWriter[] interfaces to convert HTTP requests and responses.
They are configured with javadoc:org.springframework.http.codec.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.
It also applies further customization by using javadoc:org.springframework.boot.web.codec.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:
If you need to add or customize codecs, you can create a custom javadoc:org.springframework.boot.web.codec.CodecCustomizer[] component, as shown in the following example:
include-code::MyCodecsConfiguration[]
@ -103,7 +103,7 @@ You can also leverage xref:features/json.adoc#features.json.jackson.custom-seria
=== 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.
It uses the javadoc:org.springframework.web.reactive.resource.ResourceWebHandler[] from Spring WebFlux so that you can modify that behavior by adding your own javadoc:org.springframework.web.reactive.config.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:
@ -137,15 +137,15 @@ 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 `org.springframework.web.reactive.HandlerMapping` beans which is by default the following:
The ordering is defined by the order of javadoc:org.springframework.web.reactive.HandlerMapping[] beans which is by default the following:
[cols="1,1"]
|===
|`org.springframework.web.reactive.function.server.support.RouterFunctionMapping`
|Endpoints declared with `org.springframework.web.reactive.function.server.RouterFunction` beans
|Endpoints declared with javadoc:org.springframework.web.reactive.function.server.RouterFunction[] beans
|`org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping`
|Endpoints declared in `@Controller` beans
|Endpoints declared in javadoc:org.springframework.stereotype.Controller[format=annotation] beans
|`RouterFunctionMapping` for the Welcome Page
|The welcome page support
@ -175,7 +175,7 @@ When you use one of these templating engines with the default configuration, you
[[web.reactive.webflux.error-handling]]
=== Error Handling
Spring Boot provides a `WebExceptionHandler` that handles all errors in a sensible way.
Spring Boot provides a javadoc:org.springframework.web.server.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.
@ -199,14 +199,14 @@ This support can be enabled by setting configprop:spring.webflux.problemdetails.
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 `org.springframework.boot.web.reactive.error.ErrorAttributes`.
For that, you can add a bean of type javadoc:org.springframework.boot.web.reactive.error.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:
To change the error handling behavior, you can implement javadoc:org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler[] and register a bean definition of that type.
Because an javadoc:org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler[] is quite low-level, Spring Boot also provides a convenient javadoc:org.springframework.boot.autoconfigure.web.reactive.error.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.
For a more complete picture, you can also subclass javadoc:org.springframework.boot.autoconfigure.web.reactive.error.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].
@ -256,20 +256,20 @@ src/
[[web.reactive.webflux.web-filters]]
=== Web Filters
Spring WebFlux provides a `org.springframework.web.server.WebFilter` interface that can be implemented to filter HTTP request-response exchanges.
`org.springframework.web.server.WebFilter` beans found in the application context will be automatically used to filter each exchange.
Spring WebFlux provides a javadoc:org.springframework.web.server.WebFilter[] interface that can be implemented to filter HTTP request-response exchanges.
javadoc:org.springframework.web.server.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`.
Where the order of the filters is important they can implement javadoc:org.springframework.core.Ordered[] or be annotated with javadoc:org.springframework.core.annotation.Order[format=annotation].
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)
| javadoc:org.springframework.security.web.server.WebFilterChainProxy[] (Spring Security)
| `-100`
| `HttpExchangesWebFilter`
| javadoc:org.springframework.boot.actuate.web.exchanges.reactive.HttpExchangesWebFilter[]
| `Ordered.LOWEST_PRECEDENCE - 10`
|===
@ -287,7 +287,7 @@ 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.
Common reactive web server settings can be configured by using Spring javadoc:org.springframework.core.env.Environment[] properties.
Usually, you would define the properties in your `application.properties` or `application.yaml` file.
Common server settings include:
@ -307,14 +307,14 @@ TIP: See the javadoc:org.springframework.boot.autoconfigure.web.ServerProperties
[[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.
If you need to programmatically configure your reactive web server, you can register a Spring bean that implements the javadoc:org.springframework.boot.web.server.WebServerFactoryCustomizer[] interface.
javadoc:org.springframework.boot.web.server.WebServerFactoryCustomizer[] provides access to the javadoc:org.springframework.boot.web.reactive.server.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:
javadoc:org.springframework.boot.web.embedded.jetty.JettyReactiveWebServerFactory[], javadoc:org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory[], javadoc:org.springframework.boot.web.embedded.tomcat.TomcatReactiveWebServerFactory[], and javadoc:org.springframework.boot.web.embedded.undertow.UndertowReactiveWebServerFactory[] are dedicated variants of javadoc:org.springframework.boot.web.reactive.server.ConfigurableReactiveWebServerFactory[] that have additional customization setter methods for Jetty, Reactor Netty, Tomcat, and Undertow respectively.
The following example shows how to customize javadoc:org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory[] that provides access to Reactor Netty-specific configuration options:
include-code::MyNettyWebServerFactoryCustomizer[]
@ -323,7 +323,7 @@ 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.
For more advanced use cases that require you to extend from javadoc:org.springframework.boot.web.reactive.server.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.
@ -336,14 +336,14 @@ NOTE: Auto-configured customizers are still applied on your custom factory, so u
[[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`.
When auto-configuring a Reactor Netty or Jetty server, Spring Boot will create specific beans that will provide HTTP resources to the server instance: javadoc:org.springframework.http.client.ReactorResourceFactory[] or javadoc:org.springframework.http.client.reactive.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
* the client instance is built using the javadoc:org.springframework.web.reactive.function.client.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.
Developers can override the resource configuration for Jetty and Reactor Netty by providing a custom javadoc:org.springframework.http.client.ReactorResourceFactory[] or javadoc:org.springframework.http.client.reactive.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[] section.

View File

@ -9,10 +9,10 @@ If you want to build servlet-based web applications, you can take advantage of S
== 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.
Spring MVC lets you create special javadoc:org.springframework.stereotype.Controller[format=annotation] or javadoc:org.springframework.web.bind.annotation.RestController[format=annotation] beans to handle incoming HTTP requests.
Methods in your controller are mapped to HTTP by using javadoc:org.springframework.web.bind.annotation.RequestMapping[format=annotation] annotations.
The following code shows a typical `@RestController` that serves JSON data:
The following code shows a typical javadoc:org.springframework.web.bind.annotation.RestController[format=annotation] that serves JSON data:
include-code::MyRestController[]
@ -25,7 +25,7 @@ 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 `org.springframework.web.servlet.function.RouterFunction` beans as you like to modularize the definition of the router.
TIP: You can define as many javadoc:org.springframework.web.servlet.function.RouterFunction[] beans as you like to modularize the definition of the router.
Beans can be ordered if you need to apply a precedence.
@ -34,36 +34,36 @@ Beans can be ordered if you need to apply a precedence.
=== 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.
It replaces the need for javadoc:org.springframework.web.servlet.config.annotation.EnableWebMvc[format=annotation] 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.
* Inclusion of javadoc:org.springframework.web.servlet.view.ContentNegotiatingViewResolver[] and javadoc:org.springframework.web.servlet.view.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 `org.springframework.core.convert.converter.Converter`, `org.springframework.core.convert.converter.GenericConverter`, and `org.springframework.format.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]).
* Automatic registration of javadoc:org.springframework.core.convert.converter.Converter[], javadoc:org.springframework.core.convert.converter.GenericConverter[], and javadoc:org.springframework.format.Formatter[] beans.
* Support for javadoc:org.springframework.boot.autoconfigure.http.HttpMessageConverters[] (covered xref:web/servlet.adoc#web.servlet.spring-mvc.message-converters[later in this document]).
* Automatic registration of javadoc:org.springframework.validation.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]).
* Automatic use of a javadoc:org.springframework.web.bind.support.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 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 javadoc:org.springframework.context.annotation.Configuration[format=annotation] class of type javadoc:org.springframework.web.servlet.config.annotation.WebMvcConfigurer[] but *without* javadoc:org.springframework.web.servlet.config.annotation.EnableWebMvc[format=annotation].
If you want to provide custom instances of `org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping`, `org.springframework.web.servlet.mvc.method.annotation.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.
If you want to provide custom instances of javadoc:org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping[], javadoc:org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter[], or javadoc:org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver[], and still keep the Spring Boot MVC customizations, you can declare a bean of type javadoc:org.springframework.boot.autoconfigure.web.servlet.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.
To participate in, and if desired, override that subsequent processing, a javadoc:org.springframework.web.servlet.config.annotation.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 `@EnableWebMvc` API documentation.
If you do not want to use the auto-configuration and want to take complete control of Spring MVC, add your own javadoc:org.springframework.context.annotation.Configuration[format=annotation] annotated with javadoc:org.springframework.web.servlet.config.annotation.EnableWebMvc[format=annotation].
Alternatively, add your own javadoc:org.springframework.context.annotation.Configuration[format=annotation]-annotated javadoc:org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration[] as described in the javadoc:org.springframework.web.servlet.config.annotation.EnableWebMvc[format=annotation] API documentation.
[[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 `java.time.Period`, `java.time.Duration` and `DataSize` converters are not available and that `@DurationUnit` and `@DataSizeUnit` annotations will be ignored.
Spring MVC uses a different javadoc:org.springframework.core.convert.ConversionService[] to the one used to convert values from your `application.properties` or `application.yaml` file.
It means that javadoc:java.time.Period[], javadoc:java.time.Duration[] and javadoc:org.springframework.util.unit.DataSize[] converters are not available and that javadoc:org.springframework.boot.convert.DurationUnit[format=annotation] and javadoc:org.springframework.boot.convert.DataSizeUnit[format=annotation] 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`.
If you want to customize the javadoc:org.springframework.core.convert.ConversionService[] used by Spring MVC, you can provide a javadoc:org.springframework.web.servlet.config.annotation.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 javadoc:org.springframework.boot.convert.ApplicationConversionService[].
Conversion can also be customized using the `spring.mvc.format.*` configuration properties.
When not configured, the following defaults are used:
@ -73,15 +73,15 @@ When not configured, the following defaults are used:
|configprop:spring.mvc.format.date[]
|`ofLocalizedDate(FormatStyle.SHORT)`
|`java.util.Date` and `java.time.LocalDate`
|`java.util.Date` and javadoc:java.time.LocalDate[]
|configprop:spring.mvc.format.time[]
|`ofLocalizedTime(FormatStyle.SHORT)`
|java.time's `LocalTime` and `OffsetTime`
|java.time's javadoc:java.time.LocalTime[] and javadoc:java.time.OffsetTime[]
|configprop:spring.mvc.format.date-time[]
|`ofLocalizedDateTime(FormatStyle.SHORT)`
|java.time's `LocalDateTime`, `OffsetDateTime`, and `ZonedDateTime`
|java.time's javadoc:java.time.LocalDateTime[], javadoc:java.time.OffsetDateTime[], and javadoc:java.time.ZonedDateTime[]
|===
@ -89,19 +89,19 @@ When not configured, the following defaults are used:
[[web.servlet.spring-mvc.message-converters]]
=== HttpMessageConverters
Spring MVC uses the `HttpMessageConverter` interface to convert HTTP requests and responses.
Spring MVC uses the javadoc:org.springframework.http.converter.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`.
Any `HttpMessageConverter` bean that is present in the context is added to the list of converters.
Any javadoc:org.springframework.http.converter.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.
If you need to add or customize converters, you can use Spring Boot's `HttpMessageConverters` class, as shown in the following listing:
If you need to add or customize converters, you can use Spring Boot's javadoc:org.springframework.boot.autoconfigure.http.HttpMessageConverters[] class, as shown in the following listing:
include-code::MyHttpMessageConvertersConfiguration[]
For further control, you can also sub-class `HttpMessageConverters` and override its `postProcessConverters` and/or `postProcessPartConverters` methods.
For further control, you can also sub-class javadoc:org.springframework.boot.autoconfigure.http.HttpMessageConverters[] and override its `postProcessConverters` and/or `postProcessPartConverters` methods.
This can be useful when you want to re-order or remove some of the converters that Spring MVC configures by default.
@ -109,7 +109,7 @@ This can be useful when you want to re-order or remove some of the converters th
[[web.servlet.spring-mvc.message-codes]]
=== MessageCodesResolver
Spring MVC has a strategy for generating error codes for rendering error messages from binding errors: `MessageCodesResolver`.
Spring MVC has a strategy for generating error codes for rendering error messages from binding errors: javadoc:org.springframework.validation.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 javadoc:{url-spring-framework-javadoc}/org.springframework.validation.DefaultMessageCodesResolver#Format[]).
@ -117,14 +117,14 @@ If you set the configprop:spring.mvc.message-codes-resolver-format[] property `P
[[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.
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 javadoc:jakarta.servlet.ServletContext[].
It uses the javadoc:org.springframework.web.servlet.resource.ResourceHttpRequestHandler[] from Spring MVC so that you can modify that behavior by adding your own javadoc:org.springframework.web.servlet.config.annotation.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`.
The default servlet acts as a fallback, serving content from the root of the javadoc:jakarta.servlet.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 javadoc:org.springframework.web.servlet.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:
@ -166,7 +166,7 @@ spring:
paths: "/**"
----
NOTE: Links to resources are rewritten in templates at runtime, thanks to a `ResourceUrlEncodingFilter` that is auto-configured for Thymeleaf and FreeMarker.
NOTE: Links to resources are rewritten in templates at runtime, thanks to a javadoc:org.springframework.web.servlet.resource.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 javadoc:{url-spring-framework-javadoc}/org.springframework.web.servlet.resource.ResourceUrlProvider[].
@ -210,15 +210,15 @@ 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 `org.springframework.web.servlet.HandlerMapping` beans which is by default the following:
The ordering is defined by the order of javadoc:org.springframework.web.servlet.HandlerMapping[] beans which is by default the following:
[cols="1,1"]
|===
|`RouterFunctionMapping`
|Endpoints declared with `org.springframework.web.servlet.function.RouterFunction` beans
|Endpoints declared with javadoc:org.springframework.web.servlet.function.RouterFunction[] beans
|`RequestMappingHandlerMapping`
|Endpoints declared in `@Controller` beans
|Endpoints declared in javadoc:org.springframework.stereotype.Controller[format=annotation] beans
|`WelcomePageHandlerMapping`
|The welcome page support
@ -237,7 +237,7 @@ If such a file is present, it is automatically used as the favicon of the applic
[[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 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, javadoc:org.springframework.web.bind.annotation.GetMapping[format=annotation] 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].
@ -278,10 +278,10 @@ spring:
----
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[]).
By default, Spring Boot uses the javadoc:org.springframework.web.util.pattern.PathPatternParser[] strategy.
javadoc:org.springframework.web.util.pattern.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 javadoc:org.springframework.util.AntPathMatcher[] strategy.
javadoc:org.springframework.web.util.pattern.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 javadoc:org.springframework.web.servlet.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:
@ -293,18 +293,18 @@ spring:
matching-strategy: "ant-path-matcher"
----
Spring MVC will throw a `NoHandlerFoundException` if a handler is not found for a request.
Spring MVC will throw a javadoc:org.springframework.web.servlet.NoHandlerFoundException[] if a handler is not found for a request.
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.
If no static content is available, `ResourceHttpRequestHandler` will throw a `org.springframework.web.servlet.resource.NoResourceFoundException`.
For a `NoHandlerFoundException` to be thrown, 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.
If no static content is available, javadoc:org.springframework.web.servlet.resource.ResourceHttpRequestHandler[] will throw a javadoc:org.springframework.web.servlet.resource.NoResourceFoundException[].
For a javadoc:org.springframework.web.servlet.NoHandlerFoundException[] to be thrown, 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.
Spring MVC uses a javadoc:org.springframework.web.bind.support.WebBindingInitializer[] to initialize a javadoc:org.springframework.web.bind.WebDataBinder[] for a particular request.
If you create your own javadoc:org.springframework.web.bind.support.ConfigurableWebBindingInitializer[] javadoc:org.springframework.context.annotation.Bean[format=annotation], Spring Boot automatically configures Spring MVC to use it.
@ -339,16 +339,16 @@ If you have this problem, you can reorder the classpath in the IDE to place the
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 `org.springframework.web.servlet.View` that resolves to `error`).
For browser clients, there is a "`whitelabel`" error view that renders the same data in HTML format (to customize it, add a javadoc:org.springframework.web.servlet.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 `org.springframework.boot.web.servlet.error.ErrorAttributes` to use the existing mechanism but replace the contents.
To replace the default behavior completely, you can implement javadoc:org.springframework.boot.web.servlet.error.ErrorController[] and register a bean definition of that type or add a bean of type javadoc:org.springframework.boot.web.servlet.error.ErrorAttributes[] to use the existing mechanism but replace the contents.
TIP: The `BasicErrorController` can be used as a base class for a custom `ErrorController`.
TIP: The javadoc:org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController[] can be used as a base class for a custom javadoc:org.springframework.boot.web.servlet.error.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.
To do so, extend javadoc:org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController[], add a public method with a javadoc:org.springframework.web.bind.annotation.RequestMapping[format=annotation] 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 9457 Problem Details] is supported.
Spring MVC can produce custom error messages with the `application/problem+json` media type, like:
@ -366,11 +366,11 @@ Spring MVC can produce custom error messages with the `application/problem+json`
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:
You can also define a class annotated with javadoc:org.springframework.web.bind.annotation.ControllerAdvice[format=annotation] 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 `org.springframework.boot.web.servlet.error.ErrorAttributes` representation.
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 javadoc:org.springframework.boot.web.servlet.error.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].
@ -414,28 +414,28 @@ src/
+- <other templates>
----
For more complex mappings, you can also add beans that implement the `ErrorViewResolver` interface, as shown in the following example:
For more complex mappings, you can also add beans that implement the javadoc:org.springframework.boot.autoconfigure.web.servlet.error.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.
The javadoc:org.springframework.boot.web.servlet.error.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 `org.springframework.boot.web.server.ErrorPage` instances.
This abstraction works directly with the underlying embedded servlet container and works even if you do not have a Spring MVC `DispatcherServlet`.
For applications that do not use Spring MVC, you can use the javadoc:org.springframework.boot.web.server.ErrorPageRegistrar[] interface to directly register javadoc:org.springframework.boot.web.server.ErrorPage[] instances.
This abstraction works directly with the underlying embedded servlet container and works even if you do not have a Spring MVC javadoc:org.springframework.web.servlet.DispatcherServlet[].
include-code::MyErrorPagesConfiguration[]
NOTE: If you register an `org.springframework.boot.web.server.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:
NOTE: If you register an javadoc:org.springframework.boot.web.server.ErrorPage[] with a path that ends up being handled by a javadoc:jakarta.servlet.Filter[] (as is common with some non-Spring web frameworks, like Jersey and Wicket), then the javadoc:jakarta.servlet.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.
Note that the default javadoc:org.springframework.boot.web.servlet.FilterRegistrationBean[] does not include the `ERROR` dispatcher type.
@ -459,7 +459,7 @@ https://en.wikipedia.org/wiki/Cross-origin_resource_sharing[Cross-origin resourc
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 javadoc:{url-spring-framework-javadoc}/org.springframework.web.bind.annotation.CrossOrigin[format=annotation] 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:
{url-spring-framework-docs}/web/webmvc-cors.html#mvc-cors-global[Global CORS configuration] can be defined by registering a javadoc:org.springframework.web.servlet.config.annotation.WebMvcConfigurer[] bean with a customized `addCorsMappings(CorsRegistry)` method, as shown in the following example:
include-code::MyCorsConfiguration[]
@ -470,10 +470,10 @@ include-code::MyCorsConfiguration[]
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.
CXF requires you to register its javadoc:jakarta.servlet.Servlet[] or javadoc:jakarta.servlet.Filter[] as a javadoc:org.springframework.context.annotation.Bean[format=annotation] 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 `org.glassfish.jersey.server.ResourceConfig` in which you register all the endpoints, as shown in the following example:
To get started with Jersey, include the `spring-boot-starter-jersey` as a dependency and then you need one javadoc:org.springframework.context.annotation.Bean[format=annotation] of type javadoc:org.glassfish.jersey.server.ResourceConfig[] in which you register all the endpoints, as shown in the following example:
include-code::MyJerseyConfig[]
@ -481,21 +481,21 @@ 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:how-to: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`.
For more advanced customizations, you can also register an arbitrary number of beans that implement javadoc:org.springframework.boot.autoconfigure.jersey.ResourceConfigCustomizer[].
All the registered endpoints should be a `@Component` with HTTP resource annotations (`@GET` and others), as shown in the following example:
All the registered endpoints should be a javadoc:org.springframework.stereotype.Component[format=annotation] 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.
Since the javadoc:org.springframework.boot.actuate.endpoint.annotation.Endpoint[format=annotation] is a Spring javadoc:org.springframework.stereotype.Component[format=annotation], its lifecycle is managed by Spring and you can use the javadoc:org.springframework.beans.factory.annotation.Autowired[format=annotation] annotation to inject dependencies and use the javadoc:org.springframework.beans.factory.annotation.Value[format=annotation] 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 `org.glassfish.jersey.server.ResourceConfig`.
You can change the mapping by adding javadoc:jakarta.ws.rs.ApplicationPath[format=annotation] to your javadoc:org.glassfish.jersey.server.ResourceConfig[].
By default, Jersey is set up as a servlet in a `@Bean` of type `ServletRegistrationBean` named `jerseyServletRegistration`.
By default, Jersey is set up as a servlet in a javadoc:org.springframework.context.annotation.Bean[format=annotation] of type javadoc:org.springframework.boot.web.servlet.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`.
You can also use a filter instead of a servlet by setting `spring.jersey.type=filter` (in which case, the javadoc:org.springframework.context.annotation.Bean[format=annotation] to replace or override is `jerseyFilterRegistration`).
The filter has an javadoc:org.springframework.core.annotation.Order[format=annotation], 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.
@ -514,72 +514,72 @@ 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.
When using an embedded servlet container, you can register servlets, filters, and all the listeners (such as javadoc:jakarta.servlet.http.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.
Any javadoc:jakarta.servlet.Servlet[], javadoc:jakarta.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.
If convention-based mapping is not flexible enough, you can use the javadoc:org.springframework.boot.web.servlet.ServletRegistrationBean[], javadoc:org.springframework.boot.web.servlet.FilterRegistrationBean[], and javadoc:org.springframework.boot.web.servlet.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.
If a specific order is required, you should annotate the javadoc:jakarta.servlet.Filter[] with javadoc:org.springframework.core.annotation.Order[format=annotation] or make it implement javadoc:org.springframework.core.Ordered[].
You cannot configure the order of a javadoc:jakarta.servlet.Filter[] by annotating its bean method with javadoc:org.springframework.core.annotation.Order[format=annotation].
If you cannot change the javadoc:jakarta.servlet.Filter[] class to add javadoc:org.springframework.core.annotation.Order[format=annotation] or implement javadoc:org.springframework.core.Ordered[], you must define a javadoc:org.springframework.boot.web.servlet.FilterRegistrationBean[] for the javadoc:jakarta.servlet.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`).
TIP: To see the order of every javadoc:jakarta.servlet.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 javadoc:org.springframework.boot.web.servlet.DelegatingFilterProxyRegistrationBean[] instead.
WARNING: Take care when registering javadoc:jakarta.servlet.Filter[] beans since they are initialized very early in the application lifecycle.
If you need to register a javadoc:jakarta.servlet.Filter[] that interacts with other beans, consider using a javadoc:org.springframework.boot.web.servlet.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.
Embedded servlet containers do not directly execute the javadoc:jakarta.servlet.ServletContainerInitializer[] interface or Spring's javadoc: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`.
If you need to perform servlet context initialization in a Spring Boot application, you should register a bean that implements the javadoc:org.springframework.boot.web.servlet.ServletContextInitializer[] interface.
The single `onStartup` method provides access to the javadoc:jakarta.servlet.ServletContext[] and, if necessary, can easily be used as an adapter to an existing javadoc:org.springframework.web.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 `@jakarta.servlet.annotation.WebServlet`, `@jakarta.servlet.annotation.WebFilter`, and `@jakarta.servlet.annotation.WebListener` can be enabled by using `@ServletComponentScan`.
When using an embedded container, automatic registration of classes annotated with javadoc:jakarta.servlet.annotation.WebServlet[format=annotation], javadoc:jakarta.servlet.annotation.WebFilter[format=annotation], and javadoc:jakarta.servlet.annotation.WebListener[format=annotation] can be enabled by using javadoc:org.springframework.boot.web.servlet.ServletComponentScan[format=annotation].
TIP: `@ServletComponentScan` has no effect in a standalone container, where the container's built-in discovery mechanisms are used instead.
TIP: javadoc:org.springframework.boot.web.servlet.ServletComponentScan[format=annotation] 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.
Under the hood, Spring Boot uses a different type of javadoc:org.springframework.context.ApplicationContext[] for embedded servlet container support.
The javadoc:org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext[] is a special type of javadoc:org.springframework.web.context.WebApplicationContext[] that bootstraps itself by searching for a single javadoc:org.springframework.boot.web.servlet.server.ServletWebServerFactory[] bean.
Usually a javadoc:org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory[], javadoc:org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory[], or javadoc:org.springframework.boot.web.embedded.undertow.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.
Most applications are auto-configured, and the appropriate javadoc:org.springframework.context.ApplicationContext[] and javadoc:org.springframework.boot.web.servlet.server.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.
In an embedded container setup, the javadoc:jakarta.servlet.ServletContext[] is set as part of server startup which happens during application context initialization.
Because of this beans in the javadoc:org.springframework.context.ApplicationContext[] cannot be reliably initialized with a javadoc:jakarta.servlet.ServletContext[].
One way to get around this is to inject javadoc:org.springframework.context.ApplicationContext[] as a dependency of the bean and access the javadoc:jakarta.servlet.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:
This can be done using an javadoc:org.springframework.context.ApplicationListener[] which listens for the javadoc:org.springframework.boot.context.event.ApplicationStartedEvent[] as follows:
include-code::MyDemoBean[]
@ -588,7 +588,7 @@ include-code::MyDemoBean[]
[[web.servlet.embedded-container.customizing]]
=== Customizing Embedded Servlet Containers
Common servlet container settings can be configured by using Spring `Environment` properties.
Common servlet container settings can be configured by using Spring javadoc:org.springframework.core.env.Environment[] properties.
Usually, you would define the properties in your `application.properties` or `application.yaml` file.
Common server settings include:
@ -615,7 +615,7 @@ The attribute is particularly relevant for modern web browsers which have starte
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.
It is also used to configure Spring Session servlet based javadoc:org.springframework.session.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:
@ -628,8 +628,8 @@ server:
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 `jakarta.servlet.http.Cookie` and may return a `+SameSite+` value, or `null`.
If you want to change the `+SameSite+` attribute on other cookies added to your javadoc:jakarta.servlet.http.HttpServletResponse[], you can use a javadoc:org.springframework.boot.web.servlet.server.CookieSameSiteSupplier[].
The javadoc:org.springframework.boot.web.servlet.server.CookieSameSiteSupplier[] is passed a javadoc:jakarta.servlet.http.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.*`.
@ -664,14 +664,14 @@ This is equivalent to a `<locale-encoding-mapping-list>` entry in a `web.xml` fi
[[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.
If you need to programmatically configure your embedded servlet container, you can register a Spring bean that implements the javadoc:org.springframework.boot.web.server.WebServerFactoryCustomizer[] interface.
javadoc:org.springframework.boot.web.server.WebServerFactoryCustomizer[] provides access to the javadoc:org.springframework.boot.web.servlet.server.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:
javadoc:org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory[], javadoc:org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory[] and javadoc:org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory[] are dedicated variants of javadoc:org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory[] that have additional customization setter methods for Tomcat, Jetty and Undertow respectively.
The following example shows how to customize javadoc:org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory[] that provides access to Tomcat-specific configuration options:
include-code::MyTomcatWebServerFactoryCustomizer[]
@ -680,7 +680,7 @@ 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.
For more advanced use cases that require you to extend from javadoc:org.springframework.boot.web.servlet.server.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.

View File

@ -55,13 +55,13 @@ If you wish to not expose information about the schema, you can disable introspe
[[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`.
The GraphQL Java javadoc:graphql.schema.idl.RuntimeWiring$Builder[] can be used to register custom scalar types, directives, type resolvers, javadoc:graphql.schema.DataFetcher[], and more.
You can declare javadoc:org.springframework.graphql.execution.RuntimeWiringConfigurer[] beans in your Spring config to get access to the javadoc:graphql.schema.idl.RuntimeWiring$Builder[].
Spring Boot detects such beans and adds them to the {url-spring-graphql-docs}/request-execution.html#execution.graphqlsource[GraphQlSource builder].
Typically, however, applications will not implement `DataFetcher` directly and will instead create {url-spring-graphql-docs}/controllers.html[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:
Typically, however, applications will not implement javadoc:graphql.schema.DataFetcher[] directly and will instead create {url-spring-graphql-docs}/controllers.html[annotated controllers].
Spring Boot will automatically detect javadoc:org.springframework.stereotype.Controller[format=annotation] classes with annotated handler methods and register those as ``DataFetcher``s.
Here's a sample implementation for our greeting query with a javadoc:org.springframework.stereotype.Controller[format=annotation] class:
include-code::GreetingController[]
@ -71,16 +71,16 @@ include-code::GreetingController[]
== Querydsl and QueryByExample Repositories Support
Spring Data offers support for both Querydsl and QueryByExample repositories.
Spring GraphQL can {url-spring-graphql-docs}/data.html[configure Querydsl and QueryByExample repositories as `DataFetcher`].
Spring GraphQL can {url-spring-graphql-docs}/data.html[configure Querydsl and QueryByExample repositories as javadoc:graphql.schema.DataFetcher[]].
Spring Data repositories annotated with `@GraphQlRepository` and extending one of:
Spring Data repositories annotated with javadoc:org.springframework.graphql.data.GraphQlRepository[format=annotation] and extending one of:
* `QuerydslPredicateExecutor`
* `ReactiveQuerydslPredicateExecutor`
* `QueryByExampleExecutor`
* `ReactiveQueryByExampleExecutor`
* javadoc:org.springframework.data.querydsl.QuerydslPredicateExecutor[]
* javadoc:org.springframework.data.querydsl.ReactiveQuerydslPredicateExecutor[]
* javadoc:org.springframework.data.repository.query.QueryByExampleExecutor[]
* javadoc:org.springframework.data.repository.query.ReactiveQueryByExampleExecutor[]
are detected by Spring Boot and considered as candidates for `DataFetcher` for matching top-level queries.
are detected by Spring Boot and considered as candidates for javadoc:graphql.schema.DataFetcher[] for matching top-level queries.
@ -96,8 +96,8 @@ 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.
TIP: The HTTP endpoint for both Spring MVC and Spring WebFlux is provided by a `+RouterFunction+` bean with an javadoc:org.springframework.core.annotation.Order[format=annotation] of `0`.
If you define your own `+RouterFunction+` beans, you may want to add appropriate javadoc:org.springframework.core.annotation.Order[format=annotation] annotations to ensure that they are sorted correctly.
The GraphQL WebSocket endpoint is off by default. To enable it:
@ -107,7 +107,7 @@ The GraphQL WebSocket endpoint is off by default. To enable it:
Spring GraphQL provides a {url-spring-graphql-docs}/transports.html#server.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 `WebGraphQlInterceptor` bean to have it registered with the web transport.
With Spring Boot, you can declare a javadoc:org.springframework.graphql.server.WebGraphQlInterceptor[] 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.
@ -131,7 +131,7 @@ spring:
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`.
For example, configuring that mapping as `"graphql"` means we can use that as a route when sending requests with the javadoc:org.springframework.graphql.client.RSocketGraphQlClient[].
Spring Boot auto-configures a `RSocketGraphQlClient.Builder<?>` bean that you can inject in your components:
@ -145,9 +145,9 @@ 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}/controllers.html#controllers.exception-handler[Spring GraphQL exception handling documentation].
Spring Boot will automatically detect `DataFetcherExceptionResolver` beans and register them with the `GraphQlSource.Builder`.
Spring GraphQL enables applications to register one or more Spring javadoc:org.springframework.graphql.execution.DataFetcherExceptionResolver[] components that are invoked sequentially.
The Exception must be resolved to a list of javadoc:{url-graphql-java-javadoc}/graphql.GraphQLError[] objects, see {url-spring-graphql-docs}/controllers.html#controllers.exception-handler[Spring GraphQL exception handling documentation].
Spring Boot will automatically detect javadoc:org.springframework.graphql.execution.DataFetcherExceptionResolver[] beans and register them with the javadoc:org.springframework.graphql.execution.GraphQlSource$Builder[].

View File

@ -2,14 +2,14 @@
= 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.
The auto-configuration replaces the need to use javadoc:org.springframework.hateoas.config.EnableHypermediaSupport[format=annotation] and registers a number of beans to ease building hypermedia-based applications, including a javadoc:org.springframework.hateoas.client.LinkDiscoverers[] (for client side support) and an javadoc:com.fasterxml.jackson.databind.ObjectMapper[] configured to correctly marshal responses into the desired representation.
The javadoc:com.fasterxml.jackson.databind.ObjectMapper[] is customized by setting the various `spring.jackson.*` properties or, if one exists, by a javadoc:org.springframework.http.converter.json.Jackson2ObjectMapperBuilder[] bean.
You can take control of Spring HATEOAS's configuration by using `@EnableHypermediaSupport`.
Note that doing so disables the `ObjectMapper` customization described earlier.
You can take control of Spring HATEOAS's configuration by using javadoc:org.springframework.hateoas.config.EnableHypermediaSupport[format=annotation].
Note that doing so disables the javadoc:com.fasterxml.jackson.databind.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.
To disable this behavior set configprop:spring.hateoas.use-hal-as-default-json-media-type[] to `false` and define a javadoc:org.springframework.hateoas.config.HypermediaMappingInformation[] or javadoc:org.springframework.hateoas.mediatype.hal.HalConfiguration[] to configure Spring HATEOAS to meet the needs of your application and its clients.

View File

@ -3,10 +3,10 @@
If {url-spring-security-site}[Spring Security] is on the classpath, then web applications are secured by default.
Spring Boot relies on Spring Securitys 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.
To add method-level security to a web application, you can also add javadoc:org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity[format=annotation] 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 default javadoc:org.springframework.security.core.userdetails.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]
@ -23,35 +23,35 @@ You can change the username and password by providing a `spring.security.user.na
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 javadoc:org.springframework.boot.autoconfigure.security.SecurityProperties$User[] for the properties of the user).
* A javadoc:org.springframework.security.core.userdetails.UserDetailsService[] (or javadoc:org.springframework.security.core.userdetails.ReactiveUserDetailsService[] in case of a WebFlux application) bean with in-memory store and a single user with a generated password (see javadoc:org.springframework.boot.autoconfigure.security.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.
* A javadoc:org.springframework.security.authentication.DefaultAuthenticationEventPublisher[] for publishing authentication events.
You can provide a different `AuthenticationEventPublisher` by adding a bean for it.
You can provide a different javadoc:org.springframework.security.authentication.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.
The default security configuration is implemented in javadoc:org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration[] and javadoc:org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration[].
javadoc:org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration[] imports `+SpringBootWebSecurityConfiguration+` for web security and javadoc:org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration[] configures authentication, which is also relevant in non-web applications.
To completely switch off the default web application security configuration, including Actuator security, 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).
To also switch off the `UserDetailsService` configuration, add a bean of type `UserDetailsService`, `org.springframework.security.authentication.AuthenticationProvider`, or `AuthenticationManager`.
To completely switch off the default web application security configuration, including Actuator security, or to combine multiple Spring Security components such as OAuth2 Client and Resource Server, add a bean of type javadoc:org.springframework.security.web.SecurityFilterChain[] (doing so does not disable the javadoc:org.springframework.security.core.userdetails.UserDetailsService[] configuration).
To also switch off the javadoc:org.springframework.security.core.userdetails.UserDetailsService[] configuration, add a bean of type javadoc:org.springframework.security.core.userdetails.UserDetailsService[], javadoc:org.springframework.security.authentication.AuthenticationProvider[], or javadoc:org.springframework.security.authentication.AuthenticationManager[].
The auto-configuration of a `UserDetailsService` will also back off any of the following Spring Security modules is on the classpath:
The auto-configuration of a javadoc:org.springframework.security.core.userdetails.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.
To use javadoc:org.springframework.security.core.userdetails.UserDetailsService[] in addition to one or more of these dependencies, define your own javadoc:org.springframework.security.provisioning.InMemoryUserDetailsManager[] bean.
Access rules can be overridden by adding a custom `SecurityFilterChain` bean.
Access rules can be overridden by adding a custom javadoc:org.springframework.security.web.SecurityFilterChain[] bean.
Spring Boot provides convenience methods that can be used to override access rules for actuator endpoints and static resources.
`org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest` can be used to create a `org.springframework.security.web.util.matcher.RequestMatcher` that is based on the configprop:management.endpoints.web.base-path[] property.
`org.springframework.boot.autoconfigure.security.servlet.PathRequest` can be used to create a `org.springframework.security.web.util.matcher.RequestMatcher` for resources in commonly used locations.
javadoc:org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest[] can be used to create a javadoc:org.springframework.security.web.util.matcher.RequestMatcher[] that is based on the configprop:management.endpoints.web.base-path[] property.
javadoc:org.springframework.boot.autoconfigure.security.servlet.PathRequest[] can be used to create a javadoc:org.springframework.security.web.util.matcher.RequestMatcher[] for resources in commonly used locations.
@ -59,24 +59,24 @@ Spring Boot provides convenience methods that can be used to override access rul
== 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.
The default security configuration is implemented in javadoc:org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration[] and javadoc:org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration[].
javadoc:org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration[] imports `+WebFluxSecurityConfiguration+` for web security and javadoc:org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration[] configures authentication, which is also relevant in non-web applications.
To completely switch off the default web application security configuration, including Actuator security, add a bean of type `WebFilterChainProxy` (doing so does not disable the `UserDetailsService` configuration).
To also switch off the `UserDetailsService` configuration, add a bean of type `ReactiveUserDetailsService` or `ReactiveAuthenticationManager`.
To completely switch off the default web application security configuration, including Actuator security, add a bean of type javadoc:org.springframework.security.web.server.WebFilterChainProxy[] (doing so does not disable the javadoc:org.springframework.security.core.userdetails.UserDetailsService[] configuration).
To also switch off the javadoc:org.springframework.security.core.userdetails.UserDetailsService[] configuration, add a bean of type javadoc:org.springframework.security.core.userdetails.ReactiveUserDetailsService[] or javadoc:org.springframework.security.authentication.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.
To use javadoc:org.springframework.security.core.userdetails.ReactiveUserDetailsService[] in addition to one or more of these dependencies, define your own javadoc:org.springframework.security.core.userdetails.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.
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 javadoc:org.springframework.security.web.server.SecurityWebFilterChain[] bean.
Spring Boot provides convenience methods that can be used to override access rules for actuator endpoints and static resources.
`org.springframework.boot.actuate.autoconfigure.security.reactive.EndpointRequest` can be used to create a `ServerWebExchangeMatcher` that is based on the configprop:management.endpoints.web.base-path[] property.
javadoc:org.springframework.boot.actuate.autoconfigure.security.reactive.EndpointRequest[] can be used to create a javadoc:org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher[] that is based on the configprop:management.endpoints.web.base-path[] property.
`org.springframework.boot.autoconfigure.security.reactive.PathRequest` can be used to create a `ServerWebExchangeMatcher` for resources in commonly used locations.
javadoc:org.springframework.boot.autoconfigure.security.reactive.PathRequest[] can be used to create a javadoc:org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher[] for resources in commonly used locations.
For example, you can customize your security configuration by adding something like:
@ -95,7 +95,7 @@ https://oauth.net/2/[OAuth2] is a widely used authorization framework that is su
=== 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`.
This configuration makes use of the properties under javadoc:org.springframework.boot.autoconfigure.security.oauth2.client.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:
@ -164,15 +164,15 @@ spring:
issuer-uri: "https://dev-123456.oktapreview.com/oauth2/default/"
----
By default, Spring Security's `OAuth2LoginAuthenticationFilter` only processes URLs matching `/login/oauth2/code/*`.
By default, Spring Security's javadoc:org.springframework.security.oauth2.client.web.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:
For example, for servlet applications, you can add your own javadoc:org.springframework.security.web.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`.
TIP: Spring Boot auto-configures an javadoc:org.springframework.security.oauth2.client.InMemoryOAuth2AuthorizedClientService[] which is used by Spring Security for the management of client registrations.
The javadoc:org.springframework.security.oauth2.client.InMemoryOAuth2AuthorizedClientService[] has limited capabilities and we recommend using it only for development environments.
For production environments, consider using a javadoc:org.springframework.security.oauth2.client.JdbcOAuth2AuthorizedClientService[] or creating your own implementation of javadoc:org.springframework.security.oauth2.client.OAuth2AuthorizedClientService[].
@ -248,7 +248,7 @@ spring:
----
The same properties are applicable for both servlet and reactive applications.
Alternatively, you can define your own `org.springframework.security.oauth2.jwt.JwtDecoder` bean for servlet applications or a `org.springframework.security.oauth2.jwt.ReactiveJwtDecoder` for reactive applications.
Alternatively, you can define your own javadoc:org.springframework.security.oauth2.jwt.JwtDecoder[] bean for servlet applications or a javadoc:org.springframework.security.oauth2.jwt.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:
@ -265,7 +265,7 @@ spring:
----
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.
Alternatively, you can define your own javadoc:org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector[] bean for servlet applications or a javadoc:org.springframework.security.oauth2.server.resource.introspection.ReactiveOpaqueTokenIntrospector[] for reactive applications.
@ -317,23 +317,23 @@ spring:
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()`.
NOTE: The `client-secret` property must be in a format that can be matched by the configured javadoc:org.springframework.security.crypto.password.PasswordEncoder[].
The default instance of javadoc:org.springframework.security.crypto.password.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`
* javadoc:org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository[]
* javadoc:org.springframework.security.oauth2.server.authorization.settings.AuthorizationServerSettings[]
* javadoc:org.springframework.security.web.SecurityFilterChain[]
* `com.nimbusds.jose.jwk.source.JWKSource<com.nimbusds.jose.proc.SecurityContext>`
* `org.springframework.security.oauth2.jwt.JwtDecoder`
* javadoc:org.springframework.security.oauth2.jwt.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`.
TIP: Spring Boot auto-configures an javadoc:org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository[] which is used by Spring Authorization Server for the management of registered clients.
The javadoc:org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository[] has limited capabilities and we recommend using it only for development environments.
For production environments, consider using a javadoc:org.springframework.security.oauth2.server.authorization.client.JdbcRegisteredClientRepository[] or creating your own implementation of javadoc:org.springframework.security.oauth2.server.authorization.client.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].
@ -348,7 +348,7 @@ Additional information can be found in the {url-spring-authorization-server-docs
=== 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`.
This configuration makes use of the properties under javadoc:org.springframework.boot.autoconfigure.security.saml2.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:
@ -401,8 +401,8 @@ spring:
binding: "POST"
----
For SAML2 logout, by default, Spring Security's `Saml2LogoutRequestFilter` and `Saml2LogoutResponseFilter` only process URLs matching `/logout/saml2/slo`.
For SAML2 logout, by default, Spring Security's javadoc:org.springframework.security.saml2.provider.service.web.authentication.logout.Saml2LogoutRequestFilter[] and javadoc:org.springframework.security.saml2.provider.service.web.authentication.logout.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:
For example, for servlet applications, you can add your own javadoc:org.springframework.security.web.SecurityFilterChain[] that resembles the following:
include-code::MySamlRelyingPartyConfiguration[]

View File

@ -20,7 +20,7 @@ If you have more than one implementation, Spring Boot uses the following order f
. JDBC
. Hazelcast
. MongoDB
. If none of Redis, JDBC, Hazelcast and MongoDB are available, we do not configure a `SessionRepository`.
. If none of Redis, JDBC, Hazelcast and MongoDB are available, we do not configure a javadoc:org.springframework.session.SessionRepository[].
When building a reactive web application, the following stores can be auto-configured:
@ -34,7 +34,7 @@ Similar to the servlet configuration, if you have more than one implementation,
. Redis
. MongoDB
. If neither Redis nor MongoDB are available, we do not configure a `ReactiveSessionRepository`.
. If neither Redis nor MongoDB are available, we do not configure a javadoc:org.springframework.session.ReactiveSessionRepository[].
Each store has specific additional settings.

View File

@ -1,7 +1,7 @@
[[appendix.configuration-metadata.annotation-processor]]
= Generating Your Own Metadata by Using the Annotation Processor
You can easily generate your own configuration metadata file from items annotated with `@ConfigurationProperties` by using the `spring-boot-configuration-processor` jar.
You can easily generate your own configuration metadata file from items annotated with javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] by using the `spring-boot-configuration-processor` jar.
The jar includes a Java annotation processor which is invoked as your project is compiled.
@ -73,14 +73,14 @@ If you are not using this attribute, and annotation processors are picked up by
[[appendix.configuration-metadata.annotation-processor.automatic-metadata-generation]]
== Automatic Metadata Generation
The processor picks up both classes and methods that are annotated with `@ConfigurationProperties`.
The processor picks up both classes and methods that are annotated with javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation].
NOTE: Custom annotations that are meta-annotated with `@ConfigurationProperties` are not supported.
NOTE: Custom annotations that are meta-annotated with javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] are not supported.
If the class has a single parameterized constructor, one property is created per constructor parameter, unless the constructor is annotated with `@Autowired`.
If the class has a constructor explicitly annotated with `@ConstructorBinding`, one property is created per constructor parameter for that constructor.
If the class has a single parameterized constructor, one property is created per constructor parameter, unless the constructor is annotated with javadoc:org.springframework.beans.factory.annotation.Autowired[format=annotation].
If the class has a constructor explicitly annotated with javadoc:org.springframework.boot.context.properties.bind.ConstructorBinding[format=annotation], one property is created per constructor parameter for that constructor.
Otherwise, properties are discovered through the presence of standard getters and setters with special handling for collection and map types (that is detected even if only a getter is present).
The annotation processor also supports the use of the `@lombok.Data`, `@lombok.Value`, `@lombok.Getter`, and `@lombok.Setter` lombok annotations.
The annotation processor also supports the use of the javadoc:{url-lombok-javadoc}/lombok.Data[format=annotation], javadoc:{url-lombok-javadoc}/lombok.Value[format=annotation], javadoc:{url-lombok-javadoc}/lombok.Getter[format=annotation], and javadoc:{url-lombok-javadoc}/lombok.Setter[format=annotation] lombok annotations.
Consider the following example:
@ -89,9 +89,9 @@ include-code::MyServerProperties[]
This exposes three properties where `my.server.name` has no default and `my.server.ip` and `my.server.port` defaults to `"127.0.0.1"` and `9797` respectively.
The Javadoc on fields is used to populate the `description` attribute. For instance, the description of `my.server.ip` is "IP address to listen to.".
NOTE: You should only use plain text with `@ConfigurationProperties` field Javadoc, since they are not processed before being added to the JSON.
NOTE: You should only use plain text with javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] field Javadoc, since they are not processed before being added to the JSON.
If you use `@ConfigurationProperties` with record class then record components' descriptions should be provided via class-level Javadoc tag `@param` (there are no explicit instance fields in record classes to put regular field-level Javadocs on).
If you use javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] with record class then record components' descriptions should be provided via class-level Javadoc tag `@param` (there are no explicit instance fields in record classes to put regular field-level Javadocs on).
The annotation processor applies a number of heuristics to extract the default value from the source model.
Default values have to be provided statically. In particular, do not refer to a constant defined in another class.
@ -132,7 +132,7 @@ Consider the updated example:
include-code::MyServerProperties[]
The preceding example produces metadata information for `my.server.name`, `my.server.host.ip`, and `my.server.host.port` properties.
You can use the `@NestedConfigurationProperty` annotation on a field or a getter method to indicate that a regular (non-inner) class should be treated as if it were nested.
You can use the javadoc:org.springframework.boot.context.properties.NestedConfigurationProperty[format=annotation] annotation on a field or a getter method to indicate that a regular (non-inner) class should be treated as if it were nested.
TIP: This has no effect on collections and maps, as those types are automatically identified, and a single metadata property is generated for each of them.
@ -141,7 +141,7 @@ TIP: This has no effect on collections and maps, as those types are automaticall
[[appendix.configuration-metadata.annotation-processor.adding-additional-metadata]]
== Adding Additional Metadata
Spring Boot's configuration file handling is quite flexible, and it is often the case that properties may exist that are not bound to a `@ConfigurationProperties` bean.
Spring Boot's configuration file handling is quite flexible, and it is often the case that properties may exist that are not bound to a javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] bean.
You may also need to tune some attributes of an existing key.
To support such cases and let you provide custom "hints", the annotation processor automatically merges items from `META-INF/additional-spring-configuration-metadata.json` into the main metadata file.

View File

@ -104,8 +104,8 @@ The JSON object contained in the `groups` array can contain the attributes shown
| `type`
| String
| The class name of the data type of the group.
For example, if the group were based on a class annotated with `@ConfigurationProperties`, the attribute would contain the fully qualified name of that class.
If it were based on a `@Bean` method, it would be the return type of that method.
For example, if the group were based on a class annotated with javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation], the attribute would contain the fully qualified name of that class.
If it were based on a javadoc:org.springframework.context.annotation.Bean[format=annotation] method, it would be the return type of that method.
If the type is not known, the attribute may be omitted.
| `description`
@ -118,12 +118,12 @@ The JSON object contained in the `groups` array can contain the attributes shown
| `sourceType`
| String
| The class name of the source that contributed this group.
For example, if the group were based on a `@Bean` method annotated with `@ConfigurationProperties`, this attribute would contain the fully qualified name of the `@Configuration` class that contains the method.
For example, if the group were based on a javadoc:org.springframework.context.annotation.Bean[format=annotation] method annotated with javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation], this attribute would contain the fully qualified name of the javadoc:org.springframework.context.annotation.Configuration[format=annotation] class that contains the method.
If the source type is not known, the attribute may be omitted.
| `sourceMethod`
| String
| The full name of the method (include parenthesis and argument types) that contributed this group (for example, the name of a `@ConfigurationProperties` annotated `@Bean` method).
| The full name of the method (include parenthesis and argument types) that contributed this group (for example, the name of a javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation] annotated javadoc:org.springframework.context.annotation.Bean[format=annotation] method).
If the source method is not known, it may be omitted.
|===
@ -146,10 +146,10 @@ The JSON object contained in the `properties` array can contain the attributes d
| `type`
| String
| The full signature of the data type of the property (for example, `java.lang.String`) but also a full generic type (such as `java.util.Map<java.lang.String,com.example.MyEnum>`).
| The full signature of the data type of the property (for example, javadoc:java.lang.String[]) but also a full generic type (such as `java.util.Map<java.lang.String,com.example.MyEnum>`).
You can use this attribute to guide the user as to the types of values that they can enter.
For consistency, the type of a primitive is specified by using its wrapper counterpart (for example, `boolean` becomes `java.lang.Boolean`).
Note that this class may be a complex type that gets converted from a `String` as values are bound.
For consistency, the type of a primitive is specified by using its wrapper counterpart (for example, `boolean` becomes javadoc:java.lang.Boolean[]).
Note that this class may be a complex type that gets converted from a javadoc:java.lang.String[] as values are bound.
If the type is not known, it may be omitted.
| `description`
@ -162,7 +162,7 @@ The JSON object contained in the `properties` array can contain the attributes d
| `sourceType`
| String
| The class name of the source that contributed this property.
For example, if the property were from a class annotated with `@ConfigurationProperties`, this attribute would contain the fully qualified name of that class.
For example, if the property were from a class annotated with javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation], this attribute would contain the fully qualified name of that class.
If the source type is unknown, it may be omitted.
| `defaultValue`
@ -212,7 +212,7 @@ NOTE: Prior to Spring Boot 1.3, a single `deprecated` boolean attribute can be u
This is still supported in a deprecated fashion and should no longer be used.
If no reason and replacement are available, an empty `deprecation` object should be set.
Deprecation can also be specified declaratively in code by adding the `@DeprecatedConfigurationProperty` annotation to the getter exposing the deprecated property.
Deprecation can also be specified declaratively in code by adding the javadoc:org.springframework.boot.context.properties.DeprecatedConfigurationProperty[format=annotation] annotation to the getter exposing the deprecated property.
For instance, assume that the `my.app.target` property was confusing and was renamed to `my.app.name`.
The following example shows how to handle that situation:

View File

@ -5,5 +5,5 @@
Spring Boot jars include metadata files that provide details of all supported configuration properties.
The files are designed to let IDE developers offer contextual help and "`code completion`" as users are working with `application.properties` or `application.yaml` files.
The majority of the metadata file is generated automatically at compile time by processing all items annotated with `@ConfigurationProperties`.
The majority of the metadata file is generated automatically at compile time by processing all items annotated with javadoc:org.springframework.boot.context.properties.ConfigurationProperties[format=annotation].
However, it is possible to xref:configuration-metadata/annotation-processor.adoc#appendix.configuration-metadata.annotation-processor.adding-additional-metadata[write part of the metadata manually] for corner cases or more advanced use cases.

View File

@ -15,10 +15,10 @@ The `name` attribute of each hint refers to the `name` of a property.
In the xref:configuration-metadata/format.adoc[initial example shown earlier], we provide five values for the `spring.jpa.hibernate.ddl-auto` property: `none`, `validate`, `update`, `create`, and `create-drop`.
Each value may have a description as well.
If your property is of type `java.util.Map`, you can provide hints for both the keys and the values (but not for the map itself).
If your property is of type javadoc:java.util.Map[], you can provide hints for both the keys and the values (but not for the map itself).
The special `.keys` and `.values` suffixes must refer to the keys and the values, respectively.
Assume a `my.contexts` maps magic `String` values to an integer, as shown in the following example:
Assume a `my.contexts` maps magic javadoc:java.lang.String[] values to an integer, as shown in the following example:
include-code::MyProperties[]
@ -42,7 +42,7 @@ In order to offer additional content assistance for the keys, you could add the
]}
----
TIP: We recommend that you use an `Enum` for those two values instead.
TIP: We recommend that you use an javadoc:java.lang.Enum[] for those two values instead.
If your IDE supports it, this is by far the most effective approach to auto-completion.
@ -139,7 +139,7 @@ This provider supports the following parameters:
| Parameter | Type | Default value | Description
| `target`
| `String` (`Class`)
| javadoc:java.lang.String[] (`Class`)
| _none_
| The fully qualified name of the class that should be assignable to the chosen value.
Typically used to filter out-non candidate classes.
@ -152,7 +152,7 @@ This provider supports the following parameters:
|===
The following metadata snippet corresponds to the standard `server.servlet.jsp.class-name` property that defines the class name to use must be an `HttpServlet`:
The following metadata snippet corresponds to the standard `server.servlet.jsp.class-name` property that defines the class name to use must be an javadoc:jakarta.servlet.http.HttpServlet[]:
[source,json]
----
@ -177,7 +177,7 @@ The following metadata snippet corresponds to the standard `server.servlet.jsp.c
=== Handle As
The **handle-as** provider lets you substitute the type of the property to a more high-level type.
This typically happens when the property has a `java.lang.String` type, because you do not want your configuration classes to rely on classes that may not be on the classpath.
This typically happens when the property has a javadoc:java.lang.String[] type, because you do not want your configuration classes to rely on classes that may not be on the classpath.
This provider supports the following parameters:
[cols="1,1,2,4"]
@ -185,7 +185,7 @@ This provider supports the following parameters:
| Parameter | Type | Default value | Description
| **`target`**
| `String` (`Class`)
| javadoc:java.lang.String[] (`Class`)
| _none_
| The fully qualified name of the type to consider for the property.
This parameter is mandatory.
@ -193,17 +193,17 @@ This provider supports the following parameters:
The following types can be used:
* Any `java.lang.Enum`: Lists the possible values for the property.
(We recommend defining the property with the `Enum` type, as no further hint should be required for the IDE to auto-complete the values)
* `java.nio.charset.Charset`: Supports auto-completion of charset/encoding values (such as `UTF-8`)
* `java.util.Locale`: auto-completion of locales (such as `en_US`)
* `org.springframework.util.MimeType`: Supports auto-completion of content type values (such as `text/plain`)
* `org.springframework.core.io.Resource`: Supports auto-completion of Springs Resource abstraction to refer to a file on the filesystem or on the classpath (such as `classpath:/sample.properties`)
* Any javadoc:java.lang.Enum[]: Lists the possible values for the property.
(We recommend defining the property with the javadoc:java.lang.Enum[] type, as no further hint should be required for the IDE to auto-complete the values)
* javadoc:java.nio.charset.Charset[]: Supports auto-completion of charset/encoding values (such as `UTF-8`)
* javadoc:java.util.Locale[]: auto-completion of locales (such as `en_US`)
* javadoc:org.springframework.util.MimeType[]: Supports auto-completion of content type values (such as `text/plain`)
* javadoc:org.springframework.core.io.Resource[]: Supports auto-completion of Springs Resource abstraction to refer to a file on the filesystem or on the classpath (such as `classpath:/sample.properties`)
TIP: If multiple values can be provided, use a `java.util.Collection` or _Array_ type to teach the IDE about it.
TIP: If multiple values can be provided, use a javadoc:java.util.Collection[] or _Array_ type to teach the IDE about it.
The following metadata snippet corresponds to the standard `spring.liquibase.change-log` property that defines the path to the changelog to use.
It is actually used internally as a `org.springframework.core.io.Resource` but cannot be exposed as such, because we need to keep the original String value to pass it to the Liquibase API.
It is actually used internally as a javadoc:org.springframework.core.io.Resource[] but cannot be exposed as such, because we need to keep the original String value to pass it to the Liquibase API.
[source,json]
----
@ -323,13 +323,13 @@ This provider supports the following parameters:
| Parameter | Type | Default value | Description
| `target`
| `String` (`Class`)
| javadoc:java.lang.String[] (`Class`)
| _none_
| The fully qualified name of the bean class that should be assignable to the candidate.
Typically used to filter out non-candidate beans.
|===
The following metadata snippet corresponds to the standard `spring.jmx.server` property that defines the name of the `MBeanServer` bean to use:
The following metadata snippet corresponds to the standard `spring.jmx.server` property that defines the name of the javadoc:javax.management.MBeanServer[] bean to use:
[source,json]
----
@ -349,7 +349,7 @@ The following metadata snippet corresponds to the standard `spring.jmx.server` p
----
NOTE: The binder is not aware of the metadata.
If you provide that hint, you still need to transform the bean name into an actual Bean reference using by the `ApplicationContext`.
If you provide that hint, you still need to transform the bean name into an actual Bean reference using by the javadoc:org.springframework.context.ApplicationContext[].

View File

@ -1,9 +1,9 @@
[[appendix.executable-jar.jarfile-class]]
= Spring Boot's "`NestedJarFile`" Class
The core class used to support loading nested jars is `org.springframework.boot.loader.jar.NestedJarFile`.
The core class used to support loading nested jars is javadoc:org.springframework.boot.loader.jar.NestedJarFile[].
It lets you load jar content from nested child jar data.
When first loaded, the location of each `JarEntry` is mapped to a physical file offset of the outer jar, as shown in the following example:
When first loaded, the location of each javadoc:java.util.jar.JarEntry[] is mapped to a physical file offset of the outer jar, as shown in the following example:
[source]
----
@ -30,7 +30,7 @@ We do not need to unpack the archive, and we do not need to read all entry data
== Compatibility With the Standard Java "`JarFile`"
Spring Boot Loader strives to remain compatible with existing code and libraries.
`org.springframework.boot.loader.jar.NestedJarFile` extends from `java.util.jar.JarFile` and should work as a drop-in replacement.
javadoc:org.springframework.boot.loader.jar.NestedJarFile[] extends from javadoc:java.util.jar.JarFile[] and should work as a drop-in replacement.
Nested JAR URLs of the form `jar:nested:/path/myjar.jar/!BOOT-INF/lib/mylib.jar!/B.class` are supported and open a connection compatible with `java.net.JarURLConnection`.
These can be used with Java's `URLClassLoader`.
Nested JAR URLs of the form `jar:nested:/path/myjar.jar/!BOOT-INF/lib/mylib.jar!/B.class` are supported and open a connection compatible with javadoc:java.net.JarURLConnection[].
These can be used with Java's javadoc:java.net.URLClassLoader[].

View File

@ -1,16 +1,16 @@
[[appendix.executable-jar.launching]]
= Launching Executable Jars
The `org.springframework.boot.loader.launch.Launcher` class is a special bootstrap class that is used as an executable jar's main entry point.
It is the actual `Main-Class` in your jar file, and it is used to setup an appropriate `ClassLoader` and ultimately call your `main()` method.
The javadoc:org.springframework.boot.loader.launch.Launcher[] class is a special bootstrap class that is used as an executable jar's main entry point.
It is the actual `Main-Class` in your jar file, and it is used to setup an appropriate javadoc:java.lang.ClassLoader[] and ultimately call your `main()` method.
There are three launcher subclasses (`JarLauncher`, `WarLauncher`, and `PropertiesLauncher`).
There are three launcher subclasses (`JarLauncher`, javadoc:org.springframework.boot.loader.launch.WarLauncher[], and javadoc:org.springframework.boot.loader.launch.PropertiesLauncher[]).
Their purpose is to load resources (`.class` files and so on) from nested jar files or war files in directories (as opposed to those explicitly on the classpath).
In the case of `JarLauncher` and `WarLauncher`, the nested paths are fixed.
`JarLauncher` looks in `BOOT-INF/lib/`, and `WarLauncher` looks in `WEB-INF/lib/` and `WEB-INF/lib-provided/`.
In the case of javadoc:org.springframework.boot.loader.launch.JarLauncher[] and javadoc:org.springframework.boot.loader.launch.WarLauncher[], the nested paths are fixed.
javadoc:org.springframework.boot.loader.launch.JarLauncher[] looks in `BOOT-INF/lib/`, and javadoc:org.springframework.boot.loader.launch.WarLauncher[] looks in `WEB-INF/lib/` and `WEB-INF/lib-provided/`.
You can add extra jars in those locations if you want more.
The `PropertiesLauncher` looks in `BOOT-INF/lib/` in your application archive by default.
The javadoc:org.springframework.boot.loader.launch.PropertiesLauncher[] looks in `BOOT-INF/lib/` in your application archive by default.
You can add additional locations by setting an environment variable called `LOADER_PATH` or `loader.path` in `loader.properties` (which is a comma-separated list of directories, archives, or directories within archives).
@ -18,7 +18,7 @@ You can add additional locations by setting an environment variable called `LOAD
[[appendix.executable-jar.launching.manifest]]
== Launcher Manifest
You need to specify an appropriate `org.springframework.boot.loader.launch.Launcher` as the `Main-Class` attribute of `META-INF/MANIFEST.MF`.
You need to specify an appropriate javadoc:org.springframework.boot.loader.launch.Launcher[] as the `Main-Class` attribute of `META-INF/MANIFEST.MF`.
The actual class that you want to launch (that is, the class that contains a `main` method) should be specified in the `Start-Class` attribute.
The following example shows a typical `MANIFEST.MF` for an executable jar file:

View File

@ -1,7 +1,7 @@
[[appendix.executable-jar.property-launcher]]
= PropertiesLauncher Features
`PropertiesLauncher` has a few special features that can be enabled with external properties (System properties, environment variables, manifest entries, or `loader.properties`).
javadoc:org.springframework.boot.loader.launch.PropertiesLauncher[] has a few special features that can be enabled with external properties (System properties, environment variables, manifest entries, or `loader.properties`).
The following table describes these properties:
|===
@ -68,7 +68,7 @@ When specified as environment variables or manifest entries, the following names
TIP: Build plugins automatically move the `Main-Class` attribute to `Start-Class` when the uber jar is built.
If you use that, specify the name of the class to launch by using the `Main-Class` attribute and leaving out `Start-Class`.
The following rules apply to working with `PropertiesLauncher`:
The following rules apply to working with javadoc:org.springframework.boot.loader.launch.PropertiesLauncher[]:
* `loader.properties` is searched for in `loader.home`, then in the root of the classpath, and then in `classpath:/BOOT-INF/classes`.
The first location where a file with that name exists is used.
@ -76,7 +76,7 @@ The following rules apply to working with `PropertiesLauncher`:
* `loader.path` can contain directories (which are scanned recursively for jar and zip files), archive paths, a directory within an archive that is scanned for jar files (for example, `dependencies.jar!/lib`), or wildcard patterns (for the default JVM behavior).
Archive paths can be relative to `loader.home` or anywhere in the file system with a `jar:file:` prefix.
* `loader.path` (if empty) defaults to `BOOT-INF/lib` (meaning a local directory or a nested one if running from an archive).
Because of this, `PropertiesLauncher` behaves the same as `JarLauncher` when no additional configuration is provided.
* `loader.path` can not be used to configure the location of `loader.properties` (the classpath used to search for the latter is the JVM classpath when `PropertiesLauncher` is launched).
Because of this, javadoc:org.springframework.boot.loader.launch.PropertiesLauncher[] behaves the same as javadoc:org.springframework.boot.loader.launch.JarLauncher[] when no additional configuration is provided.
* `loader.path` can not be used to configure the location of `loader.properties` (the classpath used to search for the latter is the JVM classpath when javadoc:org.springframework.boot.loader.launch.PropertiesLauncher[] is launched).
* Placeholder replacement is done from System and environment variables plus the properties file itself on all values before use.
* The search order for properties (where it makes sense to look in more than one place) is environment variables, system properties, `loader.properties`, the exploded archive manifest, and the archive manifest.

View File

@ -7,7 +7,7 @@ You need to consider the following restrictions when working with a Spring Boot
[[appendix.executable-jar-zip-entry-compression]]
* Zip entry compression:
The `ZipEntry` for a nested jar must be saved by using the javadoc:java.util.zip.ZipEntry#STORED[] method.
The javadoc:java.util.zip.ZipEntry[] for a nested jar must be saved by using the javadoc:java.util.zip.ZipEntry#STORED[] method.
This is required so that we can seek directly to individual content within the nested jar.
The content of the nested jar file itself can still be compressed, as can any other entry in the outer jar.

View File

@ -298,16 +298,16 @@ We step through the important parts in the next few sections.
[[getting-started.first-application.code.mvc-annotations]]
=== The @RestController and @RequestMapping Annotations
The first annotation on our `MyApplication` class is `@RestController`.
The first annotation on our `MyApplication` class is javadoc:org.springframework.web.bind.annotation.RestController[format=annotation].
This is known as a _stereotype_ annotation.
It provides hints for people reading the code and for Spring that the class plays a specific role.
In this case, our class is a web `@Controller`, so Spring considers it when handling incoming web requests.
In this case, our class is a web javadoc:org.springframework.stereotype.Controller[format=annotation], so Spring considers it when handling incoming web requests.
The `@RequestMapping` annotation provides "`routing`" information.
The javadoc:org.springframework.web.bind.annotation.RequestMapping[format=annotation] annotation provides "`routing`" information.
It tells Spring that any HTTP request with the `/` path should be mapped to the `home` method.
The `@RestController` annotation tells Spring to render the resulting string directly back to the caller.
The javadoc:org.springframework.web.bind.annotation.RestController[format=annotation] annotation tells Spring to render the resulting string directly back to the caller.
TIP: The `@RestController` and `@RequestMapping` annotations are Spring MVC annotations (they are not specific to Spring Boot).
TIP: The javadoc:org.springframework.web.bind.annotation.RestController[format=annotation] and javadoc:org.springframework.web.bind.annotation.RequestMapping[format=annotation] annotations are Spring MVC annotations (they are not specific to Spring Boot).
See the {url-spring-framework-docs}/web/webmvc.html[MVC section] in the Spring Reference Documentation for more details.
@ -315,11 +315,11 @@ See the {url-spring-framework-docs}/web/webmvc.html[MVC section] in the Spring R
[[getting-started.first-application.code.spring-boot-application]]
=== The @SpringBootApplication Annotation
The second class-level annotation is `@SpringBootApplication`.
This annotation is known as a _meta-annotation_, it combines `@SpringBootConfiguration`, `@EnableAutoConfiguration` and `@ComponentScan`.
The second class-level annotation is javadoc:org.springframework.boot.autoconfigure.SpringBootApplication[format=annotation].
This annotation is known as a _meta-annotation_, it combines javadoc:org.springframework.boot.SpringBootConfiguration[format=annotation], javadoc:org.springframework.boot.autoconfigure.EnableAutoConfiguration[format=annotation] and javadoc:org.springframework.context.annotation.ComponentScan[format=annotation].
Of those, the annotation we're most interested in here is `@EnableAutoConfiguration`.
`@EnableAutoConfiguration` tells Spring Boot to "`guess`" how you want to configure Spring, based on the jar dependencies that you have added.
Of those, the annotation we're most interested in here is javadoc:org.springframework.boot.autoconfigure.EnableAutoConfiguration[format=annotation].
javadoc:org.springframework.boot.autoconfigure.EnableAutoConfiguration[format=annotation] tells Spring Boot to "`guess`" how you want to configure Spring, based on the jar dependencies that you have added.
Since `spring-boot-starter-web` added Tomcat and Spring MVC, the auto-configuration assumes that you are developing a web application and sets up Spring accordingly.
.Starters and Auto-configuration
@ -336,9 +336,9 @@ Spring Boot still does its best to auto-configure your application.
The final part of our application is the `main` method.
This is a standard method that follows the Java convention for an application entry point.
Our main method delegates to Spring Boot's `SpringApplication` class by calling `run`.
`SpringApplication` bootstraps our application, starting Spring, which, in turn, starts the auto-configured Tomcat web server.
We need to pass `MyApplication.class` as an argument to the `run` method to tell `SpringApplication` which is the primary Spring component.
Our main method delegates to Spring Boot's javadoc:org.springframework.boot.SpringApplication[] class by calling `run`.
javadoc:org.springframework.boot.SpringApplication[] bootstraps our application, starting Spring, which, in turn, starts the auto-configured Tomcat web server.
We need to pass `MyApplication.class` as an argument to the `run` method to tell javadoc:org.springframework.boot.SpringApplication[] which is the primary Spring component.
The `args` array is also passed through to expose any command-line arguments.