The preceding example uses `EndpointRequest.toAnyEndpoint()` to match a request to any endpoint and then ensures that all have the `ENDPOINT_ADMIN` role.
Several other matcher methods are also available on `EndpointRequest`.
@ -351,10 +348,7 @@ You can do so by changing the configprop:management.endpoints.web.exposure.inclu
Additionally, if Spring Security is present, you would need to add custom security configuration that allows unauthenticated access to the endpoints, as the following example shows:
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.
@ -442,10 +436,7 @@ Endpoints can be exposed over HTTP by using Spring MVC, or Spring WebFlux.
The following example exposes a read operation that returns a custom object:
NOTE: The identifier for a given `HealthIndicator` is the name of the bean without the `HealthIndicator` suffix, if it exists.
In the preceding example, the health information is available in an entry named `my`.
@ -833,10 +818,7 @@ If you need to register a regular `HealthContributor`, you should wrap it with `
To provide custom health information from a reactive API, you can register Spring beans that implement the {spring-boot-actuator-module-code}/health/ReactiveHealthIndicator.java[`ReactiveHealthIndicator`] interface.
The following code shows a sample `ReactiveHealthIndicator` implementation:
@ -65,17 +65,11 @@ Spring Boot also adds any auto-configured registries to the global static compos
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:
Spring Boot also <<actuator#actuator.metrics.supported,configures built-in instrumentation>> that you can control through configuration or dedicated annotation markers.
@ -308,10 +302,7 @@ Micrometer provides a default `HierarchicalNameMapper` that governs how a dimens
To take control over this behavior, define your `GraphiteMeterRegistry` and supply your own `HierarchicalNameMapper`.
An auto-configured `GraphiteConfig` and `Clock` beans are provided unless you define your own:
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.
@ -1071,10 +1038,7 @@ If you need to apply customizations to specific `Meter` instances, you can use t
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:
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.".
@ -86,10 +83,7 @@ Also, the annotation processor cannot auto-detect default values for ``Enum``s a
For cases where the default value could not be detected, <<configuration-metadata#configuration-metadata.annotation-processor.adding-additional-metadata,manual metadata>> should be provided.
In order to document default values for properties in the class above, you could add the following content to <<configuration-metadata#configuration-metadata.annotation-processor.adding-additional-metadata,the manual metadata of the module>>:
@ -117,10 +111,7 @@ The annotation processor automatically considers inner classes as nested propert
Rather than documenting the `ip` and `port` at the root of the namespace, we could create a sub-namespace for it.
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 to indicate that a regular (non-inner) class should be treated as if it were nested.
The magic values are (in this example) are `sample1` and `sample2`.
In order to offer additional content assistance for the keys, you could add the following JSON to <<configuration-metadata#configuration-metadata.annotation-processor.adding-additional-metadata,the manual metadata of the module>>:
If you have defined your own `MongoClient`, it will be used to auto-configure a suitable `MongoDatabaseFactory`.
@ -119,10 +113,7 @@ The auto-configuration configures this factory automatically if Netty is availab
{spring-data-mongodb}[Spring Data MongoDB] provides a {spring-data-mongodb-api}/core/MongoTemplate.html[`MongoTemplate`] class that is very similar in its design to Spring's `JdbcTemplate`.
As with `JdbcTemplate`, Spring Boot auto-configures a bean for you to inject the template, as follows:
See the {spring-data-mongodb-api}/core/MongoOperations.html[`MongoOperations` Javadoc] for complete details.
@ -136,10 +127,7 @@ As with the JPA repositories discussed earlier, the basic principle is that quer
In fact, both Spring Data JPA and Spring Data MongoDB share the same common infrastructure.
You could take the JPA example from earlier and, assuming that `City` is now a MongoDB data class rather than a JPA `@Entity`, it works in the same way, as shown in the following example:
You can configure various aspects of the driver using `spring.neo4j.*` properties.
The following example shows how to configure the uri and credentials to use:
@ -213,10 +198,7 @@ For complete details of Spring Data Neo4j, see the {spring-data-neo4j-docs}[refe
Spring Data Neo4j shares the common infrastructure with Spring Data JPA as many other Spring Data modules do.
You could take the JPA example from earlier and define `City` as Spring Data Neo4j `@Node` rather than JPA `@Entity` and the repository abstraction works in the same way, as shown in the following example:
In the presence of `spring-data-elasticsearch` and the required dependencies for using a `WebClient` (typically `spring-boot-starter-webflux`), Spring Boot can also auto-configure a <<features#data.nosql.elasticsearch.connecting-using-rest.webclient,ReactiveElasticsearchClient>> and a `ReactiveElasticsearchTemplate` as beans.
They are the reactive equivalent of the other REST clients.
@ -435,10 +408,7 @@ NOTE: If you use `CqlSessionBuilder` to create multiple `CqlSession` beans, keep
The following code listing shows how to inject a Cassandra bean:
@ -158,10 +158,7 @@ For example, the following section in `application.properties` shows how you can
=== Using JdbcTemplate
Spring's `JdbcTemplate` and `NamedParameterJdbcTemplate` classes are auto-configured, and you can `@Autowire` them directly into your own beans, as shown in the following example:
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.
@ -253,10 +244,7 @@ If {spring-data-envers}[Spring Data Envers] is available, JPA repositories are a
To use Spring Data Envers, make sure your repository extends from `RevisionRepository` as show in the following example:
@ -427,17 +409,11 @@ TIP: The "`How-to`" section includes a <<howto#howto.data-initialization.using-b
To customize the connections created by a `ConnectionFactory`, that is, set specific parameters that you do not want (or cannot) configure in your central database configuration, you can use a `ConnectionFactoryOptionsBuilderCustomizer` `@Bean`.
The following example shows how to manually override the database port while the rest of the options is taken from the application configuration:
When a `ConnectionFactory` bean is available, the regular JDBC `DataSource` auto-configuration backs off.
If you want to retain the JDBC `DataSource` auto-configuration, and are comfortable with the risk of using the blocking JDBC API in a reactive application, add `@Import(DataSourceAutoConfiguration.class)` on a `@Configuration` class in your application to re-enable it.
@ -471,10 +447,7 @@ If you want to make sure that each context has a separate embedded database, you
==== Using DatabaseClient
A `DatabaseClient` bean is auto-configured, and you can `@Autowire` it directly into your own beans, as shown in the following example:
TIP: We have barely scratched the surface of Spring Data R2DBC. For complete details, see the {spring-data-r2dbc-docs}[Spring Data R2DBC reference documentation].
@ -93,10 +93,7 @@ Process-scoped environment variables are language agnostic.
Environment variables do not always make for the easiest API, so Spring Boot automatically extracts them and flattens the data into properties that can be accessed through Spring's `Environment` abstraction, as shown in the following example:
All Cloud Foundry properties are prefixed with `vcap`.
You can use `vcap` properties to access application information (such as the public URL of the application) and service information (such as database credentials).
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.
@ -93,10 +90,7 @@ The `search` attribute lets you limit the `ApplicationContext` hierarchy that sh
When placed on a `@Bean` method, the target type defaults to the return type of the method, as shown in the following example:
In the preceding example, the `someService` bean is going to be created if no bean of type `SomeService` is already contained in the `ApplicationContext`.
@ -157,10 +151,7 @@ Concretely, each test should create a well defined `ApplicationContext` that rep
`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:
TIP: If multiple auto-configurations have to be defined, there is no need to order their declarations as they are invoked in the exact same order as when running the application.
@ -168,26 +159,17 @@ Each test can use the runner to represent a particular use case.
For instance, the sample below invokes a user configuration (`UserConfiguration`) and checks that the auto-configuration backs off properly.
Invoking `run` provides a callback context that can be used with `AssertJ`.
On your application classpath (for example, inside your jar) you can have an `application.properties` file that provides a sensible default property value for `name`.
When running in a new environment, an `application.properties` file can be provided outside of your jar that overrides the `name`.
@ -667,10 +664,7 @@ TIP: See also the <<features#features.external-config.typesafe-configuration-pro
==== JavaBean properties binding
It is possible to bind a bean declaring standard JavaBean properties as shown in the following example:
In this setup, the `@ConstructorBinding` annotation is used to indicate that constructor binding should be used.
This means that the binder will expect to find a constructor with the parameters that you wish to have bound.
@ -724,10 +715,7 @@ Default values can be specified using `@DefaultValue` and the same conversion se
By default, if no properties are bound to `Security`, the `MyProperties` instance will contain a `null` value for `security`.
If you wish you return a non-null instance of `Security` even when no properties are bound to it, you can use an empty `@DefaultValue` annotation to do so:
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.
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:
Any JavaBean property defined with the `another` prefix is mapped onto that `AnotherComponent` bean in manner similar to the preceding `SomeProperties` example.
@ -830,10 +806,7 @@ Common examples where this is useful include dash-separated environment properti
As an example, consider the following `@ConfigurationProperties` class:
TIP: If you are upgrading a `Long` property, make sure to define the unit (using `@DataSizeUnit`) if it is not bytes.
Doing so gives a transparent upgrade path while supporting a much richer format.
@ -1162,20 +1117,14 @@ Spring Boot attempts to validate `@ConfigurationProperties` classes whenever the
You can use JSR-303 `javax.validation` constraint annotations directly on your configuration class.
To do so, ensure that a compliant JSR-303 implementation is on your classpath and then add constraint annotations to your fields, as shown in the following example:
TIP: You can also trigger validation by annotating the `@Bean` method that creates the configuration properties with `@Validated`.
To ensure that validation is always triggered for nested properties, even when no properties are found, the associated field must be annotated with `@Valid`.
The following example builds on the preceding `MyProperties` example:
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:
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: 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.
@ -184,10 +178,7 @@ If you need to build an `ApplicationContext` hierarchy (multiple contexts with a
The `SpringApplicationBuilder` lets you chain together multiple method calls and includes `parent` and `child` methods that let you create a hierarchy, as shown in the following example:
Spring Boot provides <<actuator#actuator.endpoints.kubernetes-probes,Kubernetes HTTP probes for "Liveness" and "Readiness" with Actuator Health Endpoints>>.
You can get more guidance about <<deployment#deployment.cloud.kubernetes,deploying Spring Boot applications on Kubernetes in the dedicated section>>.
@ -330,10 +315,7 @@ TIP: It is often desirable to call `setWebApplicationType(WebApplicationType.NON
If you need to access the application arguments that were passed to `SpringApplication.run(...)`, you can inject a `org.springframework.boot.ApplicationArguments` bean.
The `ApplicationArguments` interface provides access to both the raw `String[]` arguments as well as parsed `option` and `non-option` arguments, as shown in the following example:
TIP: Spring Boot also registers a `CommandLinePropertySource` with the Spring `Environment`.
This lets you also inject single application arguments by using the `@Value` annotation.
@ -351,10 +333,7 @@ NOTE: This contract is well suited for tasks that should run after application s
The `CommandLineRunner` interfaces provides access to application arguments as a string array, whereas the `ApplicationRunner` uses the `ApplicationArguments` interface discussed earlier.
The following example shows a `CommandLineRunner` with a `run` method:
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.
@ -368,10 +347,7 @@ All the standard Spring lifecycle callbacks (such as the `DisposableBean` interf
In addition, beans may implement the `org.springframework.boot.ExitCodeGenerator` interface if they wish to return a specific exit code when `SpringApplication.exit()` is called.
This exit code can then be passed to `System.exit()` to return it as a status code, as shown in the following example:
The first available implementation, `FlightRecorderApplicationStartup` is provided by Spring Framework.
It adds Spring-specific startup events to a Java Flight Recorder session and is meant for profiling applications and correlating their Spring context lifecycle with JVM events (such as allocations, GCs, class loading...).
@ -176,19 +167,13 @@ By default, `@SpringBootTest` does not start the server but instead sets up a mo
With Spring MVC, we can query our web endpoints using {spring-framework-docs}/testing.html#spring-mvc-test-framework[`MockMvc`] or `WebTestClient`, as shown in the following example:
TIP: If you want to focus only on the web layer and not start a complete `ApplicationContext`, consider <<features#features.testing.spring-boot-applications.spring-mvc-tests,using `@WebMvcTest` instead>>.
With Spring WebFlux endpoints, you can use {spring-framework-docs}/testing.html#webtestclient-tests[`WebTestClient`] as shown in the following example:
@ -210,20 +195,14 @@ If you use `@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)`, an avai
The `@LocalServerPort` annotation can be used to <<howto#howto.webserver.discover-port,inject the actual port used>> into your test.
For convenience, tests that need to make REST calls to the started server can additionally `@Autowire` a {spring-framework-docs}/testing.html#webtestclient-tests[`WebTestClient`], which resolves relative links to the running server and comes with a dedicated API for verifying responses, as shown in the following example:
TIP: `WebTestClient` can be used against both live servers and <<features#features.testing.spring-boot-applications.with-mock-environment, mock environments>>.
This setup requires `spring-webflux` on the classpath.
If you can not or will not add webflux, Spring Boot also provides a `TestRestTemplate` facility:
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.
If you use HtmlUnit and Selenium, auto-configuration also provides an HtmlUnit `WebClient` bean and/or a Selenium `WebDriver` bean.
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("singleton")` to your `WebDriver` `@Bean` definition.
@ -431,10 +389,7 @@ Often, `@WebFluxTest` is limited to a single controller and used in combination
TIP: You can also auto-configure `WebTestClient` in a non-`@WebFluxTest` (such as `@SpringBootTest`) by annotating it with `@AutoConfigureWebTestClient`.
The following example shows a class that uses both `@WebFluxTest` and a `WebTestClient`:
@ -484,10 +436,7 @@ By default, data JPA tests are transactional and roll back at the end of each te
See the {spring-framework-docs}/testing.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details.
If that is not what you want, you can disable transaction management for a test or for the whole class as follows:
Data JPA tests may also inject a {spring-boot-test-autoconfigure-module-code}/orm/jpa/TestEntityManager.java[`TestEntityManager`] bean, which provides an alternative to the standard JPA `EntityManager` that is specifically designed for tests.
@ -497,18 +446,12 @@ When doing so, make sure that your test is running in a transaction, for instanc
A `JdbcTemplate` is also available if you need that.
The following example shows the `@DataJpaTest` annotation in use:
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:
@ -525,10 +468,7 @@ By default, JDBC tests are transactional and roll back at the end of each test.
See the {spring-framework-docs}/testing.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details.
If that is not what you want, you can disable transaction management for a test or for the whole class, as follows:
JOOQ tests are transactional and roll back at the end of each test by default.
If that is not what you want, you can disable transaction management for a test or for the whole test class as <<features#features.testing.spring-boot-applications.autoconfigured-jdbc,shown in the JDBC example>>.
@ -589,18 +526,12 @@ TIP: A list of the auto-configuration settings that are enabled by `@DataMongoTe
The following class shows the `@DataMongoTest` annotation in use:
In-memory embedded MongoDB generally works well for tests, since it is fast and does not require any developer installation.
If, however, you prefer to run tests against a real MongoDB server, you should exclude the embedded MongoDB auto-configuration, as shown in the following example:
By default, Data Neo4j tests are transactional and roll back at the end of each test.
See the {spring-framework-docs}/testing.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details.
If that is not what you want, you can disable transaction management for a test or for the whole class, as follows:
In-memory embedded LDAP generally works well for tests, since it is fast and does not require any developer installation.
If, however, you prefer to run tests against a real LDAP server, you should exclude the embedded LDAP auto-configuration, as shown in the following example:
@ -692,10 +608,7 @@ TIP: A list of the auto-configuration settings that are enabled by `@RestClientT
The specific beans that you want to test should be specified by using the `value` or `components` attribute of `@RestClientTest`, as shown in the following example:
@ -714,26 +627,17 @@ It can also be used to configure the host, scheme, and port that appears in any
`@AutoConfigureRestDocs` customizes the `MockMvc` bean to use Spring REST Docs when testing servlet-based web applications.
You can inject it by using `@Autowired` and use it in your tests as you normally would when using Mock MVC and Spring REST Docs, as shown in the following example:
If you require more control over Spring REST Docs configuration than offered by the attributes of `@AutoConfigureRestDocs`, you can use a `RestDocsMockMvcConfigurationCustomizer` bean, as shown in the following example:
`@AutoConfigureRestDocs` can also be used with `WebTestClient` when testing reactive web applications.
You can inject it by using `@Autowired` and use it in your tests as you normally would when using `@WebFluxTest` and Spring REST Docs, as shown in the following example:
If you require more control over Spring REST Docs configuration than offered by the attributes of `@AutoConfigureRestDocs`, you can use a `RestDocsWebTestClientConfigurationCustomizer` bean, as shown in the following example:
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:
`@AutoConfigureRestDocs` makes a `RequestSpecification` bean, preconfigured to use Spring REST Docs, available to your tests.
You can inject it by using `@Autowired` and use it in your tests as you normally would when using REST Assured and Spring REST Docs, as shown in the following example:
If you require more control over Spring REST Docs configuration than offered by the attributes of `@AutoConfigureRestDocs`, a `RestDocsRestAssuredConfigurationCustomizer` bean can be used, as shown in the following example:
Each slice provides one or more `@AutoConfigure...` annotations that namely defines the auto-configurations that should be included as part of a slice.
Additional auto-configurations can be added on a test-by-test basis by creating a custom `@AutoConfigure...` annotation or by adding `@ImportAutoConfiguration` to the test as shown in the following example:
Because this class is the source configuration for the test, any slice test actually tries to start Spring Batch, which is definitely not what you want to do.
A recommended approach is to move that area-specific configuration to a separate `@Configuration` class at the same level as your application, as shown in the following example:
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.
@ -875,26 +749,17 @@ The latter approach lets you enable it in one of your tests, if necessary, with
Test slices exclude `@Configuration` classes from scanning.
For example, for a `@WebMvcTest`, the following configuration will not include the given `WebMvcConfigurer` bean in the application context loaded by the test slice:
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.
@ -925,10 +790,7 @@ A few test utility classes that are generally useful when testing your applicati
`ConfigDataApplicationContextInitializer` is an `ApplicationContextInitializer` that you can apply to your tests to load Spring Boot `application.properties` files.
You can use it when you do not need the full set of features provided by `@SpringBootTest`, as shown in the following example:
`OutputCapture` is a JUnit `Extension` that you can use to capture `System.out` and `System.err` output.
To use add `@ExtendWith(OutputCaptureExtension.class)` and inject `CapturedOutput` as an argument to your test class constructor or test method as follows:
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.
Any URLs that do not specify a host and port automatically connect to the embedded server, as shown in the following example:
@ -137,10 +137,7 @@ If you run `mvn dependency:tree` again, you see that there are now a number of a
To finish our application, we need to create a single Java file.
By default, Maven compiles sources from `src/main/java`, so you need to create that directory structure and then add a file named `src/main/java/MyApplication.java` to contain the following code:
You can even go further by leveraging what `DataSourceProperties` does for you -- that is, by providing a default embedded database with a sensible username and password if no URL is provided.
You can easily initialize a `DataSourceBuilder` from the state of any `DataSourceProperties` object, so you could also inject the DataSource that Spring Boot creates automatically.
However, that would split your configuration into two namespaces: `url`, `username`, `password`, `type`, and `driver` on `spring.datasource` and the rest on your custom namespace (`app.datasource`).
To avoid that, you can redefine a custom `DataSourceProperties` on your custom namespace, as shown in the following example:
This setup puts you _in sync_ with what Spring Boot does for you by default, except that a dedicated connection pool is chosen (in code) and its settings are exposed in the `app.datasource.configuration` sub namespace.
Because `DataSourceProperties` is taking care of the `url`/`jdbcUrl` translation for you, you can configure it as follows:
@ -125,10 +113,7 @@ You must, however, mark one of the `DataSource` instances as `@Primary`, because
If you create your own `DataSource`, the auto-configuration backs off.
In the following example, we provide the _exact_ same feature set as the auto-configuration provides on the primary data source:
@ -242,10 +221,7 @@ Alternatively, if `ImplicitNamingStrategy` or `PhysicalNamingStrategy` beans are
By default, Spring Boot configures the physical naming strategy with `SpringPhysicalNamingStrategy`.
This implementation provides the same table structure as Hibernate 4: all dots are replaced by underscores and camel casing is replaced by underscores as well. Additionally, by default, all table names are generated in lower case. For example, a `TelephoneNumber` entity is mapped to the `telephone_number` table. If your schema requires mixed-case identifiers, define a custom `SpringPhysicalNamingStrategy` bean, as shown in the following example:
See {spring-boot-autoconfigure-module-code}/orm/jpa/HibernateJpaAutoConfiguration.java[`HibernateJpaAutoConfiguration`] and {spring-boot-autoconfigure-module-code}/orm/jpa/JpaBaseConfiguration.java[`JpaBaseConfiguration`] for more details.
@ -273,10 +246,7 @@ Rather than configuring Hibernate to lookup the cache provider again, it is bett
To do this with JCache, first make sure that `org.hibernate:hibernate-jcache` is available on the classpath.
Then, add a `HibernatePropertiesCustomizer` bean as shown in the following example:
@ -390,10 +351,7 @@ For example, when Flyway is auto-configured, Hibernate is configured to depend u
If you are configuring a component yourself, you can use an `EntityManagerFactoryDependsOnPostProcessor` subclass as a convenient way of setting up the necessary dependencies.
For example, if you use Hibernate Search with Elasticsearch as its index manager, any `EntityManagerFactory` beans must be configured to depend on the `elasticsearchClient` bean, as shown in the following example:
@ -110,17 +110,11 @@ Then the Spring Boot banner is not printed on startup, and the application is no
Properties defined in external configuration override and replace the values specified with the Java API, with the notable exception of the primary sources.
Primary sources are those provided to the `SpringApplication` constructor:
@ -42,7 +42,4 @@ Alternatively, you can add the `RemoteIpValve` by customizing the `TomcatServlet
To configure Spring Security to require a secure channel for all (or some) requests, consider adding your own `SecurityFilterChain` bean that adds the following `HttpSecurity` configuration:
@ -10,10 +10,7 @@ This section answers common questions about Spring MVC and Spring Boot.
=== Write a JSON REST Service
Any Spring `@RestController` in a Spring Boot application should render JSON response by default as long as Jackson2 is on the classpath, as shown in the following example:
As long as `MyThing` can be serialized by Jackson2 (true for a normal POJO or Groovy object), then `http://localhost:8080/thing` serves a JSON representation of it by default.
Note that, in a browser, you might sometimes see XML responses, because browsers tend to send accept headers that prefer XML.
@ -36,10 +33,7 @@ To use the Jackson XML renderer, add the following dependency to your project:
If Jackson's XML extension is not available and JAXB is available, XML can be rendered with the additional requirement of having `MyThing` annotated as `@XmlRootElement`, as shown in the following example:
Spring Security provides comprehensive integration with Spring MVC Test and this can also be used when testing controllers using the `@WebMvcTest` slice and `MockMvc`.
@ -29,19 +26,13 @@ It integrates with JUnit, allowing you to write a test class that can start up a
Testcontainers is especially useful for writing integration tests that talk to a real backend service such as MySQL, MongoDB, Cassandra and others.
Testcontainers can be used in a Spring Boot test as follows:
The above configuration allows Neo4j-related beans in the application to communicate with Neo4j running inside the Testcontainers-managed Docker container.
The next step is to update your build configuration such that your project produces a war file rather than a jar file.
If you use Maven and `spring-boot-starter-parent` (which configures Maven's war plugin for you), all you need to do is to modify `pom.xml` to change the packaging to war, as follows:
@ -79,10 +76,7 @@ See the https://spring.io/guides/gs/convert-jar-to-war/[Getting Started Guide on
To create a deployable war by extending `SpringBootServletInitializer` (for example, in a class called `Application`) and adding the Spring Boot `@SpringBootApplication` annotation, use code similar to that shown in the following example:
If you intend to start your application as a war or as an executable application, you need to share the customizations of the builder in a method that is both available to the `SpringBootServletInitializer` callback and in the `main` method in a class similar to the following:
@ -101,10 +101,7 @@ The best way to get that and be sure it has been initialized is to add a `@Bean`
Tests that use `@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)` can also inject the actual port into a field by using the `@LocalServerPort` annotation, as shown in the following example:
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.
@ -317,10 +311,7 @@ Like any other Spring bean, you can define the order of servlet filter beans; pl
As <<howto#howto.webserver.add-servlet-filter-listener.spring-bean,described earlier>>, any `Servlet` or `Filter` beans are registered with the servlet container automatically.
To disable registration of a particular `Filter` or `Servlet` bean, create a registration bean for it and mark it as disabled, as shown in the following example:
@ -439,10 +430,7 @@ You can take complete control of the configuration of Tomcat's `RemoteIpValve` b
=== Enable Multiple Connectors with Tomcat
You can add an `org.apache.catalina.connector.Connector` to the `TomcatServletWebServerFactory`, which can allow multiple connectors, including HTTP and HTTPS connectors, as shown in the following example:
@ -459,10 +447,7 @@ If at all possible, you should consider updating your code to only store values
If, however, you cannot change the way that cookies are written, you can instead configure Tomcat to use a `LegacyCookieProcessor`.
To switch to the `LegacyCookieProcessor`, use an `WebServerFactoryCustomizer` bean that adds a `TomcatContextCustomizer`, as shown in the following example:
=== 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:
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.
This example demonstrates the use of caching on a potentially costly operation.
Before invoking `computePiDecimal`, the abstraction looks for an entry in the `piDecimals` cache that matches the `i` argument.
@ -57,10 +54,7 @@ If you add dependencies manually, you must include `spring-context-support` in o
If the `CacheManager` is auto-configured by Spring Boot, you can further tune its configuration before it is fully initialized by exposing a bean that implements the `CacheManagerCustomizer` interface.
The following example sets a flag to say that `null` values should not be passed down to the underlying map:
Finally, you can define your own `RestTemplateBuilder` bean.
Doing so will replace the auto-configured builder.
If you want any `RestTemplateCustomizer` beans to be applied to your custom builder, as the auto-configuration would have done, configure it using a `RestTemplateBuilderConfigurer`.
The following example exposes a `RestTemplateBuilder` that matches what Spring Boot's auto-configuration would have done, except that custom connect and read timeouts are also specified:
By default, `WebServiceTemplateBuilder` detects a suitable HTTP-based `WebServiceMessageSender` using the available HTTP client libraries on the classpath.
You can also customize read and connection timeouts as follows:
You should now have a good understanding of Spring Boot's <<features#features, core features>> and the various technologies that Spring Boot provides support for via auto-configuration.
The next few sections go into detail about deploying applications to cloud platforms.
You can read about <<container-images#container-images, building container images>> in the next section or skip to the <<actuator#actuator, production-ready features>> section.
You can read about <<container-images#container-images, building container images>> in the next section or skip to the <<actuator#actuator, production-ready features>> section.
@ -49,10 +49,7 @@ TIP: See https://spring.io/blog/2010/06/14/understanding-amqp-the-protocol-used-
=== Sending a Message
Spring's `AmqpTemplate` and `AmqpAdmin` are auto-configured, and you can autowire them directly into your own beans, as shown in the following example:
If a `KafkaTransactionManager` bean is defined, it is automatically associated to the container factory.
Similarly, if a `RecordFilterStrategy`, `ErrorHandler`, `CommonErrorHandler`, `AfterRollbackProcessor` or `ConsumerAwareRebalanceListener` bean is defined, it is automatically associated to the default factory.
@ -71,10 +65,7 @@ See also <<features#messaging.kafka.additional-properties>> for more information
To use the factory bean, wire `StreamsBuilder` into your `@Bean` as shown in the following example:
The next section describes how to enable <<io#io, IO capabilities>> in your application.
You can read about <<io#io.caching, caching>>, <<io#io.email, mail>>, <<io#io.validation, validation>>, <<io#io.rest-client, rest clients>> and more in this section.
You can read about <<io#io.caching, caching>>, <<io#io.email, mail>>, <<io#io.validation, validation>>, <<io#io.rest-client, rest clients>> and more in this section.
To upgrade an existing CLI installation, use the appropriate package manager command (for example, `brew upgrade`).
If you manually installed the CLI, follow the <<getting-started#getting-started.installing.cli.manual-installation, standard instructions>>, remembering to update your `PATH` environment variable to remove any older references.
If you manually installed the CLI, follow the <<getting-started#getting-started.installing.cli.manual-installation, standard instructions>>, remembering to update your `PATH` environment variable to remove any older references.
If you are upgrading from the `1.x` release of Spring Boot, check the {github-wiki}/Spring-Boot-2.0-Migration-Guide["`migration guide`" on the project wiki] that provides detailed upgrade instructions.
Check also the {github-wiki}["`release notes`"] for a list of "`new and noteworthy`" features for each release.
Check also the {github-wiki}["`release notes`"] for a list of "`new and noteworthy`" features for each release.
Once you've decided to upgrade your application, you can find detailed information regarding specific features in the rest of the document.
Spring Boot's documentation is specific to that version, so any information that you find in here will contain the most up-to-date changes that are in that version.
Spring Boot's documentation is specific to that version, so any information that you find in here will contain the most up-to-date changes that are in that version.
@ -25,10 +25,7 @@ Doing so enables debug logs for a selection of core loggers and logs a condition
=== Disabling Specific Auto-configuration Classes
If you find that specific auto-configuration classes that you do not want are being applied, you can use the exclude attribute of `@SpringBootApplication` to disable them, as shown in the following example:
@ -178,10 +178,7 @@ In most cases, you can set this property in your `application.properties` (doing
If you need to _completely_ disable restart support (for example, because it does not work with a specific library), you need to set the configprop:spring.devtools.restart.enabled[] `System` property to `false` before calling `SpringApplication.run(...)`, as shown in the following example:
@ -8,10 +8,7 @@ A single `@SpringBootApplication` annotation can be used to enable those three f
* `@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 <<features#features.testing.spring-boot-applications.detecting-configuration,configuration detection>> in your integration tests.
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`).
"`WebFlux.fn`", the functional variant, separates the routing configuration from the actual handling of the requests, as shown in the following example:
WebFlux is part of the Spring Framework and detailed information is available in its {spring-framework-docs}/web-reactive.html#webflux-fn[reference documentation].
@ -41,15 +32,9 @@ You can still enforce your choice by setting the chosen application type to `Spr
"`WebFlux.fn`", the functional variant, separates the routing configuration from the actual handling of the requests, as shown in the following example:
WebFlux is part of the Spring Framework and detailed information is available in its {spring-framework-docs}/web-reactive.html#webflux-fn[reference documentation].
@ -88,10 +73,7 @@ For example, `+spring.jackson.*+` configuration keys are applied to the Jackson
If you need to add or customize codecs, you can create a custom `CodecCustomizer` component, as shown in the following example:
You can also leverage <<web#web.servlet.spring-mvc.json,Boot's custom JSON serializers and deserializers>>.
@ -162,20 +144,14 @@ For that, you can add a bean of type `ErrorAttributes`.
To change the error handling behavior, you can implement `ErrorWebExceptionHandler` and register a bean definition of that type.
Because a `ErrorWebExceptionHandler` is quite low-level, Spring Boot also provides a convenient `AbstractErrorWebExceptionHandler` to let you handle errors in a WebFlux functional way, as shown in the following example:
For a more complete picture, you can also subclass `DefaultErrorWebExceptionHandler` directly and override specific methods.
In some cases, errors handled at the controller or handler function level are not recorded by the <<actuator#actuator.metrics.supported.spring-webflux, metrics infrastructure>>.
Applications can ensure that such exceptions are recorded with the request metrics by setting the handled exception as a request attribute:
Spring MVC is part of the core Spring Framework, and detailed information is available in the {spring-framework-docs}/web.html#mvc[reference documentation].
There are also several guides that cover Spring MVC available at https://spring.io/guides.
@ -60,10 +57,7 @@ By default, strings are encoded in `UTF-8`.
If you need to add or customize converters, you can use Spring Boot's `HttpMessageConverters` class, as shown in the following listing:
@ -340,20 +328,14 @@ To do so, extend `BasicErrorController`, add a public method with a `@RequestMap
You can also define a class annotated with `@ControllerAdvice` to customize the JSON document to return for a particular controller and/or exception type, as shown in the following example:
In the preceding example, if `YourException` is thrown by a controller defined in the same package as `SomeController`, a JSON representation of the `CustomErrorType` POJO is used instead of the `ErrorAttributes` representation.
In some cases, errors handled at the controller level are not recorded by the <<actuator#actuator.metrics.supported.spring-mvc, metrics infrastructure>>.
Applications can ensure that such exceptions are recorded with the request metrics by setting the handled exception as a request attribute:
You can also use regular Spring MVC features such as {spring-framework-docs}/web.html#mvc-exceptionhandlers[`@ExceptionHandler` methods] and {spring-framework-docs}/web.html#mvc-ann-controller-advice[`@ControllerAdvice`].
The `ErrorController` then picks up any unhandled exceptions.
@ -410,17 +389,11 @@ The `ErrorController` then picks up any unhandled exceptions.
For applications that do not use Spring MVC, you can use the `ErrorPageRegistrar` interface to directly register `ErrorPages`.
This abstraction works directly with the underlying embedded servlet container and works even if you do not have a Spring MVC `DispatcherServlet`.
NOTE: If you register an `ErrorPage` with a path that ends up being handled by a `Filter` (as is common with some non-Spring web frameworks, like Jersey and Wicket), then the `Filter` has to be explicitly registered as an `ERROR` dispatcher, as shown in the following example:
Note that the default `FilterRegistrationBean` does not include the `ERROR` dispatcher type.
@ -449,10 +422,7 @@ As of version 4.2, Spring MVC {spring-framework-docs}/web.html#mvc-cors[supports
Using {spring-framework-docs}/web.html#mvc-cors-controller[controller method CORS configuration] with {spring-framework-api}/web/bind/annotation/CrossOrigin.html[`@CrossOrigin`] annotations in your Spring Boot application does not require any specific configuration.
{spring-framework-docs}/web.html#mvc-cors-global[Global CORS configuration] can be defined by registering a `WebMvcConfigurer` bean with a customized `addCorsMappings(CorsRegistry)` method, as shown in the following example:
@ -572,10 +542,7 @@ The `CookieSameSiteSupplier` is passed a `Cookie` and may return a `SameSite` va
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.*`.
`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:
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.