From 32a1644cca312d35dbd5d400f5e908a9e8a5a3b6 Mon Sep 17 00:00:00 2001 From: Madhura Bhave Date: Tue, 22 Jun 2021 18:06:49 -0700 Subject: [PATCH] Split spring boot features into multiple sections See gh-27132 --- .../src/docs/asciidoc/actuator.adoc | 2 +- .../src/docs/asciidoc/actuator/endpoints.adoc | 23 +- .../src/docs/asciidoc/actuator/from-1x.adoc | 5 - .../src/docs/asciidoc/actuator/jmx.adoc | 10 +- .../src/docs/asciidoc/actuator/metrics.adoc | 4 +- .../docs/asciidoc/anchor-rewrite.properties | 166 ++++++ .../src/docs/asciidoc/container-images.adoc | 11 + .../cloud-native-buildpacks.adoc | 19 + .../container-images/dockerfiles.adoc | 63 +++ .../container-images/efficient-images.adoc | 76 +++ .../src/docs/asciidoc/data.adoc | 9 + .../asciidoc/{features => data}/nosql.adoc | 62 +-- .../docs/asciidoc/{features => data}/sql.adoc | 58 +-- .../src/docs/asciidoc/deployment.adoc | 5 +- .../src/docs/asciidoc/deployment/cloud.adoc | 2 +- .../docs/asciidoc/deployment/containers.adoc | 28 - .../src/docs/asciidoc/documentation.adoc | 10 +- .../documentation/container-images.adoc | 7 + .../src/docs/asciidoc/documentation/data.adoc | 6 + .../docs/asciidoc/documentation/features.adoc | 10 +- .../src/docs/asciidoc/documentation/io.adoc | 11 + .../asciidoc/documentation/messaging.adoc | 9 + .../src/docs/asciidoc/documentation/web.adoc | 10 + .../src/docs/asciidoc/features.adoc | 42 +- .../asciidoc/features/container-images.adoc | 141 ----- .../src/docs/asciidoc/features/hazelcast.adoc | 2 +- .../src/docs/asciidoc/features/jmx.adoc | 10 - .../src/docs/asciidoc/features/messaging.adoc | 492 ------------------ .../docs/asciidoc/features/resttemplate.adoc | 47 -- .../src/docs/asciidoc/features/testing.adoc | 16 +- .../src/docs/asciidoc/features/webclient.adoc | 48 -- .../src/docs/asciidoc/howto/actuator.adoc | 2 +- .../src/docs/asciidoc/howto/data-access.adoc | 2 +- .../src/docs/asciidoc/howto/http-clients.adoc | 2 +- .../src/docs/asciidoc/howto/webserver.adoc | 4 +- .../src/docs/asciidoc/index.adoc | 9 +- .../src/docs/asciidoc/index.singleadoc | 10 + .../src/docs/asciidoc/io.adoc | 22 + .../asciidoc/{features => io}/caching.adoc | 50 +- .../docs/asciidoc/{features => io}/jta.adoc | 12 +- .../{features/email.adoc => io/mail.adoc} | 2 +- .../asciidoc/{features => io}/quartz.adoc | 2 +- .../src/docs/asciidoc/io/rest-client.adoc | 101 ++++ .../asciidoc/{features => io}/validation.adoc | 2 +- .../{features => io}/webservices.adoc | 4 +- .../src/docs/asciidoc/messaging.adoc | 25 + .../src/docs/asciidoc/messaging/amqp.adoc | 123 +++++ .../src/docs/asciidoc/messaging/jms.adoc | 175 +++++++ .../src/docs/asciidoc/messaging/kafka.adoc | 178 +++++++ .../{features => messaging}/rsocket.adoc | 10 +- .../spring-integration.adoc | 2 +- .../{features => messaging}/websockets.adoc | 0 .../src/docs/asciidoc/using/devtools.adoc | 2 +- .../src/docs/asciidoc/web.adoc | 22 + .../{features => web}/graceful-shutdown.adoc | 4 +- .../src/docs/asciidoc/web/reactive.adoc | 263 ++++++++++ .../servlet.adoc} | 342 ++---------- .../src/docs/asciidoc/web/spring-hateoas.adoc | 10 + .../spring-security.adoc} | 45 +- .../{features => web}/spring-session.adoc | 2 +- 60 files changed, 1544 insertions(+), 1287 deletions(-) delete mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/from-1x.adoc create mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images.adoc create mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images/cloud-native-buildpacks.adoc create mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images/dockerfiles.adoc create mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images/efficient-images.adoc create mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/data.adoc rename spring-boot-project/spring-boot-docs/src/docs/asciidoc/{features => data}/nosql.adoc (95%) rename spring-boot-project/spring-boot-docs/src/docs/asciidoc/{features => data}/sql.adoc (95%) delete mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment/containers.adoc create mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/container-images.adoc create mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/data.adoc create mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/io.adoc create mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/messaging.adoc create mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/web.adoc delete mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/container-images.adoc delete mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/jmx.adoc delete mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/messaging.adoc delete mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/resttemplate.adoc delete mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/webclient.adoc create mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/io.adoc rename spring-boot-project/spring-boot-docs/src/docs/asciidoc/{features => io}/caching.adoc (89%) rename spring-boot-project/spring-boot-docs/src/docs/asciidoc/{features => io}/jta.adoc (93%) rename spring-boot-project/spring-boot-docs/src/docs/asciidoc/{features/email.adoc => io/mail.adoc} (98%) rename spring-boot-project/spring-boot-docs/src/docs/asciidoc/{features => io}/quartz.adoc (99%) create mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/rest-client.adoc rename spring-boot-project/spring-boot-docs/src/docs/asciidoc/{features => io}/validation.adoc (96%) rename spring-boot-project/spring-boot-docs/src/docs/asciidoc/{features => io}/webservices.adoc (96%) create mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging.adoc create mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/amqp.adoc create mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/jms.adoc create mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/kafka.adoc rename spring-boot-project/spring-boot-docs/src/docs/asciidoc/{features => messaging}/rsocket.adoc (95%) rename spring-boot-project/spring-boot-docs/src/docs/asciidoc/{features => messaging}/spring-integration.adoc (98%) rename spring-boot-project/spring-boot-docs/src/docs/asciidoc/{features => messaging}/websockets.adoc (100%) create mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/web.adoc rename spring-boot-project/spring-boot-docs/src/docs/asciidoc/{features => web}/graceful-shutdown.adoc (96%) create mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/reactive.adoc rename spring-boot-project/spring-boot-docs/src/docs/asciidoc/{features/developing-web-applications.adoc => web/servlet.adoc} (67%) create mode 100644 spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-hateoas.adoc rename spring-boot-project/spring-boot-docs/src/docs/asciidoc/{features/security.adoc => web/spring-security.adoc} (88%) rename spring-boot-project/spring-boot-docs/src/docs/asciidoc/{features => web}/spring-session.adoc (98%) diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator.adoc index f9e97e30b274..fc6b430aa02f 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator.adoc @@ -1,5 +1,5 @@ [[actuator]] -= Spring Boot Actuator: Production-ready Features += Production-ready Features include::attributes.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/endpoints.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/endpoints.adoc index 8b0c34bc2469..6c27817e5c1f 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/endpoints.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/endpoints.adoc @@ -314,9 +314,15 @@ TIP: If you want to implement your own strategy for when endpoints are exposed, [[actuator.endpoints.security]] -=== Securing HTTP Endpoints -You should take care to secure HTTP endpoints in the same way that you would any other sensitive URL. -If Spring Security is present, endpoints are secured by default using Spring Security’s content-negotiation strategy. +=== Security +For security purposes, all actuators other than `/health` are disabled by default. +The configprop:management.endpoints.web.exposure.include[] property can be used to enable the actuators. + +NOTE: Before setting the `management.endpoints.web.exposure.include`, ensure that the exposed actuators do not contain sensitive information and/or are secured by placing them behind a firewall or by something like Spring Security. + +If Spring Security is on the classpath and no other `WebSecurityConfigurerAdapter` or `SecurityFilterChain` bean is present, all actuators other than `/health` are secured by Spring Boot auto-configuration. +If you define a custom `WebSecurityConfigurerAdapter` or `SecurityFilterChain` bean, Spring Boot auto-configuration will back off and you will be in full control of actuator access rules. + If you wish to configure custom security for HTTP endpoints, for example, only allow users with a certain role to access them, Spring Boot provides some convenient `RequestMatcher` objects that can be used in combination with Spring Security. A typical Spring Security configuration might look something like the following example: @@ -352,6 +358,15 @@ include::{docs-java}/actuator/endpoints/security/exposeall/MySecurityConfigurati NOTE: In both the examples above, 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 will need to configure an additional `SecurityFilterChain` bean with rules that apply to the rest of the application. +[[actuator.endpoints.security.csrf]] +==== Cross Site Request Forgery Protection +Since Spring Boot relies on Spring Security's defaults, CSRF protection is turned on by default. +This means that the actuator endpoints that require a `POST` (shutdown and loggers endpoints), `PUT` or `DELETE` will get a 403 forbidden error when the default security configuration is in use. + +NOTE: We recommend disabling CSRF protection completely only if you are creating a service that is used by non-browser clients. + +Additional information about CSRF protection can be found in the {spring-security-docs}#csrf[Spring Security Reference Guide]. + [[actuator.endpoints.caching]] @@ -1061,7 +1076,7 @@ When a Spring Boot application shuts down: |`CORRECT` |`REFUSING_TRAFFIC` |New requests are rejected -|If enabled, <>. +|If enabled, <>. |Shutdown complete |N/A diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/from-1x.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/from-1x.adoc deleted file mode 100644 index 10b440cac895..000000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/from-1x.adoc +++ /dev/null @@ -1,5 +0,0 @@ -[[upgrading.from-1x]] -== Upgrading from 1.x - -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. \ No newline at end of file diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/jmx.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/jmx.adoc index 16b0936b80ec..f22e8b13b6ff 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/jmx.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/jmx.adoc @@ -2,7 +2,15 @@ == Monitoring and Management over JMX Java Management Extensions (JMX) provide a standard mechanism to monitor and manage applications. By default, this feature is not enabled and can be turned on by setting the configuration property configprop:spring.jmx.enabled[] to `true`. -Spring Boot exposes management endpoints as JMX MBeans under the `org.springframework.boot` domain by default. +Spring Boot exposes the most suitable `MBeanServer` as a bean with an ID of `mbeanServer`. +Any of your beans that are annotated with Spring JMX annotations (`@ManagedResource`, `@ManagedAttribute`, or `@ManagedOperation`) are exposed to it. + +If your platform provides a standard `MBeanServer`, Spring Boot will use that and default to the VM `MBeanServer` if necessary. +If all that fails, a new `MBeanServer` will be created. + +See the {spring-boot-autoconfigure-module-code}/jmx/JmxAutoConfiguration.java[`JmxAutoConfiguration`] class for more details. + +Spring Boot also exposes management endpoints as JMX MBeans under the `org.springframework.boot` domain by default. To Take full control over endpoints registration in the JMX domain, consider registering your own `EndpointObjectNameFactory` implementation. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/metrics.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/metrics.adoc index b80976a5842d..0a2d240cdf4f 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/metrics.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/metrics.adoc @@ -628,7 +628,7 @@ To add to the default tags, provide one or more ``@Bean``s that implement `WebMv To replace the default tags, provide a `@Bean` that implements `WebMvcTagsProvider`. TIP: In some cases, exceptions handled in Web controllers are not recorded as request metrics tags. -Applications can opt-in and record exceptions by <>. +Applications can opt-in and record exceptions by <>. @@ -667,7 +667,7 @@ To add to the default tags, provide one or more ``@Bean``s that implement `WebFl To replace the default tags, provide a `@Bean` that implements `WebFluxTagsProvider`. 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 <>. +Applications can opt-in and record exceptions by <>. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/anchor-rewrite.properties b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/anchor-rewrite.properties index 96c36c296d5f..7c9a7f0d5b33 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/anchor-rewrite.properties +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/anchor-rewrite.properties @@ -778,3 +778,169 @@ rsocket-properties=application-properties.rsocket actuator-properties=application-properties.actuator devtools-properties=application-properties.devtools testing-properties=application-properties.testing +features.caching=io.caching +features.caching.provider=io.caching.provider +features.caching.provider.generic=io.caching.provider.generic +features.caching.provider.jcache=io.caching.provider.jcache +features.caching.provider.ehcache2=io.caching.provider.ehcache2 +features.caching.provider.hazelcast=io.caching.provider.hazelcast +features.caching.provider.infinispan=io.caching.provider.infinispan +features.caching.provider.couchbase=io.caching.provider.couchbase +features.caching.provider.redis=io.caching.provider.redis +features.caching.provider.caffeine=io.caching.provider.caffeine +features.caching.provider.simple=io.caching.provider.simple +features.caching.provider.none=io.caching.provider.none +features.jta=io.jta +features.jta.atomikos=io.jta.atomikos +features.jta.javaee=io.jta.javaee +features.jta.mixing-xa-and-non-xa-connections=io.jta.mixing-xa-and-non-xa-connections +features.jta.supporting-alternative-embedded-transaction-manager=io.jta.supporting-alternative-embedded-transaction-manager +features.email=io.email +features.quartz=io.quartz +features.resttemplate=io.rest-client.resttemplate +features.resttemplate.customization=io.rest-client.resttemplate.customization +features.webclient=io.rest-client.webclient +features.webclient.runtime=io.rest-client.webclient.runtime +features.webclient.customization=io.rest-client.webclient.customization +features.validation=io.validation +features.webservices=io.webservices +features.webservices.template=io.webservices.template +features.messaging=messaging +features.messaging.amqp=messaging.amqp +features.messaging.amqp.rabbit=messaging.amqp.rabbit +features.messaging.amqp.sending=messaging.amqp.sending +features.messaging.amqp.receiving=messaging.amqp.receiving +features.messaging.jms.activemq=messaging.jms.activemq +features.messaging.jms.artemis=messaging.jms.artemis +features.messaging.jms.jndi=messaging.jms.jndi +features.messaging.jms.sending=messaging.jms.sending +features.messaging.jms.receiving=messaging.jms.receiving +features.messaging.kafka=messaging.kafka +features.messaging.kafka.sending=messaging.kafka.sending +features.messaging.kafka.receiving=messaging.kafka.receiving +features.messaging.kafka.streams=messaging.kafka.streams +features.messaging.kafka.additional-properties=messaging.kafka.additional-properties +features.messaging.kafka.embedded=messaging.kafka.embedded +features.rsocket=messaging.rsocket +features.rsocket.strategies-auto-configuration=messaging.rsocket.strategies-auto-configuration +features.rsocket.server-auto-configuration=messaging.rsocket.server-auto-configuration +features.rsocket.messaging=messaging.rsocket.messaging +features.rsocket.requester=messaging.rsocket.requester +features.spring-integration=messaging.spring-integration +features.websockets=messaging.websockets +features.developing-web-applications=web +features.graceful-shutdown=web.graceful-shutdown +features.developing-web-applications.spring-webflux=web.reactive.webflux +features.developing-web-applications.spring-webflux.auto-configuration=web.reactive.webflux.auto-configuration +features.developing-web-applications.spring-webflux.httpcodecs=web.reactive.webflux.httpcodecs +features.developing-web-applications.spring-webflux.static-context=web.reactive.webflux.static-content +features.developing-web-applications.spring-webflux.welcome-page=web.reactive.webflux.welcome-page +features.developing-web-applications.spring-webflux.template-engines=web.reactive.webflux.template-engines +features.developing-web-applications.spring-webflux.error-handling=web.reactive.webflux.error-handling +features.developing-web-applications.spring-webflux.error-pages=web.reactive.webflux.error-handling.error-pages +features.developing-web-applications.spring-webflux.web-filters=web.reactive.webflux.web-filters +features.developing-web-applications.spring-mvc=web.servlet.spring-mvc +features.developing-web-applications.spring-mvc.auto-configuration=web.servlet.spring-mvc.auto-configuration +features.developing-web-applications.spring-mvc.message-converters=web.servlet.spring-mvc.message-converters +features.developing-web-applications.spring-mvc.json=web.servlet.spring-mvc.json +features.developing-web-applications.spring-mvc.message-codes=web.servlet.spring-mvc.message-codes +features.developing-web-applications.spring-mvc.static-content=web.servlet.spring-mvc.static-content +features.developing-web-applications.spring-mvc.welcome-page=web.servlet.spring-mvc.welcome-page +features.developing-web-applications.spring-mvc.content-negotiation=web.servlet.spring-mvc.content-negotiation +features.developing-web-applications.spring-mvc.binding-initializer=web.servlet.spring-mvc.binding-initializer +features.developing-web-applications.spring-mvc.template-engines=web.servlet.spring-mvc.template-engines +features.developing-web-applications.spring-mvc.error-handling=web.servlet.spring-mvc.error-handling +features.developing-web-applications.spring-mvc.error-handling.error-pages=web.servlet.spring-mvc.error-handling.error-pages +features.developing-web-applications.spring-mvc.error-handling.error-pages-without-spring-mvc=web.servlet.spring-mvc.error-handling.error-pages-without-spring-mvc +features.developing-web-applications.spring-mvc.error-handling.in-a-war-deployment=web.servlet.spring-mvc.error-handling.in-a-war-deployment +features.developing-web-applications.spring-mvc.cors=web.servlet.spring-mvc.cors +features.developing-web-applications.jersey=web.servlet.jersey +features.developing-web-applications.embedded-container=web.servlet.embedded-container +features.developing-web-applications.embedded-container.servlets-filters-listeners=web.servlet.embedded-container.servlets-filters-listeners +features.developing-web-applications.embedded-container.servlets-filters-listeners.beans=web.servlet.embedded-container.servlets-filters-listeners.beans +features.developing-web-applications.embedded-container.context-initializer=web.servlet.embedded-container.context-initializer +features.developing-web-applications.embedded-container.context-initializer.scanning=web.servlet.embedded-container.context-initializer.scanning +features.developing-web-applications.embedded-container.application-context=web.servlet.embedded-container.application-context +features.developing-web-applications.embedded-container.customizing=web.servlet.embedded-container.customizing +features.developing-web-applications.embedded-container.customizing.programmatic=web.servlet.embedded-container.customizing.programmatic +features.developing-web-applications.embedded-container.customizing.direct=web.servlet.embedded-container.customizing.direct +features.developing-web-applications.embedded-container.jsp-limitations=web.servlet.embedded-container.jsp-limitations +features.developing-web-applications.reactive-server=web.reactive.reactive-server +features.developing-web-applications.reactive-server-resources-configuration=web.reactive.reactive-server-resources-configuration +features.spring-hateoas=web.spring-hateoas +features.security=web.security +features.security.spring-mvc=web.security.spring-mvc +features.security.spring-webflux=web.security.spring-webflux +features.security.oauth2=web.security.oauth2 +features.security.oauth2.client=web.security.oauth2.client +features.security.oauth2.client.common-providers=web.security.oauth2.client.common-providers +features.security.oauth2.server=web.security.oauth2.server +features.security.authorization-server=web.security.oauth2.authorization-server +features.security.saml2=web.security.saml2 +features.security.saml2.relying-party=web.security.saml2.relying-party +features.security.actuator=actuator.endpoints.security +features.security.actuator.csrf=actuator.endpoints.security.csrf +features.spring-session=web.spring-session +features.nosql=data.nosql +features.nosql.redis=data.nosql.redis +features.nosql.redis.connecting=data.nosql.redis.connecting +features.nosql.mongodb=data.nosql.mongodb +features.nosql.mongodb.connecting=data.nosql.mongodb.connecting +features.nosql.mongodb.template=data.nosql.mongodb.template +features.nosql.mongodb.repositories=data.nosql.mongodb.repositories +features.nosql.mongodb.embedded=data.nosql.mongodb.embedded +features.nosql.neo4j=data.nosql.neo4j +features.nosql.neo4j.connecting=data.nosql.neo4j.connecting +features.nosql.neo4j.repositories=data.nosql.neo4j.repositories +features.nosql.solr=data.nosql.solr +features.nosql.solr.connecting=data.nosql.solr.connecting +features.nosql.elasticsearch=data.nosql.elasticsearch +features.nosql.elasticsearch.connecting-using-rest=data.nosql.elasticsearch.connecting-using-rest +features.nosql.elasticsearch.connecting-using-reactive-rest=data.nosql.elasticsearch.connecting-using-reactive-rest +features.nosql.elasticsearch.connecting-using-spring-data=data.nosql.elasticsearch.connecting-using-spring-data +features.nosql.elasticsearch.repositories=data.nosql.elasticsearch.repositories +features.nosql.cassandra=data.nosql.cassandra +features.nosql.cassandra.connecting=data.nosql.cassandra.connecting +features.nosql.cassandra.repositories=data.nosql.cassandra.repositories +features.nosql.couchbase=data.nosql.couchbase +features.nosql.couchbase.connecting=data.nosql.couchbase.connecting +features.nosql.couchbase.repositories=data.nosql.couchbase.repositories +features.nosql.ldap=data.nosql.ldap +features.nosql.ldap.connecting=data.nosql.ldap.connecting +features.nosql.ldap.repositories=data.nosql.ldap.repositories +features.nosql.ldap.embedded=data.nosql.ldap.embedded +features.nosql.influxdb=data.nosql.influxdb +features.nosql.influxdb.connecting=data.nosql.influxdb.connecting +features.sql=data.sql +features.sql.datasource=data.sql.datasource +features.sql.datasource.embedded=data.sql.datasource.embedded +features.sql.datasource.production=data.sql.datasource.production +features.sql.datasource.configuration=data.sql.datasource.configuration +features.sql.datasource.connection-pool=data.sql.datasource.connection-pool +features.sql.datasource.jndi=data.sql.datasource.jndi +features.sql.jdbc-template=data.sql.jdbc-template +features.sql.jpa-and-spring-data=data.sql.jpa-and-spring-data +features.sql.jpa-and-spring-data.entity-classes=data.sql.jpa-and-spring-data.entity-classes +features.sql.jpa-and-spring-data.repositories=data.sql.jpa-and-spring-data.repositories +features.sql.jpa-and-spring-data.envers-repositories=data.sql.jpa-and-spring-data.envers-repositories +features.sql.jpa-and-spring-data.creating-and-dropping=data.sql.jpa-and-spring-data.creating-and-dropping +features.sql.jpa-and-spring-data.open-entity-manager-in-view=data.sql.jpa-and-spring-data.open-entity-manager-in-view +features.sql.jdbc=data.sql.jdbc +features.sql.h2-web-console=data.sql.h2-web-console +features.sql.h2-web-console.custom-path=data.sql.h2-web-console.custom-path +features.sql.jooq=data.sql.jooq +features.sql.jooq.codegen=data.sql.jooq.codegen +features.sql.jooq.dslcontext=data.sql.jooq.dslcontext +features.sql.jooq.sqldialect=data.sql.jooq.sqldialect +features.sql.jooq.customizing=data.sql.jooq.customizing +features.sql.r2dbc=data.sql.r2dbc +features.sql.r2dbc.embedded=data.sql.r2dbc.embedded +features.sql.r2dbc.using-database-client=data.sql.r2dbc.using-database-client +features.sql.r2dbc.repositories=data.sql.r2dbc.repositories +features.container-images.building=container-images.efficient-images +features.container-images.building.buildpacks=container-images.buildpacks +features.container-images.building.dockerfiles=container-images.dockerfiles +features.container-images=container-images.efficient-images +features.container-images.layering=container-images.efficient-images.layering +features.jmx=actuator.jmx +deployment.containers=container-images.efficient-images.unpacking diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images.adoc new file mode 100644 index 000000000000..04fe1a7801f9 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images.adoc @@ -0,0 +1,11 @@ +[[container-images]] += Container Images +include::attributes.adoc[] + +Spring Boot applications can be containerized <>, or by <>. + +include::container-images/efficient-images.adoc[] + +include::container-images/dockerfiles.adoc[] + +include::container-images/cloud-native-buildpacks.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images/cloud-native-buildpacks.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images/cloud-native-buildpacks.adoc new file mode 100644 index 000000000000..af3ff3bddf64 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images/cloud-native-buildpacks.adoc @@ -0,0 +1,19 @@ +[[container-images.buildpacks]] +== Cloud Native Buildpacks +Dockerfiles are just one way to build docker images. +Another way to build docker images is directly from your Maven or Gradle plugin, using buildpacks. +If you’ve ever used an application platform such as Cloud Foundry or Heroku then you’ve probably used a buildpack. +Buildpacks are the part of the platform that takes your application and converts it into something that the platform can actually run. +For example, Cloud Foundry’s Java buildpack will notice that you’re pushing a `.jar` file and automatically add a relevant JRE. + +With Cloud Native Buildpacks, you can create Docker compatible images that you can run anywhere. +Spring Boot includes buildpack support directly for both Maven and Gradle. +This means you can just type a single command and quickly get a sensible image into your locally running Docker daemon. + +Refer to the individual plugin documentation on how to use buildpacks with {spring-boot-maven-plugin-docs}#build-image[Maven] and {spring-boot-gradle-plugin-docs}#build-image[Gradle]. + +NOTE: The https://github.com/paketo-buildpacks/spring-boot[Paketo Spring Boot buildpack] has also been updated to support the `layers.idx` file so any customization that is applied to it will be reflected in the image created by the buildpack. + +NOTE: In order to achieve reproducible builds and container image caching, Buildpacks can manipulate the application resources metadata (such as the file "last modified" information). +You should ensure that your application does not rely on that metadata at runtime. +Spring Boot can use that information when serving static resources, but this can be disabled with configprop:spring.web.resources.cache.use-last-modified[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images/dockerfiles.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images/dockerfiles.adoc new file mode 100644 index 000000000000..1a31849bca92 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images/dockerfiles.adoc @@ -0,0 +1,63 @@ +[[container-images.dockerfiles]] +== Dockerfiles +While it is possible to convert a Spring Boot fat jar into a docker image with just a few lines in the Dockerfile, we will use the <> to create an optimized docker image. +When you create a jar containing the layers index file, the `spring-boot-jarmode-layertools` jar will be added as a dependency to your jar. +With this jar on the classpath, you can launch your application in a special mode which allows the bootstrap code to run something entirely different from your application, for example, something that extracts the layers. + +CAUTION: The `layertools` mode can not be used with a <> that includes a launch script. +Disable launch script configuration when building a jar file that is intended to be used with `layertools`. + +Here’s how you can launch your jar with a `layertools` jar mode: + +[source,shell,indent=0,subs="verbatim"] +---- +$ java -Djarmode=layertools -jar my-app.jar +---- + +This will provide the following output: + +[subs="verbatim"] +---- +Usage: + java -Djarmode=layertools -jar my-app.jar + +Available commands: + list List layers from the jar that can be extracted + extract Extracts layers from the jar for image creation + help Help about any command +---- + +The `extract` command can be used to easily split the application into layers to be added to the dockerfile. +Here's an example of a Dockerfile using `jarmode`. + +[source,dockerfile,indent=0,subs="verbatim"] +---- +FROM adoptopenjdk:11-jre-hotspot as builder +WORKDIR application +ARG JAR_FILE=target/*.jar +COPY ${JAR_FILE} application.jar +RUN java -Djarmode=layertools -jar application.jar extract + +FROM adoptopenjdk:11-jre-hotspot +WORKDIR application +COPY --from=builder application/dependencies/ ./ +COPY --from=builder application/spring-boot-loader/ ./ +COPY --from=builder application/snapshot-dependencies/ ./ +COPY --from=builder application/application/ ./ +ENTRYPOINT ["java", "org.springframework.boot.loader.JarLauncher"] +---- + +Assuming the above `Dockerfile` is in the current directory, your docker image can be built with `docker build .`, or optionally specifying the path to your application jar, as shown in the following example: + +[source,shell,indent=0,subs="verbatim"] +---- + $ docker build --build-arg JAR_FILE=path/to/myapp.jar . +---- + +This is a multi-stage dockerfile. +The builder stage extracts the directories that are needed later. +Each of the `COPY` commands relates to the layers extracted by the jarmode. + +Of course, a Dockerfile can be written without using the jarmode. +You can use some combination of `unzip` and `mv` to move things to the right layer but jarmode simplifies that. + diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images/efficient-images.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images/efficient-images.adoc new file mode 100644 index 000000000000..e69b991e450b --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images/efficient-images.adoc @@ -0,0 +1,76 @@ +[[container-images.efficient-images]] +== Efficient container images +It is easily possible to package a Spring Boot fat jar as a docker image. +However, there are various downsides to copying and running the fat jar as is in the docker image. +There’s always a certain amount of overhead when running a fat jar without unpacking it, and in a containerized environment this can be noticeable. +The other issue is that putting your application's code and all its dependencies in one layer in the Docker image is sub-optimal. +Since you probably recompile your code more often than you upgrade the version of Spring Boot you use, it’s often better to separate things a bit more. +If you put jar files in the layer before your application classes, Docker often only needs to change the very bottom layer and can pick others up from its cache. + + +[[container-images.efficient-images.unpacking]] +=== Unpacking the fat jar +If you are running your application from a container, you can use an executable jar, but it is also often an advantage to explode it and run it in a different way. +Certain PaaS implementations may also choose to unpack archives before they run. +For example, Cloud Foundry operates this way. +One way to run an unpacked archive is by starting the appropriate launcher, as follows: + +[source,shell,indent=0,subs="verbatim"] +---- + $ jar -xf myapp.jar + $ java org.springframework.boot.loader.JarLauncher +---- + +This is actually slightly faster on startup (depending on the size of the jar) than running from an unexploded archive. +At runtime you shouldn't expect any differences. + +Once you have unpacked the jar file, you can also get an extra boost to startup time by running the app with its "natural" main method instead of the `JarLauncher`. For example: + +[source,shell,indent=0,subs="verbatim"] +---- + $ jar -xf myapp.jar + $ java -cp BOOT-INF/classes:BOOT-INF/lib/* com.example.MyApplication +---- + +NOTE: Using the `JarLauncher` over the application's main method has the added benefit of a predictable classpath order. +The jar contains a `classpath.idx` file which is used by the `JarLauncher` when constructing the classpath. + + + +[[container-images.efficient-images.layering]] +=== Layering Docker Images +To make it easier to create optimized Docker images, Spring Boot supports adding a layer index file to the jar. +It provides a list of layers and the parts of the jar that should be contained within them. +The list of layers in the index is ordered based on the order in which the layers should be added to the Docker/OCI image. +Out-of-the-box, the following layers are supported: + +* `dependencies` (for regular released dependencies) +* `spring-boot-loader` (for everything under `org/springframework/boot/loader`) +* `snapshot-dependencies` (for snapshot dependencies) +* `application` (for application classes and resources) + +The following shows an example of a `layers.idx` file: + +[source,yaml,indent=0,subs="verbatim"] +---- + - "dependencies": + - BOOT-INF/lib/library1.jar + - BOOT-INF/lib/library2.jar + - "spring-boot-loader": + - org/springframework/boot/loader/JarLauncher.class + - org/springframework/boot/loader/jar/JarEntry.class + - "snapshot-dependencies": + - BOOT-INF/lib/library3-SNAPSHOT.jar + - "application": + - META-INF/MANIFEST.MF + - BOOT-INF/classes/a/b/C.class +---- + +This layering is designed to separate code based on how likely it is to change between application builds. +Library code is less likely to change between builds, so it is placed in its own layers to allow tooling to re-use the layers from cache. +Application code is more likely to change between builds so it is isolated in a separate layer. + +Spring Boot also supports layering for war files with the help of a `layers.idx`. + +For Maven, refer to the {spring-boot-maven-plugin-docs}#repackage-layers[packaging layered jar or war section] for more details on adding a layer index to the archive. +For Gradle, refer to the {spring-boot-gradle-plugin-docs}#packaging-layered-archives[packaging layered jar or war section] of the Gradle plugin documentation. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data.adoc new file mode 100644 index 000000000000..b80aa7306d9f --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data.adoc @@ -0,0 +1,9 @@ +[[data]] += Data +include::attributes.adoc[] + +Spring Boot integrates with a number of data technologies, both SQL and NoSQL. + +include::data/sql.adoc[] + +include::data/nosql.adoc[] \ No newline at end of file diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/nosql.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data/nosql.adoc similarity index 95% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/nosql.adoc rename to spring-boot-project/spring-boot-docs/src/docs/asciidoc/data/nosql.adoc index 916cf121cd08..ffb39291b9c3 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/nosql.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data/nosql.adoc @@ -1,4 +1,4 @@ -[[features.nosql]] +[[data.nosql]] == Working with NoSQL Technologies Spring Data provides additional projects that help you access a variety of NoSQL technologies, including: @@ -17,7 +17,7 @@ Refer to the appropriate reference documentation at {spring-data}. -[[features.nosql.redis]] +[[data.nosql.redis]] === Redis https://redis.io/[Redis] is a cache, message broker, and richly-featured key-value store. Spring Boot offers basic auto-configuration for the https://github.com/lettuce-io/lettuce-core/[Lettuce] and https://github.com/xetorthio/jedis/[Jedis] client libraries and the abstractions on top of them provided by https://github.com/spring-projects/spring-data-redis[Spring Data Redis]. @@ -30,7 +30,7 @@ TIP: We also provide a `spring-boot-starter-data-redis-reactive` "`Starter`" for -[[features.nosql.redis.connecting]] +[[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. By default, the instance tries to connect to a Redis server at `localhost:6379`. @@ -51,14 +51,14 @@ By default, a pooled connection factory is auto-configured if `commons-pool2` is -[[features.nosql.mongodb]] +[[data.nosql.mongodb]] === MongoDB https://www.mongodb.com/[MongoDB] is an open-source NoSQL document database that uses a JSON-like schema instead of traditional table-based relational data. Spring Boot offers several conveniences for working with MongoDB, including the `spring-boot-starter-data-mongodb` and `spring-boot-starter-data-mongodb-reactive` "`Starters`". -[[features.nosql.mongodb.connecting]] +[[data.nosql.mongodb.connecting]] ==== Connecting to a MongoDB Database To access MongoDB databases, you can inject an auto-configured `org.springframework.data.mongodb.MongoDatabaseFactory`. By default, the instance tries to connect to a MongoDB server at `mongodb://localhost/test`. @@ -113,7 +113,7 @@ The auto-configuration configures this factory automatically if Netty is availab -[[features.nosql.mongodb.template]] +[[data.nosql.mongodb.template]] ==== MongoTemplate {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: @@ -127,7 +127,7 @@ See the {spring-data-mongodb-api}/core/MongoOperations.html[`MongoOperations` Ja -[[features.nosql.mongodb.repositories]] +[[data.nosql.mongodb.repositories]] ==== Spring Data MongoDB Repositories Spring Data includes repository support for MongoDB. As with the JPA repositories discussed earlier, the basic principle is that queries are constructed automatically, based on method names. @@ -146,7 +146,7 @@ TIP: For complete details of Spring Data MongoDB, including its rich object mapp -[[features.nosql.mongodb.embedded]] +[[data.nosql.mongodb.embedded]] ==== Embedded Mongo Spring Boot offers auto-configuration for https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo[Embedded Mongo]. To use it in your Spring Boot application, add a dependency on `de.flapdoodle.embed:de.flapdoodle.embed.mongo`. @@ -164,14 +164,14 @@ The download configuration can be customized by declaring a `DownloadConfigBuild -[[features.nosql.neo4j]] +[[data.nosql.neo4j]] === Neo4j https://neo4j.com/[Neo4j] is an open-source NoSQL graph database that uses a rich data model of nodes connected by first class relationships, which is better suited for connected big data than traditional RDBMS approaches. Spring Boot offers several conveniences for working with Neo4j, including the `spring-boot-starter-data-neo4j` "`Starter`". -[[features.nosql.neo4j.connecting]] +[[data.nosql.neo4j.connecting]] ==== Connecting to a Neo4j Database To access a Neo4j server, you can inject an auto-configured `org.neo4j.driver.Driver`. By default, the instance tries to connect to a Neo4j server at `localhost:7687` using the Bolt protocol. @@ -201,7 +201,7 @@ Each will be called in order with the `ConfigBuilder` that is used to build the -[[features.nosql.neo4j.repositories]] +[[data.nosql.neo4j.repositories]] ==== Spring Data Neo4j Repositories Spring Data includes repository support for Neo4j. For complete details of Spring Data Neo4j, refer to the {spring-data-neo4j-docs}[reference documentation]. @@ -233,14 +233,14 @@ include::{docs-java}/features/nosql/neo4j/repositories/MyNeo4jConfiguration.java -[[features.nosql.solr]] +[[data.nosql.solr]] === Solr https://lucene.apache.org/solr/[Apache Solr] is a search engine. Spring Boot offers basic auto-configuration for the Solr 5 client library. -[[features.nosql.solr.connecting]] +[[data.nosql.solr.connecting]] ==== Connecting to Solr You can inject an auto-configured `SolrClient` instance as you would any other Spring bean. By default, the instance tries to connect to a server at `http://localhost:8983/solr`. @@ -255,7 +255,7 @@ If you add your own `@Bean` of type `SolrClient`, it replaces the default. -[[features.nosql.elasticsearch]] +[[data.nosql.elasticsearch]] === Elasticsearch https://www.elastic.co/products/elasticsearch[Elasticsearch] is an open source, distributed, RESTful search and analytics engine. Spring Boot offers basic auto-configuration for Elasticsearch. @@ -269,7 +269,7 @@ Spring Boot provides a dedicated "`Starter`", `spring-boot-starter-data-elastics -[[features.nosql.elasticsearch.connecting-using-rest]] +[[data.nosql.elasticsearch.connecting-using-rest]] ==== Connecting to Elasticsearch using REST clients Elasticsearch ships https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/index.html[two different REST clients] that you can use to query a cluster: the "Low Level" client and the "High Level" client. Spring Boot provides support for the "High Level" client, which ships with `org.elasticsearch.client:elasticsearch-rest-high-level-client`. @@ -308,7 +308,7 @@ You can further tune how `Sniffer` is configured, as shown in the following exam -[[features.nosql.elasticsearch.connecting-using-reactive-rest]] +[[data.nosql.elasticsearch.connecting-using-reactive-rest]] ==== Connecting to Elasticsearch using Reactive REST clients {spring-data-elasticsearch}[Spring Data Elasticsearch] ships `ReactiveElasticsearchClient` for querying Elasticsearch instances in a reactive fashion. It is built on top of WebFlux's `WebClient`, so both `spring-boot-starter-elasticsearch` and `spring-boot-starter-webflux` dependencies are useful to enable this support. @@ -336,7 +336,7 @@ configuration, you can register a custom `ClientConfiguration` bean. -[[features.nosql.elasticsearch.connecting-using-spring-data]] +[[data.nosql.elasticsearch.connecting-using-spring-data]] ==== Connecting to Elasticsearch by Using Spring Data To connect to Elasticsearch, a `RestHighLevelClient` bean must be defined, auto-configured by Spring Boot or manually provided by the application (see previous sections). @@ -349,12 +349,12 @@ as shown in the following example: include::{docs-java}/features/nosql/elasticsearch/connectingusingspringdata/MyBean.java[] ---- -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 <> and a `ReactiveElasticsearchTemplate` as beans. +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 <> and a `ReactiveElasticsearchTemplate` as beans. They are the reactive equivalent of the other REST clients. -[[features.nosql.elasticsearch.repositories]] +[[data.nosql.elasticsearch.repositories]] ==== Spring Data Elasticsearch Repositories Spring Data includes repository support for Elasticsearch. As with the JPA repositories discussed earlier, the basic principle is that queries are constructed for you automatically based on method names. @@ -383,7 +383,7 @@ You can choose to disable the repositories support with the following property: -[[features.nosql.cassandra]] +[[data.nosql.cassandra]] === Cassandra https://cassandra.apache.org/[Cassandra] is an open source, distributed database management system designed to handle large amounts of data across many commodity servers. Spring Boot offers auto-configuration for Cassandra and the abstractions on top of it provided by https://github.com/spring-projects/spring-data-cassandra[Spring Data Cassandra]. @@ -391,7 +391,7 @@ There is a `spring-boot-starter-data-cassandra` "`Starter`" for collecting the d -[[features.nosql.cassandra.connecting]] +[[data.nosql.cassandra.connecting]] ==== Connecting to Cassandra You can inject an auto-configured `CassandraTemplate` or a Cassandra `CqlSession` instance as you would with any other Spring Bean. The `spring.data.cassandra.*` properties can be used to customize the connection. @@ -446,7 +446,7 @@ If you add your own `@Bean` of type `CassandraTemplate`, it replaces the default -[[features.nosql.cassandra.repositories]] +[[data.nosql.cassandra.repositories]] ==== Spring Data Cassandra Repositories Spring Data includes basic repository support for Cassandra. Currently, this is more limited than the JPA repositories discussed earlier and needs to annotate finder methods with `@Query`. @@ -455,7 +455,7 @@ TIP: For complete details of Spring Data Cassandra, refer to the https://docs.sp -[[features.nosql.couchbase]] +[[data.nosql.couchbase]] === Couchbase https://www.couchbase.com/[Couchbase] is an open-source, distributed, multi-model NoSQL document-oriented database that is optimized for interactive applications. Spring Boot offers auto-configuration for Couchbase and the abstractions on top of it provided by https://github.com/spring-projects/spring-data-couchbase[Spring Data Couchbase]. @@ -463,7 +463,7 @@ There are `spring-boot-starter-data-couchbase` and `spring-boot-starter-data-cou -[[features.nosql.couchbase.connecting]] +[[data.nosql.couchbase.connecting]] ==== Connecting to Couchbase You can get a `Cluster` by adding the Couchbase SDK and some configuration. The `spring.couchbase.*` properties can be used to customize the connection. @@ -498,7 +498,7 @@ To take more control, one or more `ClusterEnvironmentBuilderCustomizer` beans ca -[[features.nosql.couchbase.repositories]] +[[data.nosql.couchbase.repositories]] ==== Spring Data Couchbase Repositories Spring Data includes repository support for Couchbase. For complete details of Spring Data Couchbase, refer to the {spring-data-couchbase-docs}[reference documentation]. @@ -537,7 +537,7 @@ include::{docs-java}/features/nosql/couchbase/repositories/MyCouchbaseConfigurat -[[features.nosql.ldap]] +[[data.nosql.ldap]] === LDAP https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol[LDAP] (Lightweight Directory Access Protocol) is an open, vendor-neutral, industry standard application protocol for accessing and maintaining distributed directory information services over an IP network. Spring Boot offers auto-configuration for any compliant LDAP server as well as support for the embedded in-memory LDAP server from https://ldap.com/unboundid-ldap-sdk-for-java/[UnboundID]. @@ -547,7 +547,7 @@ There is a `spring-boot-starter-data-ldap` "`Starter`" for collecting the depend -[[features.nosql.ldap.connecting]] +[[data.nosql.ldap.connecting]] ==== Connecting to an LDAP Server To connect to an LDAP server, make sure you declare a dependency on the `spring-boot-starter-data-ldap` "`Starter`" or `spring-ldap-core` and then declare the URLs of your server in your application.properties, as shown in the following example: @@ -569,7 +569,7 @@ Make sure to flag your customized `ContextSource` as `@Primary` so that the auto -[[features.nosql.ldap.repositories]] +[[data.nosql.ldap.repositories]] ==== Spring Data LDAP Repositories Spring Data includes repository support for LDAP. For complete details of Spring Data LDAP, refer to the https://docs.spring.io/spring-data/ldap/docs/1.0.x/reference/html/[reference documentation]. @@ -584,7 +584,7 @@ include::{docs-java}/features/nosql/ldap/repositories/MyBean.java[] -[[features.nosql.ldap.embedded]] +[[data.nosql.ldap.embedded]] ==== Embedded In-memory LDAP Server For testing purposes, Spring Boot supports auto-configuration of an in-memory LDAP server from https://ldap.com/unboundid-ldap-sdk-for-java/[UnboundID]. To configure the server, add a dependency to `com.unboundid:unboundid-ldapsdk` and declare a configprop:spring.ldap.embedded.base-dn[] property, as follows: @@ -623,13 +623,13 @@ If you have custom attributes, you can use configprop:spring.ldap.embedded.valid -[[features.nosql.influxdb]] +[[data.nosql.influxdb]] === InfluxDB https://www.influxdata.com/[InfluxDB] is an open-source time series database optimized for fast, high-availability storage and retrieval of time series data in fields such as operations monitoring, application metrics, Internet-of-Things sensor data, and real-time analytics. -[[features.nosql.influxdb.connecting]] +[[data.nosql.influxdb.connecting]] ==== Connecting to InfluxDB Spring Boot auto-configures a client instance, provided that either `influxdb-java` (Influx 1.x) or `influxdb-client-java` (Influx 2.x) is on the classpath and the URL of the database is set, as shown in the following example: diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/sql.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data/sql.adoc similarity index 95% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/sql.adoc rename to spring-boot-project/spring-boot-docs/src/docs/asciidoc/data/sql.adoc index fe19e70b8a25..33fd1741bac5 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/sql.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data/sql.adoc @@ -1,11 +1,11 @@ -[[features.sql]] -== Working with SQL Databases +[[data.sql]] +== SQL Databases The {spring-framework}[Spring Framework] provides extensive support for working with SQL databases, from direct JDBC access using `JdbcTemplate` to complete "`object relational mapping`" technologies such as Hibernate. {spring-data}[Spring Data] provides an additional level of functionality: creating `Repository` implementations directly from interfaces and using conventions to generate queries from your method names. -[[features.sql.datasource]] +[[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. @@ -14,7 +14,7 @@ TIP: See <>. +These are the standard options that work regardless of <>. It is also possible to fine-tune implementation-specific settings by using their respective prefix (`+spring.datasource.hikari.*+`, `+spring.datasource.tomcat.*+`, `+spring.datasource.dbcp2.*+`, and `+spring.datasource.oracleucp.*+`). Refer to the documentation of the connection pool implementation you are using for more details. @@ -109,7 +109,7 @@ This will set the pool to wait 10000ms before throwing an exception if no connec -[[features.sql.datasource.connection-pool]] +[[data.sql.datasource.connection-pool]] ==== Supported Connection Pools Spring Boot uses the following algorithm for choosing a specific implementation: @@ -138,7 +138,7 @@ The following connection pools are supported by `DataSourceBuilder`: -[[features.sql.datasource.jndi]] +[[data.sql.datasource.jndi]] ==== Connection to a JNDI DataSource If you deploy your Spring Boot application to an Application Server, you might want to configure and manage your DataSource by using your Application Server's built-in features and access it by using JNDI. @@ -154,7 +154,7 @@ For example, the following section in `application.properties` shows how you can -[[features.sql.jdbc-template]] +[[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: @@ -178,7 +178,7 @@ If more than one `JdbcTemplate` is defined and no primary candidate exists, the -[[features.sql.jpa-and-spring-data]] +[[data.sql.jpa-and-spring-data]] === JPA and Spring Data JPA The Java Persistence API is a standard technology that lets you "`map`" objects to relational databases. The `spring-boot-starter-data-jpa` POM provides a quick way to get started. @@ -193,7 +193,7 @@ You can follow the https://spring.io/guides/gs/accessing-data-jpa/["`Accessing D -[[features.sql.jpa-and-spring-data.entity-classes]] +[[data.sql.jpa-and-spring-data.entity-classes]] ==== Entity Classes Traditionally, JPA "`Entity`" classes are specified in a `persistence.xml` file. With Spring Boot, this file is not necessary and "`Entity Scanning`" is used instead. @@ -212,7 +212,7 @@ See the "`<>, Spring Boot can automatically configure an embedded database for reactive usage. +Similarly to <>, Spring Boot can automatically configure an embedded database for reactive usage. You need not provide any connection URLs. You need only include a build dependency to the embedded database that you want to use, as shown in the following example: @@ -489,7 +489,7 @@ If you want to make sure that each context has a separate embedded database, you -[[features.sql.r2dbc.using-database-client]] +[[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: @@ -500,7 +500,7 @@ include::{docs-java}/features/sql/r2dbc/usingdatabaseclient/MyBean.java[] -[[features.sql.r2dbc.repositories]] +[[data.sql.r2dbc.repositories]] ==== Spring Data R2DBC Repositories https://spring.io/projects/spring-data-r2dbc[Spring Data R2DBC] repositories are interfaces that you can define to access data. Queries are created automatically from your method names. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment.adoc index 9e3736de913f..33d3f685e0bd 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment.adoc @@ -5,14 +5,11 @@ include::attributes.adoc[] Spring Boot's flexible packaging options provide a great deal of choice when it comes to deploying your application. -You can deploy Spring Boot applications to a variety of cloud platforms, to container images (such as Docker), or to virtual/real machines. +You can deploy Spring Boot applications to a variety of cloud platforms, to virtual/real machines, or make them fully executable for Unix systems. This section covers some of the more common deployment scenarios. - -include::deployment/containers.adoc[] - include::deployment/cloud.adoc[] include::deployment/installing.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment/cloud.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment/cloud.adoc index 3a78c5bbf70c..386693476889 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment/cloud.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment/cloud.adoc @@ -136,7 +136,7 @@ The preStop handler can be configured via the PodSpec in the pod's configuration command: ["sh", "-c", "sleep 10"] ---- -Once the pre-stop hook has completed, SIGTERM will be sent to the container and <> will begin, allowing any remaining in-flight requests to complete. +Once the pre-stop hook has completed, SIGTERM will be sent to the container and <> will begin, allowing any remaining in-flight requests to complete. NOTE: When Kubernetes sends a SIGTERM signal to the pod, it waits for a specified time called the termination grace period (the default for which is 30 seconds). If the containers are still running after the grace period, they are sent the SIGKILL signal and forcibly removed. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment/containers.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment/containers.adoc deleted file mode 100644 index ee67b1c01174..000000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment/containers.adoc +++ /dev/null @@ -1,28 +0,0 @@ -[[deployment.containers]] -== Deploying to Containers -If you are running your application from a container, you can use an executable jar, but it is also often an advantage to explode it and run it in a different way. -Certain PaaS implementations may also choose to unpack archives before they run. -For example, Cloud Foundry operates this way. -One way to run an unpacked archive is by starting the appropriate launcher, as follows: - -[source,shell,indent=0,subs="verbatim"] ----- - $ jar -xf myapp.jar - $ java org.springframework.boot.loader.JarLauncher ----- - -This is actually slightly faster on startup (depending on the size of the jar) than running from an unexploded archive. -At runtime you shouldn't expect any differences. - -Once you have unpacked the jar file, you can also get an extra boost to startup time by running the app with its "natural" main method instead of the `JarLauncher`. For example: - -[source,shell,indent=0,subs="verbatim"] ----- - $ jar -xf myapp.jar - $ java -cp BOOT-INF/classes:BOOT-INF/lib/* com.example.MyApplication ----- - -NOTE: Using the `JarLauncher` over the application's main method has the added benefit of a predictable classpath order. -The jar contains a `classpath.idx` file which is used by the `JarLauncher` when constructing the classpath. - -More efficient container images can also be created by <> for your dependencies and application classes and resources (which normally change more frequently). diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation.adoc index 759efc3b0390..e8eb8df6a7e9 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation.adoc @@ -22,6 +22,14 @@ include::documentation/using.adoc[] include::documentation/features.adoc[] -include::documentation/actuator.adoc[] +include::documentation/web.adoc[] + +include::documentation/data.adoc[] + +include::documentation/messaging.adoc[] + +include::documentation/io.adoc[] + +include::documentation/container-images.adoc[] include::documentation/advanced.adoc[] \ No newline at end of file diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/container-images.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/container-images.adoc new file mode 100644 index 000000000000..a136da68c80e --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/container-images.adoc @@ -0,0 +1,7 @@ +[[documentation.container-images]] +== Container Images +Spring Boot provides first-class support for building efficient container images. You can read more about it here: + +* *Efficient Container Images:* <> +* *Dockerfiles:* <> +* *Cloud Native Buildpacks:* <> \ No newline at end of file diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/data.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/data.adoc new file mode 100644 index 000000000000..85e1a862ed07 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/data.adoc @@ -0,0 +1,6 @@ +[[documentation.data]] +== Data +If your application deals with a datastore, you can see how to configure that here: + +* *SQL:* <> +* *NOSQL:* <> diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/features.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/features.adoc index 0e6a8f8657c1..62a4cfc21bb1 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/features.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/features.adoc @@ -3,9 +3,7 @@ Need more details about Spring Boot's core features? <>: -* *Core Features:* <> | <> | <> | <> -* *Web Applications:* <> | <> -* *Working with data:* <> | <> -* *Messaging:* <> | <> -* *Testing:* <> | <> | <> -* *Extending:* <> | <> +* *Spring Application:* <> +* *External Configuration:* <> +* *Profiles:* <> +* *Logging:* <> <> diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/io.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/io.adoc new file mode 100644 index 000000000000..f02f5350b824 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/io.adoc @@ -0,0 +1,11 @@ +[[documentation.io]] +== IO +If your application needs IO capabilities, check out this section: + +* *Caching:* <> +* *Quartz:* <> +* *Mail:* <> +* *Validation:* <> +* *REST Clients:* <> +* *Webservices:* <> +* *JTA:* <> \ No newline at end of file diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/messaging.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/messaging.adoc new file mode 100644 index 000000000000..904e71989f92 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/messaging.adoc @@ -0,0 +1,9 @@ +[[documentation.messaging]] +== Messaging +If your application uses any messaging protocol, check out this section: + +* *JMS:* <> +* *AMQP:* <> +* *Kafka:* <> +* *RSocket:* <> +* *Spring Integration:* <> \ No newline at end of file diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/web.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/web.adoc new file mode 100644 index 000000000000..49de19ad4c91 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/web.adoc @@ -0,0 +1,10 @@ +[[documentation.web]] +== Web +If you're developing Spring Boot web applications, take a look at the following content: + +* *Servlet Web Applications:* <> +* *Reactive Web Applications:* <> +* *Graceful Shutdown:* <> +* *Spring Security:* <> +* *Spring Session:* <> +* *Spring HATEOAS:* <> \ No newline at end of file diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features.adoc index 6d60adc5e5ff..6b26fa98c955 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features.adoc @@ -1,5 +1,5 @@ [[features]] -= Spring Boot Features += Core Features include::attributes.adoc[] @@ -22,54 +22,14 @@ include::features/internationalization.adoc[] include::features/json.adoc[] -include::features/developing-web-applications.adoc[] - -include::features/graceful-shutdown.adoc[] - -include::features/rsocket.adoc[] - -include::features/security.adoc[] - -include::features/sql.adoc[] - -include::features/nosql.adoc[] - -include::features/caching.adoc[] - -include::features/messaging.adoc[] - -include::features/resttemplate.adoc[] - -include::features/webclient.adoc[] - -include::features/validation.adoc[] - -include::features/email.adoc[] - -include::features/jta.adoc[] - include::features/hazelcast.adoc[] -include::features/quartz.adoc[] - include::features/task-execution-and-scheduling.adoc[] -include::features/spring-integration.adoc[] - -include::features/spring-session.adoc[] - -include::features/jmx.adoc[] - include::features/testing.adoc[] -include::features/websockets.adoc[] - -include::features/webservices.adoc[] - include::features/developing-auto-configuration.adoc[] include::features/kotlin.adoc[] -include::features/container-images.adoc[] - include::features/whats-next.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/container-images.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/container-images.adoc deleted file mode 100644 index 8fae91b84f89..000000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/container-images.adoc +++ /dev/null @@ -1,141 +0,0 @@ -[[features.container-images]] -== Container Images -It is easily possible to package a Spring Boot fat jar as a docker image. -However, there are various downsides to copying and running the fat jar as is in the docker image. -There’s always a certain amount of overhead when running a fat jar without unpacking it, and in a containerized environment this can be noticeable. -The other issue is that putting your application's code and all its dependencies in one layer in the Docker image is sub-optimal. -Since you probably recompile your code more often than you upgrade the version of Spring Boot you use, it’s often better to separate things a bit more. -If you put jar files in the layer before your application classes, Docker often only needs to change the very bottom layer and can pick others up from its cache. - - - -[[features.container-images.layering]] -=== Layering Docker Images -To make it easier to create optimized Docker images, Spring Boot supports adding a layer index file to the jar. -It provides a list of layers and the parts of the jar that should be contained within them. -The list of layers in the index is ordered based on the order in which the layers should be added to the Docker/OCI image. -Out-of-the-box, the following layers are supported: - -* `dependencies` (for regular released dependencies) -* `spring-boot-loader` (for everything under `org/springframework/boot/loader`) -* `snapshot-dependencies` (for snapshot dependencies) -* `application` (for application classes and resources) - -The following shows an example of a `layers.idx` file: - -[source,yaml,indent=0,subs="verbatim"] ----- - - "dependencies": - - BOOT-INF/lib/library1.jar - - BOOT-INF/lib/library2.jar - - "spring-boot-loader": - - org/springframework/boot/loader/JarLauncher.class - - org/springframework/boot/loader/jar/JarEntry.class - - "snapshot-dependencies": - - BOOT-INF/lib/library3-SNAPSHOT.jar - - "application": - - META-INF/MANIFEST.MF - - BOOT-INF/classes/a/b/C.class ----- - -This layering is designed to separate code based on how likely it is to change between application builds. -Library code is less likely to change between builds, so it is placed in its own layers to allow tooling to re-use the layers from cache. -Application code is more likely to change between builds so it is isolated in a separate layer. - -Spring Boot also supports layering for war files with the help of a `layers.idx`. - -For Maven, refer to the {spring-boot-maven-plugin-docs}#repackage-layers[packaging layered jar or war section] for more details on adding a layer index to the archive. -For Gradle, refer to the {spring-boot-gradle-plugin-docs}#packaging-layered-archives[packaging layered jar or war section] of the Gradle plugin documentation. - - - -[[features.container-images.building]] -=== Building Container Images -Spring Boot applications can be containerized <>, or by <>. - - - -[[features.container-images.building.dockerfiles]] -==== Dockerfiles -While it is possible to convert a Spring Boot fat jar into a docker image with just a few lines in the Dockerfile, we will use the <> to create an optimized docker image. -When you create a jar containing the layers index file, the `spring-boot-jarmode-layertools` jar will be added as a dependency to your jar. -With this jar on the classpath, you can launch your application in a special mode which allows the bootstrap code to run something entirely different from your application, for example, something that extracts the layers. - -CAUTION: The `layertools` mode can not be used with a <> that includes a launch script. -Disable launch script configuration when building a jar file that is intended to be used with `layertools`. - -Here’s how you can launch your jar with a `layertools` jar mode: - -[source,shell,indent=0,subs="verbatim"] ----- -$ java -Djarmode=layertools -jar my-app.jar ----- - -This will provide the following output: - -[subs="verbatim"] ----- -Usage: - java -Djarmode=layertools -jar my-app.jar - -Available commands: - list List layers from the jar that can be extracted - extract Extracts layers from the jar for image creation - help Help about any command ----- - -The `extract` command can be used to easily split the application into layers to be added to the dockerfile. -Here's an example of a Dockerfile using `jarmode`. - -[source,dockerfile,indent=0,subs="verbatim"] ----- -FROM adoptopenjdk:11-jre-hotspot as builder -WORKDIR application -ARG JAR_FILE=target/*.jar -COPY ${JAR_FILE} application.jar -RUN java -Djarmode=layertools -jar application.jar extract - -FROM adoptopenjdk:11-jre-hotspot -WORKDIR application -COPY --from=builder application/dependencies/ ./ -COPY --from=builder application/spring-boot-loader/ ./ -COPY --from=builder application/snapshot-dependencies/ ./ -COPY --from=builder application/application/ ./ -ENTRYPOINT ["java", "org.springframework.boot.loader.JarLauncher"] ----- - -Assuming the above `Dockerfile` is in the current directory, your docker image can be built with `docker build .`, or optionally specifying the path to your application jar, as shown in the following example: - -[source,shell,indent=0,subs="verbatim"] ----- - $ docker build --build-arg JAR_FILE=path/to/myapp.jar . ----- - -This is a multi-stage dockerfile. -The builder stage extracts the directories that are needed later. -Each of the `COPY` commands relates to the layers extracted by the jarmode. - -Of course, a Dockerfile can be written without using the jarmode. -You can use some combination of `unzip` and `mv` to move things to the right layer but jarmode simplifies that. - - - -[[features.container-images.building.buildpacks]] -==== Cloud Native Buildpacks -Dockerfiles are just one way to build docker images. -Another way to build docker images is directly from your Maven or Gradle plugin, using buildpacks. -If you’ve ever used an application platform such as Cloud Foundry or Heroku then you’ve probably used a buildpack. -Buildpacks are the part of the platform that takes your application and converts it into something that the platform can actually run. -For example, Cloud Foundry’s Java buildpack will notice that you’re pushing a `.jar` file and automatically add a relevant JRE. - -With Cloud Native Buildpacks, you can create Docker compatible images that you can run anywhere. -Spring Boot includes buildpack support directly for both Maven and Gradle. -This means you can just type a single command and quickly get a sensible image into your locally running Docker daemon. - -Refer to the individual plugin documentation on how to use buildpacks with {spring-boot-maven-plugin-docs}#build-image[Maven] and {spring-boot-gradle-plugin-docs}#build-image[Gradle]. - -NOTE: The https://github.com/paketo-buildpacks/spring-boot[Paketo Spring Boot buildpack] has also been updated to support the `layers.idx` file so any customization that is applied to it will be reflected in the image created by the buildpack. - -NOTE: In order to achieve reproducible builds and container image caching, Buildpacks can manipulate the application resources metadata (such as the file "last modified" information). -You should ensure that your application does not rely on that metadata at runtime. -Spring Boot can use that information when serving static resources, but this can be disabled with configprop:spring.web.resources.cache.use-last-modified[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/hazelcast.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/hazelcast.adoc index 4e8d8e5466a2..67c53fe6a60e 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/hazelcast.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/hazelcast.adoc @@ -30,5 +30,5 @@ 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. -NOTE: Spring Boot also has <>. +NOTE: Spring Boot also has <>. If caching is enabled, the `HazelcastInstance` is automatically wrapped in a `CacheManager` implementation. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/jmx.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/jmx.adoc deleted file mode 100644 index e0ac4ec3d19d..000000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/jmx.adoc +++ /dev/null @@ -1,10 +0,0 @@ -[[features.jmx]] -== Monitoring and Management over JMX -Java Management Extensions (JMX) provide a standard mechanism to monitor and manage applications. -Spring Boot exposes the most suitable `MBeanServer` as a bean with an ID of `mbeanServer`. -Any of your beans that are annotated with Spring JMX annotations (`@ManagedResource`, `@ManagedAttribute`, or `@ManagedOperation`) are exposed to it. - -If your platform provides a standard `MBeanServer`, Spring Boot will use that and default to the VM `MBeanServer` if necessary. -If all that fails, a new `MBeanServer` will be created. - -See the {spring-boot-autoconfigure-module-code}/jmx/JmxAutoConfiguration.java[`JmxAutoConfiguration`] class for more details. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/messaging.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/messaging.adoc deleted file mode 100644 index eaeef4872cdb..000000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/messaging.adoc +++ /dev/null @@ -1,492 +0,0 @@ -[[features.messaging]] -== Messaging -The Spring Framework provides extensive support for integrating with messaging systems, from simplified use of the JMS API using `JmsTemplate` to a complete infrastructure to receive messages asynchronously. -Spring AMQP provides a similar feature set for the Advanced Message Queuing Protocol. -Spring Boot also provides auto-configuration options for `RabbitTemplate` and RabbitMQ. -Spring WebSocket natively includes support for STOMP messaging, and Spring Boot has support for that through starters and a small amount of auto-configuration. -Spring Boot also has support for Apache Kafka. - - - -[[features.messaging.jms]] -=== JMS -The `javax.jms.ConnectionFactory` interface provides a standard method of creating a `javax.jms.Connection` for interacting with a JMS broker. -Although Spring needs a `ConnectionFactory` to work with JMS, you generally need not use it directly yourself and can instead rely on higher level messaging abstractions. -(See the {spring-framework-docs}/integration.html#jms[relevant section] of the Spring Framework reference documentation for details.) -Spring Boot also auto-configures the necessary infrastructure to send and receive messages. - - - -[[features.messaging.jms.activemq]] -==== ActiveMQ Support -When https://activemq.apache.org/[ActiveMQ] is available on the classpath, Spring Boot can also configure a `ConnectionFactory`. -If the broker is present, an embedded broker is automatically started and configured (provided no broker URL is specified through configuration). - -NOTE: If you use `spring-boot-starter-activemq`, the necessary dependencies to connect or embed an ActiveMQ instance are provided, as is the Spring infrastructure to integrate with JMS. - -ActiveMQ configuration is controlled by external configuration properties in `+spring.activemq.*+`. -For example, you might declare the following section in `application.properties`: - -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] ----- - spring: - activemq: - broker-url: "tcp://192.168.1.210:9876" - user: "admin" - password: "secret" ----- - -By default, a `CachingConnectionFactory` wraps the native `ConnectionFactory` with sensible settings that you can control by external configuration properties in `+spring.jms.*+`: - -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] ----- - spring: - jms: - cache: - session-cache-size: 5 ----- - -If you'd rather use native pooling, you can do so by adding a dependency to `org.messaginghub:pooled-jms` and configuring the `JmsPoolConnectionFactory` accordingly, as shown in the following example: - -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] ----- - spring: - activemq: - pool: - enabled: true - max-connections: 50 ----- - -TIP: See {spring-boot-autoconfigure-module-code}/jms/activemq/ActiveMQProperties.java[`ActiveMQProperties`] for more of the supported options. -You can also register an arbitrary number of beans that implement `ActiveMQConnectionFactoryCustomizer` for more advanced customizations. - -By default, ActiveMQ creates a destination if it does not yet exist so that destinations are resolved against their provided names. - - - -[[features.messaging.jms.artemis]] -==== ActiveMQ Artemis Support -Spring Boot can auto-configure a `ConnectionFactory` when it detects that https://activemq.apache.org/components/artemis/[ActiveMQ Artemis] is available on the classpath. -If the broker is present, an embedded broker is automatically started and configured (unless the mode property has been explicitly set). -The supported modes are `embedded` (to make explicit that an embedded broker is required and that an error should occur if the broker is not available on the classpath) and `native` (to connect to a broker using the `netty` transport protocol). -When the latter is configured, Spring Boot configures a `ConnectionFactory` that connects to a broker running on the local machine with the default settings. - -NOTE: If you use `spring-boot-starter-artemis`, the necessary dependencies to connect to an existing ActiveMQ Artemis instance are provided, as well as the Spring infrastructure to integrate with JMS. -Adding `org.apache.activemq:artemis-jms-server` to your application lets you use embedded mode. - -ActiveMQ Artemis configuration is controlled by external configuration properties in `+spring.artemis.*+`. -For example, you might declare the following section in `application.properties`: - -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] ----- - spring: - artemis: - mode: native - broker-url: "tcp://192.168.1.210:9876" - user: "admin" - password: "secret" ----- - -When embedding the broker, you can choose if you want to enable persistence and list the destinations that should be made available. -These can be specified as a comma-separated list to create them with the default options, or you can define bean(s) of type `org.apache.activemq.artemis.jms.server.config.JMSQueueConfiguration` or `org.apache.activemq.artemis.jms.server.config.TopicConfiguration`, for advanced queue and topic configurations, respectively. - -By default, a `CachingConnectionFactory` wraps the native `ConnectionFactory` with sensible settings that you can control by external configuration properties in `+spring.jms.*+`: - -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] ----- - spring: - jms: - cache: - session-cache-size: 5 ----- - -If you'd rather use native pooling, you can do so by adding a dependency to `org.messaginghub:pooled-jms` and configuring the `JmsPoolConnectionFactory` accordingly, as shown in the following example: - -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] ----- - spring: - artemis: - pool: - enabled: true - max-connections: 50 ----- - -See {spring-boot-autoconfigure-module-code}/jms/artemis/ArtemisProperties.java[`ArtemisProperties`] for more supported options. - -No JNDI lookup is involved, and destinations are resolved against their names, using either the `name` attribute in the Artemis configuration or the names provided through configuration. - - - -[[features.messaging.jms.jndi]] -==== Using a JNDI ConnectionFactory -If you are running your application in an application server, Spring Boot tries to locate a JMS `ConnectionFactory` by using JNDI. -By default, the `java:/JmsXA` and `java:/XAConnectionFactory` location are checked. -You can use the configprop:spring.jms.jndi-name[] property if you need to specify an alternative location, as shown in the following example: - -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] ----- - spring: - jms: - jndi-name: "java:/MyConnectionFactory" ----- - - - -[[features.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: - -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/messaging/jms/sending/MyBean.java[] ----- - -NOTE: {spring-framework-api}/jms/core/JmsMessagingTemplate.html[`JmsMessagingTemplate`] can be injected in a similar manner. -If a `DestinationResolver` or a `MessageConverter` bean is defined, it is associated automatically to the auto-configured `JmsTemplate`. - - - -[[features.messaging.jms.receiving]] -==== Receiving a Message -When the JMS infrastructure is present, any bean can be annotated with `@JmsListener` to create a listener endpoint. -If no `JmsListenerContainerFactory` has been defined, a default one is configured automatically. -If a `DestinationResolver`, a `MessageConverter`, or a `javax.jms.ExceptionListener` beans are defined, they are associated automatically with the default factory. - -By default, the default factory is transactional. -If you run in an infrastructure where a `JtaTransactionManager` is present, it is associated to the listener container by default. -If not, the `sessionTransacted` flag is enabled. -In that latter scenario, you can associate your local data store transaction to the processing of an incoming message by adding `@Transactional` on your listener method (or a delegate thereof). -This ensures that the incoming message is acknowledged, once the local transaction has completed. -This also includes sending response messages that have been performed on the same JMS session. - -The following component creates a listener endpoint on the `someQueue` destination: - -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/messaging/jms/receiving/MyBean.java[] ----- - -TIP: See {spring-framework-api}/jms/annotation/EnableJms.html[the Javadoc of `@EnableJms`] for more details. - -If you need to create more `JmsListenerContainerFactory` instances or if you want to override the default, Spring Boot provides a `DefaultJmsListenerContainerFactoryConfigurer` that you can use to initialize a `DefaultJmsListenerContainerFactory` with the same settings as the one that is auto-configured. - -For instance, the following example exposes another factory that uses a specific `MessageConverter`: - -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/messaging/jms/receiving/custom/MyJmsConfiguration.java[] ----- - -Then you can use the factory in any `@JmsListener`-annotated method as follows: - -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/messaging/jms/receiving/custom/MyBean.java[] ----- - - - -[[features.messaging.amqp]] -=== AMQP -The Advanced Message Queuing Protocol (AMQP) is a platform-neutral, wire-level protocol for message-oriented middleware. -The Spring AMQP project applies core Spring concepts to the development of AMQP-based messaging solutions. -Spring Boot offers several conveniences for working with AMQP through RabbitMQ, including the `spring-boot-starter-amqp` "`Starter`". - - - -[[features.messaging.amqp.rabbitmq]] -==== RabbitMQ support -https://www.rabbitmq.com/[RabbitMQ] is a lightweight, reliable, scalable, and portable message broker based on the AMQP protocol. -Spring uses `RabbitMQ` to communicate through the AMQP protocol. - -RabbitMQ configuration is controlled by external configuration properties in `+spring.rabbitmq.*+`. -For example, you might declare the following section in `application.properties`: - -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] ----- - spring: - rabbitmq: - host: "localhost" - port: 5672 - username: "admin" - password: "secret" ----- - -Alternatively, you could configure the same connection using the `addresses` attribute: - -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] ----- - spring: - rabbitmq: - addresses: "amqp://admin:secret@localhost" ----- - -NOTE: When specifying addresses that way, the `host` and `port` properties are ignored. -If the address uses the `amqps` protocol, SSL support is enabled automatically. - -See {spring-boot-autoconfigure-module-code}/amqp/RabbitProperties.java[`RabbitProperties`] for more of the supported property-based configuration options. -To configure lower-level details of the RabbitMQ `ConnectionFactory` that is used by Spring AMQP, define a `ConnectionFactoryCustomizer` bean. - -If a `ConnectionNameStrategy` bean exists in the context, it will be automatically used to name connections created by the auto-configured `CachingConnectionFactory`. - -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. - - - -[[features.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: - -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/messaging/amqp/sending/MyBean.java[] ----- - -NOTE: {spring-amqp-api}/rabbit/core/RabbitMessagingTemplate.html[`RabbitMessagingTemplate`] can be injected in a similar manner. -If a `MessageConverter` bean is defined, it is associated automatically to the auto-configured `AmqpTemplate`. - -If necessary, any `org.springframework.amqp.core.Queue` that is defined as a bean is automatically used to declare a corresponding queue on the RabbitMQ instance. - -To retry operations, you can enable retries on the `AmqpTemplate` (for example, in the event that the broker connection is lost): - -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] ----- - spring: - rabbitmq: - template: - retry: - enabled: true - initial-interval: "2s" ----- - -Retries are disabled by default. -You can also customize the `RetryTemplate` programmatically by declaring a `RabbitRetryTemplateCustomizer` bean. - -If you need to create more `RabbitTemplate` instances or if you want to override the default, Spring Boot provides a `RabbitTemplateConfigurer` bean that you can use to initialize a `RabbitTemplate` with the same settings as the factories used by the auto-configuration. - - - -[[features.messaging.amqp.receiving]] -==== Receiving a Message -When the Rabbit infrastructure is present, any bean can be annotated with `@RabbitListener` to create a listener endpoint. -If no `RabbitListenerContainerFactory` has been defined, a default `SimpleRabbitListenerContainerFactory` is automatically configured and you can switch to a direct container using the configprop:spring.rabbitmq.listener.type[] property. -If a `MessageConverter` or a `MessageRecoverer` bean is defined, it is automatically associated with the default factory. - -The following sample component creates a listener endpoint on the `someQueue` queue: - -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/messaging/amqp/receiving/MyBean.java[] ----- - -TIP: See {spring-amqp-api}/rabbit/annotation/EnableRabbit.html[the Javadoc of `@EnableRabbit`] for more details. - -If you need to create more `RabbitListenerContainerFactory` instances or if you want to override the default, Spring Boot provides a `SimpleRabbitListenerContainerFactoryConfigurer` and a `DirectRabbitListenerContainerFactoryConfigurer` that you can use to initialize a `SimpleRabbitListenerContainerFactory` and a `DirectRabbitListenerContainerFactory` with the same settings as the factories used by the auto-configuration. - -TIP: It does not matter which container type you chose. -Those two beans are exposed by the auto-configuration. - -For instance, the following configuration class exposes another factory that uses a specific `MessageConverter`: - -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/messaging/amqp/receiving/custom/MyRabbitConfiguration.java[] ----- - -Then you can use the factory in any `@RabbitListener`-annotated method, as follows: - -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/messaging/amqp/receiving/custom/MyBean.java[] ----- - -You can enable retries to handle situations where your listener throws an exception. -By default, `RejectAndDontRequeueRecoverer` is used, but you can define a `MessageRecoverer` of your own. -When retries are exhausted, the message is rejected and either dropped or routed to a dead-letter exchange if the broker is configured to do so. -By default, retries are disabled. -You can also customize the `RetryTemplate` programmatically by declaring a `RabbitRetryTemplateCustomizer` bean. - -IMPORTANT: By default, if retries are disabled and the listener throws an exception, the delivery is retried indefinitely. -You can modify this behavior in two ways: Set the `defaultRequeueRejected` property to `false` so that zero re-deliveries are attempted or throw an `AmqpRejectAndDontRequeueException` to signal the message should be rejected. -The latter is the mechanism used when retries are enabled and the maximum number of delivery attempts is reached. - - - -[[features.messaging.kafka]] -=== Apache Kafka Support -https://kafka.apache.org/[Apache Kafka] is supported by providing auto-configuration of the `spring-kafka` project. - -Kafka configuration is controlled by external configuration properties in `spring.kafka.*`. -For example, you might declare the following section in `application.properties`: - -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] ----- - spring: - kafka: - bootstrap-servers: "localhost:9092" - consumer: - group-id: "myGroup" ----- - -TIP: To create a topic on startup, add a bean of type `NewTopic`. -If the topic already exists, the bean is ignored. - -See {spring-boot-autoconfigure-module-code}/kafka/KafkaProperties.java[`KafkaProperties`] for more supported options. - - - -[[features.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: - -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/messaging/kafka/sending/MyBean.java[] ----- - -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`. - - - -[[features.messaging.kafka.receiving]] -==== Receiving a Message -When the Apache Kafka infrastructure is present, any bean can be annotated with `@KafkaListener` to create a listener endpoint. -If no `KafkaListenerContainerFactory` has been defined, a default one is automatically configured with keys defined in `spring.kafka.listener.*`. - -The following component creates a listener endpoint on the `someTopic` topic: - -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/messaging/kafka/receiving/MyBean.java[] ----- - -If a `KafkaTransactionManager` bean is defined, it is automatically associated to the container factory. -Similarly, if a `RecordFilterStrategy`, `ErrorHandler`, `AfterRollbackProcessor` or `ConsumerAwareRebalanceListener` bean is defined, it is automatically associated to the default factory. - -Depending on the listener type, a `RecordMessageConverter` or `BatchMessageConverter` bean is associated to the default factory. -If only a `RecordMessageConverter` bean is present for a batch listener, it is wrapped in a `BatchMessageConverter`. - -TIP: A custom `ChainedKafkaTransactionManager` must be marked `@Primary` as it usually references the auto-configured `KafkaTransactionManager` bean. - - - -[[features.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 via the `@EnableKafkaStreams` annotation. - -Enabling Kafka Streams means that the application id and bootstrap servers must be set. -The former can be configured using `spring.kafka.streams.application-id`, defaulting to `spring.application.name` if not set. -The latter can be set globally or specifically overridden only for streams. - -Several additional properties are available using dedicated properties; other arbitrary Kafka properties can be set using the `spring.kafka.streams.properties` namespace. -See also <> for more information. - -To use the factory bean, wire `StreamsBuilder` into your `@Bean` as shown in the following example: - -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/messaging/kafka/streams/MyKafkaStreamsConfiguration.java[] ----- - -By default, the streams managed by the `StreamBuilder` object it creates are started automatically. -You can customize this behavior using the configprop:spring.kafka.streams.auto-startup[] property. - - - -[[features.messaging.kafka.additional-properties]] -==== Additional Kafka Properties -The properties supported by auto configuration are shown in <>. -Note that, for the most part, these properties (hyphenated or camelCase) map directly to the Apache Kafka dotted properties. -Refer to the Apache Kafka documentation for details. - -The first few of these properties apply to all components (producers, consumers, admins, and streams) but can be specified at the component level if you wish to use different values. -Apache Kafka designates properties with an importance of HIGH, MEDIUM, or LOW. -Spring Boot auto-configuration supports all HIGH importance properties, some selected MEDIUM and LOW properties, and any properties that do not have a default value. - -Only a subset of the properties supported by Kafka are available directly through the `KafkaProperties` class. -If you wish to configure the producer or consumer with additional properties that are not directly supported, use the following properties: - -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] ----- - spring: - kafka: - properties: - "[prop.one]": "first" - admin: - properties: - "[prop.two]": "second" - consumer: - properties: - "[prop.three]": "third" - producer: - properties: - "[prop.four]": "fourth" - streams: - properties: - "[prop.five]": "fifth" ----- - -This sets the common `prop.one` Kafka property to `first` (applies to producers, consumers and admins), the `prop.two` admin property to `second`, the `prop.three` consumer property to `third`, the `prop.four` producer property to `fourth` and the `prop.five` streams property to `fifth`. - -You can also configure the Spring Kafka `JsonDeserializer` as follows: - -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] ----- - spring: - kafka: - consumer: - value-deserializer: "org.springframework.kafka.support.serializer.JsonDeserializer" - properties: - "[spring.json.value.default.type]": "com.example.Invoice" - "[spring.json.trusted.packages]": "com.example.main,com.example.another" ----- - -Similarly, you can disable the `JsonSerializer` default behavior of sending type information in headers: - -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] ----- - spring: - kafka: - producer: - value-serializer: "org.springframework.kafka.support.serializer.JsonSerializer" - properties: - "[spring.json.add.type.headers]": false ----- - -IMPORTANT: Properties set in this way override any configuration item that Spring Boot explicitly supports. - - - -[[features.messaging.kafka.embedded]] -==== Testing with Embedded Kafka -Spring for Apache Kafka provides a convenient way to test projects with an embedded Apache Kafka broker. -To use this feature, annotate a test class with `@EmbeddedKafka` from the `spring-kafka-test` module. -For more information, please see the Spring for Apache Kafka {spring-kafka-docs}#embedded-kafka-annotation[reference manual]. - -To make Spring Boot auto-configuration work with the aforementioned embedded Apache Kafka broker, you need to remap a system property for embedded broker addresses (populated by the `EmbeddedKafkaBroker`) into the Spring Boot configuration property for Apache Kafka. -There are several ways to do that: - -* Provide a system property to map embedded broker addresses into configprop:spring.kafka.bootstrap-servers[] in the test class: - -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/messaging/kafka/embedded/property/MyTest.java[tag=*] ----- - -* Configure a property name on the `@EmbeddedKafka` annotation: - -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/messaging/kafka/embedded/annotation/MyTest.java[] ----- - -* Use a placeholder in configuration properties: - -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] ----- - spring: - kafka: - bootstrap-servers: "${spring.embedded.kafka.brokers}" ----- diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/resttemplate.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/resttemplate.adoc deleted file mode 100644 index 84e8378b0b6b..000000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/resttemplate.adoc +++ /dev/null @@ -1,47 +0,0 @@ -[[features.resttemplate]] -== Calling REST Services with RestTemplate -If you need to call remote REST services from your application, you can use the Spring Framework's {spring-framework-api}/web/client/RestTemplate.html[`RestTemplate`] class. -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` are applied to `RestTemplate` instances. - -The following code shows a typical example: - -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/resttemplate/MyService.java[] ----- - -TIP: `RestTemplateBuilder` includes a number of useful methods that can be used to quickly configure a `RestTemplate`. -For example, to add BASIC auth support, you can use `builder.basicAuthentication("user", "password").build()`. - - - -[[features.resttemplate.customization]] -=== RestTemplate Customization -There are three main approaches to `RestTemplate` customization, depending on how broadly you want the customizations to apply. - -To make the scope of any customizations as narrow as possible, inject the auto-configured `RestTemplateBuilder` and then call its methods as required. -Each method call returns a new `RestTemplateBuilder` instance, so the customizations only affect this use of the builder. - -To make an application-wide, additive customization, use a `RestTemplateCustomizer` bean. -All such beans are automatically registered with the auto-configured `RestTemplateBuilder` and are applied to any templates that are built with it. - -The following example shows a customizer that configures the use of a proxy for all hosts except `192.168.0.5`: - -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/resttemplate/customization/MyRestTemplateCustomizer.java[] ----- - -Finally, you can also create your own `RestTemplateBuilder` bean. -To prevent switching off the auto-configuration of a `RestTemplateBuilder` and prevent any `RestTemplateCustomizer` beans from being used, make sure to configure your custom instance with a `RestTemplateBuilderConfigurer`. -The following example exposes a `RestTemplateBuilder` with what Spring Boot would auto-configure, except that custom connect and read timeouts are also specified: - -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/resttemplate/customization/MyRestTemplateBuilderConfiguration.java[] ----- - -The most extreme (and rarely used) option is to create your own `RestTemplateBuilder` bean without using a configurer. -Doing so switches off the auto-configuration of a `RestTemplateBuilder` and prevents any `RestTemplateCustomizer` beans from being used. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/testing.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/testing.adoc index 2679586f500f..46ee954506c0 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/testing.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/testing.adoc @@ -195,7 +195,7 @@ Testing within a mocked environment is usually faster than running with a full S However, since mocking occurs at the Spring MVC layer, code that relies on lower-level Servlet container behavior cannot be directly tested with MockMvc. For example, Spring Boot's error handling is based on the "`error page`" support provided by the Servlet container. -This means that, whilst you can test your MVC layer throws and handles exceptions as expected, you cannot directly test that a specific <> is rendered. +This means that, whilst you can test your MVC layer throws and handles exceptions as expected, you cannot directly test that a specific <> is rendered. If you need to test these lower-level concerns, you can start a fully running server as described in the next section. ==== @@ -451,7 +451,7 @@ You can use `@DataCassandraTest` to test Cassandra applications. By default, it configures a `CassandraTemplate`, scans for `@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. -(For more about using Cassandra with Spring Boot, see "<>", earlier in this chapter.) +(For more about using Cassandra with Spring Boot, see "<>", earlier in this chapter.) TIP: A list of the auto-configuration settings that are enabled by `@DataCassandraTest` can be <>. @@ -552,7 +552,7 @@ If you prefer your test to run against a real database, you can use the `@AutoCo 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. -(For more about using jOOQ with Spring Boot, see "<>", earlier in this chapter.) +(For more about using jOOQ with Spring Boot, see "<>", earlier in this chapter.) Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@JooqTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. @@ -577,7 +577,7 @@ You can use `@DataMongoTest` to test MongoDB applications. By default, it configures an in-memory embedded MongoDB (if available), configures a `MongoTemplate`, scans for `@Document` classes, and configures Spring Data MongoDB repositories. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataMongoTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. -(For more about using MongoDB with Spring Boot, see "<>", earlier in this chapter.) +(For more about using MongoDB with Spring Boot, see "<>", earlier in this chapter.) TIP: A list of the auto-configuration settings that are enabled by `@DataMongoTest` can be <>. @@ -604,7 +604,7 @@ You can use `@DataNeo4jTest` to test Neo4j applications. By default, it scans for `@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. -(For more about using Neo4J with Spring Boot, see "<>", earlier in this chapter.) +(For more about using Neo4J with Spring Boot, see "<>", earlier in this chapter.) TIP: A list of the auto-configuration settings that are enabled by `@DataNeo4jTest` can be <>. @@ -635,7 +635,7 @@ 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. -(For more about using Redis with Spring Boot, see "<>", earlier in this chapter.) +(For more about using Redis with Spring Boot, see "<>", earlier in this chapter.) TIP: A list of the auto-configuration settings that are enabled by `@DataRedisTest` can be <>. @@ -654,7 +654,7 @@ 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. -(For more about using LDAP with Spring Boot, see "<>", earlier in this chapter.) +(For more about using LDAP with Spring Boot, see "<>", earlier in this chapter.) TIP: A list of the auto-configuration settings that are enabled by `@DataLdapTest` can be <>. @@ -773,7 +773,7 @@ include::{docs-java}/features/testing/springbootapplications/autoconfiguredsprin ==== Auto-configured Spring Web Services Tests You can use `@WebServiceClientTest` to test applications that use call web services using the Spring Web Services project. By default, it configures a mock `WebServiceServer` bean and automatically customizes your `WebServiceTemplateBuilder`. -(For more about using Web Services with Spring Boot, see "<>", earlier in this chapter.) +(For more about using Web Services with Spring Boot, see "<>", earlier in this chapter.) TIP: A list of the auto-configuration settings that are enabled by `@WebServiceClientTest` can be <>. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/webclient.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/webclient.adoc deleted file mode 100644 index ccf22e177a6f..000000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/webclient.adoc +++ /dev/null @@ -1,48 +0,0 @@ -[[features.webclient]] -== Calling REST Services with WebClient -If you have Spring WebFlux on your classpath, you can also choose to use `WebClient` to call remote REST services. -Compared to `RestTemplate`, this client has a more functional feel and is fully reactive. -You can learn more about the `WebClient` in the dedicated {spring-framework-docs}/web-reactive.html#webflux-client[section in the Spring Framework docs]. - -Spring Boot creates and pre-configures a `WebClient.Builder` for you. -It is strongly advised to inject it in your components and use it to create `WebClient` instances. -Spring Boot is configuring that builder to share HTTP resources, reflect codecs setup in the same fashion as the server ones (see <>), and more. - -The following code shows a typical example: - -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/webclient/MyService.java[] ----- - - - -[[features.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. -For now, Reactor Netty and Jetty RS client are supported. - -The `spring-boot-starter-webflux` starter depends on `io.projectreactor.netty:reactor-netty` by default, which brings both server and client implementations. -If you choose to use Jetty as a reactive server instead, you should add a dependency on the Jetty Reactive HTTP client library, `org.eclipse.jetty:jetty-reactive-httpclient`. -Using the same technology for server and client has it advantages, as it will automatically share HTTP resources between client and server. - -Developers can override the resource configuration for Jetty and Reactor Netty by providing a custom `ReactorResourceFactory` or `JettyResourceFactory` bean - this will be applied to both clients and servers. - -If you wish to override that choice for the client, you can define your own `ClientHttpConnector` bean and have full control over the client configuration. - -You can learn more about the {spring-framework-docs}/web-reactive.html#webflux-client-builder[`WebClient` configuration options in the Spring Framework reference documentation]. - - - -[[features.webclient.customization]] -=== WebClient Customization -There are three main approaches to `WebClient` customization, depending on how broadly you want the customizations to apply. - -To make the scope of any customizations as narrow as possible, inject the auto-configured `WebClient.Builder` and then call its methods as required. -`WebClient.Builder` instances are stateful: Any change on the builder is reflected in all clients subsequently created with it. -If you want to create several clients with the same builder, you can also consider cloning the builder with `WebClient.Builder other = builder.clone();`. - -To make an application-wide, additive customization to all `WebClient.Builder` instances, you can declare `WebClientCustomizer` beans and change the `WebClient.Builder` locally at the point of injection. - -Finally, you can fall back to the original API and use `WebClient.create()`. -In that case, no auto-configuration or `WebClientCustomizer` is applied. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/actuator.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/actuator.adoc index 1474d9806717..bd478ad63319 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/actuator.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/actuator.adoc @@ -30,7 +30,7 @@ In general, you need a `View` that resolves with a name of `error` or a `@Contro 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. See {spring-boot-autoconfigure-module-code}/web/servlet/error/ErrorMvcAutoConfiguration.java[`ErrorMvcAutoConfiguration`] for more options. -See also the section on "`<>`" for details of how to register handlers in the servlet container. +See also the section on "`<>`" for details of how to register handlers in the servlet container. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/data-access.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/data-access.adoc index 3a5357475a0a..20594ecbbd32 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/data-access.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/data-access.adoc @@ -113,7 +113,7 @@ This example uses a more generic `configuration` sub namespace as the example do NOTE: Because your custom configuration chooses to go with Hikari, `app.datasource.type` has no effect. In practice, the builder is initialized with whatever value you might set there and then overridden by the call to `.type()`. -See "`<>`" in the "`Spring Boot features`" section and the {spring-boot-autoconfigure-module-code}/jdbc/DataSourceAutoConfiguration.java[`DataSourceAutoConfiguration`] class for more details. +See "`<>`" in the "`Spring Boot features`" section and the {spring-boot-autoconfigure-module-code}/jdbc/DataSourceAutoConfiguration.java[`DataSourceAutoConfiguration`] class for more details. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/http-clients.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/http-clients.adoc index 540e7a5737f3..36a335975bb2 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/http-clients.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/http-clients.adoc @@ -7,7 +7,7 @@ This section answers questions related to using them. [[howto.http-clients.rest-template-proxy-configuration]] === Configure RestTemplate to Use a Proxy -As described in <>, you can use a `RestTemplateCustomizer` with `RestTemplateBuilder` to build a customized `RestTemplate`. +As described in <>, you can use a `RestTemplateCustomizer` with `RestTemplateBuilder` to build a customized `RestTemplate`. This is the recommended approach for creating a `RestTemplate` configured to use a proxy. The exact details of the proxy configuration depend on the underlying client request factory that is being used. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/webserver.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/webserver.adoc index 68806c7bf2de..89ea15d0f1e4 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/webserver.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/webserver.adoc @@ -84,7 +84,7 @@ Thanks to relaxed binding of `Environment` values, you can also use configprop:s To switch off the HTTP endpoints completely but still create a `WebApplicationContext`, use `server.port=-1` (doing so is sometimes useful for testing). -For more details, see "`<>`" in the '`Spring Boot Features`' section, or the {spring-boot-autoconfigure-module-code}/web/ServerProperties.java[`ServerProperties`] source code. +For more details, see "`<>`" in the '`Spring Boot Features`' section, or the {spring-boot-autoconfigure-module-code}/web/ServerProperties.java[`ServerProperties`] source code. @@ -307,7 +307,7 @@ If no `dispatcherType` is specified on a filter registration, `REQUEST` is used. This aligns with the Servlet Specification's default dispatcher type. ==== -Like any other Spring bean, you can define the order of Servlet filter beans; please make sure to check the "`<>`" section. +Like any other Spring bean, you can define the order of Servlet filter beans; please make sure to check the "`<>`" section. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/index.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/index.adoc index 19feeae45c5d..d29f3018b84e 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/index.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/index.adoc @@ -16,8 +16,13 @@ The reference documentation consists of the following sections: <> :: Introducing Spring Boot, System Requirements, Servlet Containers, Installing Spring Boot, Developing Your First Spring Boot Application <> :: Upgrading from 1.x, Upgrading to a new feature release, Upgrading the Spring Boot CLI <> :: Build Systems, Structuring Your Code, Configuration, Spring Beans and Dependency Injection, DevTools, and more. -<> :: Profiles, Logging, Security, Caching, Spring Integration, Testing, and more. -<> :: Monitoring, Metrics, Auditing, and more. +<> :: Profiles, Logging, Security, Caching, Spring Integration, Testing, and more. +<> :: Servlet Web, Reactive Web, Embedded Container Support, Graceful Shutdown and more. +<> :: SQL and NOSQL data access. +<> :: Caching, Quartz Scheduler, REST clients, Sending email, Spring Web Services and more. +<> :: JMS, AMQP, RSocket, WebSocket, Spring Integration. +<> :: Efficient container images, Building container images with Dockerfiles and Cloud Native Buildpacks. +<> :: Monitoring, Metrics, Auditing, and more. <> :: Deploying to the Cloud, Installing as a Unix application. <> :: Installing the CLI, Using the CLI, Configuring the CLI, and more. <> :: Maven Plugin, Gradle Plugin, Antlib, and more. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/index.singleadoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/index.singleadoc index 25c6c144c6fc..3763f21d43af 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/index.singleadoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/index.singleadoc @@ -21,6 +21,16 @@ include::using.adoc[leveloffset=+1] include::features.adoc[leveloffset=+1] +include::web.adoc[leveloffset=+1] + +include::data.adoc[leveloffset=+1] + +include::messaging.adoc[leveloffset=+1] + +include::io.adoc[leveloffset=+1] + +include::container-images.adoc[leveloffset=+1] + include::actuator.adoc[leveloffset=+1] include::deployment.adoc[leveloffset=+1] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io.adoc new file mode 100644 index 000000000000..fe6279070964 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io.adoc @@ -0,0 +1,22 @@ +[[io]] += IO +include::attributes.adoc[] + +Most applications will need to deal with input and output concerns at some point. +Spring Boot provides utilities and integrations with a range of technologies to help when you need IO capabilities. +This section covers standard IO features such as caching and validation as well as more advanced topics such as scheduling and distributed transactions. +We'll also cover calling remote REST or SOAP services and sending email. + +include::io/caching.adoc[] + +include::io/quartz.adoc[] + +include::io/mail.adoc[] + +include::io/validation.adoc[] + +include::io/rest-client.adoc[] + +include::io/webservices.adoc[] + +include::io/jta.adoc[] \ No newline at end of file diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/caching.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/caching.adoc similarity index 89% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/caching.adoc rename to spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/caching.adoc index ca8d0b8b6adc..10eeee40e874 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/caching.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/caching.adoc @@ -1,4 +1,4 @@ -[[features.caching]] +[[io.caching]] == Caching The Spring Framework provides support for transparently adding caching to an application. At its core, the abstraction applies caching to methods, thus reducing the number of executions based on the information available in the cache. @@ -22,7 +22,7 @@ Otherwise, the method is invoked, and the cache is updated before returning the CAUTION: You can also use the standard JSR-107 (JCache) annotations (such as `@CacheResult`) transparently. However, we strongly advise you to not mix and match the Spring Cache and JCache annotations. -If you do not add any specific cache library, Spring Boot auto-configures a <> that uses concurrent maps in memory. +If you do not add any specific cache library, Spring Boot auto-configures a <> that uses concurrent maps in memory. When a cache is required (such as `piDecimals` in the preceding example), this provider creates it for you. The simple provider is not really recommended for production usage, but it is great for getting started and making sure that you understand the features. When you have made up your mind about the cache provider to use, please make sure to read its documentation to figure out how to configure the caches that your application uses. @@ -33,24 +33,24 @@ TIP: It is also possible to transparently {spring-framework-docs}/integration.ht -[[features.caching.provider]] +[[io.caching.provider]] === Supported Cache Providers The cache abstraction does not provide an actual store and relies on abstraction materialized by the `org.springframework.cache.Cache` and `org.springframework.cache.CacheManager` interfaces. If you have not defined a bean of type `CacheManager` or a `CacheResolver` named `cacheResolver` (see {spring-framework-api}/cache/annotation/CachingConfigurer.html[`CachingConfigurer`]), Spring Boot tries to detect the following providers (in the indicated order): -. <> -. <> (EhCache 3, Hazelcast, Infinispan, and others) -. <> -. <> -. <> -. <> -. <> -. <> -. <> +. <> +. <> (EhCache 3, Hazelcast, Infinispan, and others) +. <> +. <> +. <> +. <> +. <> +. <> +. <> TIP: It is also possible to _force_ a particular cache provider by setting the configprop:spring.cache.type[] property. -Use this property if you need to <> in certain environment (such as tests). +Use this property if you need to <> in certain environment (such as tests). TIP: Use the `spring-boot-starter-cache` "`Starter`" to quickly add basic caching dependencies. The starter brings in `spring-context-support`. @@ -70,14 +70,14 @@ You can have as many customizers as you want, and you can also order them by usi -[[features.caching.provider.generic]] +[[io.caching.provider.generic]] ==== Generic Generic caching is used if the context defines _at least_ one `org.springframework.cache.Cache` bean. A `CacheManager` wrapping all beans of that type is created. -[[features.caching.provider.jcache]] +[[io.caching.provider.jcache]] ==== JCache (JSR-107) https://jcp.org/en/jsr/detail?id=107[JCache] is bootstrapped through the presence of a `javax.cache.spi.CachingProvider` on the classpath (that is, a JSR-107 compliant caching library exists on the classpath), and the `JCacheCacheManager` is provided by the `spring-boot-starter-cache` "`Starter`". Various compliant libraries are available, and Spring Boot provides dependency management for Ehcache 3, Hazelcast, and Infinispan. @@ -104,7 +104,7 @@ If a single `HazelcastInstance` is available, it is automatically reused for the There are two ways to customize the underlying `javax.cache.cacheManager`: * Caches can be created on startup by setting the configprop:spring.cache.cache-names[] property. - If a custom `javax.cache.configuration.Configuration` bean is defined, it is used to customize them. +If a custom `javax.cache.configuration.Configuration` bean is defined, it is used to customize them. * `org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer` beans are invoked with the reference of the `CacheManager` for full customization. TIP: If a standard `javax.cache.CacheManager` bean is defined, it is wrapped automatically in an `org.springframework.cache.CacheManager` implementation that the abstraction expects. @@ -112,7 +112,7 @@ No further customization is applied to it. -[[features.caching.provider.ehcache2]] +[[io.caching.provider.ehcache2]] ==== EhCache 2.x https://www.ehcache.org/[EhCache] 2.x is used if a file named `ehcache.xml` can be found at the root of the classpath. If EhCache 2.x is found, the `EhCacheCacheManager` provided by the `spring-boot-starter-cache` "`Starter`" is used to bootstrap the cache manager. @@ -128,14 +128,14 @@ An alternate configuration file can be provided as well, as shown in the followi -[[features.caching.provider.hazelcast]] +[[io.caching.provider.hazelcast]] ==== Hazelcast Spring Boot has <>. If a `HazelcastInstance` has been auto-configured, it is automatically wrapped in a `CacheManager`. -[[features.caching.provider.infinispan]] +[[io.caching.provider.infinispan]] ==== Infinispan https://infinispan.org/[Infinispan] has no default configuration file location, so it must be specified explicitly. Otherwise, the default bootstrap is used. @@ -157,9 +157,9 @@ See https://github.com/infinispan/infinispan-spring-boot[Infinispan's documentat -[[features.caching.provider.couchbase]] +[[io.caching.provider.couchbase]] ==== Couchbase -If Spring Data Couchbase is available and Couchbase is <>, a `CouchbaseCacheManager` is auto-configured. +If Spring Data Couchbase is available and Couchbase is <>, a `CouchbaseCacheManager` is auto-configured. It is possible to create additional caches on startup by setting the configprop:spring.cache.cache-names[] property and cache defaults can be configured by using `spring.cache.couchbase.*` properties. For instance, the following configuration creates `cache1` and `cache2` caches with an entry _expiration_ of 10 minutes: @@ -182,7 +182,7 @@ include::{docs-java}/features/caching/provider/couchbase/MyCouchbaseCacheManager -[[features.caching.provider.redis]] +[[io.caching.provider.redis]] ==== Redis If https://redis.io/[Redis] is available and configured, a `RedisCacheManager` is auto-configured. It is possible to create additional caches on startup by setting the configprop:spring.cache.cache-names[] property and cache defaults can be configured by using `spring.cache.redis.*` properties. @@ -213,7 +213,7 @@ include::{docs-java}/features/caching/provider/redis/MyRedisCacheManagerConfigur -[[features.caching.provider.caffeine]] +[[io.caching.provider.caffeine]] ==== Caffeine https://github.com/ben-manes/caffeine[Caffeine] is a Java 8 rewrite of Guava's cache that supersedes support for Guava. If Caffeine is present, a `CaffeineCacheManager` (provided by the `spring-boot-starter-cache` "`Starter`") is auto-configured. @@ -240,7 +240,7 @@ The auto-configuration ignores any other generic type. -[[features.caching.provider.simple]] +[[io.caching.provider.simple]] ==== Simple If none of the other providers can be found, a simple implementation using a `ConcurrentHashMap` as the cache store is configured. This is the default if no caching library is present in your application. @@ -259,7 +259,7 @@ This is similar to the way the "real" cache providers behave if you use an undec -[[features.caching.provider.none]] +[[io.caching.provider.none]] ==== None When `@EnableCaching` is present in your configuration, a suitable cache configuration is expected as well. If you need to disable caching altogether in certain environments, force the cache type to `none` to use a no-op implementation, as shown in the following example: diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/jta.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/jta.adoc similarity index 93% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/jta.adoc rename to spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/jta.adoc index 611516b9b232..0bda883a2f9b 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/jta.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/jta.adoc @@ -1,4 +1,4 @@ -[[features.jta]] +[[io.jta]] == Distributed Transactions with JTA Spring Boot supports distributed JTA transactions across multiple XA resources by using an https://www.atomikos.com/[Atomikos] embedded transaction manager. JTA transactions are also supported when deploying to a suitable Java EE Application Server. @@ -10,7 +10,7 @@ If you are within a JTA environment and still want to use local transactions, yo -[[features.jta.atomikos]] +[[io.jta.atomikos]] === Using an Atomikos Transaction Manager https://www.atomikos.com/[Atomikos] is a popular open source transaction manager which can be embedded into your Spring Boot application. You can use the `spring-boot-starter-jta-atomikos` starter to pull in the appropriate Atomikos libraries. @@ -27,16 +27,16 @@ To ensure uniqueness in production, you should configure the configprop:spring.j -[[features.jta.javaee]] +[[io.jta.javaee]] === Using a Java EE Managed Transaction Manager If you package your Spring Boot application as a `war` or `ear` file and deploy it to a Java EE application server, you can use your application server's built-in transaction manager. Spring Boot tries to auto-configure a transaction manager by looking at common JNDI locations (`java:comp/UserTransaction`, `java:comp/TransactionManager`, and so on). If you use a transaction service provided by your application server, you generally also want to ensure that all resources are managed by the server and exposed over JNDI. -Spring Boot tries to auto-configure JMS by looking for a `ConnectionFactory` at the JNDI path (`java:/JmsXA` or `java:/XAConnectionFactory`), and you can use the <> to configure your `DataSource`. +Spring Boot tries to auto-configure JMS by looking for a `ConnectionFactory` at the JNDI path (`java:/JmsXA` or `java:/XAConnectionFactory`), and you can use the <> to configure your `DataSource`. -[[features.jta.mixing-xa-and-non-xa-connections]] +[[io.jta.mixing-xa-and-non-xa-connections]] === Mixing XA and Non-XA JMS Connections When using JTA, the primary JMS `ConnectionFactory` bean is XA-aware and participates in distributed transactions. You can inject into your bean without needing to use any `@Qualifier`: @@ -65,7 +65,7 @@ include::{docs-java}/features/jta/mixingxaandnonxaconnections/xa/MyBean.java[tag -[[features.jta.supporting-alternative-embedded-transaction-manager]] +[[io.jta.supporting-alternative-embedded-transaction-manager]] === Supporting an Alternative Embedded Transaction Manager The {spring-boot-module-code}/jms/XAConnectionFactoryWrapper.java[`XAConnectionFactoryWrapper`] and {spring-boot-module-code}/jdbc/XADataSourceWrapper.java[`XADataSourceWrapper`] interfaces can be used to support alternative embedded transaction managers. The interfaces are responsible for wrapping `XAConnectionFactory` and `XADataSource` beans and exposing them as regular `ConnectionFactory` and `DataSource` beans, which transparently enroll in the distributed transaction. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/email.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/mail.adoc similarity index 98% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/email.adoc rename to spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/mail.adoc index 6409ecb71847..24df7f09525d 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/email.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/mail.adoc @@ -1,4 +1,4 @@ -[[features.email]] +[[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. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/quartz.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/quartz.adoc similarity index 99% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/quartz.adoc rename to spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/quartz.adoc index 1bf925d7eb64..cd71ab90080b 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/quartz.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/quartz.adoc @@ -1,4 +1,4 @@ -[[features.quartz]] +[[io.quartz]] == Quartz Scheduler Spring Boot offers several conveniences for working with the https://www.quartz-scheduler.org/[Quartz scheduler], including the `spring-boot-starter-quartz` "`Starter`". If Quartz is available, a `Scheduler` is auto-configured (through the `SchedulerFactoryBean` abstraction). diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/rest-client.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/rest-client.adoc new file mode 100644 index 000000000000..67ae6865dc98 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/rest-client.adoc @@ -0,0 +1,101 @@ +[[io.rest-client]] +== Calling REST Services +If your application calls remote REST services, Spring Boot makes that very convenient using a `RestTemplate` or a `WebClient`. + +[[io.rest-client.resttemplate]] +=== RestTemplate +If you need to call remote REST services from your application, you can use the Spring Framework's {spring-framework-api}/web/client/RestTemplate.html[`RestTemplate`] class. +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` are applied to `RestTemplate` instances. + +The following code shows a typical example: + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/resttemplate/MyService.java[] +---- + +TIP: `RestTemplateBuilder` includes a number of useful methods that can be used to quickly configure a `RestTemplate`. +For example, to add BASIC auth support, you can use `builder.basicAuthentication("user", "password").build()`. + + + +[[io.rest-client.resttemplate.customization]] +==== RestTemplate Customization +There are three main approaches to `RestTemplate` customization, depending on how broadly you want the customizations to apply. + +To make the scope of any customizations as narrow as possible, inject the auto-configured `RestTemplateBuilder` and then call its methods as required. +Each method call returns a new `RestTemplateBuilder` instance, so the customizations only affect this use of the builder. + +To make an application-wide, additive customization, use a `RestTemplateCustomizer` bean. +All such beans are automatically registered with the auto-configured `RestTemplateBuilder` and are applied to any templates that are built with it. + +The following example shows a customizer that configures the use of a proxy for all hosts except `192.168.0.5`: + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/resttemplate/customization/MyRestTemplateCustomizer.java[] +---- + +Finally, you can also create your own `RestTemplateBuilder` bean. +To prevent switching off the auto-configuration of a `RestTemplateBuilder` and prevent any `RestTemplateCustomizer` beans from being used, make sure to configure your custom instance with a `RestTemplateBuilderConfigurer`. +The following example exposes a `RestTemplateBuilder` with what Spring Boot would auto-configure, except that custom connect and read timeouts are also specified: + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/resttemplate/customization/MyRestTemplateBuilderConfiguration.java[] +---- + +The most extreme (and rarely used) option is to create your own `RestTemplateBuilder` bean without using a configurer. +Doing so switches off the auto-configuration of a `RestTemplateBuilder` and prevents any `RestTemplateCustomizer` beans from being used. + + +[[io.rest-client.webclient]] +=== WebClient +If you have Spring WebFlux on your classpath, you can also choose to use `WebClient` to call remote REST services. +Compared to `RestTemplate`, this client has a more functional feel and is fully reactive. +You can learn more about the `WebClient` in the dedicated {spring-framework-docs}/web-reactive.html#webflux-client[section in the Spring Framework docs]. + +Spring Boot creates and pre-configures a `WebClient.Builder` for you. +It is strongly advised to inject it in your components and use it to create `WebClient` instances. +Spring Boot is configuring that builder to share HTTP resources, reflect codecs setup in the same fashion as the server ones (see <>), and more. + +The following code shows a typical example: + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/webclient/MyService.java[] +---- + + + +[[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. +For now, Reactor Netty and Jetty RS client are supported. + +The `spring-boot-starter-webflux` starter depends on `io.projectreactor.netty:reactor-netty` by default, which brings both server and client implementations. +If you choose to use Jetty as a reactive server instead, you should add a dependency on the Jetty Reactive HTTP client library, `org.eclipse.jetty:jetty-reactive-httpclient`. +Using the same technology for server and client has it advantages, as it will automatically share HTTP resources between client and server. + +Developers can override the resource configuration for Jetty and Reactor Netty by providing a custom `ReactorResourceFactory` or `JettyResourceFactory` bean - this will be applied to both clients and servers. + +If you wish to override that choice for the client, you can define your own `ClientHttpConnector` bean and have full control over the client configuration. + +You can learn more about the {spring-framework-docs}/web-reactive.html#webflux-client-builder[`WebClient` configuration options in the Spring Framework reference documentation]. + + + +[[io.rest-client.webclient.customization]] +==== WebClient Customization +There are three main approaches to `WebClient` customization, depending on how broadly you want the customizations to apply. + +To make the scope of any customizations as narrow as possible, inject the auto-configured `WebClient.Builder` and then call its methods as required. +`WebClient.Builder` instances are stateful: Any change on the builder is reflected in all clients subsequently created with it. +If you want to create several clients with the same builder, you can also consider cloning the builder with `WebClient.Builder other = builder.clone();`. + +To make an application-wide, additive customization to all `WebClient.Builder` instances, you can declare `WebClientCustomizer` beans and change the `WebClient.Builder` locally at the point of injection. + +Finally, you can fall back to the original API and use `WebClient.create()`. +In that case, no auto-configuration or `WebClientCustomizer` is applied. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/validation.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/validation.adoc similarity index 96% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/validation.adoc rename to spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/validation.adoc index 009b5dd324ce..06cd5f77832c 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/validation.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/validation.adoc @@ -1,4 +1,4 @@ -[[features.validation]] +[[io.validation]] == Validation The method validation feature supported by Bean Validation 1.1 is automatically enabled as long as a JSR-303 implementation (such as Hibernate validator) is on the classpath. This lets bean methods be annotated with `javax.validation` constraints on their parameters and/or on their return value. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/webservices.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/webservices.adoc similarity index 96% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/webservices.adoc rename to spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/webservices.adoc index f345260b9958..e66a8e573567 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/webservices.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/webservices.adoc @@ -1,4 +1,4 @@ -[[features.webservices]] +[[io.webservices]] == Web Services Spring Boot provides Web Services auto-configuration so that all you must do is define your `Endpoints`. @@ -17,7 +17,7 @@ To do so, configure their location, as shown in the following example: -[[features.webservices.template]] +[[io.webservices.template]] === Calling Web Services with WebServiceTemplate If you need to call remote Web services from your application, you can use the {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. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging.adoc new file mode 100644 index 000000000000..e5648eaed9b0 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging.adoc @@ -0,0 +1,25 @@ +[[messaging]] += Messaging +include::attributes.adoc[] + +The Spring Framework provides extensive support for integrating with messaging systems, from simplified use of the JMS API using `JmsTemplate` to a complete infrastructure to receive messages asynchronously. +Spring AMQP provides a similar feature set for the Advanced Message Queuing Protocol. +Spring Boot also provides auto-configuration options for `RabbitTemplate` and RabbitMQ. +Spring WebSocket natively includes support for STOMP messaging, and Spring Boot has support for that through starters and a small amount of auto-configuration. +Spring Boot also has support for Apache Kafka. + + +include::messaging/jms.adoc[] + +include::messaging/amqp.adoc[] + +include::messaging/kafka.adoc[] + +include::messaging/rsocket.adoc[] + +include::messaging/spring-integration.adoc[] + + + + + diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/amqp.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/amqp.adoc new file mode 100644 index 000000000000..436336e5bede --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/amqp.adoc @@ -0,0 +1,123 @@ +[[messaging.amqp]] +== AMQP +The Advanced Message Queuing Protocol (AMQP) is a platform-neutral, wire-level protocol for message-oriented middleware. +The Spring AMQP project applies core Spring concepts to the development of AMQP-based messaging solutions. +Spring Boot offers several conveniences for working with AMQP through RabbitMQ, including the `spring-boot-starter-amqp` "`Starter`". + + + +[[messaging.amqp.rabbitmq]] +=== RabbitMQ support +https://www.rabbitmq.com/[RabbitMQ] is a lightweight, reliable, scalable, and portable message broker based on the AMQP protocol. +Spring uses `RabbitMQ` to communicate through the AMQP protocol. + +RabbitMQ configuration is controlled by external configuration properties in `+spring.rabbitmq.*+`. +For example, you might declare the following section in `application.properties`: + +[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +---- + spring: + rabbitmq: + host: "localhost" + port: 5672 + username: "admin" + password: "secret" +---- + +Alternatively, you could configure the same connection using the `addresses` attribute: + +[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +---- + spring: + rabbitmq: + addresses: "amqp://admin:secret@localhost" +---- + +NOTE: When specifying addresses that way, the `host` and `port` properties are ignored. +If the address uses the `amqps` protocol, SSL support is enabled automatically. + +See {spring-boot-autoconfigure-module-code}/amqp/RabbitProperties.java[`RabbitProperties`] for more of the supported property-based configuration options. +To configure lower-level details of the RabbitMQ `ConnectionFactory` that is used by Spring AMQP, define a `ConnectionFactoryCustomizer` bean. + +If a `ConnectionNameStrategy` bean exists in the context, it will be automatically used to name connections created by the auto-configured `CachingConnectionFactory`. + +TIP: See https://spring.io/blog/2010/06/14/understanding-amqp-the-protocol-used-by-rabbitmq/[Understanding AMQP, the protocol used by RabbitMQ] for more details. + + + +[[messaging.amqp.sending]] +=== Sending a Message +Spring's `AmqpTemplate` and `AmqpAdmin` are auto-configured, and you can autowire them directly into your own beans, as shown in the following example: + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/messaging/amqp/sending/MyBean.java[] +---- + +NOTE: {spring-amqp-api}/rabbit/core/RabbitMessagingTemplate.html[`RabbitMessagingTemplate`] can be injected in a similar manner. +If a `MessageConverter` bean is defined, it is associated automatically to the auto-configured `AmqpTemplate`. + +If necessary, any `org.springframework.amqp.core.Queue` that is defined as a bean is automatically used to declare a corresponding queue on the RabbitMQ instance. + +To retry operations, you can enable retries on the `AmqpTemplate` (for example, in the event that the broker connection is lost): + +[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +---- + spring: + rabbitmq: + template: + retry: + enabled: true + initial-interval: "2s" +---- + +Retries are disabled by default. +You can also customize the `RetryTemplate` programmatically by declaring a `RabbitRetryTemplateCustomizer` bean. + +If you need to create more `RabbitTemplate` instances or if you want to override the default, Spring Boot provides a `RabbitTemplateConfigurer` bean that you can use to initialize a `RabbitTemplate` with the same settings as the factories used by the auto-configuration. + + + +[[messaging.amqp.receiving]] +=== Receiving a Message +When the Rabbit infrastructure is present, any bean can be annotated with `@RabbitListener` to create a listener endpoint. +If no `RabbitListenerContainerFactory` has been defined, a default `SimpleRabbitListenerContainerFactory` is automatically configured and you can switch to a direct container using the configprop:spring.rabbitmq.listener.type[] property. +If a `MessageConverter` or a `MessageRecoverer` bean is defined, it is automatically associated with the default factory. + +The following sample component creates a listener endpoint on the `someQueue` queue: + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/messaging/amqp/receiving/MyBean.java[] +---- + +TIP: See {spring-amqp-api}/rabbit/annotation/EnableRabbit.html[the Javadoc of `@EnableRabbit`] for more details. + +If you need to create more `RabbitListenerContainerFactory` instances or if you want to override the default, Spring Boot provides a `SimpleRabbitListenerContainerFactoryConfigurer` and a `DirectRabbitListenerContainerFactoryConfigurer` that you can use to initialize a `SimpleRabbitListenerContainerFactory` and a `DirectRabbitListenerContainerFactory` with the same settings as the factories used by the auto-configuration. + +TIP: It does not matter which container type you chose. +Those two beans are exposed by the auto-configuration. + +For instance, the following configuration class exposes another factory that uses a specific `MessageConverter`: + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/messaging/amqp/receiving/custom/MyRabbitConfiguration.java[] +---- + +Then you can use the factory in any `@RabbitListener`-annotated method, as follows: + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/messaging/amqp/receiving/custom/MyBean.java[] +---- + +You can enable retries to handle situations where your listener throws an exception. +By default, `RejectAndDontRequeueRecoverer` is used, but you can define a `MessageRecoverer` of your own. +When retries are exhausted, the message is rejected and either dropped or routed to a dead-letter exchange if the broker is configured to do so. +By default, retries are disabled. +You can also customize the `RetryTemplate` programmatically by declaring a `RabbitRetryTemplateCustomizer` bean. + +IMPORTANT: By default, if retries are disabled and the listener throws an exception, the delivery is retried indefinitely. +You can modify this behavior in two ways: Set the `defaultRequeueRejected` property to `false` so that zero re-deliveries are attempted or throw an `AmqpRejectAndDontRequeueException` to signal the message should be rejected. +The latter is the mechanism used when retries are enabled and the maximum number of delivery attempts is reached. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/jms.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/jms.adoc new file mode 100644 index 000000000000..337cf171afeb --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/jms.adoc @@ -0,0 +1,175 @@ +[[messaging.jms]] +== JMS +The `javax.jms.ConnectionFactory` interface provides a standard method of creating a `javax.jms.Connection` for interacting with a JMS broker. +Although Spring needs a `ConnectionFactory` to work with JMS, you generally need not use it directly yourself and can instead rely on higher level messaging abstractions. +(See the {spring-framework-docs}/integration.html#jms[relevant section] of the Spring Framework reference documentation for details.) +Spring Boot also auto-configures the necessary infrastructure to send and receive messages. + + + +[[messaging.jms.activemq]] +=== ActiveMQ Support +When https://activemq.apache.org/[ActiveMQ] is available on the classpath, Spring Boot can also configure a `ConnectionFactory`. +If the broker is present, an embedded broker is automatically started and configured (provided no broker URL is specified through configuration). + +NOTE: If you use `spring-boot-starter-activemq`, the necessary dependencies to connect or embed an ActiveMQ instance are provided, as is the Spring infrastructure to integrate with JMS. + +ActiveMQ configuration is controlled by external configuration properties in `+spring.activemq.*+`. +For example, you might declare the following section in `application.properties`: + +[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +---- + spring: + activemq: + broker-url: "tcp://192.168.1.210:9876" + user: "admin" + password: "secret" +---- + +By default, a `CachingConnectionFactory` wraps the native `ConnectionFactory` with sensible settings that you can control by external configuration properties in `+spring.jms.*+`: + +[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +---- + spring: + jms: + cache: + session-cache-size: 5 +---- + +If you'd rather use native pooling, you can do so by adding a dependency to `org.messaginghub:pooled-jms` and configuring the `JmsPoolConnectionFactory` accordingly, as shown in the following example: + +[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +---- + spring: + activemq: + pool: + enabled: true + max-connections: 50 +---- + +TIP: See {spring-boot-autoconfigure-module-code}/jms/activemq/ActiveMQProperties.java[`ActiveMQProperties`] for more of the supported options. +You can also register an arbitrary number of beans that implement `ActiveMQConnectionFactoryCustomizer` for more advanced customizations. + +By default, ActiveMQ creates a destination if it does not yet exist so that destinations are resolved against their provided names. + + + +[[messaging.jms.artemis]] +=== ActiveMQ Artemis Support +Spring Boot can auto-configure a `ConnectionFactory` when it detects that https://activemq.apache.org/components/artemis/[ActiveMQ Artemis] is available on the classpath. +If the broker is present, an embedded broker is automatically started and configured (unless the mode property has been explicitly set). +The supported modes are `embedded` (to make explicit that an embedded broker is required and that an error should occur if the broker is not available on the classpath) and `native` (to connect to a broker using the `netty` transport protocol). +When the latter is configured, Spring Boot configures a `ConnectionFactory` that connects to a broker running on the local machine with the default settings. + +NOTE: If you use `spring-boot-starter-artemis`, the necessary dependencies to connect to an existing ActiveMQ Artemis instance are provided, as well as the Spring infrastructure to integrate with JMS. +Adding `org.apache.activemq:artemis-jms-server` to your application lets you use embedded mode. + +ActiveMQ Artemis configuration is controlled by external configuration properties in `+spring.artemis.*+`. +For example, you might declare the following section in `application.properties`: + +[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +---- + spring: + artemis: + mode: native + broker-url: "tcp://192.168.1.210:9876" + user: "admin" + password: "secret" +---- + +When embedding the broker, you can choose if you want to enable persistence and list the destinations that should be made available. +These can be specified as a comma-separated list to create them with the default options, or you can define bean(s) of type `org.apache.activemq.artemis.jms.server.config.JMSQueueConfiguration` or `org.apache.activemq.artemis.jms.server.config.TopicConfiguration`, for advanced queue and topic configurations, respectively. + +By default, a `CachingConnectionFactory` wraps the native `ConnectionFactory` with sensible settings that you can control by external configuration properties in `+spring.jms.*+`: + +[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +---- + spring: + jms: + cache: + session-cache-size: 5 +---- + +If you'd rather use native pooling, you can do so by adding a dependency to `org.messaginghub:pooled-jms` and configuring the `JmsPoolConnectionFactory` accordingly, as shown in the following example: + +[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +---- + spring: + artemis: + pool: + enabled: true + max-connections: 50 +---- + +See {spring-boot-autoconfigure-module-code}/jms/artemis/ArtemisProperties.java[`ArtemisProperties`] for more supported options. + +No JNDI lookup is involved, and destinations are resolved against their names, using either the `name` attribute in the Artemis configuration or the names provided through configuration. + + + +[[messaging.jms.jndi]] +=== Using a JNDI ConnectionFactory +If you are running your application in an application server, Spring Boot tries to locate a JMS `ConnectionFactory` by using JNDI. +By default, the `java:/JmsXA` and `java:/XAConnectionFactory` location are checked. +You can use the configprop:spring.jms.jndi-name[] property if you need to specify an alternative location, as shown in the following example: + +[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +---- + spring: + jms: + jndi-name: "java:/MyConnectionFactory" +---- + + + +[[messaging.jms.sending]] +=== Sending a Message +Spring's `JmsTemplate` is auto-configured, and you can autowire it directly into your own beans, as shown in the following example: + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/messaging/jms/sending/MyBean.java[] +---- + +NOTE: {spring-framework-api}/jms/core/JmsMessagingTemplate.html[`JmsMessagingTemplate`] can be injected in a similar manner. +If a `DestinationResolver` or a `MessageConverter` bean is defined, it is associated automatically to the auto-configured `JmsTemplate`. + + + +[[messaging.jms.receiving]] +=== Receiving a Message +When the JMS infrastructure is present, any bean can be annotated with `@JmsListener` to create a listener endpoint. +If no `JmsListenerContainerFactory` has been defined, a default one is configured automatically. +If a `DestinationResolver`, a `MessageConverter`, or a `javax.jms.ExceptionListener` beans are defined, they are associated automatically with the default factory. + +By default, the default factory is transactional. +If you run in an infrastructure where a `JtaTransactionManager` is present, it is associated to the listener container by default. +If not, the `sessionTransacted` flag is enabled. +In that latter scenario, you can associate your local data store transaction to the processing of an incoming message by adding `@Transactional` on your listener method (or a delegate thereof). +This ensures that the incoming message is acknowledged, once the local transaction has completed. +This also includes sending response messages that have been performed on the same JMS session. + +The following component creates a listener endpoint on the `someQueue` destination: + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/messaging/jms/receiving/MyBean.java[] +---- + +TIP: See {spring-framework-api}/jms/annotation/EnableJms.html[the Javadoc of `@EnableJms`] for more details. + +If you need to create more `JmsListenerContainerFactory` instances or if you want to override the default, Spring Boot provides a `DefaultJmsListenerContainerFactoryConfigurer` that you can use to initialize a `DefaultJmsListenerContainerFactory` with the same settings as the one that is auto-configured. + +For instance, the following example exposes another factory that uses a specific `MessageConverter`: + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/messaging/jms/receiving/custom/MyJmsConfiguration.java[] +---- + +Then you can use the factory in any `@JmsListener`-annotated method as follows: + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/messaging/jms/receiving/custom/MyBean.java[] +---- diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/kafka.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/kafka.adoc new file mode 100644 index 000000000000..4e2a538e826a --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/kafka.adoc @@ -0,0 +1,178 @@ +[[messaging.kafka]] +== Apache Kafka Support +https://kafka.apache.org/[Apache Kafka] is supported by providing auto-configuration of the `spring-kafka` project. + +Kafka configuration is controlled by external configuration properties in `spring.kafka.*`. +For example, you might declare the following section in `application.properties`: + +[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +---- + spring: + kafka: + bootstrap-servers: "localhost:9092" + consumer: + group-id: "myGroup" +---- + +TIP: To create a topic on startup, add a bean of type `NewTopic`. +If the topic already exists, the bean is ignored. + +See {spring-boot-autoconfigure-module-code}/kafka/KafkaProperties.java[`KafkaProperties`] for more supported options. + + + +[[messaging.kafka.sending]] +=== Sending a Message +Spring's `KafkaTemplate` is auto-configured, and you can autowire it directly in your own beans, as shown in the following example: + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/messaging/kafka/sending/MyBean.java[] +---- + +NOTE: If the property configprop:spring.kafka.producer.transaction-id-prefix[] is defined, a `KafkaTransactionManager` is automatically configured. +Also, if a `RecordMessageConverter` bean is defined, it is automatically associated to the auto-configured `KafkaTemplate`. + + + +[[messaging.kafka.receiving]] +=== Receiving a Message +When the Apache Kafka infrastructure is present, any bean can be annotated with `@KafkaListener` to create a listener endpoint. +If no `KafkaListenerContainerFactory` has been defined, a default one is automatically configured with keys defined in `spring.kafka.listener.*`. + +The following component creates a listener endpoint on the `someTopic` topic: + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/messaging/kafka/receiving/MyBean.java[] +---- + +If a `KafkaTransactionManager` bean is defined, it is automatically associated to the container factory. +Similarly, if a `RecordFilterStrategy`, `ErrorHandler`, `AfterRollbackProcessor` or `ConsumerAwareRebalanceListener` bean is defined, it is automatically associated to the default factory. + +Depending on the listener type, a `RecordMessageConverter` or `BatchMessageConverter` bean is associated to the default factory. +If only a `RecordMessageConverter` bean is present for a batch listener, it is wrapped in a `BatchMessageConverter`. + +TIP: A custom `ChainedKafkaTransactionManager` must be marked `@Primary` as it usually references the auto-configured `KafkaTransactionManager` bean. + + + +[[messaging.kafka.streams]] +=== Kafka Streams +Spring for Apache Kafka provides a factory bean to create a `StreamsBuilder` object and manage the lifecycle of its streams. +Spring Boot auto-configures the required `KafkaStreamsConfiguration` bean as long as `kafka-streams` is on the classpath and Kafka Streams is enabled via the `@EnableKafkaStreams` annotation. + +Enabling Kafka Streams means that the application id and bootstrap servers must be set. +The former can be configured using `spring.kafka.streams.application-id`, defaulting to `spring.application.name` if not set. +The latter can be set globally or specifically overridden only for streams. + +Several additional properties are available using dedicated properties; other arbitrary Kafka properties can be set using the `spring.kafka.streams.properties` namespace. +See also <> for more information. + +To use the factory bean, wire `StreamsBuilder` into your `@Bean` as shown in the following example: + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/messaging/kafka/streams/MyKafkaStreamsConfiguration.java[] +---- + +By default, the streams managed by the `StreamBuilder` object it creates are started automatically. +You can customize this behavior using the configprop:spring.kafka.streams.auto-startup[] property. + + + +[[messaging.kafka.additional-properties]] +=== Additional Kafka Properties +The properties supported by auto configuration are shown in <>. +Note that, for the most part, these properties (hyphenated or camelCase) map directly to the Apache Kafka dotted properties. +Refer to the Apache Kafka documentation for details. + +The first few of these properties apply to all components (producers, consumers, admins, and streams) but can be specified at the component level if you wish to use different values. +Apache Kafka designates properties with an importance of HIGH, MEDIUM, or LOW. +Spring Boot auto-configuration supports all HIGH importance properties, some selected MEDIUM and LOW properties, and any properties that do not have a default value. + +Only a subset of the properties supported by Kafka are available directly through the `KafkaProperties` class. +If you wish to configure the producer or consumer with additional properties that are not directly supported, use the following properties: + +[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +---- + spring: + kafka: + properties: + "[prop.one]": "first" + admin: + properties: + "[prop.two]": "second" + consumer: + properties: + "[prop.three]": "third" + producer: + properties: + "[prop.four]": "fourth" + streams: + properties: + "[prop.five]": "fifth" +---- + +This sets the common `prop.one` Kafka property to `first` (applies to producers, consumers and admins), the `prop.two` admin property to `second`, the `prop.three` consumer property to `third`, the `prop.four` producer property to `fourth` and the `prop.five` streams property to `fifth`. + +You can also configure the Spring Kafka `JsonDeserializer` as follows: + +[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +---- + spring: + kafka: + consumer: + value-deserializer: "org.springframework.kafka.support.serializer.JsonDeserializer" + properties: + "[spring.json.value.default.type]": "com.example.Invoice" + "[spring.json.trusted.packages]": "com.example.main,com.example.another" +---- + +Similarly, you can disable the `JsonSerializer` default behavior of sending type information in headers: + +[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +---- + spring: + kafka: + producer: + value-serializer: "org.springframework.kafka.support.serializer.JsonSerializer" + properties: + "[spring.json.add.type.headers]": false +---- + +IMPORTANT: Properties set in this way override any configuration item that Spring Boot explicitly supports. + + + +[[messaging.kafka.embedded]] +=== Testing with Embedded Kafka +Spring for Apache Kafka provides a convenient way to test projects with an embedded Apache Kafka broker. +To use this feature, annotate a test class with `@EmbeddedKafka` from the `spring-kafka-test` module. +For more information, please see the Spring for Apache Kafka {spring-kafka-docs}#embedded-kafka-annotation[reference manual]. + +To make Spring Boot auto-configuration work with the aforementioned embedded Apache Kafka broker, you need to remap a system property for embedded broker addresses (populated by the `EmbeddedKafkaBroker`) into the Spring Boot configuration property for Apache Kafka. +There are several ways to do that: + +* Provide a system property to map embedded broker addresses into configprop:spring.kafka.bootstrap-servers[] in the test class: + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/messaging/kafka/embedded/property/MyTest.java[tag=*] +---- + +* Configure a property name on the `@EmbeddedKafka` annotation: + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/messaging/kafka/embedded/annotation/MyTest.java[] +---- + +* Use a placeholder in configuration properties: + +[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +---- + spring: + kafka: + bootstrap-servers: "${spring.embedded.kafka.brokers}" +---- diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/rsocket.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/rsocket.adoc similarity index 95% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/rsocket.adoc rename to spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/rsocket.adoc index 16ad8315e57e..238d1bc1141e 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/rsocket.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/rsocket.adoc @@ -1,4 +1,4 @@ -[[features.rsocket]] +[[messaging.rsocket]] == RSocket https://rsocket.io[RSocket] is a binary protocol for use on byte stream transports. It enables symmetric interaction models via async message passing over a single connection. @@ -9,7 +9,7 @@ See the {spring-framework-docs}/web-reactive.html#rsocket-spring[RSocket section -[[features.rsocket.strategies-auto-configuration]] +[[messaging.rsocket.strategies-auto-configuration]] === RSocket Strategies Auto-configuration Spring Boot auto-configures an `RSocketStrategies` bean that provides all the required infrastructure for encoding and decoding RSocket payloads. By default, the auto-configuration will try to configure the following (in order): @@ -25,7 +25,7 @@ Note that their `@Order` is important, as it determines the order of codecs. -[[features.rsocket.server-auto-configuration]] +[[messaging.rsocket.server-auto-configuration]] === RSocket server Auto-configuration Spring Boot provides RSocket server auto-configuration. The required dependencies are provided by the `spring-boot-starter-rsocket`. @@ -59,7 +59,7 @@ Besides the dependency requirements, the only required configuration is to defin -[[features.rsocket.messaging]] +[[messaging.rsocket.messaging]] === Spring Messaging RSocket support Spring Boot will auto-configure the Spring Messaging infrastructure for RSocket. @@ -67,7 +67,7 @@ This means that Spring Boot will create a `RSocketMessageHandler` bean that will -[[features.rsocket.requester]] +[[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. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/spring-integration.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/spring-integration.adoc similarity index 98% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/spring-integration.adoc rename to spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/spring-integration.adoc index 159430645ff9..607b653bda7e 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/spring-integration.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/spring-integration.adoc @@ -1,4 +1,4 @@ -[[features.spring-integration]] +[[messaging.spring-integration]] == Spring Integration Spring Boot offers several conveniences for working with {spring-integration}[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. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/websockets.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/websockets.adoc similarity index 100% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/websockets.adoc rename to spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/websockets.adoc diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/devtools.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/devtools.adoc index 416008582d63..2e534f01526b 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/devtools.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/devtools.adoc @@ -43,7 +43,7 @@ When using the Gradle plugin, {spring-boot-gradle-plugin-docs}#packaging-executa [[using.devtools.property-defaults]] === Property Defaults Several of the libraries supported by Spring Boot use caches to improve performance. -For example, <> cache compiled templates to avoid repeatedly parsing template files. +For example, <> cache compiled templates to avoid repeatedly parsing template files. Also, Spring MVC can add HTTP caching headers to responses when serving static resources. While caching is very beneficial in production, it can be counter-productive during development, preventing you from seeing the changes you just made in your application. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web.adoc new file mode 100644 index 000000000000..07944f56e714 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web.adoc @@ -0,0 +1,22 @@ +[[web]] += Web +include::attributes.adoc[] + +Spring Boot is well suited for web application development. +You can create a self-contained HTTP server by using embedded Tomcat, Jetty, Undertow, or Netty. +Most web applications use the `spring-boot-starter-web` module to get up and running quickly. +You can also choose to build reactive web applications by using the `spring-boot-starter-webflux` module. + +If you have not yet developed a Spring Boot web application, you can follow the "Hello World!" example in the _<>_ section. + +include::web/servlet.adoc[] + +include::web/reactive.adoc[] + +include::web/graceful-shutdown.adoc[] + +include::web/spring-security.adoc[] + +include::web/spring-session.adoc[] + +include::web/spring-hateoas.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/graceful-shutdown.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/graceful-shutdown.adoc similarity index 96% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/graceful-shutdown.adoc rename to spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/graceful-shutdown.adoc index 823005a0a3e6..7c8d5d14300f 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/graceful-shutdown.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/graceful-shutdown.adoc @@ -1,5 +1,5 @@ -[[features.graceful-shutdown]] -== Graceful shutdown +[[web.graceful-shutdown]] +== Graceful Shutdown Graceful shutdown is supported with all four embedded web servers (Jetty, Reactor Netty, Tomcat, and Undertow) and with both reactive and Servlet-based web applications. It occurs as part of closing the application context and is performed in the earliest phase of stopping `SmartLifecycle` beans. This stop processing uses a timeout which provides a grace period during which existing requests will be allowed to complete but no new requests will be permitted. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/reactive.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/reactive.adoc new file mode 100644 index 000000000000..dd1b63c7650c --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/reactive.adoc @@ -0,0 +1,263 @@ +[[web.reactive]] +== Reactive Web Applications +Spring Boot simplifies development of reactive web applications by providing auto-configuration for Spring Webflux. + +[[web.reactive.webflux]] +=== The "`Spring WebFlux Framework`" +Spring WebFlux is the new reactive web framework introduced in Spring Framework 5.0. +Unlike Spring MVC, it does not require the Servlet API, is fully asynchronous and non-blocking, and implements the https://www.reactive-streams.org/[Reactive Streams] specification through https://projectreactor.io/[the Reactor project]. + +Spring WebFlux comes in two flavors: functional and annotation-based. +The annotation-based one is quite close to the Spring MVC model, as shown in the following example: + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/developingwebapplications/springwebflux/MyRestController.java[] +---- + +"`WebFlux.fn`", the functional variant, separates the routing configuration from the actual handling of the requests, as shown in the following example: + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/developingwebapplications/springwebflux/MyRoutingConfiguration.java[] +---- + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/developingwebapplications/springwebflux/MyUserHandler.java[] +---- + +WebFlux is part of the Spring Framework and detailed information is available in its {spring-framework-docs}/web-reactive.html#webflux-fn[reference documentation]. + +TIP: You can define as many `RouterFunction` beans as you like to modularize the definition of the router. +Beans can be ordered if you need to apply a precedence. + +To get started, add the `spring-boot-starter-webflux` module to your application. + +NOTE: Adding both `spring-boot-starter-web` and `spring-boot-starter-webflux` modules in your application results in Spring Boot auto-configuring Spring MVC, not WebFlux. +This behavior has been chosen because many Spring developers add `spring-boot-starter-webflux` to their Spring MVC application to use the reactive `WebClient`. +You can still enforce your choice by setting the chosen application type to `SpringApplication.setWebApplicationType(WebApplicationType.REACTIVE)`. + + +"`WebFlux.fn`", the functional variant, separates the routing configuration from the actual handling of the requests, as shown in the following example: + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/developingwebapplications/springwebflux/MyRoutingConfiguration.java[] +---- + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/developingwebapplications/springwebflux/MyUserHandler.java[] +---- + +WebFlux is part of the Spring Framework and detailed information is available in its {spring-framework-docs}/web-reactive.html#webflux-fn[reference documentation]. + +TIP: You can define as many `RouterFunction` beans as you like to modularize the definition of the router. +Beans can be ordered if you need to apply a precedence. + +To get started, add the `spring-boot-starter-webflux` module to your application. + +NOTE: Adding both `spring-boot-starter-web` and `spring-boot-starter-webflux` modules in your application results in Spring Boot auto-configuring Spring MVC, not WebFlux. +This behavior has been chosen because many Spring developers add `spring-boot-starter-webflux` to their Spring MVC application to use the reactive `WebClient`. +You can still enforce your choice by setting the chosen application type to `SpringApplication.setWebApplicationType(WebApplicationType.REACTIVE)`. + +[[web.reactive.webflux.auto-configuration]] +==== Spring WebFlux Auto-configuration +Spring Boot provides auto-configuration for Spring WebFlux that works well with most applications. + +The auto-configuration adds the following features on top of Spring's defaults: + +* Configuring codecs for `HttpMessageReader` and `HttpMessageWriter` instances (described <>). +* Support for serving static resources, including support for WebJars (described <>). + +If you want to keep Spring Boot WebFlux features and you want to add additional {spring-framework-docs}/web-reactive.html#webflux-config[WebFlux configuration], you can add your own `@Configuration` class of type `WebFluxConfigurer` but *without* `@EnableWebFlux`. + +If you want to take complete control of Spring WebFlux, you can add your own `@Configuration` annotated with `@EnableWebFlux`. + + + +[[web.reactive.webflux.httpcodecs]] +==== HTTP Codecs with HttpMessageReaders and HttpMessageWriters +Spring WebFlux uses the `HttpMessageReader` and `HttpMessageWriter` interfaces to convert HTTP requests and responses. +They are configured with `CodecConfigurer` to have sensible defaults by looking at the libraries available in your classpath. + +Spring Boot provides dedicated configuration properties for codecs, `+spring.codec.*+`. +It also applies further customization by using `CodecCustomizer` instances. +For example, `+spring.jackson.*+` configuration keys are applied to the Jackson codec. + +If you need to add or customize codecs, you can create a custom `CodecCustomizer` component, as shown in the following example: + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/developingwebapplications/springwebflux/httpcodecs/MyCodecsConfiguration.java[] +---- + +You can also leverage <>. + + + +[[web.reactive.webflux.static-content]] +==== Static Content +By default, Spring Boot serves static content from a directory called `/static` (or `/public` or `/resources` or `/META-INF/resources`) in the classpath. +It uses the `ResourceWebHandler` from Spring WebFlux so that you can modify that behavior by adding your own `WebFluxConfigurer` and overriding the `addResourceHandlers` method. + +By default, resources are mapped on `+/**+`, but you can tune that by setting the configprop:spring.webflux.static-path-pattern[] property. +For instance, relocating all resources to `/resources/**` can be achieved as follows: + +[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +---- + spring: + webflux: + static-path-pattern: "/resources/**" +---- + +You can also customize the static resource locations by using `spring.web.resources.static-locations`. +Doing so replaces the default values with a list of directory locations. +If you do so, the default welcome page detection switches to your custom locations. +So, if there is an `index.html` in any of your locations on startup, it is the home page of the application. + +In addition to the "`standard`" static resource locations listed earlier, a special case is made for https://www.webjars.org/[Webjars content]. +Any resources with a path in `+/webjars/**+` are served from jar files if they are packaged in the Webjars format. + +TIP: Spring WebFlux applications do not strictly depend on the Servlet API, so they cannot be deployed as war files and do not use the `src/main/webapp` directory. + + + +[[web.reactive.webflux.welcome-page]] +==== Welcome Page +Spring Boot supports both static and templated welcome pages. +It first looks for an `index.html` file in the configured static content locations. +If one is not found, it then looks for an `index` template. +If either is found, it is automatically used as the welcome page of the application. + + + +[[web.reactive.webflux.template-engines]] +==== Template Engines +As well as REST web services, you can also use Spring WebFlux to serve dynamic HTML content. +Spring WebFlux supports a variety of templating technologies, including Thymeleaf, FreeMarker, and Mustache. + +Spring Boot includes auto-configuration support for the following templating engines: + +* https://freemarker.apache.org/docs/[FreeMarker] +* https://www.thymeleaf.org[Thymeleaf] +* https://mustache.github.io/[Mustache] + +When you use one of these templating engines with the default configuration, your templates are picked up automatically from `src/main/resources/templates`. + + + +[[web.reactive.webflux.error-handling]] +==== Error Handling +Spring Boot provides a `WebExceptionHandler` that handles all errors in a sensible way. +Its position in the processing order is immediately before the handlers provided by WebFlux, which are considered last. +For machine clients, it produces a JSON response with details of the error, the HTTP status, and the exception message. +For browser clients, there is a "`whitelabel`" error handler that renders the same data in HTML format. +You can also provide your own HTML templates to display errors (see the <>). + +The first step to customizing this feature often involves using the existing mechanism but replacing or augmenting the error contents. +For that, you can add a bean of type `ErrorAttributes`. + +To change the error handling behavior, you can implement `ErrorWebExceptionHandler` and register a bean definition of that type. +Because 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: + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/developingwebapplications/springwebflux/errorhandling/MyErrorWebExceptionHandler.java[] +---- + +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 <>. +Applications can ensure that such exceptions are recorded with the request metrics by setting the handled exception as a request attribute: + +[source,java,indent=0,subs="verbatim"] +---- +include::{docs-java}/features/developingwebapplications/springwebflux/errorhandling/MyExceptionHandlingController.java[] +---- + + + +[[web.reactive.webflux.error-handling.error-pages]] +===== Custom Error Pages +If you want to display a custom HTML error page for a given status code, you can add a file to an `/error` directory. +Error pages can either be static HTML (that is, added under any of the static resource directories) or built with templates. +The name of the file should be the exact status code or a series mask. + +For example, to map `404` to a static HTML file, your directory structure would be as follows: + +[source,indent=0,subs="verbatim"] +---- + src/ + +- main/ + +- java/ + | + + +- resources/ + +- public/ + +- error/ + | +- 404.html + +- +---- + +To map all `5xx` errors by using a Mustache template, your directory structure would be as follows: + +[source,indent=0,subs="verbatim"] +---- + src/ + +- main/ + +- java/ + | + + +- resources/ + +- templates/ + +- error/ + | +- 5xx.mustache + +- +---- + + + +[[web.reactive.webflux.web-filters]] +==== Web Filters +Spring WebFlux provides a `WebFilter` interface that can be implemented to filter HTTP request-response exchanges. +`WebFilter` beans found in the application context will be automatically used to filter each exchange. + +Where the order of the filters is important they can implement `Ordered` or be annotated with `@Order`. +Spring Boot auto-configuration may configure web filters for you. +When it does so, the orders shown in the following table will be used: + +|=== +| Web Filter | Order + +| `MetricsWebFilter` +| `Ordered.HIGHEST_PRECEDENCE + 1` + +| `WebFilterChainProxy` (Spring Security) +| `-100` + +| `HttpTraceWebFilter` +| `Ordered.LOWEST_PRECEDENCE - 10` +|=== + + + +[[web.reactive.reactive-server]] +=== Embedded Reactive Server Support +Spring Boot includes support for the following embedded reactive web servers: Reactor Netty, Tomcat, Jetty, and Undertow. +Most developers use the appropriate “Starter” to obtain a fully configured instance. +By default, the embedded server listens for HTTP requests on port 8080. + + + +[[web.reactive.reactive-server-resources-configuration]] +=== Reactive Server Resources Configuration +When auto-configuring a Reactor Netty or Jetty server, Spring Boot will create specific beans that will provide HTTP resources to the server instance: `ReactorResourceFactory` or `JettyResourceFactory`. + +By default, those resources will be also shared with the Reactor Netty and Jetty clients for optimal performances, given: + +* the same technology is used for server and client +* the client instance is built using the `WebClient.Builder` bean auto-configured by Spring Boot + +Developers can override the resource configuration for Jetty and Reactor Netty by providing a custom `ReactorResourceFactory` or `JettyResourceFactory` bean - this will be applied to both clients and servers. + +You can learn more about the resource configuration on the client side in the <>. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/developing-web-applications.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/servlet.adoc similarity index 67% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/developing-web-applications.adoc rename to spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/servlet.adoc index 60c87a03a062..64ab2f0143cd 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/developing-web-applications.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/servlet.adoc @@ -1,15 +1,8 @@ -[[features.developing-web-applications]] -== Developing Web Applications -Spring Boot is well suited for web application development. -You can create a self-contained HTTP server by using embedded Tomcat, Jetty, Undertow, or Netty. -Most web applications use the `spring-boot-starter-web` module to get up and running quickly. -You can also choose to build reactive web applications by using the `spring-boot-starter-webflux` module. +[[web.servlet]] +== Servlet Web Applications +If you're looking to build servlet-based web applications, you can take advantange of Spring Boot's auto-configuration for Spring MVC or Jersey. -If you have not yet developed a Spring Boot web application, you can follow the "Hello World!" example in the _<>_ section. - - - -[[features.developing-web-applications.spring-mvc]] +[[web.servlet.spring-mvc]] === The "`Spring Web MVC Framework`" The {spring-framework-docs}/web.html#mvc[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. @@ -27,19 +20,19 @@ There are also several guides that cover Spring MVC available at https://spring. -[[features.developing-web-applications.spring-mvc.auto-configuration]] +[[web.servlet.spring-mvc.auto-configuration]] ==== Spring MVC Auto-configuration Spring Boot provides auto-configuration for Spring MVC that works well with most applications. The auto-configuration adds the following features on top of Spring's defaults: * Inclusion of `ContentNegotiatingViewResolver` and `BeanNameViewResolver` beans. -* Support for serving static resources, including support for WebJars (covered <>). +* Support for serving static resources, including support for WebJars (covered <>). * Automatic registration of `Converter`, `GenericConverter`, and `Formatter` beans. -* Support for `HttpMessageConverters` (covered <>). -* Automatic registration of `MessageCodesResolver` (covered <>). +* Support for `HttpMessageConverters` (covered <>). +* Automatic registration of `MessageCodesResolver` (covered <>). * Static `index.html` support. -* Automatic use of a `ConfigurableWebBindingInitializer` bean (covered <>). +* Automatic use of a `ConfigurableWebBindingInitializer` bean (covered <>). If you want to keep those Spring Boot MVC customizations and make more {spring-framework-docs}/web.html#mvc[MVC customizations] (interceptors, formatters, view controllers, and other features), you can add your own `@Configuration` class of type `WebMvcConfigurer` but *without* `@EnableWebMvc`. @@ -58,7 +51,7 @@ From this method you can register any converter that you like, or you can delega -[[features.developing-web-applications.spring-mvc.message-converters]] +[[web.servlet.spring-mvc.message-converters]] ==== HttpMessageConverters Spring MVC uses the `HttpMessageConverter` interface to convert HTTP requests and responses. Sensible defaults are included out of the box. @@ -77,7 +70,7 @@ You can also override default converters in the same way. -[[features.developing-web-applications.spring-mvc.json]] +[[web.servlet.spring-mvc.json]] ==== Custom JSON Serializers and Deserializers If you use Jackson to serialize and deserialize JSON data, you might want to write your own `JsonSerializer` and `JsonDeserializer` classes. Custom serializers are usually 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. @@ -105,14 +98,14 @@ include::{docs-java}/features/developingwebapplications/springmvc/json/object/My -[[features.developing-web-applications.spring-mvc.message-codes]] +[[web.servlet.spring-mvc.message-codes]] ==== MessageCodesResolver Spring MVC has a strategy for generating error codes for rendering error messages from binding errors: `MessageCodesResolver`. If you set the configprop:spring.mvc.message-codes-resolver-format[] property `PREFIX_ERROR_CODE` or `POSTFIX_ERROR_CODE`, Spring Boot creates one for you (see the enumeration in {spring-framework-api}/validation/DefaultMessageCodesResolver.Format.html[`DefaultMessageCodesResolver.Format`]). -[[features.developing-web-applications.spring-mvc.static-content]] +[[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. @@ -197,7 +190,7 @@ This feature has been thoroughly described in a dedicated https://spring.io/blog -[[features.developing-web-applications.spring-mvc.welcome-page]] +[[web.servlet.spring-mvc.welcome-page]] ==== Welcome Page Spring Boot supports both static and templated welcome pages. It first looks for an `index.html` file in the configured static content locations. @@ -206,7 +199,7 @@ If either is found, it is automatically used as the welcome page of the applicat -[[features.developing-web-applications.spring-mvc.content-negotiation]] +[[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). @@ -298,14 +291,14 @@ with a Servlet prefix (configprop:spring.mvc.servlet.path[]). -[[features.developing-web-applications.spring-mvc.binding-initializer]] +[[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. -[[features.developing-web-applications.spring-mvc.template-engines]] +[[web.servlet.spring-mvc.template-engines]] ==== Template Engines As well as REST web services, you can also use Spring MVC to serve dynamic HTML content. Spring MVC supports a variety of templating technologies, including Thymeleaf, FreeMarker, and JSPs. @@ -313,13 +306,13 @@ Also, many other templating engines include their own Spring MVC integrations. Spring Boot includes auto-configuration support for the following templating engines: - * https://freemarker.apache.org/docs/[FreeMarker] - * https://docs.groovy-lang.org/docs/next/html/documentation/template-engines.html#_the_markuptemplateengine[Groovy] - * https://www.thymeleaf.org[Thymeleaf] - * https://mustache.github.io/[Mustache] +* https://freemarker.apache.org/docs/[FreeMarker] +* https://docs.groovy-lang.org/docs/next/html/documentation/template-engines.html#_the_markuptemplateengine[Groovy] +* https://www.thymeleaf.org[Thymeleaf] +* https://mustache.github.io/[Mustache] TIP: If possible, JSPs should be avoided. -There are several <> when using them with embedded servlet containers. +There are several <> when using them with embedded servlet containers. When you use one of these templating engines with the default configuration, your templates are picked up automatically from `src/main/resources/templates`. @@ -330,7 +323,7 @@ If you have this problem, you can reorder the classpath in the IDE to place the -[[features.developing-web-applications.spring-mvc.error-handling]] +[[web.servlet.spring-mvc.error-handling]] ==== Error Handling By default, Spring Boot provides an `/error` mapping that handles all errors in a sensible way, and it is registered as a "`global`" error page in the servlet container. For machine clients, it produces a JSON response with details of the error, the HTTP status, and the exception message. @@ -364,7 +357,7 @@ include::{docs-java}/features/developingwebapplications/springmvc/errorhandling/ -[[features.developing-web-applications.spring-mvc.error-handling.error-pages]] +[[web.servlet.spring-mvc.error-handling.error-pages]] ===== Custom Error Pages If you want to display a custom HTML error page for a given status code, you can add a file to an `/error` directory. Error pages can either be static HTML (that is, added under any of the static resource directories) or be built by using templates. @@ -412,7 +405,7 @@ The `ErrorController` then picks up any unhandled exceptions. -[[features.developing-web-applications.spring-mvc.error-handling.error-pages-without-spring-mvc]] +[[web.servlet.spring-mvc.error-handling.error-pages-without-spring-mvc]] ===== Mapping Error Pages outside of Spring MVC For applications that do not use Spring MVC, you can use the `ErrorPageRegistrar` interface to directly register `ErrorPages`. This abstraction works directly with the underlying embedded servlet container and works even if you do not have a Spring MVC `DispatcherServlet`. @@ -433,7 +426,7 @@ Note that the default `FilterRegistrationBean` does not include the `ERROR` disp -[[features.developing-web-applications.spring-mvc.error-handling.in-a-war-deployment]] +[[web.servlet.spring-mvc.error-handling.in-a-war-deployment]] ===== Error handling in a war deployment When deployed to a servlet container, Spring Boot uses its error page filter to forward a request with an error status to the appropriate error page. This is necessary as the Servlet specification does not provide an API for registering error pages. @@ -448,18 +441,7 @@ To do so, set the `spring.security.filter.dispatcher-types` property to `async, -[[features.developing-web-applications.spring-mvc.spring-hateoas]] -==== Spring HATEOAS -If you develop a RESTful API that makes use of hypermedia, Spring Boot provides auto-configuration for Spring HATEOAS that works well with most applications. -The auto-configuration replaces the need to use `@EnableHypermediaSupport` and registers a number of beans to ease building hypermedia-based applications, including a `LinkDiscoverers` (for client side support) and an `ObjectMapper` configured to correctly marshal responses into the desired representation. -The `ObjectMapper` is customized by setting the various `spring.jackson.*` properties or, if one exists, by a `Jackson2ObjectMapperBuilder` bean. - -You can take control of Spring HATEOAS's configuration by using `@EnableHypermediaSupport`. -Note that doing so disables the `ObjectMapper` customization described earlier. - - - -[[features.developing-web-applications.spring-mvc.cors]] +[[web.servlet.spring-mvc.cors]] ==== CORS Support https://en.wikipedia.org/wiki/Cross-origin_resource_sharing[Cross-origin resource sharing] (CORS) is a https://www.w3.org/TR/cors/[W3C specification] implemented by https://caniuse.com/#feat=cors[most browsers] that lets you specify in a flexible way what kind of cross-domain requests are authorized., instead of using some less secure and less powerful approaches such as IFRAME or JSONP. @@ -474,224 +456,7 @@ include::{docs-java}/features/developingwebapplications/springmvc/cors/MyCorsCon -[[features.developing-web-applications.spring-webflux]] -=== The "`Spring WebFlux Framework`" -Spring WebFlux is the new reactive web framework introduced in Spring Framework 5.0. -Unlike Spring MVC, it does not require the Servlet API, is fully asynchronous and non-blocking, and implements the https://www.reactive-streams.org/[Reactive Streams] specification through https://projectreactor.io/[the Reactor project]. - -Spring WebFlux comes in two flavors: functional and annotation-based. -The annotation-based one is quite close to the Spring MVC model, as shown in the following example: - -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/developingwebapplications/springwebflux/MyRestController.java[] ----- - -"`WebFlux.fn`", the functional variant, separates the routing configuration from the actual handling of the requests, as shown in the following example: - -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/developingwebapplications/springwebflux/MyRoutingConfiguration.java[] ----- - -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/developingwebapplications/springwebflux/MyUserHandler.java[] ----- - -WebFlux is part of the Spring Framework and detailed information is available in its {spring-framework-docs}/web-reactive.html#webflux-fn[reference documentation]. - -TIP: You can define as many `RouterFunction` beans as you like to modularize the definition of the router. -Beans can be ordered if you need to apply a precedence. - -To get started, add the `spring-boot-starter-webflux` module to your application. - -NOTE: Adding both `spring-boot-starter-web` and `spring-boot-starter-webflux` modules in your application results in Spring Boot auto-configuring Spring MVC, not WebFlux. -This behavior has been chosen because many Spring developers add `spring-boot-starter-webflux` to their Spring MVC application to use the reactive `WebClient`. -You can still enforce your choice by setting the chosen application type to `SpringApplication.setWebApplicationType(WebApplicationType.REACTIVE)`. - - - -[[features.developing-web-applications.spring-webflux.auto-configuration]] -==== Spring WebFlux Auto-configuration -Spring Boot provides auto-configuration for Spring WebFlux that works well with most applications. - -The auto-configuration adds the following features on top of Spring's defaults: - -* Configuring codecs for `HttpMessageReader` and `HttpMessageWriter` instances (described <>). -* Support for serving static resources, including support for WebJars (described <>). - -If you want to keep Spring Boot WebFlux features and you want to add additional {spring-framework-docs}/web-reactive.html#webflux-config[WebFlux configuration], you can add your own `@Configuration` class of type `WebFluxConfigurer` but *without* `@EnableWebFlux`. - -If you want to take complete control of Spring WebFlux, you can add your own `@Configuration` annotated with `@EnableWebFlux`. - - - -[[features.developing-web-applications.spring-webflux.httpcodecs]] -==== HTTP Codecs with HttpMessageReaders and HttpMessageWriters -Spring WebFlux uses the `HttpMessageReader` and `HttpMessageWriter` interfaces to convert HTTP requests and responses. -They are configured with `CodecConfigurer` to have sensible defaults by looking at the libraries available in your classpath. - -Spring Boot provides dedicated configuration properties for codecs, `+spring.codec.*+`. -It also applies further customization by using `CodecCustomizer` instances. -For example, `+spring.jackson.*+` configuration keys are applied to the Jackson codec. - -If you need to add or customize codecs, you can create a custom `CodecCustomizer` component, as shown in the following example: - -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/developingwebapplications/springwebflux/httpcodecs/MyCodecsConfiguration.java[] ----- - -You can also leverage <>. - - - -[[features.developing-web-applications.spring-webflux.static-content]] -==== Static Content -By default, Spring Boot serves static content from a directory called `/static` (or `/public` or `/resources` or `/META-INF/resources`) in the classpath. -It uses the `ResourceWebHandler` from Spring WebFlux so that you can modify that behavior by adding your own `WebFluxConfigurer` and overriding the `addResourceHandlers` method. - -By default, resources are mapped on `+/**+`, but you can tune that by setting the configprop:spring.webflux.static-path-pattern[] property. -For instance, relocating all resources to `/resources/**` can be achieved as follows: - -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] ----- - spring: - webflux: - static-path-pattern: "/resources/**" ----- - -You can also customize the static resource locations by using `spring.web.resources.static-locations`. -Doing so replaces the default values with a list of directory locations. -If you do so, the default welcome page detection switches to your custom locations. -So, if there is an `index.html` in any of your locations on startup, it is the home page of the application. - -In addition to the "`standard`" static resource locations listed earlier, a special case is made for https://www.webjars.org/[Webjars content]. -Any resources with a path in `+/webjars/**+` are served from jar files if they are packaged in the Webjars format. - -TIP: Spring WebFlux applications do not strictly depend on the Servlet API, so they cannot be deployed as war files and do not use the `src/main/webapp` directory. - - - -[[features.developing-web-applications.spring-webflux.welcome-page]] -==== Welcome Page -Spring Boot supports both static and templated welcome pages. -It first looks for an `index.html` file in the configured static content locations. -If one is not found, it then looks for an `index` template. -If either is found, it is automatically used as the welcome page of the application. - - - -[[features.developing-web-applications.spring-webflux.template-engines]] -==== Template Engines -As well as REST web services, you can also use Spring WebFlux to serve dynamic HTML content. -Spring WebFlux supports a variety of templating technologies, including Thymeleaf, FreeMarker, and Mustache. - -Spring Boot includes auto-configuration support for the following templating engines: - - * https://freemarker.apache.org/docs/[FreeMarker] - * https://www.thymeleaf.org[Thymeleaf] - * https://mustache.github.io/[Mustache] - -When you use one of these templating engines with the default configuration, your templates are picked up automatically from `src/main/resources/templates`. - - - -[[features.developing-web-applications.spring-webflux.error-handling]] -==== Error Handling -Spring Boot provides a `WebExceptionHandler` that handles all errors in a sensible way. -Its position in the processing order is immediately before the handlers provided by WebFlux, which are considered last. -For machine clients, it produces a JSON response with details of the error, the HTTP status, and the exception message. -For browser clients, there is a "`whitelabel`" error handler that renders the same data in HTML format. -You can also provide your own HTML templates to display errors (see the <>). - -The first step to customizing this feature often involves using the existing mechanism but replacing or augmenting the error contents. -For that, you can add a bean of type `ErrorAttributes`. - -To change the error handling behavior, you can implement `ErrorWebExceptionHandler` and register a bean definition of that type. -Because 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: - -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/developingwebapplications/springwebflux/errorhandling/MyErrorWebExceptionHandler.java[] ----- - -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 <>. -Applications can ensure that such exceptions are recorded with the request metrics by setting the handled exception as a request attribute: - -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/features/developingwebapplications/springwebflux/errorhandling/MyExceptionHandlingController.java[] ----- - - - -[[features.developing-web-applications.spring-webflux.error-handling.error-pages]] -===== Custom Error Pages -If you want to display a custom HTML error page for a given status code, you can add a file to an `/error` directory. -Error pages can either be static HTML (that is, added under any of the static resource directories) or built with templates. -The name of the file should be the exact status code or a series mask. - -For example, to map `404` to a static HTML file, your directory structure would be as follows: - -[source,indent=0,subs="verbatim"] ----- - src/ - +- main/ - +- java/ - | + - +- resources/ - +- public/ - +- error/ - | +- 404.html - +- ----- - -To map all `5xx` errors by using a Mustache template, your directory structure would be as follows: - -[source,indent=0,subs="verbatim"] ----- - src/ - +- main/ - +- java/ - | + - +- resources/ - +- templates/ - +- error/ - | +- 5xx.mustache - +- ----- - - - -[[features.developing-web-applications.spring-webflux.web-filters]] -==== Web Filters -Spring WebFlux provides a `WebFilter` interface that can be implemented to filter HTTP request-response exchanges. -`WebFilter` beans found in the application context will be automatically used to filter each exchange. - -Where the order of the filters is important they can implement `Ordered` or be annotated with `@Order`. -Spring Boot auto-configuration may configure web filters for you. -When it does so, the orders shown in the following table will be used: - -|=== -| Web Filter | Order - -| `MetricsWebFilter` -| `Ordered.HIGHEST_PRECEDENCE + 1` - -| `WebFilterChainProxy` (Spring Security) -| `-100` - -| `HttpTraceWebFilter` -| `Ordered.LOWEST_PRECEDENCE - 10` -|=== - - - -[[features.developing-web-applications.jersey]] +[[web.servlet.jersey]] === JAX-RS and Jersey If you prefer the JAX-RS programming model for REST endpoints, you can use one of the available implementations instead of Spring MVC. https://jersey.github.io/[Jersey] and https://cxf.apache.org/[Apache CXF] work quite well out of the box. @@ -733,21 +498,21 @@ Both the servlet and the filter registrations can be given init parameters by us -[[features.developing-web-applications.embedded-container]] +[[web.servlet.embedded-container]] === Embedded Servlet Container Support -Spring Boot includes support for embedded https://tomcat.apache.org/[Tomcat], https://www.eclipse.org/jetty/[Jetty], and https://github.com/undertow-io/undertow[Undertow] servers. +For servlet application, Spring Boot includes support for embedded https://tomcat.apache.org/[Tomcat], https://www.eclipse.org/jetty/[Jetty], and https://github.com/undertow-io/undertow[Undertow] servers. Most developers use the appropriate "`Starter`" to obtain a fully configured instance. By default, the embedded server listens for HTTP requests on port `8080`. -[[features.developing-web-applications.embedded-container.servlets-filters-listeners]] +[[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. -[[features.developing-web-applications.embedded-container.servlets-filters-listeners.beans]] +[[web.servlet.embedded-container.servlets-filters-listeners.beans]] ===== Registering Servlets, Filters, and Listeners as Spring Beans Any `Servlet`, `Filter`, or servlet `*Listener` instance that is a Spring bean is registered with the embedded container. This can be particularly convenient if you want to refer to a value from your `application.properties` during configuration. @@ -773,7 +538,7 @@ If you need to register a `Filter` that interacts with other beans, consider usi -[[features.developing-web-applications.embedded-container.context-initializer]] +[[web.servlet.embedded-container.context-initializer]] ==== Servlet Context Initialization Embedded servlet containers do not directly execute the Servlet 3.0+ `javax.servlet.ServletContainerInitializer` interface or Spring's `org.springframework.web.WebApplicationInitializer` interface. This is an intentional design decision intended to reduce the risk that third party libraries designed to run inside a war may break Spring Boot applications. @@ -783,7 +548,7 @@ The single `onStartup` method provides access to the `ServletContext` and, if ne -[[features.developing-web-applications.embedded-container.context-initializer.scanning]] +[[web.servlet.embedded-container.context-initializer.scanning]] ===== Scanning for Servlets, Filters, and listeners When using an embedded container, automatic registration of classes annotated with `@WebServlet`, `@WebFilter`, and `@WebListener` can be enabled by using `@ServletComponentScan`. @@ -791,7 +556,7 @@ TIP: `@ServletComponentScan` has no effect in a standalone container, where the -[[features.developing-web-applications.embedded-container.application-context]] +[[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. @@ -802,7 +567,7 @@ Most applications are auto-configured, and the appropriate `ApplicationContext` -[[features.developing-web-applications.embedded-container.customizing]] +[[web.servlet.embedded-container.customizing]] ==== Customizing Embedded Servlet Containers Common servlet container settings can be configured by using Spring `Environment` properties. Usually, you would define the properties in your `application.properties` or `application.yaml` file. @@ -823,7 +588,7 @@ TIP: See the {spring-boot-autoconfigure-module-code}/web/ServerProperties.java[` -[[features.developing-web-applications.embedded-container.customizing.programmatic]] +[[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. @@ -844,7 +609,7 @@ include::{docs-java}/features/developingwebapplications/embeddedcontainer/custom -[[features.developing-web-applications.embedded-container.customizing.direct]] +[[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. @@ -856,38 +621,17 @@ NOTE: Auto-configured customizers are still applied on your custom factory, so u -[[features.developing-web-applications.embedded-container.jsp-limitations]] +[[web.servlet.embedded-container.jsp-limitations]] ==== JSP Limitations When running a Spring Boot application that uses an embedded servlet container (and is packaged as an executable archive), there are some limitations in the JSP support. * With Jetty and Tomcat, it should work if you use war packaging. - An executable war will work when launched with `java -jar`, and will also be deployable to any standard container. - JSPs are not supported when using an executable jar. +An executable war will work when launched with `java -jar`, and will also be deployable to any standard container. +JSPs are not supported when using an executable jar. * Undertow does not support JSPs. -* Creating a custom `error.jsp` page does not override the default view for <>. - <> should be used instead. - - - -[[features.developing-web-applications.reactive-server]] -=== Embedded Reactive Server Support -Spring Boot includes support for the following embedded reactive web servers: Reactor Netty, Tomcat, Jetty, and Undertow. -Most developers use the appropriate “Starter” to obtain a fully configured instance. -By default, the embedded server listens for HTTP requests on port 8080. - - - -[[features.developing-web-applications.reactive-server-resources-configuration]] -=== Reactive Server Resources Configuration -When auto-configuring a Reactor Netty or Jetty server, Spring Boot will create specific beans that will provide HTTP resources to the server instance: `ReactorResourceFactory` or `JettyResourceFactory`. - -By default, those resources will be also shared with the Reactor Netty and Jetty clients for optimal performances, given: - -* the same technology is used for server and client -* the client instance is built using the `WebClient.Builder` bean auto-configured by Spring Boot +* Creating a custom `error.jsp` page does not override the default view for <>. + <> should be used instead. -Developers can override the resource configuration for Jetty and Reactor Netty by providing a custom `ReactorResourceFactory` or `JettyResourceFactory` bean - this will be applied to both clients and servers. -You can learn more about the resource configuration on the client side in the <>. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-hateoas.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-hateoas.adoc new file mode 100644 index 000000000000..1564f4197eb5 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-hateoas.adoc @@ -0,0 +1,10 @@ +[[web.spring-hateoas]] +== Spring HATEOAS +If you develop a RESTful API that makes use of hypermedia, Spring Boot provides auto-configuration for Spring HATEOAS that works well with most applications. +The auto-configuration replaces the need to use `@EnableHypermediaSupport` and registers a number of beans to ease building hypermedia-based applications, including a `LinkDiscoverers` (for client side support) and an `ObjectMapper` configured to correctly marshal responses into the desired representation. +The `ObjectMapper` is customized by setting the various `spring.jackson.*` properties or, if one exists, by a `Jackson2ObjectMapperBuilder` bean. + +You can take control of Spring HATEOAS's configuration by using `@EnableHypermediaSupport`. +Note that doing so disables the `ObjectMapper` customization described earlier. + +NOTE: Spring HATEOAS support is not available for Spring Webflux applications yet. \ No newline at end of file diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/security.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-security.adoc similarity index 88% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/security.adoc rename to spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-security.adoc index f7d372e261dc..72e1ca52e19c 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/security.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-security.adoc @@ -1,5 +1,5 @@ -[[features.security]] -== Security +[[web.security]] +== Spring Security If {spring-security}[Spring Security] is on the classpath, then web applications are secured by default. Spring Boot relies on Spring Security’s content-negotiation strategy to determine whether to use `httpBasic` or `formLogin`. To add method-level security to a web application, you can also add `@EnableGlobalMethodSecurity` with your desired settings. @@ -28,7 +28,7 @@ You can provide a different `AuthenticationEventPublisher` by adding a bean for -[[features.security.spring-mvc]] +[[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. @@ -43,7 +43,7 @@ Spring Boot provides convenience methods that can be used to override access rul -[[features.security.spring-webflux]] +[[web.security.spring-webflux]] === WebFlux Security Similar to Spring MVC applications, you can secure your WebFlux applications by adding the `spring-boot-starter-security` dependency. The default security configuration is implemented in `ReactiveSecurityAutoConfiguration` and `UserDetailsServiceAutoConfiguration`. @@ -67,13 +67,13 @@ include::{docs-java}/features/security/springwebflux/MyWebFluxSecurityConfigurat -[[features.security.oauth2]] +[[web.security.oauth2]] === OAuth2 https://oauth.net/2/[OAuth2] is a widely used authorization framework that is supported by Spring. -[[features.security.oauth2.client]] +[[web.security.oauth2.client]] ==== Client If you have `spring-security-oauth2-client` on your classpath, you can take advantage of some auto-configuration to set up an OAuth2/Open ID Connect clients. This configuration makes use of the properties under `OAuth2ClientProperties`. @@ -150,7 +150,7 @@ For production environments, consider using a `JdbcOAuth2AuthorizedClientService -[[features.security.oauth2.client.common-providers]] +[[web.security.oauth2.client.common-providers]] ===== OAuth2 client registration for common providers For common OAuth2 and OpenID providers, including Google, Github, Facebook, and Okta, we provide a set of provider defaults (`google`, `github`, `facebook`, and `okta`, respectively). @@ -177,7 +177,7 @@ In other words, the two configurations in the following example use the Google p -[[features.security.oauth2.server]] +[[web.security.oauth2.server]] ==== Resource Server If you have `spring-security-oauth2-resource-server` on your classpath, Spring Boot can set up an OAuth2 Resource Server. For JWT configuration, a JWK Set URI or OIDC Issuer URI needs to be specified, as shown in the following examples: @@ -229,7 +229,7 @@ Alternatively, you can define your own `OpaqueTokenIntrospector` bean for servle -[[features.security.oauth2.authorization-server]] +[[web.security.oauth2.authorization-server]] ==== Authorization Server Currently, Spring Security does not provide support for implementing an OAuth 2.0 Authorization Server. However, this functionality is available from the {spring-security-oauth2}[Spring Security OAuth] project, which will eventually be superseded by Spring Security completely. @@ -237,12 +237,12 @@ Until then, you can use the `spring-security-oauth2-autoconfigure` module to eas -[[features.security.saml2]] +[[web.security.saml2]] === SAML 2.0 -[[features.security.saml2.relying-party]] +[[web.security.saml2.relying-party]] ==== Relying Party If you have `spring-security-saml2-service-provider` on your classpath, you can take advantage of some auto-configuration to set up a SAML 2.0 Relying Party. This configuration makes use of the properties under `Saml2RelyingPartyProperties`. @@ -289,26 +289,3 @@ You can register multiple relying parties under the `spring.security.saml2.relyi entity-id: "remote-idp-entity-id2" sso-url: "https://remoteidp2.sso.url" ---- - - - -[[features.security.actuator]] -=== Actuator Security -For security purposes, all actuators other than `/health` are disabled by default. -The configprop:management.endpoints.web.exposure.include[] property can be used to enable the actuators. - -If Spring Security is on the classpath and no other `WebSecurityConfigurerAdapter` or `SecurityFilterChain` bean is present, all actuators other than `/health` are secured by Spring Boot auto-configuration. -If you define a custom `WebSecurityConfigurerAdapter` or `SecurityFilterChain` bean, Spring Boot auto-configuration will back off and you will be in full control of actuator access rules. - -NOTE: Before setting the `management.endpoints.web.exposure.include`, ensure that the exposed actuators do not contain sensitive information and/or are secured by placing them behind a firewall or by something like Spring Security. - - - -[[features.security.actuator.csrf]] -==== Cross Site Request Forgery Protection -Since Spring Boot relies on Spring Security's defaults, CSRF protection is turned on by default. -This means that the actuator endpoints that require a `POST` (shutdown and loggers endpoints), `PUT` or `DELETE` will get a 403 forbidden error when the default security configuration is in use. - -NOTE: We recommend disabling CSRF protection completely only if you are creating a service that is used by non-browser clients. - -Additional information about CSRF protection can be found in the {spring-security-docs}#csrf[Spring Security Reference Guide]. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/spring-session.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-session.adoc similarity index 98% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/spring-session.adoc rename to spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-session.adoc index 6e627cd1f647..4c075ae56db8 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/spring-session.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-session.adoc @@ -1,4 +1,4 @@ -[[features.spring-session]] +[[web.spring-session]] == Spring Session Spring Boot provides {spring-session}[Spring Session] auto-configuration for a wide range of data stores. When building a Servlet web application, the following stores can be auto-configured: