diff --git a/spring-boot-project/spring-boot-docs/build.gradle b/spring-boot-project/spring-boot-docs/build.gradle index dba2031dd9..f35de29529 100644 --- a/spring-boot-project/spring-boot-docs/build.gradle +++ b/spring-boot-project/spring-boot-docs/build.gradle @@ -1,6 +1,6 @@ plugins { id "java" - id "org.asciidoctor.jvm.convert" + id "org.antora" id "org.springframework.boot.conventions" id "org.springframework.boot.deployed" id 'org.jetbrains.kotlin.jvm' @@ -9,25 +9,12 @@ plugins { description = "Spring Boot Docs" configurations { - actuatorApiDocumentation autoConfiguration configurationProperties - gradlePluginDocumentation - mavenPluginDocumentation remoteSpringApplicationExample springApplicationExample testSlices - asciidoctorExtensions { - resolutionStrategy { - eachDependency { dependency -> - // Downgrade SnakeYAML as Asciidoctor fails due to an incompatibility - // in the Pysch gem - if (dependency.requested.group.equals("org.yaml")) { - dependency.useVersion("1.33") - } - } - } - } + antoraContent } jar { @@ -53,16 +40,6 @@ plugins.withType(EclipsePlugin) { } dependencies { - actuatorApiDocumentation(project(path: ":spring-boot-project:spring-boot-actuator-autoconfigure", configuration: "documentation")) - - asciidoctorExtensions("io.spring.asciidoctor:spring-asciidoctor-extensions-spring-boot") - asciidoctorExtensions("io.spring.asciidoctor:spring-asciidoctor-extensions-section-ids") - asciidoctorExtensions(project(path: ":spring-boot-project:spring-boot-actuator-autoconfigure")) - asciidoctorExtensions(project(path: ":spring-boot-project:spring-boot-autoconfigure")) - asciidoctorExtensions(project(path: ":spring-boot-project:spring-boot-devtools")) - asciidoctorExtensions(project(path: ":spring-boot-project:spring-boot-docker-compose")) - asciidoctorExtensions(project(path: ":spring-boot-project:spring-boot-testcontainers")) - autoConfiguration(project(path: ":spring-boot-project:spring-boot-autoconfigure", configuration: "autoConfigurationMetadata")) autoConfiguration(project(path: ":spring-boot-project:spring-boot-actuator-autoconfigure", configuration: "autoConfigurationMetadata")) autoConfiguration(project(path: ":spring-boot-project:spring-boot-devtools", configuration: "autoConfigurationMetadata")) @@ -77,8 +54,6 @@ dependencies { configurationProperties(project(path: ":spring-boot-project:spring-boot-test-autoconfigure", configuration: "configurationPropertiesMetadata")) configurationProperties(project(path: ":spring-boot-project:spring-boot-testcontainers", configuration: "configurationPropertiesMetadata")) - gradlePluginDocumentation(project(path: ":spring-boot-project:spring-boot-tools:spring-boot-gradle-plugin", configuration: "documentation")) - implementation(project(path: ":spring-boot-project:spring-boot-actuator")) implementation(project(path: ":spring-boot-project:spring-boot-actuator-autoconfigure")) implementation(project(path: ":spring-boot-project:spring-boot-autoconfigure")) @@ -184,8 +159,6 @@ dependencies { implementation("org.junit.jupiter:junit-jupiter") implementation("org.yaml:snakeyaml") - mavenPluginDocumentation(project(path: ":spring-boot-project:spring-boot-tools:spring-boot-maven-plugin", configuration: "documentation")) - remoteSpringApplicationExample(platform(project(":spring-boot-project:spring-boot-dependencies"))) remoteSpringApplicationExample(project(":spring-boot-project:spring-boot-devtools")) remoteSpringApplicationExample(project(":spring-boot-project:spring-boot-starters:spring-boot-starter-logging")) @@ -194,6 +167,10 @@ dependencies { springApplicationExample(platform(project(":spring-boot-project:spring-boot-dependencies"))) springApplicationExample(project(path: ":spring-boot-project:spring-boot-starters:spring-boot-starter-web")) + antoraContent(project(path: ":spring-boot-project:spring-boot-actuator-autoconfigure", configuration: "antoraContent")) + antoraContent(project(path: ":spring-boot-project:spring-boot-tools:spring-boot-gradle-plugin", configuration: "antoraContent")) + antoraContent(project(path: ":spring-boot-project:spring-boot-tools:spring-boot-maven-plugin", configuration: "antoraContent")) + testImplementation(project(":spring-boot-project:spring-boot-actuator-autoconfigure")) testImplementation(project(":spring-boot-project:spring-boot-tools:spring-boot-test-support")) testImplementation("org.assertj:assertj-core") @@ -206,16 +183,14 @@ dependencies { testSlices(project(path: ":spring-boot-project:spring-boot-test-autoconfigure", configuration: "testSliceMetadata")) } -task dependencyVersions(type: org.springframework.boot.build.constraints.ExtractVersionConstraints) { - enforcedPlatform(":spring-boot-project:spring-boot-dependencies") -} - task aggregatedJavadoc(type: Javadoc) { dependsOn dependencyVersions project.rootProject.gradle.projectsEvaluated { Set publishedProjects = rootProject.subprojects.findAll { it != project } .findAll { it.plugins.hasPlugin(JavaPlugin) && it.plugins.hasPlugin(MavenPublishPlugin) } - .findAll { !it.path.contains(":spring-boot-tools:") } + .findAll { !it.path.contains(":spring-boot-tools:") || + it.path.contains(":spring-boot-tools:spring-boot-buildpack-platform") || + it.path.contains(":spring-boot-tools:spring-boot-loader-tools") } .findAll { !it.name.startsWith('spring-boot-starter') } dependsOn publishedProjects.javadoc source publishedProjects.javadoc.source @@ -247,33 +222,33 @@ task aggregatedJavadoc(type: Javadoc) { task documentTestSlices(type: org.springframework.boot.build.test.autoconfigure.DocumentTestSlices) { testSlices = configurations.testSlices - outputFile = file("${buildDir}/docs/generated/test-auto-configuration/documented-slices.adoc") + outputFile = file("${buildDir}/generated/docs/test-auto-configuration/documented-slices.adoc") } task documentStarters(type: org.springframework.boot.build.starters.DocumentStarters) { - outputDir = file("${buildDir}/docs/generated/using/starters/") + outputDir = file("${buildDir}/generated/docs/using/starters/") } task documentAutoConfigurationClasses(type: org.springframework.boot.build.autoconfigure.DocumentAutoConfigurationClasses) { autoConfiguration = configurations.autoConfiguration - outputDir = file("${buildDir}/docs/generated/auto-configuration-classes/documented-auto-configuration-classes/") + outputDir = file("${buildDir}/generated/docs/auto-configuration-classes/documented-auto-configuration-classes/") } -task documentDependencyVersions(type: org.springframework.boot.build.constraints.DocumentConstrainedVersions) { +task documentDependencyVersionCoordinates(type: org.springframework.boot.build.constraints.DocumentConstrainedVersions) { dependsOn dependencyVersions constrainedVersions.set(providers.provider { dependencyVersions.constrainedVersions }) - outputFile = file("${buildDir}/docs/generated/dependency-versions/documented-coordinates.adoc") + outputFile = file("${buildDir}/generated/docs/dependency-versions/documented-coordinates.adoc") } -task documentVersionProperties(type: org.springframework.boot.build.constraints.DocumentVersionProperties) { +task documentDependencyVersionProperties(type: org.springframework.boot.build.constraints.DocumentVersionProperties) { dependsOn dependencyVersions versionProperties.set(providers.provider { dependencyVersions.versionProperties}) - outputFile = file("${buildDir}/docs/generated/dependency-versions/documented-properties.adoc") + outputFile = file("${buildDir}/generated/docs/dependency-versions/documented-properties.adoc") } task documentConfigurationProperties(type: org.springframework.boot.build.context.properties.DocumentConfigurationProperties) { configurationPropertyMetadata = configurations.configurationProperties - outputDir = file("${buildDir}/docs/generated/") + outputDir = file("${buildDir}/generated/docs/application-properties") } task documentDevtoolsPropertyDefaults(type: org.springframework.boot.build.devtools.DocumentDevtoolsPropertyDefaults) {} @@ -306,203 +281,92 @@ task runLoggingFormatExample(type: org.springframework.boot.build.docs.Applicati normalizeTomcatPort() } -tasks.withType(org.asciidoctor.gradle.jvm.AbstractAsciidoctorTask) { - outputs.doNotCacheIf("This task uses log files as inputs which contain changing data (timestamp, pid)") { true } - dependsOn dependencyVersions - inputs.files(runRemoteSpringApplicationExample).withPropertyName("runRemoteSpringApplicationExample").withPathSensitivity(PathSensitivity.RELATIVE) - inputs.files(runSpringApplicationExample).withPropertyName("runSpringApplicationExample").withPathSensitivity(PathSensitivity.RELATIVE) - inputs.files(runLoggingFormatExample).withPropertyName("runLoggingFormatExample").withPathSensitivity(PathSensitivity.RELATIVE) - asciidoctorj { - fatalWarnings = ['^((?!successfully validated).)*$'] +def getRelativeExamplesPath(var outputs) { + def fileName = outputs.files.singleFile.name + 'example$example-output/' + fileName +} + +def antoraRootAggregateContent = tasks.register("antoraRootAggregateContent", Zip) { + destinationDirectory = layout.buildDirectory.dir('generated/docs/antora-content') + archiveClassifier = "root-aggregate-content" + from("src/main") { + into "modules/ROOT/examples" } - doFirst { - def versionConstraints = dependencyVersions.versionConstraints - def toAntoraVersion = version -> { - String formatted = version.split("\\.").take(2).join('.') - return version.endsWith("-SNAPSHOT") ? formatted + "-SNAPSHOT" : formatted + from(project.configurations.configurationProperties) { + eachFile { + it.path = it.file.toString() + .replaceFirst('/build/(?:classes|resources)/java/main/', '/') + .replaceFirst('^.*/([^/]+)/META-INF/(spring-configuration-metadata\\.json)$', 'modules/ROOT/partials/$1/$2') } - attributes "hibernate-version": versionConstraints["org.hibernate.orm:hibernate-core"].split("\\.").take(2).join('.'), - "jetty-version": versionConstraints["org.eclipse.jetty:jetty-server"], - "jooq-version": versionConstraints["org.jooq:jooq"], - "lettuce-version": versionConstraints["io.lettuce:lettuce-core"], - "native-build-tools-version": nativeBuildToolsVersion, - "spring-amqp-version": versionConstraints["org.springframework.amqp:spring-amqp"], - "spring-batch-version": versionConstraints["org.springframework.batch:spring-batch-core"], - "spring-batch-version-antora": toAntoraVersion(versionConstraints["org.springframework.batch:spring-batch-core"]), - "spring-boot-version": project.version, - "spring-data-commons-version": versionConstraints["org.springframework.data:spring-data-commons"], - "spring-data-couchbase-version": versionConstraints["org.springframework.data:spring-data-couchbase"], - "spring-data-jdbc-version": versionConstraints["org.springframework.data:spring-data-jdbc"], - "spring-data-jpa-version": versionConstraints["org.springframework.data:spring-data-jpa"], - "spring-data-mongodb-version": versionConstraints["org.springframework.data:spring-data-mongodb"], - "spring-data-neo4j-version": versionConstraints["org.springframework.data:spring-data-neo4j"], - "spring-data-r2dbc-version": versionConstraints["org.springframework.data:spring-data-r2dbc"], - "spring-data-rest-version": versionConstraints["org.springframework.data:spring-data-rest-core"], - "spring-framework-version": versionConstraints["org.springframework:spring-core"], - "spring-framework-version-antora": toAntoraVersion(versionConstraints["org.springframework:spring-core"]), - "spring-graphql-version-antora": toAntoraVersion(versionConstraints["org.springframework.graphql:spring-graphql"]), - "spring-integration-version-antora": toAntoraVersion(versionConstraints["org.springframework.integration:spring-integration-core"]), - "spring-kafka-version": versionConstraints["org.springframework.kafka:spring-kafka"], - "spring-pulsar-version": versionConstraints["org.springframework.pulsar:spring-pulsar"], - "spring-security-version-antora": toAntoraVersion(versionConstraints["org.springframework.security:spring-security-core"]), - "spring-authorization-server-version-antora": toAntoraVersion(versionConstraints["org.springframework.security:spring-security-oauth2-authorization-server"]), - "spring-webservices-version": versionConstraints["org.springframework.ws:spring-ws-core"], - "tomcat-version": tomcatVersion.split("\\.").take(2).join('.'), - "remote-spring-application-output": runRemoteSpringApplicationExample.outputs.files.singleFile, - "spring-application-output": runSpringApplicationExample.outputs.files.singleFile, - "logging-format-output": runLoggingFormatExample.outputs.files.singleFile + } + from(runRemoteSpringApplicationExample) { + into "modules/ROOT/examples" + } + from(documentDevtoolsPropertyDefaults) { + into "modules/ROOT/partials/propertydefaults" + } + from(documentStarters) { + into "modules/ROOT/partials/starters" + } + from(documentTestSlices) { + into "modules/appendix/partials/slices" + } + from(runSpringApplicationExample) { + into "modules/ROOT/partials/application" + } + from(runLoggingFormatExample) { + into "modules/ROOT/partials/logging" + } + from(documentDependencyVersionCoordinates) { + into "modules/appendix/partials/dependency-versions" + } + from(documentDependencyVersionProperties) { + into "modules/appendix/partials/dependency-versions" + } + from(documentAutoConfigurationClasses) { + into "modules/appendix/partials/auto-configuration-classes" + } + from(documentConfigurationProperties) { + into "modules/appendix/partials/configuration-properties" + } + from(tasks.getByName("generateAntoraYml")) { + into "modules" } } -asciidoctor { - sources { - include "*.singleadoc" - } -} - -task asciidoctorPdf(type: org.asciidoctor.gradle.jvm.AsciidoctorTask) { - sources { - include "*.singleadoc" - } -} - -task asciidoctorMultipage(type: org.asciidoctor.gradle.jvm.AsciidoctorTask) { - sources { - include "*.adoc" - } -} - -syncDocumentationSourceForAsciidoctor { - dependsOn documentTestSlices - dependsOn documentStarters - dependsOn documentAutoConfigurationClasses - dependsOn documentDependencyVersions - dependsOn documentVersionProperties - dependsOn documentConfigurationProperties - dependsOn documentDevtoolsPropertyDefaults - from("${buildDir}/docs/generated") { - into "asciidoc" - } - from("src/main/java") { - into "main/java" - } - from("src/test/java") { - into "test/java" - } - from("src/main/kotlin") { - into "main/kotlin" - } - from("src/main/groovy") { - into "main/groovy" - } - from("src/main/resources") { - into "main/resources" - } -} - -syncDocumentationSourceForAsciidoctorMultipage { - dependsOn documentTestSlices - dependsOn documentStarters - dependsOn documentAutoConfigurationClasses - dependsOn documentDependencyVersions - dependsOn documentVersionProperties - dependsOn documentConfigurationProperties - dependsOn documentDevtoolsPropertyDefaults - from("${buildDir}/docs/generated") { - into "asciidoc" - } - from("src/main/java") { - into "main/java" - } - from("src/test/java") { - into "test/java" - } - from("src/main/kotlin") { - into "main/kotlin" - } - from("src/main/groovy") { - into "main/groovy" - } - from("src/main/resources") { - into "main/resources" - } -} - -syncDocumentationSourceForAsciidoctorPdf { - dependsOn documentTestSlices - dependsOn documentStarters - dependsOn documentAutoConfigurationClasses - dependsOn documentDependencyVersions - dependsOn documentVersionProperties - dependsOn documentConfigurationProperties - dependsOn documentDevtoolsPropertyDefaults - from("${buildDir}/docs/generated") { - into "asciidoc" - } - from("src/main/java") { - into "main/java" - } - from("src/test/java") { - into "test/java" - } - from("src/main/kotlin") { - into "main/kotlin" - } - from("src/main/groovy") { - into "main/groovy" - } - from("src/main/resources") { - into "main/resources" - } -} - -task zip(type: Zip) { - dependsOn asciidoctor, - asciidoctorMultipage, - asciidoctorPdf, - configurations.gradlePluginDocumentation, - configurations.actuatorApiDocumentation, - configurations.mavenPluginDocumentation - duplicatesStrategy "fail" - from(asciidoctor.outputDir) { - into "reference/htmlsingle" - } - from(asciidoctorPdf.outputDir) { - into "reference/pdf" - include "index.pdf" - rename { "spring-boot-reference.pdf" } - } - from(asciidoctorMultipage.outputDir) { - into "reference/html" - } +def antoraApiCatalogContent = tasks.register("antoraApiCatalogContent", Zip) { + destinationDirectory = layout.buildDirectory.dir('generated/docs/antora-content') + archiveClassifier = "api-catalog-content" from(aggregatedJavadoc) { - into "api" - } - into("gradle-plugin") { - from { - zipTree(configurations.gradlePluginDocumentation.singleFile) - } - } - into("actuator-api") { - from { - zipTree(configurations.actuatorApiDocumentation.singleFile) - } - } - into("maven-plugin") { - from { - zipTree(configurations.mavenPluginDocumentation.singleFile) - } + into "java" } } -artifacts { - archives zip +def copyAntoraContentDependencies = tasks.register("copyAntoraContentDependencies", Copy) { + into layout.buildDirectory.dir('generated/docs/antora-dependencies-content') + from(configurations.antoraContent) + rename("spring-boot-actuator-autoconfigure", "spring-boot-docs") + rename("spring-boot-maven-plugin", "spring-boot-docs") + rename("spring-boot-gradle-plugin", "spring-boot-docs") +} + +tasks.named("antora") { + inputs.files(antoraRootAggregateContent, antoraApiCatalogContent, copyAntoraContentDependencies) +} + +gradle.projectsEvaluated { + def mavenPublication = publishing.publications.getByName("maven"); + configurations.antoraContent.dependencies.forEach { dependency -> + dependency.dependencyProject.configurations.getByName(dependency.targetConfiguration) + .artifacts.forEach(mavenPublication::artifact) + } } publishing { publications { - maven(MavenPublication) { - artifact zip + getByName("maven") { + artifact antoraRootAggregateContent + artifact antoraApiCatalogContent } } } diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/anchor-rewrite.properties b/spring-boot-project/spring-boot-docs/src/docs/antora/anchor-rewrite.properties similarity index 100% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/anchor-rewrite.properties rename to spring-boot-project/spring-boot-docs/src/docs/antora/anchor-rewrite.properties diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/antora.yml b/spring-boot-project/spring-boot-docs/src/docs/antora/antora.yml new file mode 100644 index 0000000000..c59291daa3 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/antora.yml @@ -0,0 +1,10 @@ +name: spring-boot +ext: + zip_contents_collector: + include: + - name: root + classifier: aggregate-content + - name: api + classifier: catalog-content + module: api + destination: content-catalog diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/attachments/.keep b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/attachments/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/examples/.keep b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/examples/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/images/.keep b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/images/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-help.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/pages/community.adoc similarity index 83% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-help.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/pages/community.adoc index 93c8cbdc82..75c66b6929 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-help.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/pages/community.adoc @@ -1,10 +1,9 @@ -[[getting-help]] -= Getting Help -include::attributes.adoc[] +:navicon: question += Community If you have trouble with Spring Boot, we would like to help. -* Try the <>. +* Try the xref:how-to:index.adoc[How-to documents]. They provide solutions to the most common questions. * Learn the Spring basics. Spring Boot builds on many other Spring projects. @@ -15,4 +14,4 @@ We monitor https://stackoverflow.com[stackoverflow.com] for questions tagged wit * Report bugs with Spring Boot at https://github.com/spring-projects/spring-boot/issues. NOTE: All of Spring Boot is open source, including the documentation. -If you find problems with the docs or if you want to improve them, please {spring-boot-code}[get involved]. +If you find problems with the docs or if you want to improve them, please {url-github}[get involved]. diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/pages/documentation.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/pages/documentation.adoc new file mode 100644 index 0000000000..f3573fb456 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/pages/documentation.adoc @@ -0,0 +1,156 @@ +:navtitle: Documentation +:navicon: book +[[documentation]] += Documentation Overview + +This section provides a brief overview of Spring Boot reference documentation. +It serves as a map for the rest of the document. + + + +[[documentation.first-steps]] +== First Steps + +If you are getting started with Spring Boot or 'Spring' in general, start with the following topics: + +* *From scratch:* xref:index.adoc[Overview] | xref:system-requirements.adoc[Requirements] | xref:installing.adoc[Installation] +* *Tutorial:* xref:tutorial:first-application/index.adoc[Part 1] | xref:tutorial:first-application/index.adoc#getting-started.first-application.code[Part 2] +* *Running your example:* xref:tutorial:first-application/index.adoc#getting-started.first-application.run[Part 1] | xref:tutorial:first-application/index.adoc#getting-started.first-application.executable-jar[Part 2] + + + +[[documentation.upgrading]] +== Upgrading From an Earlier Version + +You should always ensure that you are running a {url-github-wiki}/Supported-Versions[supported version] of Spring Boot. + +Depending on the version that you are upgrading to, you can find some additional tips here: + +* *From 1.x:* xref:upgrading.adoc#upgrading.from-1x[Upgrading from 1.x] +* *To a new feature release:* xref:upgrading.adoc#upgrading.to-feature[Upgrading to New Feature Release] +* *Spring Boot CLI:* xref:upgrading.adoc#upgrading.cli[Upgrading the Spring Boot CLI] + + + +[[documentation.using]] +== Developing With Spring Boot + +Ready to actually start using Spring Boot? xref:reference:using/index.adoc[We have you covered]: + +* *Build systems:* xref:reference:using/build-systems.adoc#using.build-systems.maven[Maven] | xref:reference:using/build-systems.adoc#using.build-systems.gradle[Gradle] | xref:reference:using/build-systems.adoc#using.build-systems.ant[Ant] | xref:reference:using/build-systems.adoc#using.build-systems.starters[Starters] +* *Best practices:* xref:reference:using/structuring-your-code.adoc[Code Structure] | xref:reference:using/configuration-classes.adoc[@Configuration] | xref:reference:using/auto-configuration.adoc[@EnableAutoConfiguration] | xref:reference:using/spring-beans-and-dependency-injection.adoc[Beans and Dependency Injection] +* *Running your code:* xref:reference:using/running-your-application.adoc#using.running-your-application.from-an-ide[IDE] | xref:reference:using/running-your-application.adoc#using.running-your-application.as-a-packaged-application[Packaged] | xref:reference:using/running-your-application.adoc#using.running-your-application.with-the-maven-plugin[Maven] | xref:reference:using/running-your-application.adoc#using.running-your-application.with-the-gradle-plugin[Gradle] +* *Packaging your app:* xref:reference:using/packaging-for-production.adoc[Production jars] +* *Spring Boot CLI:* xref:cli:index.adoc[Using the CLI] + + + +[[documentation.features]] +== Learning About Spring Boot Features + +Need more details about Spring Boot's core features? +xref:reference:features/index.adoc[The following content is for you]: + +* *Spring Application:* xref:reference:features/spring-application.adoc[SpringApplication] +* *External Configuration:* xref:reference:features/external-config.adoc[External Configuration] +* *Profiles:* xref:reference:features/profiles.adoc[Profiles] +* *Logging:* xref:reference:features/logging.adoc[Logging] + + + +[[documentation.web]] +== Web + +If you develop Spring Boot web applications, take a look at the following content: + +* *Servlet Web Applications:* xref:reference:web/servlet.adoc[Spring MVC, Jersey, Embedded Servlet Containers] +* *Reactive Web Applications:* xref:reference:web/reactive.adoc[Spring Webflux, Embedded Servlet Containers] +* *Graceful Shutdown:* xref:reference:web/graceful-shutdown.adoc[Graceful Shutdown] +* *Spring Security:* xref:reference:web/spring-security.adoc[Default Security Configuration, Auto-configuration for OAuth2, SAML] +* *Spring Session:* xref:reference:web/spring-session.adoc[Auto-configuration for Spring Session] +* *Spring HATEOAS:* xref:reference:web/spring-hateoas.adoc[Auto-configuration for Spring HATEOAS] + + + +[[documentation.data]] +== Data + +If your application deals with a datastore, you can see how to configure that here: + +* *SQL:* xref:reference:data/sql.adoc[Configuring a SQL Datastore, Embedded Database support, Connection pools, and more.] +* *NOSQL:* xref:reference:data/nosql.adoc[Auto-configuration for NOSQL stores such as Redis, MongoDB, Neo4j, and others.] + + + +[[documentation.messaging]] +== Messaging + +If your application uses any messaging protocol, see one or more of the following sections: + +* *JMS:* xref:reference:messaging/jms.adoc[Auto-configuration for ActiveMQ and Artemis, Sending and Receiving messages through JMS] +* *AMQP:* xref:reference:messaging/amqp.adoc[Auto-configuration for RabbitMQ] +* *Kafka:* xref:reference:messaging/kafka.adoc[Auto-configuration for Spring Kafka] +* *Pulsar:* xref:reference:messaging/pulsar.adoc[Auto-configuration for Spring for Apache Pulsar] +* *RSocket:* xref:reference:messaging/rsocket.adoc[Auto-configuration for Spring Framework's RSocket Support] +* *Spring Integration:* xref:reference:messaging/spring-integration.adoc[Auto-configuration for Spring Integration] + + + +[[documentation.io]] +== IO + +If your application needs IO capabilities, see one or more of the following sections: + +* *Caching:* xref:reference:io/caching.adoc[Caching support with EhCache, Hazelcast, Infinispan, and more] +* *Quartz:* xref:reference:io/quartz.adoc[Quartz Scheduling] +* *Mail:* xref:reference:io/email.adoc[Sending Email] +* *Validation:* xref:reference:io/validation.adoc[JSR-303 Validation] +* *REST Clients:* xref:reference:io/rest-client.adoc[Calling REST Services with RestTemplate and WebClient] +* *Webservices:* xref:reference:io/webservices.adoc[Auto-configuration for Spring Web Services] +* *JTA:* xref:reference:io/jta.adoc[Distributed Transactions with JTA] + + + +[[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:* xref:reference:container-images/efficient-images.adoc[Tips to optimize container images such as Docker images] +* *Dockerfiles:* xref:reference:container-images/dockerfiles.adoc[Building container images using dockerfiles] +* *Cloud Native Buildpacks:* xref:reference:container-images/cloud-native-buildpacks.adoc[Support for Cloud Native Buildpacks with Maven and Gradle] + + + +[[documentation.actuator]] +== Moving to Production + +When you are ready to push your Spring Boot application to production, we have xref:how-to:actuator.adoc[some tricks] that you might like: + +* *Management endpoints:* xref:reference:actuator/endpoints.adoc[Overview] +* *Connection options:* xref:reference:actuator/monitoring.adoc[HTTP] | xref:reference:actuator/jmx.adoc[JMX] +* *Monitoring:* xref:reference:actuator/metrics.adoc[Metrics] | xref:reference:actuator/auditing.adoc[Auditing] | xref:reference:actuator/http-exchanges.adoc[HTTP Exchanges] | xref:reference:actuator/process-monitoring.adoc[Process] + + + +[[documentation.native-images]] +== GraalVM Native Images + +Spring Boot applications can be converted into native executables using GraalVM. +You can read more about our native image support here: + +* *GraalVM Native Images:* xref:reference:native-image/introducing-graalvm-native-images.adoc[Introduction] | xref:reference:native-image/introducing-graalvm-native-images.adoc#native-image.introducing-graalvm-native-images.key-differences-with-jvm-deployments[Key Differences with the JVM] | xref:reference:native-image/introducing-graalvm-native-images.adoc#native-image.introducing-graalvm-native-images.understanding-aot-processing[Ahead-of-Time Processing] +* *Getting Started:* xref:reference:native-image/developing-your-first-application.adoc#native-image.developing-your-first-application.buildpacks[Buildpacks] | xref:reference:native-image/developing-your-first-application.adoc#native-image.developing-your-first-application.native-build-tools[Native Build Tools] +* *Testing:* xref:reference:native-image/testing-native-applications.adoc#native-image.testing.with-the-jvm[JVM] | xref:reference:native-image/testing-native-applications.adoc#native-image.testing.with-native-build-tools[Native Build Tools] +* *Advanced Topics:* xref:reference:native-image/advanced-topics.adoc#native-image.advanced.nested-configuration-properties[Nested Configuration Properties] | xref:reference:native-image/advanced-topics.adoc#native-image.advanced.converting-executable-jars[Converting JARs] | xref:reference:native-image/advanced-topics.adoc#native-image.advanced.known-limitations[Known Limitations] + + + +[[documentation.advanced]] +== Advanced Topics + +Finally, we have a few topics for more advanced users: + +* *Spring Boot Applications Deployment:* xref:reference:deployment/cloud.adoc[Cloud Deployment] | xref:reference:deployment/installing.adoc[OS Service] +* *Build tool plugins:* xref:maven-plugin:index.adoc[Maven] | xref:gradle-plugin:index.adoc[Gradle] +* *Appendix:* xref:appendix:application-properties/index.adoc[Application Properties] | xref:specification:configuration-metadata/index.adoc[Configuration Metadata] | xref:appendix:auto-configuration-classes/index.adoc[Auto-configuration Classes] | xref:appendix:test-auto-configuration/index.adoc[Test Auto-configuration Annotations] | xref:specification:executable-jar/index.adoc[Executable Jars] | xref:appendix:dependency-versions/index.adoc[Dependency Versions] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-started/introducing-spring-boot.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/pages/index.adoc similarity index 93% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-started/introducing-spring-boot.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/pages/index.adoc index 06602519fa..7cafb5cfaa 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-started/introducing-spring-boot.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/pages/index.adoc @@ -1,5 +1,7 @@ -[[getting-started.introducing-spring-boot]] -== Introducing Spring Boot +:navtitle: Overview +:navicon: home += Spring Boot + Spring Boot helps you to create stand-alone, production-grade Spring-based applications that you can run. We take an opinionated view of the Spring platform and third-party libraries, so that you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-started/installing.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/pages/installing.adoc similarity index 62% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-started/installing.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/pages/installing.adoc index 4c5d3cac36..5f85b42b08 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-started/installing.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/pages/installing.adoc @@ -1,21 +1,24 @@ +:navicon: gift [[getting-started.installing]] -== Installing Spring Boot += Installing Spring Boot + Spring Boot can be used with "`classic`" Java development tools or installed as a command line tool. Either way, you need https://www.java.com[Java SDK v17] or higher. Before you begin, you should check your current Java installation by using the following command: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ java -version +$ java -version ---- -If you are new to Java development or if you want to experiment with Spring Boot, you might want to try the <> (Command Line Interface) first. +If you are new to Java development or if you want to experiment with Spring Boot, you might want to try the xref:installing.adoc#getting-started.installing.cli[Spring Boot CLI] (Command Line Interface) first. Otherwise, read on for "`classic`" installation instructions. [[getting-started.installing.java]] -=== Installation Instructions for the Java Developer +== Installation Instructions for the Java Developer + You can use Spring Boot in the same way as any standard Java library. To do so, include the appropriate `+spring-boot-*.jar+` files on your classpath. Spring Boot does not require any special tools integration, so you can use any IDE or text editor. @@ -26,7 +29,8 @@ Although you _could_ copy Spring Boot jars, we generally recommend that you use [[getting-started.installing.java.maven]] -==== Maven Installation +=== Maven Installation + Spring Boot is compatible with Apache Maven 3.6.3 or later. If you do not already have Maven installed, you can follow the instructions at https://maven.apache.org. @@ -36,35 +40,37 @@ Ubuntu users can run `sudo apt-get install maven`. Windows users with https://chocolatey.org/[Chocolatey] can run `choco install maven` from an elevated (administrator) prompt. Spring Boot dependencies use the `org.springframework.boot` group id. -Typically, your Maven POM file inherits from the `spring-boot-starter-parent` project and declares dependencies to one or more <>. -Spring Boot also provides an optional <> to create executable jars. +Typically, your Maven POM file inherits from the `spring-boot-starter-parent` project and declares dependencies to one or more xref:reference:using/build-systems.adoc#using.build-systems.starters["`Starters`"]. +Spring Boot also provides an optional xref:maven-plugin:index.adoc[Maven plugin] to create executable jars. -More details on getting started with Spring Boot and Maven can be found in the {spring-boot-maven-plugin-docs}#getting-started[Getting Started section] of the Maven plugin's reference guide. +More details on getting started with Spring Boot and Maven can be found in the xref:maven-plugin:getting-started.adoc[Getting Started section] of the Maven plugin's reference guide. [[getting-started.installing.java.gradle]] -==== Gradle Installation +=== Gradle Installation + Spring Boot is compatible with Gradle 7.x (7.5 or later) and 8.x. If you do not already have Gradle installed, you can follow the instructions at https://gradle.org. Spring Boot dependencies can be declared by using the `org.springframework.boot` `group`. -Typically, your project declares dependencies to one or more <>. -Spring Boot provides a useful <> that can be used to simplify dependency declarations and to create executable jars. +Typically, your project declares dependencies to one or more xref:reference:using/build-systems.adoc#using.build-systems.starters["`Starters`"]. +Spring Boot provides a useful xref:gradle-plugin:index.adoc[Gradle plugin] that can be used to simplify dependency declarations and to create executable jars. .Gradle Wrapper **** The Gradle Wrapper provides a nice way of "`obtaining`" Gradle when you need to build a project. It is a small script and library that you commit alongside your code to bootstrap the build process. -See {gradle-docs}/gradle_wrapper.html for details. +See {url-gradle-docs}/gradle_wrapper.html for details. **** -More details on getting started with Spring Boot and Gradle can be found in the {spring-boot-gradle-plugin-docs}#getting-started[Getting Started section] of the Gradle plugin's reference guide. +More details on getting started with Spring Boot and Gradle can be found in the xref:gradle-plugin:getting-started.adoc[Getting Started section] of the Gradle plugin's reference guide. [[getting-started.installing.cli]] -=== Installing the Spring Boot CLI +== Installing the Spring Boot CLI + The Spring Boot CLI (Command Line Interface) is a command line tool that you can use to quickly prototype with Spring. You do not need to use the CLI to work with Spring Boot, but it is a quick way to get a Spring application off the ground without an IDE. @@ -72,44 +78,46 @@ You do not need to use the CLI to work with Spring Boot, but it is a quick way t [[getting-started.installing.cli.manual-installation]] -==== Manual Installation +=== Manual Installation + ifeval::["{artifact-release-type}" == "snapshot"] -You can download one of the `spring-boot-cli-\*-bin.zip` or `spring-boot-cli-*-bin.tar.gz` files from the {artifact-download-repo}/org/springframework/boot/spring-boot-cli/{spring-boot-version}/[Spring software repository]. +You can download one of the `spring-boot-cli-\*-bin.zip` or `spring-boot-cli-*-bin.tar.gz` files from the {url-artifact-repository}/org/springframework/boot/spring-boot-cli/{version-spring-boot}/[Spring software repository]. endif::[] ifeval::["{artifact-release-type}" != "snapshot"] You can download the Spring CLI distribution from one of the following locations: -* {artifact-download-repo}/org/springframework/boot/spring-boot-cli/{spring-boot-version}/spring-boot-cli-{spring-boot-version}-bin.zip[spring-boot-cli-{spring-boot-version}-bin.zip] -* {artifact-download-repo}/org/springframework/boot/spring-boot-cli/{spring-boot-version}/spring-boot-cli-{spring-boot-version}-bin.tar.gz[spring-boot-cli-{spring-boot-version}-bin.tar.gz] +* {url-artifact-repository}/org/springframework/boot/spring-boot-cli/{version-spring-boot}/spring-boot-cli-{version-spring-boot}-bin.zip[spring-boot-cli-{version-spring-boot}-bin.zip] +* {url-artifact-repository}/org/springframework/boot/spring-boot-cli/{version-spring-boot}/spring-boot-cli-{version-spring-boot}-bin.tar.gz[spring-boot-cli-{version-spring-boot}-bin.tar.gz] endif::[] -Once downloaded, follow the {github-raw}/spring-boot-project/spring-boot-tools/spring-boot-cli/src/main/content/INSTALL.txt[INSTALL.txt] instructions from the unpacked archive. +Once downloaded, follow the {url-github-raw}/spring-boot-project/spring-boot-tools/spring-boot-cli/src/main/content/INSTALL.txt[INSTALL.txt] instructions from the unpacked archive. In summary, there is a `spring` script (`spring.bat` for Windows) in a `bin/` directory in the `.zip` file. Alternatively, you can use `java -jar` with the `.jar` file (the script helps you to be sure that the classpath is set correctly). [[getting-started.installing.cli.sdkman]] -==== Installation with SDKMAN! +=== Installation with SDKMAN! + SDKMAN! (The Software Development Kit Manager) can be used for managing multiple versions of various binary SDKs, including Groovy and the Spring Boot CLI. Get SDKMAN! from https://sdkman.io and install Spring Boot by using the following commands: -[source,shell,indent=0,subs="verbatim,attributes"] +[source,shell,subs="verbatim,attributes"] ---- - $ sdk install springboot - $ spring --version - Spring CLI v{spring-boot-version} +$ sdk install springboot +$ spring --version +Spring CLI v{version-spring-boot} ---- If you develop features for the CLI and want access to the version you built, use the following commands: -[source,shell,indent=0,subs="verbatim,attributes"] +[source,shell,subs="verbatim,attributes"] ---- - $ sdk install springboot dev /path/to/spring-boot/spring-boot-cli/target/spring-boot-cli-{spring-boot-version}-bin/spring-{spring-boot-version}/ - $ sdk default springboot dev - $ spring --version - Spring CLI v{spring-boot-version} +$ sdk install springboot dev /path/to/spring-boot/spring-boot-cli/target/spring-boot-cli-{version-spring-boot}-bin/spring-{version-spring-boot}/ +$ sdk default springboot dev +$ spring --version +Spring CLI v{version-spring-boot} ---- The preceding instructions install a local instance of `spring` called the `dev` instance. @@ -117,33 +125,34 @@ It points at your target build location, so every time you rebuild Spring Boot, You can see it by running the following command: -[source,shell,indent=0,subs="verbatim,attributes"] +[source,shell,subs="verbatim,attributes"] ---- - $ sdk ls springboot +$ sdk ls springboot - ================================================================================ - Available Springboot Versions - ================================================================================ - > + dev - * {spring-boot-version} +================================================================================ +Available Springboot Versions +================================================================================ +> + dev +* {version-spring-boot} - ================================================================================ - + - local version - * - installed - > - currently in use - ================================================================================ +================================================================================ ++ - local version +* - installed +> - currently in use +================================================================================ ---- [[getting-started.installing.cli.homebrew]] -==== OSX Homebrew Installation +=== OSX Homebrew Installation + If you are on a Mac and use https://brew.sh/[Homebrew], you can install the Spring Boot CLI by using the following commands: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ brew tap spring-io/tap - $ brew install spring-boot +$ brew tap spring-io/tap +$ brew install spring-boot ---- Homebrew installs `spring` to `/usr/local/bin`. @@ -154,28 +163,30 @@ In that case, run `brew update` and try again. [[getting-started.installing.cli.macports]] -==== MacPorts Installation +=== MacPorts Installation + If you are on a Mac and use https://www.macports.org/[MacPorts], you can install the Spring Boot CLI by using the following command: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ sudo port install spring-boot-cli +$ sudo port install spring-boot-cli ---- [[getting-started.installing.cli.completion]] -==== Command-line Completion +=== Command-line Completion + The Spring Boot CLI includes scripts that provide command completion for the https://en.wikipedia.org/wiki/Bash_%28Unix_shell%29[BASH] and https://en.wikipedia.org/wiki/Z_shell[zsh] shells. You can `source` the script (also named `spring`) in any shell or put it in your personal or system-wide bash completion initialization. On a Debian system, the system-wide scripts are in `/shell-completion/bash` and all scripts in that directory are executed when a new shell starts. For example, to run the script manually if you have installed by using SDKMAN!, use the following commands: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ . ~/.sdkman/candidates/springboot/current/shell-completion/bash/spring - $ spring - grab help jar run test version +$ . ~/.sdkman/candidates/springboot/current/shell-completion/bash/spring +$ spring + grab help jar run test version ---- NOTE: If you install the Spring Boot CLI by using Homebrew or MacPorts, the command-line completion scripts are automatically registered with your shell. @@ -183,13 +194,14 @@ NOTE: If you install the Spring Boot CLI by using Homebrew or MacPorts, the comm [[getting-started.installing.cli.scoop]] -==== Windows Scoop Installation +=== Windows Scoop Installation + If you are on a Windows and use https://scoop.sh/[Scoop], you can install the Spring Boot CLI by using the following commands: -[indent=0] +[source,shell] ---- - > scoop bucket add extras - > scoop install springboot +$ scoop bucket add extras +$ scoop install springboot ---- Scoop installs `spring` to `~/scoop/apps/springboot/current/bin`. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-started/system-requirements.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/pages/system-requirements.adoc similarity index 68% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-started/system-requirements.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/pages/system-requirements.adoc index fb7208597a..3931e0b4d9 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-started/system-requirements.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/pages/system-requirements.adoc @@ -1,7 +1,9 @@ +:navicon: server [[getting-started.system-requirements]] -== System Requirements -Spring Boot {spring-boot-version} requires https://www.java.com[Java 17] and is compatible up to and including Java 21. -{spring-framework-docs}/[Spring Framework {spring-framework-version}] or above is also required. += System Requirements + +Spring Boot {version-spring-boot} requires https://www.java.com[Java 17] and is compatible up to and including Java 21. +{url-spring-framework-docs}/[Spring Framework {version-spring-framework}] or above is also required. Explicit build support is provided for the following build tools: @@ -18,7 +20,8 @@ Explicit build support is provided for the following build tools: [[getting-started.system-requirements.servlet-containers]] -=== Servlet Containers +== Servlet Containers + Spring Boot supports the following embedded servlet containers: |=== @@ -39,8 +42,9 @@ You can also deploy Spring Boot applications to any servlet 5.0+ compatible cont [[getting-started.system-requirements.graal]] -=== GraalVM Native Images -Spring Boot applications can be <> using GraalVM {graal-version} or above. +== GraalVM Native Images + +Spring Boot applications can be xref:reference:native-image/introducing-graalvm-native-images.adoc[converted into a Native Image] using GraalVM {version-graal} or above. Images can be created using the https://github.com/graalvm/native-build-tools[native build tools] Gradle/Maven plugins or `native-image` tool provided by GraalVM. You can also create native images using the https://github.com/paketo-buildpacks/native-image[native-image Paketo buildpack]. @@ -51,8 +55,8 @@ The following versions are supported: | Name | Version | GraalVM Community -| {graal-version} +| {version-graal} | Native Build Tools -| {native-build-tools-version} +| {version-native-build-tools} |=== diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/pages/upgrading.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/pages/upgrading.adoc new file mode 100644 index 0000000000..30874a2748 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/pages/upgrading.adoc @@ -0,0 +1,47 @@ +:navicon: rocket +[[upgrading]] += Upgrading Spring Boot + +Instructions for how to upgrade from earlier versions of Spring Boot are provided on the project {url-github-wiki}[wiki]. +Follow the links in the {url-github-wiki}#release-notes[release notes] section to find the version that you want to upgrade to. + +Upgrading instructions are always the first item in the release notes. +If you are more than one release behind, please make sure that you also review the release notes of the versions that you jumped. + + + +[[upgrading.from-1x]] +== Upgrading From 1.x + +If you are upgrading from the `1.x` release of Spring Boot, check the {url-github-wiki}/Spring-Boot-2.0-Migration-Guide["`migration guide`" on the project wiki] that provides detailed upgrade instructions. +Check also the {url-github-wiki}["`release notes`"] for a list of "`new and noteworthy`" features for each release. + + + +[[upgrading.to-feature]] +== Upgrading to a New Feature Release + +When upgrading to a new feature release, some properties may have been renamed or removed. +Spring Boot provides a way to analyze your application's environment and print diagnostics at startup, but also temporarily migrate properties at runtime for you. +To enable that feature, add the following dependency to your project: + +[source,xml] +---- + + org.springframework.boot + spring-boot-properties-migrator + runtime + +---- + +WARNING: Properties that are added late to the environment, such as when using `@PropertySource`, will not be taken into account. + +NOTE: Once you finish the migration, please make sure to remove this module from your project's dependencies. + + + +[[upgrading.cli]] +== Upgrading the Spring Boot CLI + +To upgrade an existing CLI installation, use the appropriate package manager command (for example, `brew upgrade`). +If you manually installed the CLI, follow the xref:installing.adoc#getting-started.installing.cli.manual-installation[standard instructions], remembering to update your `PATH` environment variable to remove any older references. diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/partials/nav-root.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/partials/nav-root.adoc new file mode 100644 index 0000000000..429990ca3b --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/ROOT/partials/nav-root.adoc @@ -0,0 +1,6 @@ +* xref:index.adoc[] +* xref:documentation.adoc[] +* xref:community.adoc[] +* xref:system-requirements.adoc[] +* xref:installing.adoc[] +* xref:upgrading.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/api/partials/nav-java-api.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/api/partials/nav-java-api.adoc new file mode 100644 index 0000000000..08b90ed301 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/api/partials/nav-java-api.adoc @@ -0,0 +1,4 @@ +* Java APIs +** xref:api:java/index.html[Spring Boot] +** xref:gradle-plugin:api/java/index.html[Gradle Plugin] +** xref:maven-plugin:api/java/index.html[Maven Plugin] diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/api/partials/nav-rest-api.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/api/partials/nav-rest-api.adoc new file mode 100644 index 0000000000..700b7b1f16 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/api/partials/nav-rest-api.adoc @@ -0,0 +1,5 @@ +* Rest APIs ++ +-- +include::api:partial$nav-actuator-rest-api.adoc[] +-- diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/application-properties/index.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/application-properties/index.adoc new file mode 100644 index 0000000000..42cb81f24b --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/application-properties/index.adoc @@ -0,0 +1,48 @@ +[appendix] +[[appendix.application-properties]] += Common Application Properties + +Various properties can be specified inside your `application.properties` file, inside your `application.yaml` file, or as command line switches. +This appendix provides a list of common Spring Boot properties and references to the underlying classes that consume them. + +TIP: Spring Boot provides various conversion mechanism with advanced value formatting, make sure to review xref:reference:features/external-config.adoc#features.external-config.typesafe-configuration-properties.conversion[the properties conversion section]. + +NOTE: Property contributions can come from additional jar files on your classpath, so you should not consider this an exhaustive list. +Also, you can define your own properties. + + +include::partial$configuration-properties/core.adoc[] + +include::partial$configuration-properties/cache.adoc[] + +include::partial$configuration-properties/mail.adoc[] + +include::partial$configuration-properties/json.adoc[] + +include::partial$configuration-properties/data.adoc[] + +include::partial$configuration-properties/transaction.adoc[] + +include::partial$configuration-properties/data-migration.adoc[] + +include::partial$configuration-properties/integration.adoc[] + +include::partial$configuration-properties/web.adoc[] + +include::partial$configuration-properties/templating.adoc[] + +include::partial$configuration-properties/server.adoc[] + +include::partial$configuration-properties/security.adoc[] + +include::partial$configuration-properties/rsocket.adoc[] + +include::partial$configuration-properties/actuator.adoc[] + +include::partial$configuration-properties/devtools.adoc[] + +include::partial$configuration-properties/docker-compose.adoc[] + +include::partial$configuration-properties/testcontainers.adoc[] + +include::partial$configuration-properties/testing.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/auto-configuration-classes/actuator.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/auto-configuration-classes/actuator.adoc similarity index 53% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/auto-configuration-classes/actuator.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/auto-configuration-classes/actuator.adoc index 517465ea7b..620c7ea698 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/auto-configuration-classes/actuator.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/auto-configuration-classes/actuator.adoc @@ -1,5 +1,6 @@ [[appendix.auto-configuration-classes.actuator]] -== spring-boot-actuator-autoconfigure += spring-boot-actuator-autoconfigure + The following auto-configuration classes are from the `spring-boot-actuator-autoconfigure` module: -include::documented-auto-configuration-classes/spring-boot-actuator-autoconfigure.adoc[] +include::partial$/auto-configuration-classes/spring-boot-actuator-autoconfigure.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/auto-configuration-classes/core.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/auto-configuration-classes/core.adoc similarity index 55% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/auto-configuration-classes/core.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/auto-configuration-classes/core.adoc index 0b70c76a13..53ec8859ad 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/auto-configuration-classes/core.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/auto-configuration-classes/core.adoc @@ -1,5 +1,6 @@ [[appendix.auto-configuration-classes.core]] -== spring-boot-autoconfigure += spring-boot-autoconfigure + The following auto-configuration classes are from the `spring-boot-autoconfigure` module: -include::documented-auto-configuration-classes/spring-boot-autoconfigure.adoc[] +include::partial$/auto-configuration-classes/spring-boot-autoconfigure.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/auto-configuration-classes.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/auto-configuration-classes/index.adoc similarity index 77% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/auto-configuration-classes.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/auto-configuration-classes/index.adoc index 13252737c0..3da7db1122 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/auto-configuration-classes.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/auto-configuration-classes/index.adoc @@ -1,16 +1,7 @@ [appendix] [[appendix.auto-configuration-classes]] = Auto-configuration Classes -include::attributes.adoc[] - - This appendix contains details of all of the auto-configuration classes provided by Spring Boot, with links to documentation and source code. Remember to also look at the conditions report in your application for more details of which features are switched on. (To do so, start the app with `--debug` or `-Ddebug` or, in an Actuator application, use the `conditions` endpoint). - - - -include::auto-configuration-classes/core.adoc[] - -include::auto-configuration-classes/actuator.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/dependency-versions/coordinates.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/dependency-versions/coordinates.adoc similarity index 78% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/dependency-versions/coordinates.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/dependency-versions/coordinates.adoc index 1643a9a6c2..59b1e389e0 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/dependency-versions/coordinates.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/dependency-versions/coordinates.adoc @@ -1,7 +1,7 @@ [[appendix.dependency-versions.coordinates]] -== Managed Dependency Coordinates += Managed Dependency Coordinates The following table provides details of all of the dependency versions that are provided by Spring Boot in its CLI (Command Line Interface), Maven dependency management, and Gradle plugin. When you declare a dependency on one of these artifacts without declaring a version, the version listed in the table is used. -include::documented-coordinates.adoc[] +include::partial$dependency-versions/documented-coordinates.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/dependency-versions.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/dependency-versions/index.adoc similarity index 54% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/dependency-versions.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/dependency-versions/index.adoc index c2ca180dea..163a205875 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/dependency-versions.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/dependency-versions/index.adoc @@ -1,14 +1,5 @@ [appendix] [[appendix.dependency-versions]] = Dependency Versions -include::attributes.adoc[] - - This appendix provides details of the dependencies that are managed by Spring Boot. - - - -include::dependency-versions/coordinates.adoc[] - -include::dependency-versions/properties.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/dependency-versions/properties.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/dependency-versions/properties.adoc similarity index 58% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/dependency-versions/properties.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/dependency-versions/properties.adoc index 5d89329176..eab2e1439f 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/dependency-versions/properties.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/dependency-versions/properties.adoc @@ -1,8 +1,8 @@ [[appendix.dependency-versions.properties]] -== Version Properties += Version Properties The following table provides all properties that can be used to override the versions managed by Spring Boot. -Browse the {spring-boot-code}/spring-boot-project/spring-boot-dependencies/build.gradle[`spring-boot-dependencies` build.gradle] for a complete list of dependencies. -You can learn how to customize these versions in your application in the <>. +Browse the {code-spring-boot}/spring-boot-project/spring-boot-dependencies/build.gradle[`spring-boot-dependencies` build.gradle] for a complete list of dependencies. +You can learn how to customize these versions in your application in the xref:build-tool-plugin:index.adoc[Build Tool Plugins documentation]. -include::documented-properties.adoc[] +include::partial$dependency-versions/documented-properties.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/test-auto-configuration.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/test-auto-configuration/index.adoc similarity index 73% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/test-auto-configuration.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/test-auto-configuration/index.adoc index 23b985725e..cc72fa03fc 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/test-auto-configuration.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/test-auto-configuration/index.adoc @@ -1,12 +1,5 @@ [appendix] [[appendix.test-auto-configuration]] = Test Auto-configuration Annotations -include::attributes.adoc[] - - This appendix describes the `@...Test` auto-configuration annotations that Spring Boot provides to test slices of your application. - - - -include::test-auto-configuration/slices.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/test-auto-configuration/slices.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/test-auto-configuration/slices.adoc similarity index 77% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/test-auto-configuration/slices.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/test-auto-configuration/slices.adoc index 298de249c5..3303e1087c 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/test-auto-configuration/slices.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/pages/test-auto-configuration/slices.adoc @@ -1,6 +1,6 @@ [[appendix.test-auto-configuration.slices]] -== Test Slices += Test Slices The following table lists the various `@...Test` annotations that can be used to test slices of your application and the auto-configuration that they import by default: -include::documented-slices.adoc[] +include::partial$slices/documented-slices.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/partials/nav-appendix.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/partials/nav-appendix.adoc new file mode 100644 index 0000000000..564da76c9c --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/appendix/partials/nav-appendix.adoc @@ -0,0 +1,13 @@ +* Appendix + +** xref:appendix:application-properties/index.adoc[] +** xref:appendix:auto-configuration-classes/index.adoc[] +*** xref:appendix:auto-configuration-classes/core.adoc[] +*** xref:appendix:auto-configuration-classes/actuator.adoc[] + +** xref:appendix:test-auto-configuration/index.adoc[] +*** xref:appendix:test-auto-configuration/slices.adoc[] + +** xref:appendix:dependency-versions/index.adoc[] +*** xref:appendix:dependency-versions/coordinates.adoc[] +*** xref:appendix:dependency-versions/properties.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/build-tool-plugins/antlib.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/build-tool-plugin/pages/antlib.adoc similarity index 54% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/build-tool-plugins/antlib.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/build-tool-plugin/pages/antlib.adoc index a7be882b6b..1774bfe2c4 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/build-tool-plugins/antlib.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/build-tool-plugin/pages/antlib.adoc @@ -1,40 +1,43 @@ [[build-tool-plugins.antlib]] -== Spring Boot AntLib Module += Spring Boot AntLib Module + The Spring Boot AntLib module provides basic Spring Boot support for Apache Ant. You can use the module to create executable jars. To use the module, you need to declare an additional `spring-boot` namespace in your `build.xml`, as shown in the following example: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - ... - + + ... + ---- You need to remember to start Ant using the `-lib` option, as shown in the following example: -[source,shell,indent=0,subs="verbatim,attributes"] +[source,shell,subs="verbatim,attributes"] ---- - $ ant -lib +$ ant -lib ---- -TIP: The "`Using Spring Boot`" section includes a more complete example of <>. +TIP: The "`Using Spring Boot`" section includes a more complete example of xref:reference:using/build-systems.adoc#using.build-systems.ant[using Apache Ant with `spring-boot-antlib`]. [[build-tool-plugins.antlib.tasks]] -=== Spring Boot Ant Tasks +== Spring Boot Ant Tasks + Once the `spring-boot-antlib` namespace has been declared, the following additional tasks are available: -* <> -* <> +* xref:antlib.adoc#build-tool-plugins.antlib.tasks.exejar[Using the "`exejar`" Task] +* xref:antlib.adoc#build-tool-plugins.antlib.findmainclass[Using the "`findmainclass`" Task] [[build-tool-plugins.antlib.tasks.exejar]] -==== Using the "`exejar`" Task +=== Using the "`exejar`" Task + You can use the `exejar` task to create a Spring Boot executable jar. The following attributes are supported by the task: @@ -62,46 +65,48 @@ The following nested elements can be used with the task: | Element | Description | `resources` -| One or more {ant-docs}/Types/resources.html#collection[Resource Collections] describing a set of {ant-docs}/Types/resources.html[Resources] that should be added to the content of the created +jar+ file. +| One or more {url-ant-docs}/Types/resources.html#collection[Resource Collections] describing a set of {url-ant-docs}/Types/resources.html[Resources] that should be added to the content of the created +jar+ file. | `lib` -| One or more {ant-docs}/Types/resources.html#collection[Resource Collections] that should be added to the set of jar libraries that make up the runtime dependency classpath of the application. +| One or more {url-ant-docs}/Types/resources.html#collection[Resource Collections] that should be added to the set of jar libraries that make up the runtime dependency classpath of the application. |==== [[build-tool-plugins.antlib.tasks.examples]] -==== Examples +=== Examples + This section shows two examples of Ant tasks. .Specify +start-class+ -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - - - - - - - + + + + + + + + ---- .Detect +start-class+ -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - - - - + + + + + ---- [[build-tool-plugins.antlib.findmainclass]] -=== Using the "`findmainclass`" Task +== Using the "`findmainclass`" Task + The `findmainclass` task is used internally by `exejar` to locate a class declaring a `main`. If necessary, you can also use this task directly in your build. The following attributes are supported: @@ -126,23 +131,24 @@ The following attributes are supported: [[build-tool-plugins.antlib.findmainclass.examples]] -==== Examples +=== Examples + This section contains three examples of using `findmainclass`. .Find and log -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - + ---- .Find and set -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - + ---- .Override and set -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - + ---- diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/build-tool-plugin/pages/index.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/build-tool-plugin/pages/index.adoc new file mode 100644 index 0000000000..5c5ab0a817 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/build-tool-plugin/pages/index.adoc @@ -0,0 +1,8 @@ +[[build-tool-plugins]] += Build Tool Plugins + +Spring Boot provides build tool plugins for Maven and Gradle. +The plugins offer a variety of features, including the packaging of executable jars. +This section provides more details on both plugins as well as some help should you need to extend an unsupported build system. +If you are just getting started, you might want to read "`xref:reference:using/build-systems.adoc[Build Systems]`" from the "`xref:reference:using/index.adoc[Developing with Spring Boot]`" section first. + diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/build-tool-plugins/other-build-systems.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/build-tool-plugin/pages/other-build-systems.adoc similarity index 84% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/build-tool-plugins/other-build-systems.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/build-tool-plugin/pages/other-build-systems.adoc index 749778376d..28b718fcf5 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/build-tool-plugins/other-build-systems.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/build-tool-plugin/pages/other-build-systems.adoc @@ -1,7 +1,8 @@ [[build-tool-plugins.other-build-systems]] -== Supporting Other Build Systems += Supporting Other Build Systems + If you want to use a build tool other than Maven, Gradle, or Ant, you likely need to develop your own plugin. -Executable jars need to follow a specific format and certain entries need to be written in an uncompressed form (see the "`<>`" section in the appendix for details). +Executable jars need to follow a specific format and certain entries need to be written in an uncompressed form (see the "`xref:specification:/executable-jar/index.adoc[executable jar format]`" section in the appendix for details). The Spring Boot Maven and Gradle plugins both make use of `spring-boot-loader-tools` to actually generate jars. If you need to, you may use this library directly. @@ -9,7 +10,8 @@ If you need to, you may use this library directly. [[build-tool-plugins.other-build-systems.repackaging-archives]] -=== Repackaging Archives +== Repackaging Archives + To repackage an existing archive so that it becomes a self-contained executable archive, use `org.springframework.boot.loader.tools.Repackager`. The `Repackager` class takes a single constructor argument that refers to an existing jar or war archive. Use one of the two available `repackage()` methods to either replace the original file or write to a new destination. @@ -18,7 +20,8 @@ Various settings can also be configured on the repackager before it is run. [[build-tool-plugins.other-build-systems.nested-libraries]] -=== Nested Libraries +== Nested Libraries + When repackaging an archive, you can include references to dependency files by using the `org.springframework.boot.loader.tools.Libraries` interface. We do not provide any concrete implementations of `Libraries` here as they are usually build-system-specific. @@ -27,14 +30,16 @@ If your archive already includes libraries, you can use `Libraries.NONE`. [[build-tool-plugins.other-build-systems.finding-main-class]] -=== Finding a Main Class +== Finding a Main Class + If you do not use `Repackager.setMainClass()` to specify a main class, the repackager uses https://asm.ow2.io/[ASM] to read class files and tries to find a suitable class with a `public static void main(String[] args)` method. An exception is thrown if more than one candidate is found. [[build-tool-plugins.other-build-systems.example-repackage-implementation]] -=== Example Repackage Implementation +== Example Repackage Implementation + The following example shows a typical repackage implementation: -include::code:MyBuildTool[] +include-code::MyBuildTool[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/build-tool-plugin/partials/nav-build-tool-plugin.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/build-tool-plugin/partials/nav-build-tool-plugin.adoc new file mode 100644 index 0000000000..dd2706c108 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/build-tool-plugin/partials/nav-build-tool-plugin.adoc @@ -0,0 +1,11 @@ +* xref:build-tool-plugin:index.adoc[] ++ +-- +include::maven-plugin:partial$nav-maven-plugin.adoc[] +-- ++ +-- +include::gradle-plugin:partial$nav-gradle-plugin.adoc[] +-- +** xref:build-tool-plugin:antlib.adoc[] +** xref:build-tool-plugin:other-build-systems.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/cli.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/cli/pages/index.adoc similarity index 62% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/cli.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/cli/pages/index.adoc index fbf719066c..f30483a158 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/cli.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/cli/pages/index.adoc @@ -1,12 +1,5 @@ [[cli]] = Spring Boot CLI -include::attributes.adoc[] - The Spring Boot CLI is a command line tool that you can use to bootstrap a new project from https://start.spring.io or encode a password. - - -include::cli/installation.adoc[] - -include::cli/using-the-cli.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/cli/pages/installation.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/cli/pages/installation.adoc new file mode 100644 index 0000000000..d61508e6a0 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/cli/pages/installation.adoc @@ -0,0 +1,5 @@ +[[cli.installation]] += Installing the CLI + +The Spring Boot CLI (Command-Line Interface) can be installed manually by using SDKMAN! (the SDK Manager) or by using Homebrew or MacPorts if you are an OSX user. +See xref:ROOT:installing.adoc#getting-started.installing.cli[_Installing the Spring Boot CLI_] in the "`Getting started`" section for comprehensive installation instructions. diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/cli/pages/using-the-cli.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/cli/pages/using-the-cli.adoc new file mode 100644 index 0000000000..9204522d3b --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/cli/pages/using-the-cli.adoc @@ -0,0 +1,177 @@ +[[cli.using-the-cli]] += Using the CLI + +Once you have installed the CLI, you can run it by typing `spring` and pressing Enter at the command line. +If you run `spring` without any arguments, a help screen is displayed, as follows: + +[source,shell] +---- +$ spring +usage: spring [--help] [--version] + [] + +Available commands are: + + init [options] [location] + Initialize a new project using Spring Initializr (start.spring.io) + + encodepassword [options] + Encode a password for use with Spring Security + + shell + Start a nested shell + +Common options: + + --debug Verbose mode + Print additional status information for the command you are running + + +See 'spring help ' for more information on a specific command. +---- + +You can type `spring help` to get more details about any of the supported commands, as shown in the following example: + +[source,shell] +---- +$ spring help init +spring init - Initialize a new project using Spring Initializr (start.spring.io) + +usage: spring init [options] [location] + +Option Description +------ ----------- +-a, --artifact-id Project coordinates; infer archive name (for + example 'test') +-b, --boot-version Spring Boot version (for example '1.2.0.RELEASE') +--build Build system to use (for example 'maven' or + 'gradle') (default: maven) +-d, --dependencies Comma-separated list of dependency identifiers to + include in the generated project +--description Project description +-f, --force Force overwrite of existing files +--format Format of the generated content (for example + 'build' for a build file, 'project' for a + project archive) (default: project) +-g, --group-id Project coordinates (for example 'org.test') +-j, --java-version Language level (for example '1.8') +-l, --language Programming language (for example 'java') +--list List the capabilities of the service. Use it to + discover the dependencies and the types that are + available +-n, --name Project name; infer application name +-p, --packaging Project packaging (for example 'jar') +--package-name Package name +-t, --type Project type. Not normally needed if you use -- + build and/or --format. Check the capabilities of + the service (--list) for more details +--target URL of the service to use (default: https://start. + spring.io) +-v, --version Project version (for example '0.0.1-SNAPSHOT') +-x, --extract Extract the project archive. Inferred if a + location is specified without an extension + +examples: + + To list all the capabilities of the service: + $ spring init --list + + To creates a default project: + $ spring init + + To create a web my-app.zip: + $ spring init -d=web my-app.zip + + To create a web/data-jpa gradle project unpacked: + $ spring init -d=web,jpa --build=gradle my-dir +---- + +The `version` command provides a quick way to check which version of Spring Boot you are using, as follows: + +[source,shell,subs="verbatim,attributes"] +---- +$ spring version +Spring CLI v{version-spring-boot} +---- + + + +[[cli.using-the-cli.initialize-new-project]] +== Initialize a New Project + +The `init` command lets you create a new project by using https://start.spring.io without leaving the shell, as shown in the following example: + +[source,shell] +---- +$ spring init --dependencies=web,data-jpa my-project +Using service at https://start.spring.io +Project extracted to '/Users/developer/example/my-project' +---- + +The preceding example creates a `my-project` directory with a Maven-based project that uses `spring-boot-starter-web` and `spring-boot-starter-data-jpa`. +You can list the capabilities of the service by using the `--list` flag, as shown in the following example: + +[source,shell] +---- +$ spring init --list +======================================= +Capabilities of https://start.spring.io +======================================= + +Available dependencies: +----------------------- +actuator - Actuator: Production ready features to help you monitor and manage your application +... +web - Web: Support for full-stack web development, including Tomcat and spring-webmvc +websocket - Websocket: Support for WebSocket development +ws - WS: Support for Spring Web Services + +Available project types: +------------------------ +gradle-build - Gradle Config [format:build, build:gradle] +gradle-project - Gradle Project [format:project, build:gradle] +maven-build - Maven POM [format:build, build:maven] +maven-project - Maven Project [format:project, build:maven] (default) + +... +---- + +The `init` command supports many options. +See the `help` output for more details. +For instance, the following command creates a Gradle project that uses Java 17 and `war` packaging: + +[source,shell] +---- +$ spring init --build=gradle --java-version=17 --dependencies=websocket --packaging=war sample-app.zip +Using service at https://start.spring.io +Content saved to 'sample-app.zip' +---- + + + +[[cli.using-the-cli.embedded-shell]] +== Using the Embedded Shell + +Spring Boot includes command-line completion scripts for the BASH and zsh shells. +If you do not use either of these shells (perhaps you are a Windows user), you can use the `shell` command to launch an integrated shell, as shown in the following example: + +[source,shell,subs="verbatim,quotes,attributes"] +---- +$ spring shell +*Spring Boot* (v{version-spring-boot}) +Hit TAB to complete. Type \'help' and hit RETURN for help, and \'exit' to quit. +---- + +From inside the embedded shell, you can run other commands directly: + +[source,shell,subs="verbatim,attributes"] +---- +$ version +Spring CLI v{version-spring-boot} +---- + +The embedded shell supports ANSI color output as well as `tab` completion. +If you need to run a native command, you can use the `!` prefix. +To exit the embedded shell, press `ctrl-c`. + + diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/cli/partials/nav-cli.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/cli/partials/nav-cli.adoc new file mode 100644 index 0000000000..b24e0fcf00 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/cli/partials/nav-cli.adoc @@ -0,0 +1,4 @@ +* xref:cli:index.adoc[] + +** xref:cli:installation.adoc[] +** xref:cli:using-the-cli.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/actuator.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/actuator.adoc similarity index 76% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/actuator.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/actuator.adoc index 7c0c993eb7..0f41887464 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/actuator.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/actuator.adoc @@ -1,22 +1,25 @@ [[howto.actuator]] -== Actuator += Actuator + Spring Boot includes the Spring Boot Actuator. This section answers questions that often arise from its use. [[howto.actuator.change-http-port-or-address]] -=== Change the HTTP Port or Address of the Actuator Endpoints +== Change the HTTP Port or Address of the Actuator Endpoints + In a standalone application, the Actuator HTTP port defaults to the same as the main HTTP port. To make the application listen on a different port, set the external property: configprop:management.server.port[]. To listen on a completely different network address (such as when you have an internal network for management and an external one for user applications), you can also set `management.server.address` to a valid IP address to which the server is able to bind. -For more detail, see the {spring-boot-actuator-autoconfigure-module-code}/web/server/ManagementServerProperties.java[`ManagementServerProperties`] source code and "`<>`" in the "`Production-ready features`" section. +For more detail, see the {code-spring-boot-actuator-autoconfigure-src}/web/server/ManagementServerProperties.java[`ManagementServerProperties`] source code and "`xref:reference:actuator/monitoring.adoc#actuator.monitoring.customizing-management-server-port[Customizing the Management Server Port]`" in the "`Production-ready features`" section. [[howto.actuator.customize-whitelabel-error-page]] -=== Customize the '`whitelabel`' Error Page +== Customize the '`whitelabel`' Error Page + Spring Boot installs a '`whitelabel`' error page that you see in a browser client if you encounter a server error (machine clients consuming JSON and other media types should see a sensible response with the right error code). NOTE: Set `server.error.whitelabel.enabled=false` to switch the default error page off. @@ -28,14 +31,15 @@ For example, if you use Thymeleaf, you can add an `error.html` template. If you use FreeMarker, you can add an `error.ftlh` template. In general, you need a `View` that resolves with a name of `error` or a `@Controller` that handles the `/error` path. Unless you replaced some of the default configuration, you should find a `BeanNameViewResolver` in your `ApplicationContext`, so a `@Bean` named `error` would be one way of doing that. -See {spring-boot-autoconfigure-module-code}/web/servlet/error/ErrorMvcAutoConfiguration.java[`ErrorMvcAutoConfiguration`] for more options. +See {code-spring-boot-autoconfigure-src}/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 "`xref:reference:web/servlet.adoc#web.servlet.spring-mvc.error-handling[Error Handling]`" for details of how to register handlers in the servlet container. [[howto.actuator.customizing-sanitization]] -=== Customizing Sanitization +== Customizing Sanitization + To take control over the sanitization, define a `SanitizingFunction` bean. The `SanitizableData` with which the function is called provides access to the key and value as well as the `PropertySource` from which they came. This allows you to, for example, sanitize every value that comes from a particular property source. @@ -44,7 +48,8 @@ Each `SanitizingFunction` is called in order until a function changes the value [[howto.actuator.map-health-indicators-to-metrics]] -=== Map Health Indicators to Micrometer Metrics +== Map Health Indicators to Micrometer Metrics + Spring Boot health indicators return a `Status` type to indicate the overall system health. If you want to monitor or alert on levels of health for a particular application, you can export these statuses as metrics with Micrometer. By default, the status codes "`UP`", "`DOWN`", "`OUT_OF_SERVICE`" and "`UNKNOWN`" are used by Spring Boot. @@ -52,4 +57,4 @@ To export these, you will need to convert these states to some set of numbers so The following example shows one way to write such an exporter: -include::code:MyHealthMetricsExportConfiguration[] +include-code::MyHealthMetricsExportConfiguration[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/aot.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/aot.adoc new file mode 100644 index 0000000000..f6e217e949 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/aot.adoc @@ -0,0 +1,55 @@ +[[howto.aot]] += Ahead-of-time processing + +A number of questions often arise when people use the ahead-of-time processing of Spring Boot applications. +This section addresses those questions. + + + +[[howto.aot.conditions]] +== Conditions + +Ahead-of-time processing optimizes the application and evaluates {url-spring-framework-javadoc}/org/springframework/context/annotation/Conditional.html[conditions] based on the environment at build time. +xref:reference:features/profiles.adoc[Profiles] are implemented through conditions and are therefore affected, too. + +If you want beans that are created based on a condition in an ahead-of-time optimized application, you have to set up the environment when building the application. +The beans which are created while ahead-of-time processing at build time are then always created when running the application and can't be switched off. +To do this, you can set the profiles which should be used when building the application. + +For Maven, this works by setting the `profiles` configuration of the `spring-boot-maven-plugin:process-aot` execution: + +[source,xml] +---- + + native + + + + + org.springframework.boot + spring-boot-maven-plugin + + + process-aot + + profile-a,profile-b + + + + + + + + +---- + +For Gradle, you need to configure the `ProcessAot` task: + +[source,gradle] +---- +tasks.withType(org.springframework.boot.gradle.tasks.aot.ProcessAot).configureEach { + args('--spring.profiles.active=profile-a,profile-b') +} +---- + +Profiles which only change configuration properties that don't influence conditions are supported without limitations when running ahead-of-time optimized applications. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/application.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/application.adoc similarity index 80% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/application.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/application.adoc index 946efc45c3..1500bee78e 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/application.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/application.adoc @@ -1,12 +1,14 @@ [[howto.application]] -== Spring Boot Application += Spring Boot Application + This section includes topics relating directly to Spring Boot applications. [[howto.application.failure-analyzer]] -=== Create Your Own FailureAnalyzer -{spring-boot-module-api}/diagnostics/FailureAnalyzer.html[`FailureAnalyzer`] is a great way to intercept an exception on startup and turn it into a human-readable message, wrapped in a {spring-boot-module-api}/diagnostics/FailureAnalysis.html[`FailureAnalysis`]. +== Create Your Own FailureAnalyzer + +xref:api:java/org/springframework/boot/diagnostics/FailureAnalyzer.html[`FailureAnalyzer`] is a great way to intercept an exception on startup and turn it into a human-readable message, wrapped in a xref:api:java/org/springframework/boot/diagnostics/FailureAnalysis.html[`FailureAnalysis`]. Spring Boot provides such an analyzer for application-context-related exceptions, JSR-303 validations, and more. You can also create your own. @@ -17,10 +19,10 @@ If, for whatever reason, you cannot handle the exception, return `null` to give `FailureAnalyzer` implementations must be registered in `META-INF/spring.factories`. The following example registers `ProjectConstraintViolationFailureAnalyzer`: -[source,properties,indent=0,subs="verbatim"] +[source,properties] ---- - org.springframework.boot.diagnostics.FailureAnalyzer=\ - com.example.ProjectConstraintViolationFailureAnalyzer +org.springframework.boot.diagnostics.FailureAnalyzer=\ +com.example.ProjectConstraintViolationFailureAnalyzer ---- NOTE: If you need access to the `BeanFactory` or the `Environment`, declare them as constructor arguments in your `FailureAnalyzer` implementation. @@ -28,12 +30,13 @@ NOTE: If you need access to the `BeanFactory` or the `Environment`, declare them [[howto.application.troubleshoot-auto-configuration]] -=== Troubleshoot Auto-configuration +== Troubleshoot Auto-configuration + The Spring Boot auto-configuration tries its best to "`do the right thing`", but sometimes things fail, and it can be hard to tell why. There is a really useful `ConditionEvaluationReport` available in any Spring Boot `ApplicationContext`. You can see it if you enable `DEBUG` logging output. -If you use the `spring-boot-actuator` (see <>), there is also a `conditions` endpoint that renders the report in JSON. +If you use the `spring-boot-actuator` (see xref:actuator.adoc[the Actuator chapter]), there is also a `conditions` endpoint that renders the report in JSON. Use that endpoint to debug the application and see what features have been added (and which have not been added) by Spring Boot at runtime. Many more questions can be answered by looking at the source code and the Javadoc. @@ -43,7 +46,7 @@ When reading the code, remember the following rules of thumb: Pay special attention to the `+@Conditional*+` annotations to find out what features they enable and when. Add `--debug` to the command line or a System property `-Ddebug` to get a log on the console of all the auto-configuration decisions that were made in your app. In a running application with actuator enabled, look at the `conditions` endpoint (`/actuator/conditions` or the JMX equivalent) for the same information. -* Look for classes that are `@ConfigurationProperties` (such as {spring-boot-autoconfigure-module-code}/web/ServerProperties.java[`ServerProperties`]) and read from there the available external configuration options. +* Look for classes that are `@ConfigurationProperties` (such as {code-spring-boot-autoconfigure-src}/web/ServerProperties.java[`ServerProperties`]) and read from there the available external configuration options. The `@ConfigurationProperties` annotation has a `name` attribute that acts as a prefix to external properties. Thus, `ServerProperties` has `prefix="server"` and its configuration properties are `server.port`, `server.address`, and others. In a running application with actuator enabled, look at the `configprops` endpoint. @@ -55,7 +58,8 @@ When reading the code, remember the following rules of thumb: [[howto.application.customize-the-environment-or-application-context]] -=== Customize the Environment or ApplicationContext Before It Starts +== Customize the Environment or ApplicationContext Before It Starts + A `SpringApplication` has `ApplicationListeners` and `ApplicationContextInitializers` that are used to apply customizations to the context or environment. Spring Boot loads a number of such customizations for use internally from `META-INF/spring.factories`. There is more than one way to register additional customizations: @@ -64,20 +68,20 @@ There is more than one way to register additional customizations: * Declaratively, for all applications, by adding a `META-INF/spring.factories` and packaging a jar file that the applications all use as a library. The `SpringApplication` sends some special `ApplicationEvents` to the listeners (some even before the context is created) and then registers the listeners for events published by the `ApplicationContext` as well. -See "`<>`" in the '`Spring Boot features`' section for a complete list. +See "`xref:reference:features/spring-application.adoc#features.spring-application.application-events-and-listeners[Application Events and Listeners]`" in the '`Spring Boot features`' section for a complete list. It is also possible to customize the `Environment` before the application context is refreshed by using `EnvironmentPostProcessor`. Each implementation should be registered in `META-INF/spring.factories`, as shown in the following example: -[indent=0] +[source] ---- - org.springframework.boot.env.EnvironmentPostProcessor=com.example.YourEnvironmentPostProcessor +org.springframework.boot.env.EnvironmentPostProcessor=com.example.YourEnvironmentPostProcessor ---- The implementation can load arbitrary files and add them to the `Environment`. For instance, the following example loads a YAML configuration file from the classpath: -include::code:MyEnvironmentPostProcessor[] +include-code::MyEnvironmentPostProcessor[] TIP: The `Environment` has already been prepared with all the usual property sources that Spring Boot loads by default. It is therefore possible to get the location of the file from the environment. @@ -91,14 +95,16 @@ This is too late to configure certain properties such as `+logging.*+` and `+spr [[howto.application.context-hierarchy]] -=== Build an ApplicationContext Hierarchy (Adding a Parent or Root Context) +== Build an ApplicationContext Hierarchy (Adding a Parent or Root Context) + You can use the `ApplicationBuilder` class to create parent/child `ApplicationContext` hierarchies. -See "`<>`" in the '`Spring Boot features`' section for more information. +See "`xref:reference:features/spring-application.adoc#features.spring-application.fluent-builder-api[Fluent Builder API]`" in the '`Spring Boot features`' section for more information. [[howto.application.non-web-application]] -=== Create a Non-web Application +== Create a Non-web Application + Not all Spring applications have to be web applications (or web services). If you want to execute some code in a `main` method but also bootstrap a Spring application to set up the infrastructure to use, you can use the `SpringApplication` features of Spring Boot. A `SpringApplication` changes its `ApplicationContext` class, depending on whether it thinks it needs a web application or not. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/batch.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/batch.adoc similarity index 60% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/batch.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/batch.adoc index ef4e8b90f7..c0eac086b1 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/batch.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/batch.adoc @@ -1,61 +1,66 @@ [[howto.batch]] -== Batch Applications += Batch Applications + A number of questions often arise when people use Spring Batch from within a Spring Boot application. This section addresses those questions. [[howto.batch.specifying-a-data-source]] -=== Specifying a Batch Data Source +== Specifying a Batch Data Source + By default, batch applications require a `DataSource` to store job details. Spring Batch expects a single `DataSource` by default. To have it use a `DataSource` other than the application’s main `DataSource`, declare a `DataSource` bean, annotating its `@Bean` method with `@BatchDataSource`. If you do so and want two data sources, remember to mark the other one `@Primary`. To take greater control, add `@EnableBatchProcessing` to one of your `@Configuration` classes or extend `DefaultBatchConfiguration`. -See the Javadoc of {spring-batch-api}/core/configuration/annotation/EnableBatchProcessing.html[`@EnableBatchProcessing`] -and {spring-batch-api}/core/configuration/support/DefaultBatchConfiguration.html[`DefaultBatchConfiguration`] for more details. +See the Javadoc of {url-spring-batch-javadoc}/core/configuration/annotation/EnableBatchProcessing.html[`@EnableBatchProcessing`] +and {url-spring-batch-javadoc}/core/configuration/support/DefaultBatchConfiguration.html[`DefaultBatchConfiguration`] for more details. -For more info about Spring Batch, see the {spring-batch}[Spring Batch project page]. +For more info about Spring Batch, see the {url-spring-batch-site}[Spring Batch project page]. [[howto.batch.specifying-a-transaction-manager]] -=== Specifying a Batch Transaction Manager -Similar to <>, you can define a `PlatformTransactionManager` for use in the batch processing by marking it as `@BatchTransactionManager`. +== Specifying a Batch Transaction Manager + +Similar to xref:batch.adoc#howto.batch.specifying-a-data-source[Specifying a Batch Data Source], you can define a `PlatformTransactionManager` for use in the batch processing by marking it as `@BatchTransactionManager`. If you do so and want two transaction managers, remember to mark the other one as `@Primary`. [[howto.batch.running-jobs-on-startup]] -=== Running Spring Batch Jobs on Startup +== Running Spring Batch Jobs on Startup + Spring Batch auto-configuration is enabled by adding `spring-boot-starter-batch` to your application's classpath. -If a single `Job` bean is found in the application context, it is executed on startup (see {spring-boot-autoconfigure-module-code}/batch/JobLauncherApplicationRunner.java[`JobLauncherApplicationRunner`] for details). +If a single `Job` bean is found in the application context, it is executed on startup (see {code-spring-boot-autoconfigure-src}/batch/JobLauncherApplicationRunner.java[`JobLauncherApplicationRunner`] for details). If multiple `Job` beans are found, the job that should be executed must be specified using configprop:spring.batch.job.name[]. To disable running a `Job` found in the application context, set the configprop:spring.batch.job.enabled[] to `false`. -See {spring-boot-autoconfigure-module-code}/batch/BatchAutoConfiguration.java[BatchAutoConfiguration] for more details. +See {code-spring-boot-autoconfigure-src}/batch/BatchAutoConfiguration.java[BatchAutoConfiguration] for more details. [[howto.batch.running-from-the-command-line]] -=== Running From the Command Line -Spring Boot converts any command line argument starting with `--` to a property to add to the `Environment`, see <>. +== Running From the Command Line + +Spring Boot converts any command line argument starting with `--` to a property to add to the `Environment`, see xref:reference:features/external-config.adoc#features.external-config.command-line-args[accessing command line properties]. This should not be used to pass arguments to batch jobs. To specify batch arguments on the command line, use the regular format (that is without `--`), as shown in the following example: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ java -jar myapp.jar someParameter=someValue anotherParameter=anotherValue +$ java -jar myapp.jar someParameter=someValue anotherParameter=anotherValue ---- If you specify a property of the `Environment` on the command line, it is ignored by the job. Consider the following command: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ java -jar myapp.jar --server.port=7070 someParameter=someValue +$ java -jar myapp.jar --server.port=7070 someParameter=someValue ---- This provides only one argument to the batch job: `someParameter=someValue`. @@ -63,7 +68,8 @@ This provides only one argument to the batch job: `someParameter=someValue`. [[howto.batch.restarting-a-failed-job]] -=== Restarting a stopped or failed Job +== Restarting a stopped or failed Job + To restart a failed `Job`, all parameters (identifying and non-identifying) must be re-specified on the command line. Non-identifying parameters are *not* copied from the previous execution. This allows them to be modified or removed. @@ -73,7 +79,8 @@ NOTE: When you're using a custom `JobParametersIncrementer`, you have to gather [[howto.batch.storing-job-repository]] -=== Storing the Job Repository +== Storing the Job Repository + Spring Batch requires a data store for the `Job` repository. If you use Spring Boot, you must use an actual database. -Note that it can be an in-memory database, see {spring-batch-docs}/job.html#configuringJobRepository[Configuring a Job Repository]. +Note that it can be an in-memory database, see {url-spring-batch-docs}/job.html#configuringJobRepository[Configuring a Job Repository]. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/build.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/build.adoc similarity index 56% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/build.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/build.adoc index cfae774a95..8b7b7acb01 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/build.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/build.adoc @@ -1,79 +1,82 @@ [[howto.build]] -== Build += Build + Spring Boot includes build plugins for Maven and Gradle. This section answers common questions about these plugins. [[howto.build.generate-info]] -=== Generate Build Information +== Generate Build Information + Both the Maven plugin and the Gradle plugin allow generating build information containing the coordinates, name, and version of the project. The plugins can also be configured to add additional properties through configuration. When such a file is present, Spring Boot auto-configures a `BuildProperties` bean. To generate build information with Maven, add an execution for the `build-info` goal, as shown in the following example: -[source,xml,indent=0,subs="verbatim,attributes"] +[source,xml,subs="verbatim,attributes"] ---- - - - - org.springframework.boot - spring-boot-maven-plugin - {spring-boot-version} - - - - build-info - - - - - - + + + + org.springframework.boot + spring-boot-maven-plugin + {version-spring-boot} + + + + build-info + + + + + + ---- -TIP: See the {spring-boot-maven-plugin-docs}#goals-build-info[Spring Boot Maven Plugin documentation] for more details. +TIP: See the xref:maven-plugin:build-info.adoc[Spring Boot Maven Plugin documentation] for more details. The following example does the same with Gradle: -[source,gradle,indent=0,subs="verbatim"] +[source,gradle] ---- - springBoot { - buildInfo() - } +springBoot { + buildInfo() +} ---- -TIP: See the {spring-boot-gradle-plugin-docs}#integrating-with-actuator-build-info[Spring Boot Gradle Plugin documentation] for more details. +TIP: See the xref:gradle-plugin:integrating-with-actuator.adoc[Spring Boot Gradle Plugin documentation] for more details. [[howto.build.generate-git-info]] -=== Generate Git Information +== Generate Git Information + Both Maven and Gradle allow generating a `git.properties` file containing information about the state of your `git` source code repository when the project was built. For Maven users, the `spring-boot-starter-parent` POM includes a pre-configured plugin to generate a `git.properties` file. To use it, add the following declaration for the https://github.com/git-commit-id/git-commit-id-maven-plugin[`Git Commit Id Plugin`] to your POM: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - - - io.github.git-commit-id - git-commit-id-maven-plugin - - - + + + + io.github.git-commit-id + git-commit-id-maven-plugin + + + ---- Gradle users can achieve the same result by using the https://plugins.gradle.org/plugin/com.gorylenko.gradle-git-properties[`gradle-git-properties`] plugin, as shown in the following example: -[source,gradle,indent=0,subs="verbatim"] +[source,gradle] ---- - plugins { - id "com.gorylenko.gradle-git-properties" version "2.4.1" - } +plugins { + id "com.gorylenko.gradle-git-properties" version "2.4.1" +} ---- Both the Maven and Gradle plugins allow the properties that are included in `git.properties` to be configured. @@ -85,71 +88,74 @@ Using this format lets the time be parsed into a `Date` and its format, when ser [[howto.build.customize-dependency-versions]] -=== Customize Dependency Versions +== Customize Dependency Versions + The `spring-boot-dependencies` POM manages the versions of common dependencies. The Spring Boot plugins for Maven and Gradle allow these managed dependency versions to be customized using build properties. WARNING: Each Spring Boot release is designed and tested against this specific set of third-party dependencies. Overriding versions may cause compatibility issues. -To override dependency versions with Maven, see {spring-boot-maven-plugin-docs}#using[this section] of the Maven plugin's documentation. +To override dependency versions with Maven, see xref:maven-plugin:using.adoc[this section] of the Maven plugin's documentation. -To override dependency versions in Gradle, see {spring-boot-gradle-plugin-docs}#managing-dependencies-dependency-management-plugin-customizing[this section] of the Gradle plugin's documentation. +To override dependency versions in Gradle, see xref:gradle-plugin:managing-dependencies.adoc#managing-dependencies.dependency-management-plugin.customizing[this section] of the Gradle plugin's documentation. [[howto.build.create-an-executable-jar-with-maven]] -=== Create an Executable JAR with Maven +== Create an Executable JAR with Maven + The `spring-boot-maven-plugin` can be used to create an executable "`fat`" JAR. If you use the `spring-boot-starter-parent` POM, you can declare the plugin and your jars are repackaged as follows: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - - - org.springframework.boot - spring-boot-maven-plugin - - - + + + + org.springframework.boot + spring-boot-maven-plugin + + + ---- If you do not use the parent POM, you can still use the plugin. However, you must additionally add an `` section, as follows: -[source,xml,indent=0,subs="verbatim,attributes"] +[source,xml,subs="verbatim,attributes"] ---- - - - - org.springframework.boot - spring-boot-maven-plugin - {spring-boot-version} - - - - repackage - - - - - - + + + + org.springframework.boot + spring-boot-maven-plugin + {version-spring-boot} + + + + repackage + + + + + + ---- -See the {spring-boot-maven-plugin-docs}#repackage[plugin documentation] for full usage details. +See the xref:maven-plugin:packaging.adoc#packaging.repackage-goal[plugin documentation] for full usage details. [[howto.build.use-a-spring-boot-application-as-dependency]] -=== Use a Spring Boot Application as a Dependency +== Use a Spring Boot Application as a Dependency + Like a war file, a Spring Boot application is not intended to be used as a dependency. If your application contains classes that you want to share with other projects, the recommended approach is to move that code into a separate module. The separate module can then be depended upon by your application and other projects. If you cannot rearrange your code as recommended above, Spring Boot's Maven and Gradle plugins must be configured to produce a separate artifact that is suitable for use as a dependency. -The executable archive cannot be used as a dependency as the <> packages application classes in `BOOT-INF/classes`. +The executable archive cannot be used as a dependency as the xref:specification:executable-jar/nested-jars.adoc#appendix.executable-jar.nested-jars.jar-structure[executable jar format] packages application classes in `BOOT-INF/classes`. This means that they cannot be found when the executable jar is used as a dependency. To produce the two artifacts, one that can be used as a dependency and one that is executable, a classifier must be specified. @@ -157,25 +163,26 @@ This classifier is applied to the name of the executable archive, leaving the de To configure a classifier of `exec` in Maven, you can use the following configuration: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - - - org.springframework.boot - spring-boot-maven-plugin - - exec - - - - + + + + org.springframework.boot + spring-boot-maven-plugin + + exec + + + + ---- [[howto.build.extract-specific-libraries-when-an-executable-jar-runs]] -=== Extract Specific Libraries When an Executable Jar Runs +== Extract Specific Libraries When an Executable Jar Runs + Most nested libraries in an executable jar do not need to be unpacked in order to run. However, certain libraries can have problems. For example, JRuby includes its own nested jar support, which assumes that the `jruby-complete.jar` is always directly available as a file in its own right. @@ -187,77 +194,80 @@ WARNING: Care should be taken to ensure that your operating system is configured For example, to indicate that JRuby should be flagged for unpacking by using the Maven Plugin, you would add the following configuration: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - - - org.springframework.boot - spring-boot-maven-plugin - - - - org.jruby - jruby-complete - - - - - - + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.jruby + jruby-complete + + + + + + ---- [[howto.build.create-a-nonexecutable-jar]] -=== Create a Non-executable JAR with Exclusions +== Create a Non-executable JAR with Exclusions + Often, if you have an executable and a non-executable jar as two separate build products, the executable version has additional configuration files that are not needed in a library jar. For example, the `application.yaml` configuration file might be excluded from the non-executable JAR. In Maven, the executable jar must be the main artifact and you can add a classified jar for the library, as follows: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - - - org.springframework.boot - spring-boot-maven-plugin - - - maven-jar-plugin - - - lib - package - - jar - - - lib - - application.yaml - - - - - - - + + + + org.springframework.boot + spring-boot-maven-plugin + + + maven-jar-plugin + + + lib + package + + jar + + + lib + + application.yaml + + + + + + + ---- [[howto.build.remote-debug-maven]] -=== Remote Debug a Spring Boot Application Started with Maven -To attach a remote debugger to a Spring Boot application that was started with Maven, you can use the `jvmArguments` property of the {spring-boot-maven-plugin-docs}[maven plugin]. +== Remote Debug a Spring Boot Application Started with Maven -See {spring-boot-maven-plugin-docs}#run-example-debug[this example] for more details. +To attach a remote debugger to a Spring Boot application that was started with Maven, you can use the `jvmArguments` property of the xref:maven-plugin:index.adoc[maven plugin]. + +See xref:maven-plugin:run.adoc#run.examples.debug[this example] for more details. [[howto.build.build-an-executable-archive-with-ant-without-using-spring-boot-antlib]] -=== Build an Executable Archive From Ant without Using spring-boot-antlib +== Build an Executable Archive From Ant without Using spring-boot-antlib + To build with Ant, you need to grab dependencies, compile, and then create a jar or war archive. To make it executable, you can either use the `spring-boot-antlib` module or you can follow these instructions: @@ -272,27 +282,27 @@ To make it executable, you can either use the `spring-boot-antlib` module or you The following example shows how to build an executable archive with Ant: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + ---- 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/antora/modules/how-to/pages/data-access.adoc similarity index 76% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/data-access.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/data-access.adoc index 5c5894d837..c491d74f9f 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/data-access.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/data-access.adoc @@ -1,29 +1,31 @@ [[howto.data-access]] -== Data Access += Data Access + Spring Boot includes a number of starters for working with data sources. This section answers questions related to doing so. [[howto.data-access.configure-custom-datasource]] -=== Configure a Custom DataSource +== Configure a Custom DataSource + To configure your own `DataSource`, define a `@Bean` of that type in your configuration. Spring Boot reuses your `DataSource` anywhere one is required, including database initialization. -If you need to externalize some settings, you can bind your `DataSource` to the environment (see "`<>`"). +If you need to externalize some settings, you can bind your `DataSource` to the environment (see "`xref:reference:features/external-config.adoc#features.external-config.typesafe-configuration-properties.third-party-configuration[Third-party Configuration]`"). The following example shows how to define a data source in a bean: -include::code:custom/MyDataSourceConfiguration[] +include-code::custom/MyDataSourceConfiguration[] The following example shows how to define a data source by setting properties: -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops%novalidate,yaml] ---- - app: - datasource: - url: "jdbc:h2:mem:mydb" - username: "sa" - pool-size: 30 +app: + datasource: + url: "jdbc:h2:mem:mydb" + username: "sa" + pool-size: 30 ---- Assuming that `SomeDataSource` has regular JavaBean properties for the URL, the username, and the pool size, these settings are bound automatically before the `DataSource` is made available to other components. @@ -34,7 +36,7 @@ It also auto-detects the driver based on the JDBC URL. The following example shows how to create a data source by using a `DataSourceBuilder`: -include::code:builder/MyDataSourceConfiguration[] +include-code::builder/MyDataSourceConfiguration[] To run an app with that `DataSource`, all you need is the connection information. Pool-specific settings can also be provided. @@ -42,14 +44,14 @@ Check the implementation that is going to be used at runtime for more details. The following example shows how to define a JDBC data source by setting properties: -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops%novalidate,yaml] ---- - app: - datasource: - url: "jdbc:mysql://localhost/test" - username: "dbuser" - password: "dbpass" - pool-size: 30 +app: + datasource: + url: "jdbc:mysql://localhost/test" + username: "dbuser" + password: "dbpass" + pool-size: 30 ---- However, there is a catch. @@ -57,14 +59,14 @@ Because the actual type of the connection pool is not exposed, no keys are gener Also, if you happen to have Hikari on the classpath, this basic setup does not work, because Hikari has no `url` property (but does have a `jdbcUrl` property). In that case, you must rewrite your configuration as follows: -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops%novalidate,yaml] ---- - app: - datasource: - jdbc-url: "jdbc:mysql://localhost/test" - username: "dbuser" - password: "dbpass" - pool-size: 30 +app: + datasource: + jdbc-url: "jdbc:mysql://localhost/test" + username: "dbuser" + password: "dbpass" + pool-size: 30 ---- You can fix that by forcing the connection pool to use and return a dedicated implementation rather than `DataSource`. @@ -72,27 +74,27 @@ You cannot change the implementation at runtime, but the list of options will be The following example shows how create a `HikariDataSource` with `DataSourceBuilder`: -include::code:simple/MyDataSourceConfiguration[] +include-code::simple/MyDataSourceConfiguration[] You can even go further by leveraging what `DataSourceProperties` does for you -- that is, by providing a default embedded database with a sensible username and password if no URL is provided. You can easily initialize a `DataSourceBuilder` from the state of any `DataSourceProperties` object, so you could also inject the DataSource that Spring Boot creates automatically. However, that would split your configuration into two namespaces: `url`, `username`, `password`, `type`, and `driver` on `spring.datasource` and the rest on your custom namespace (`app.datasource`). To avoid that, you can redefine a custom `DataSourceProperties` on your custom namespace, as shown in the following example: -include::code:configurable/MyDataSourceConfiguration[] +include-code::configurable/MyDataSourceConfiguration[] This setup puts you _in sync_ with what Spring Boot does for you by default, except that a dedicated connection pool is chosen (in code) and its settings are exposed in the `app.datasource.configuration` sub namespace. Because `DataSourceProperties` is taking care of the `url`/`jdbcUrl` translation for you, you can configure it as follows: -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops%novalidate,yaml] ---- - app: - datasource: - url: "jdbc:mysql://localhost/test" - username: "dbuser" - password: "dbpass" - configuration: - maximum-pool-size: 30 +app: + datasource: + url: "jdbc:mysql://localhost/test" + username: "dbuser" + password: "dbpass" + configuration: + maximum-pool-size: 30 ---- TIP: Spring Boot will expose Hikari-specific settings to `spring.datasource.hikari`. @@ -101,46 +103,47 @@ 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 "`xref:reference:data/sql.adoc#data.sql.datasource[Configure a DataSource]`" in the "`Spring Boot features`" section and the {code-spring-boot-autoconfigure-src}/jdbc/DataSourceAutoConfiguration.java[`DataSourceAutoConfiguration`] class for more details. [[howto.data-access.configure-two-datasources]] -=== Configure Two DataSources +== Configure Two DataSources + If you need to configure multiple data sources, you can apply the same tricks that are described in the previous section. You must, however, mark one of the `DataSource` instances as `@Primary`, because various auto-configurations down the road expect to be able to get one by type. If you create your own `DataSource`, the auto-configuration backs off. In the following example, we provide the _exact_ same feature set as the auto-configuration provides on the primary data source: -include::code:MyDataSourcesConfiguration[] +include-code::MyDataSourcesConfiguration[] TIP: `firstDataSourceProperties` has to be flagged as `@Primary` so that the database initializer feature uses your copy (if you use the initializer). Both data sources are also bound for advanced customizations. For instance, you could configure them as follows: -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops%novalidate,yaml] ---- - app: - datasource: - first: - url: "jdbc:mysql://localhost/first" - username: "dbuser" - password: "dbpass" - configuration: - maximum-pool-size: 30 +app: + datasource: + first: + url: "jdbc:mysql://localhost/first" + username: "dbuser" + password: "dbpass" + configuration: + maximum-pool-size: 30 - second: - url: "jdbc:mysql://localhost/second" - username: "dbuser" - password: "dbpass" - max-total: 30 + second: + url: "jdbc:mysql://localhost/second" + username: "dbuser" + password: "dbpass" + max-total: 30 ---- You can apply the same concept to the secondary `DataSource` as well, as shown in the following example: -include::code:MyCompleteDataSourcesConfiguration[] +include-code::MyCompleteDataSourcesConfiguration[] The preceding example configures two data sources on custom namespaces with the same logic as Spring Boot would use in auto-configuration. Note that each `configuration` sub namespace provides advanced settings based on the chosen implementation. @@ -148,32 +151,35 @@ Note that each `configuration` sub namespace provides advanced settings based on [[howto.data-access.spring-data-repositories]] -=== Use Spring Data Repositories +== Use Spring Data Repositories + Spring Data can create implementations of `@Repository` interfaces of various flavors. -Spring Boot handles all of that for you, as long as those `@Repository` annotations are included in one of the <>, typically the package (or a sub-package) of your main application class that is annotated with `@SpringBootApplication` or `@EnableAutoConfiguration`. +Spring Boot handles all of that for you, as long as those `@Repository` annotations are included in one of the xref:reference:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages], typically the package (or a sub-package) of your main application class that is annotated with `@SpringBootApplication` or `@EnableAutoConfiguration`. For many applications, all you need is to put the right Spring Data dependencies on your classpath. There is a `spring-boot-starter-data-jpa` for JPA, `spring-boot-starter-data-mongodb` for Mongodb, and various other starters for supported technologies. To get started, create some repository interfaces to handle your `@Entity` objects. -Spring Boot determines the location of your `@Repository` definitions by scanning the <>. +Spring Boot determines the location of your `@Repository` definitions by scanning the xref:reference:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages]. For more control, use the `@Enable…Repositories` annotations from Spring Data. -For more about Spring Data, see the {spring-data}[Spring Data project page]. +For more about Spring Data, see the {url-spring-data-site}[Spring Data project page]. [[howto.data-access.separate-entity-definitions-from-spring-configuration]] -=== Separate @Entity Definitions from Spring Configuration -Spring Boot determines the location of your `@Entity` definitions by scanning the <>. +== Separate @Entity Definitions from Spring Configuration + +Spring Boot determines the location of your `@Entity` definitions by scanning the xref:reference:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages]. For more control, use the `@EntityScan` annotation, as shown in the following example: -include::code:MyApplication[] +include-code::MyApplication[] [[howto.data-access.jpa-properties]] -=== Configure JPA Properties +== Configure JPA Properties + Spring Data JPA already provides some vendor-independent configuration options (such as those for SQL logging), and Spring Boot exposes those options and a few more for Hibernate as external configuration properties. Some of them are automatically detected according to the context so you should not have to set them. @@ -186,14 +192,14 @@ If you prefer to set the dialect yourself, set the configprop:spring.jpa.databas The most common options to set are shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - jpa: - hibernate: - naming: - physical-strategy: "com.example.MyPhysicalNamingStrategy" - show-sql: true +spring: + jpa: + hibernate: + naming: + physical-strategy: "com.example.MyPhysicalNamingStrategy" + show-sql: true ---- In addition, all properties in `+spring.jpa.properties.*+` are passed through as normal JPA properties (with the prefix stripped) when the local `EntityManagerFactory` is created. @@ -213,8 +219,9 @@ This takes precedence to anything that is applied by the auto-configuration. [[howto.data-access.configure-hibernate-naming-strategy]] -=== Configure Hibernate Naming Strategy -Hibernate uses {hibernate-docs}#naming[two different naming strategies] to map names from the object model to the corresponding database names. +== Configure Hibernate Naming Strategy + +Hibernate uses {url-hibernate-userguide}#naming[two different naming strategies] to map names from the object model to the corresponding database names. The fully qualified class name of the physical and the implicit strategy implementations can be configured by setting the `spring.jpa.hibernate.naming.physical-strategy` and `spring.jpa.hibernate.naming.implicit-strategy` properties, respectively. Alternatively, if `ImplicitNamingStrategy` or `PhysicalNamingStrategy` beans are available in the application context, Hibernate will be automatically configured to use them. @@ -224,41 +231,47 @@ Additionally, by default, all table names are generated in lower case. For example, a `TelephoneNumber` entity is mapped to the `telephone_number` table. If your schema requires mixed-case identifiers, define a custom `CamelCaseToUnderscoresNamingStrategy` bean, as shown in the following example: -include::code:spring/MyHibernateConfiguration[] +include-code::spring/MyHibernateConfiguration[] If you prefer to use Hibernate's default instead, set the following property: -[indent=0,properties,subs="verbatim"] +[configprops,yaml] ---- - spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl +spring: + jpa: + hibernate: + naming: + physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl ---- Alternatively, you can configure the following bean: -include::code:standard/MyHibernateConfiguration[] +include-code::standard/MyHibernateConfiguration[] -See {spring-boot-autoconfigure-module-code}/orm/jpa/HibernateJpaAutoConfiguration.java[`HibernateJpaAutoConfiguration`] and {spring-boot-autoconfigure-module-code}/orm/jpa/JpaBaseConfiguration.java[`JpaBaseConfiguration`] for more details. +See {code-spring-boot-autoconfigure-src}/orm/jpa/HibernateJpaAutoConfiguration.java[`HibernateJpaAutoConfiguration`] and {code-spring-boot-autoconfigure-src}/orm/jpa/JpaBaseConfiguration.java[`JpaBaseConfiguration`] for more details. [[howto.data-access.configure-hibernate-second-level-caching]] -=== Configure Hibernate Second-Level Caching -Hibernate {hibernate-docs}#caching[second-level cache] can be configured for a range of cache providers. +== Configure Hibernate Second-Level Caching + +Hibernate {url-hibernate-userguide}#caching[second-level cache] can be configured for a range of cache providers. Rather than configuring Hibernate to lookup the cache provider again, it is better to provide the one that is available in the context whenever possible. To do this with JCache, first make sure that `org.hibernate.orm:hibernate-jcache` is available on the classpath. Then, add a `HibernatePropertiesCustomizer` bean as shown in the following example: -include::code:MyHibernateSecondLevelCacheConfiguration[] +include-code::MyHibernateSecondLevelCacheConfiguration[] This customizer will configure Hibernate to use the same `CacheManager` as the one that the application uses. It is also possible to use separate `CacheManager` instances. -For details, see {hibernate-docs}#caching-provider-jcache[the Hibernate user guide]. +For details, see {url-hibernate-userguide}#caching-provider-jcache[the Hibernate user guide]. [[howto.data-access.dependency-injection-in-hibernate-components]] -=== Use Dependency Injection in Hibernate Components +== Use Dependency Injection in Hibernate Components + By default, Spring Boot registers a `BeanContainer` implementation that uses the `BeanFactory` so that converters and entity listeners can use regular dependency injection. You can disable or tune this behavior by registering a `HibernatePropertiesCustomizer` that removes or changes the `hibernate.resource.beans.container` property. @@ -266,20 +279,21 @@ You can disable or tune this behavior by registering a `HibernatePropertiesCusto [[howto.data-access.use-custom-entity-manager]] -=== Use a Custom EntityManagerFactory +== Use a Custom EntityManagerFactory + To take full control of the configuration of the `EntityManagerFactory`, you need to add a `@Bean` named '`entityManagerFactory`'. Spring Boot auto-configuration switches off its entity manager in the presence of a bean of that type. [[howto.data-access.use-multiple-entity-managers]] -[[howto.data-access.use-multiple-entity-managers]] -=== Using Multiple EntityManagerFactories +== Using Multiple EntityManagerFactories + If you need to use JPA against multiple data sources, you likely need one `EntityManagerFactory` per data source. The `LocalContainerEntityManagerFactoryBean` from Spring ORM allows you to configure an `EntityManagerFactory` for your needs. You can also reuse `JpaProperties` to bind settings for each `EntityManagerFactory`, as shown in the following example: -include::code:MyEntityManagerFactoryConfiguration[] +include-code::MyEntityManagerFactoryConfiguration[] The example above creates an `EntityManagerFactory` using a `DataSource` bean named `firstDataSource`. It scans entities located in the same package as `Order`. @@ -295,23 +309,25 @@ Alternatively, you might be able to use a JTA transaction manager that spans bot If you use Spring Data, you need to configure `@EnableJpaRepositories` accordingly, as shown in the following examples: -include::code:OrderConfiguration[] +include-code::OrderConfiguration[] -include::code:CustomerConfiguration[] +include-code::CustomerConfiguration[] [[howto.data-access.use-traditional-persistence-xml]] -=== Use a Traditional persistence.xml File +== Use a Traditional persistence.xml File + Spring Boot will not search for or use a `META-INF/persistence.xml` by default. If you prefer to use a traditional `persistence.xml`, you need to define your own `@Bean` of type `LocalEntityManagerFactoryBean` (with an ID of '`entityManagerFactory`') and set the persistence unit name there. -See {spring-boot-autoconfigure-module-code}/orm/jpa/JpaBaseConfiguration.java[`JpaBaseConfiguration`] for the default settings. +See {code-spring-boot-autoconfigure-src}/orm/jpa/JpaBaseConfiguration.java[`JpaBaseConfiguration`] for the default settings. [[howto.data-access.use-spring-data-jpa-and-mongo-repositories]] -=== Use Spring Data JPA and Mongo Repositories +== Use Spring Data JPA and Mongo Repositories + Spring Data JPA and Spring Data Mongo can both automatically create `Repository` implementations for you. If they are both present on the classpath, you might have to do some extra configuration to tell Spring Boot which repositories to create. The most explicit way to do that is to use the standard Spring Data `+@EnableJpaRepositories+` and `+@EnableMongoRepositories+` annotations and provide the location of your `Repository` interfaces. @@ -325,7 +341,8 @@ To work with them, change the names of the annotations and flags accordingly. [[howto.data-access.customize-spring-data-web-support]] -=== Customize Spring Data's Web Support +== Customize Spring Data's Web Support + Spring Data provides web support that simplifies the use of Spring Data repositories in a web application. Spring Boot provides properties in the `spring.data.web` namespace for customizing its configuration. Note that if you are using Spring Data REST, you must use the properties in the `spring.data.rest` namespace instead. @@ -333,12 +350,13 @@ Note that if you are using Spring Data REST, you must use the properties in the [[howto.data-access.exposing-spring-data-repositories-as-rest]] -=== Expose Spring Data Repositories as REST Endpoint +== Expose Spring Data Repositories as REST Endpoint + Spring Data REST can expose the `Repository` implementations as REST endpoints for you, provided Spring MVC has been enabled for the application. -Spring Boot exposes a set of useful properties (from the `spring.data.rest` namespace) that customize the {spring-data-rest-api}/core/config/RepositoryRestConfiguration.html[`RepositoryRestConfiguration`]. -If you need to provide additional customization, you should use a {spring-data-rest-api}/webmvc/config/RepositoryRestConfigurer.html[`RepositoryRestConfigurer`] bean. +Spring Boot exposes a set of useful properties (from the `spring.data.rest` namespace) that customize the {url-spring-data-rest-javadoc}/org/springframework/data/rest/core/config/RepositoryRestConfiguration.html[`RepositoryRestConfiguration`]. +If you need to provide additional customization, you should use a {url-spring-data-rest-javadoc}/org/springframework/data/rest/webmvc/config/RepositoryRestConfigurer.html[`RepositoryRestConfigurer`] bean. NOTE: If you do not specify any order on your custom `RepositoryRestConfigurer`, it runs after the one Spring Boot uses internally. If you need to specify an order, make sure it is higher than 0. @@ -346,7 +364,8 @@ If you need to specify an order, make sure it is higher than 0. [[howto.data-access.configure-a-component-that-is-used-by-jpa]] -=== Configure a Component that is Used by JPA +== Configure a Component that is Used by JPA + If you want to configure a component that JPA uses, then you need to ensure that the component is initialized before JPA. When the component is auto-configured, Spring Boot takes care of this for you. For example, when Flyway is auto-configured, Hibernate is configured to depend upon Flyway so that Flyway has a chance to initialize the database before Hibernate tries to use it. @@ -354,13 +373,14 @@ For example, when Flyway is auto-configured, Hibernate is configured to depend u If you are configuring a component yourself, you can use an `EntityManagerFactoryDependsOnPostProcessor` subclass as a convenient way of setting up the necessary dependencies. For example, if you use Hibernate Search with Elasticsearch as its index manager, any `EntityManagerFactory` beans must be configured to depend on the `elasticsearchClient` bean, as shown in the following example: -include::code:ElasticsearchEntityManagerFactoryDependsOnPostProcessor[] +include-code::ElasticsearchEntityManagerFactoryDependsOnPostProcessor[] [[howto.data-access.configure-jooq-with-multiple-datasources]] -=== Configure jOOQ with Two DataSources +== Configure jOOQ with Two DataSources + If you need to use jOOQ with multiple data sources, you should create your own `DSLContext` for each one. -See {spring-boot-autoconfigure-module-code}/jooq/JooqAutoConfiguration.java[JooqAutoConfiguration] for more details. +See {code-spring-boot-autoconfigure-src}/jooq/JooqAutoConfiguration.java[JooqAutoConfiguration] for more details. TIP: In particular, `JooqExceptionTranslator` and `SpringTransactionProvider` can be reused to provide similar features to what the auto-configuration does with a single `DataSource`. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/data-initialization.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/data-initialization.adoc similarity index 86% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/data-initialization.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/data-initialization.adoc index d602fed56b..ee254e6279 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/data-initialization.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/data-initialization.adoc @@ -1,5 +1,6 @@ [[howto.data-initialization]] -== Database Initialization += Database Initialization + An SQL database can be initialized in different ways depending on what your stack is. Of course, you can also do it manually, provided the database is a separate process. It is recommended to use a single mechanism for schema generation. @@ -7,7 +8,8 @@ It is recommended to use a single mechanism for schema generation. [[howto.data-initialization.using-jpa]] -=== Initialize a Database Using JPA +== Initialize a Database Using JPA + JPA has features for DDL generation, and these can be set up to run on startup against the database. This is controlled through two external properties: @@ -18,7 +20,8 @@ This is controlled through two external properties: [[howto.data-initialization.using-hibernate]] -=== Initialize a Database Using Hibernate +== Initialize a Database Using Hibernate + You can set `spring.jpa.hibernate.ddl-auto` explicitly to one of the standard Hibernate property values which are `none`, `validate`, `update`, `create`, and `create-drop`. Spring Boot chooses a default value for you based on whether it thinks your database is embedded. It defaults to `create-drop` if no schema manager has been detected or `none` in all other cases. @@ -28,7 +31,7 @@ Be careful when switching from in-memory to a '`real`' database that you do not You either have to set `ddl-auto` explicitly or use one of the other mechanisms to initialize the database. NOTE: You can output the schema creation by enabling the `org.hibernate.SQL` logger. -This is done for you automatically if you enable the <>. +This is done for you automatically if you enable the xref:reference:features/logging.adoc#features.logging.console-output[debug mode]. In addition, a file named `import.sql` in the root of the classpath is executed on startup if Hibernate creates the schema from scratch (that is, if the `ddl-auto` property is set to `create` or `create-drop`). This can be useful for demos and for testing if you are careful but is probably not something you want to be on the classpath in production. @@ -37,7 +40,8 @@ It is a Hibernate feature (and has nothing to do with Spring). [[howto.data-initialization.using-basic-sql-scripts]] -=== Initialize a Database Using Basic SQL Scripts +== Initialize a Database Using Basic SQL Scripts + Spring Boot can automatically create the schema (DDL scripts) of your JDBC `DataSource` or R2DBC `ConnectionFactory` and initialize its data (DML scripts). By default, it loads schema scripts from `optional:classpath*:schema.sql` and data scripts from `optional:classpath*:data.sql`. @@ -65,26 +69,27 @@ This will defer data source initialization until after any `EntityManagerFactory NOTE: The initialization scripts support `--` for single line comments and `/++*++ ++*++/` for block comments. Other comment formats are not supported. -If you are using a <>, like Flyway or Liquibase, you should use them alone to create and initialize the schema. +If you are using a xref:data-initialization.adoc#howto.data-initialization.migration-tool[Higher-level Database Migration Tool], like Flyway or Liquibase, you should use them alone to create and initialize the schema. Using the basic `schema.sql` and `data.sql` scripts alongside Flyway or Liquibase is not recommended and support will be removed in a future release. -If you need to initialize test data using a higher-level database migration tool, please see the sections about <> and <>. +If you need to initialize test data using a higher-level database migration tool, please see the sections about xref:data-initialization.adoc#howto.data-initialization.migration-tool.flyway-tests[Flyway] and xref:data-initialization.adoc#howto.data-initialization.migration-tool.liquibase-tests[Liquibase]. [[howto.data-initialization.batch]] -=== Initialize a Spring Batch Database +== Initialize a Spring Batch Database + If you use Spring Batch, it comes pre-packaged with SQL initialization scripts for most popular database platforms. Spring Boot can detect your database type and execute those scripts on startup. If you use an embedded database, this happens by default. You can also enable it for any database type, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - batch: - jdbc: - initialize-schema: "always" +spring: + batch: + jdbc: + initialize-schema: "always" ---- You can also switch off the initialization explicitly by setting `spring.batch.jdbc.initialize-schema` to `never`. @@ -92,13 +97,15 @@ You can also switch off the initialization explicitly by setting `spring.batch.j [[howto.data-initialization.migration-tool]] -=== Use a Higher-level Database Migration Tool +== Use a Higher-level Database Migration Tool + Spring Boot supports two higher-level migration tools: https://flywaydb.org/[Flyway] and https://www.liquibase.org/[Liquibase]. [[howto.data-initialization.migration-tool.flyway]] -==== Execute Flyway Database Migrations on Startup +=== Execute Flyway Database Migrations on Startup + To automatically run Flyway database migrations on startup, add the `org.flywaydb:flyway-core` to your classpath. Typically, migrations are scripts in the form `V__.sql` (with `` an underscore-separated version, such as '`1`' or '`2_1`'). @@ -106,34 +113,34 @@ By default, they are in a directory called `classpath:db/migration`, but you can This is a comma-separated list of one or more `classpath:` or `filesystem:` locations. For example, the following configuration would search for scripts in both the default classpath location and the `/opt/migration` directory: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - flyway: - locations: "classpath:db/migration,filesystem:/opt/migration" +spring: + flyway: + locations: "classpath:db/migration,filesystem:/opt/migration" ---- You can also add a special `\{vendor}` placeholder to use vendor-specific scripts. Assume the following: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - flyway: - locations: "classpath:db/migration/{vendor}" +spring: + flyway: + locations: "classpath:db/migration/{vendor}" ---- Rather than using `db/migration`, the preceding configuration sets the directory to use according to the type of the database (such as `db/migration/mysql` for MySQL). -The list of supported databases is available in {spring-boot-module-code}/jdbc/DatabaseDriver.java[`DatabaseDriver`]. +The list of supported databases is available in {code-spring-boot-src}/jdbc/DatabaseDriver.java[`DatabaseDriver`]. Migrations can also be written in Java. Flyway will be auto-configured with any beans that implement `JavaMigration`. -{spring-boot-autoconfigure-module-code}/flyway/FlywayProperties.java[`FlywayProperties`] provides most of Flyway's settings and a small set of additional properties that can be used to disable the migrations or switch off the location checking. +{code-spring-boot-autoconfigure-src}/flyway/FlywayProperties.java[`FlywayProperties`] provides most of Flyway's settings and a small set of additional properties that can be used to disable the migrations or switch off the location checking. If you need more control over the configuration, consider registering a `FlywayConfigurationCustomizer` bean. Spring Boot calls `Flyway.migrate()` to perform the database migration. -If you would like more control, provide a `@Bean` that implements {spring-boot-autoconfigure-module-code}/flyway/FlywayMigrationStrategy.java[`FlywayMigrationStrategy`]. +If you would like more control, provide a `@Bean` that implements {code-spring-boot-autoconfigure-src}/flyway/FlywayMigrationStrategy.java[`FlywayMigrationStrategy`]. Flyway supports SQL and Java https://flywaydb.org/documentation/concepts/callbacks[callbacks]. To use SQL-based callbacks, place the callback scripts in the `classpath:db/migration` directory. @@ -154,11 +161,11 @@ For example, you can place test-specific migrations in `src/test/resources` and Also, you can use profile-specific configuration to customize `spring.flyway.locations` so that certain migrations run only when a particular profile is active. For example, in `application-dev.properties`, you might specify the following setting: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - flyway: - locations: "classpath:/db/migration,classpath:/dev/db/migration" +spring: + flyway: + locations: "classpath:/db/migration,classpath:/dev/db/migration" ---- With that setup, migrations in `dev/db/migration` run only when the `dev` profile is active. @@ -166,7 +173,8 @@ With that setup, migrations in `dev/db/migration` run only when the `dev` profil [[howto.data-initialization.migration-tool.liquibase]] -==== Execute Liquibase Database Migrations on Startup +=== Execute Liquibase Database Migrations on Startup + To automatically run Liquibase database migrations on startup, add the `org.liquibase:liquibase-core` to your classpath. [NOTE] @@ -186,12 +194,13 @@ Alternatively, you can use Liquibase's native `DataSource` by setting `spring.li Setting either `spring.liquibase.url` or `spring.liquibase.user` is sufficient to cause Liquibase to use its own `DataSource`. If any of the three properties has not been set, the value of its equivalent `spring.datasource` property will be used. -See {spring-boot-autoconfigure-module-code}/liquibase/LiquibaseProperties.java[`LiquibaseProperties`] for details about available settings such as contexts, the default schema, and others. +See {code-spring-boot-autoconfigure-src}/liquibase/LiquibaseProperties.java[`LiquibaseProperties`] for details about available settings such as contexts, the default schema, and others. [[howto.data-initialization.migration-tool.flyway-tests]] -==== Use Flyway for test-only migrations +=== Use Flyway for test-only migrations + If you want to create Flyway migrations which populate your test database, place them in `src/test/resources/db/migration`. A file named, for example, `src/test/resources/db/migration/V9999__test-data.sql` will be executed after your production migrations and only if you're running the tests. You can use this file to create the needed test data. @@ -200,14 +209,15 @@ This file will not be packaged in your uber jar or your container. [[howto.data-initialization.migration-tool.liquibase-tests]] -==== Use Liquibase for test-only migrations +=== Use Liquibase for test-only migrations + If you want to create Liquibase migrations which populate your test database, you have to create a test changelog which also includes the production changelog. First, you need to configure Liquibase to use a different changelog when running the tests. One way to do this is to create a Spring Boot `test` profile and put the Liquibase properties in there. For that, create a file named `src/test/resources/application-test.properties` and put the following property in there: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- spring: liquibase: @@ -218,7 +228,7 @@ This configures Liquibase to use a different changelog when running in the `test Now create the changelog file at `src/test/resources/db/changelog/db.changelog-test.yaml`: -[source,yaml,indent=0,subs="verbatim"] +[source,yaml] ---- databaseChangeLog: - include: @@ -240,7 +250,8 @@ To do this, you can add the `@ActiveProfiles("test")` annotation to your `@Sprin [[howto.data-initialization.dependencies]] -=== Depend Upon an Initialized Database +== Depend Upon an Initialized Database + Database initialization is performed while the application is starting up as part of application context refresh. To allow an initialized database to be accessed during startup, beans that act as database initializers and beans that require that database to have been initialized are detected automatically. Beans whose initialization depends upon the database having been initialized are configured to depend upon those that initialize it. @@ -249,7 +260,8 @@ If, during startup, your application tries to access the database and it has not [[howto.data-initialization.dependencies.initializer-detection]] -==== Detect a Database Initializer +=== Detect a Database Initializer + Spring Boot will automatically detect beans of the following types that initialize an SQL database: - `DataSourceScriptDatabaseInitializer` @@ -265,7 +277,8 @@ To have other beans be detected, register an implementation of `DatabaseInitiali [[howto.data-initialization.dependencies.depends-on-initialization-detection]] -==== Detect a Bean That Depends On Database Initialization +=== Detect a Bean That Depends On Database Initialization + Spring Boot will automatically detect beans of the following types that depends upon database initialization: - `AbstractEntityManagerFactoryBean` (unless configprop:spring.jpa.defer-datasource-initialization[] is set to `true`) diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/docker-compose.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/docker-compose.adoc similarity index 93% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/docker-compose.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/docker-compose.adoc index d889637d19..3a68d8ad35 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/docker-compose.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/docker-compose.adoc @@ -1,16 +1,18 @@ [[howto.docker-compose]] -== Docker Compose += Docker Compose This section includes topics relating to the Docker Compose support in Spring Boot. + + [[howto.docker-compose.jdbc-url]] -=== Customizing the JDBC URL +== Customizing the JDBC URL When using `JdbcConnectionDetails` with Docker Compose, the parameters of the JDBC URL can be customized by applying the `org.springframework.boot.jdbc.parameters` label to the service. For example: -[source,yaml,indent=0] +[source,yaml] ---- services: postgres: @@ -30,7 +32,7 @@ With this Docker Compose file in place, the JDBC URL used is `jdbc:postgresql:// [[howto.docker-compose.sharing-services]] -=== Sharing services between multiple applications +== Sharing services between multiple applications If you want to share services between multiple applications, create the `compose.yaml` file in one of the applications and then use the configuration property configprop:spring.docker.compose.file[] in the other applications to reference the `compose.yaml` file. You should also set configprop:spring.docker.compose.lifecycle-management[] to `start-only`, as it defaults to `start-and-stop` and stopping one application would shut down the shared services for the other still running applications as well. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/hotswapping.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/hotswapping.adoc similarity index 56% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/hotswapping.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/hotswapping.adoc index 9a6ec3f495..377e3280a3 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/hotswapping.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/hotswapping.adoc @@ -1,67 +1,75 @@ [[howto.hotswapping]] -== Hot Swapping += Hot Swapping + Spring Boot supports hot swapping. This section answers questions about how it works. [[howto.hotswapping.reload-static-content]] -=== Reload Static Content +== Reload Static Content + There are several options for hot reloading. -The recommended approach is to use <>, as it provides additional development-time features, such as support for fast application restarts and LiveReload as well as sensible development-time configuration (such as template caching). +The recommended approach is to use xref:reference:using/devtools.adoc[`spring-boot-devtools`], as it provides additional development-time features, such as support for fast application restarts and LiveReload as well as sensible development-time configuration (such as template caching). Devtools works by monitoring the classpath for changes. This means that static resource changes must be "built" for the change to take effect. By default, this happens automatically in Eclipse when you save your changes. In IntelliJ IDEA, the Make Project command triggers the necessary build. -Due to the <>, changes to static resources do not trigger a restart of your application. +Due to the xref:reference:using/devtools.adoc#using.devtools.restart.excluding-resources[default restart exclusions], changes to static resources do not trigger a restart of your application. They do, however, trigger a live reload. Alternatively, running in an IDE (especially with debugging on) is a good way to do development (all modern IDEs allow reloading of static resources and usually also allow hot-swapping of Java class changes). -Finally, the <> can be configured (see the `addResources` property) to support running from the command line with reloading of static files directly from source. +Finally, the xref:build-tool-plugin:index.adoc[Maven and Gradle plugins] can be configured (see the `addResources` property) to support running from the command line with reloading of static files directly from source. You can use that with an external css/js compiler process if you are writing that code with higher-level tools. [[howto.hotswapping.reload-templates]] -=== Reload Templates without Restarting the Container +== Reload Templates without Restarting the Container + Most of the templating technologies supported by Spring Boot include a configuration option to disable caching (described later in this document). -If you use the `spring-boot-devtools` module, these properties are <> for you at development time. +If you use the `spring-boot-devtools` module, these properties are xref:reference:using/devtools.adoc#using.devtools.property-defaults[automatically configured] for you at development time. [[howto.hotswapping.reload-templates.thymeleaf]] -==== Thymeleaf Templates +=== Thymeleaf Templates + If you use Thymeleaf, set `spring.thymeleaf.cache` to `false`. -See {spring-boot-autoconfigure-module-code}/thymeleaf/ThymeleafAutoConfiguration.java[`ThymeleafAutoConfiguration`] for other Thymeleaf customization options. +See {code-spring-boot-autoconfigure-src}/thymeleaf/ThymeleafAutoConfiguration.java[`ThymeleafAutoConfiguration`] for other Thymeleaf customization options. [[howto.hotswapping.reload-templates.freemarker]] -==== FreeMarker Templates +=== FreeMarker Templates + If you use FreeMarker, set `spring.freemarker.cache` to `false`. -See {spring-boot-autoconfigure-module-code}/freemarker/FreeMarkerAutoConfiguration.java[`FreeMarkerAutoConfiguration`] for other FreeMarker customization options. +See {code-spring-boot-autoconfigure-src}/freemarker/FreeMarkerAutoConfiguration.java[`FreeMarkerAutoConfiguration`] for other FreeMarker customization options. [[howto.hotswapping.reload-templates.groovy]] -==== Groovy Templates +=== Groovy Templates + If you use Groovy templates, set `spring.groovy.template.cache` to `false`. -See {spring-boot-autoconfigure-module-code}/groovy/template/GroovyTemplateAutoConfiguration.java[`GroovyTemplateAutoConfiguration`] for other Groovy customization options. +See {code-spring-boot-autoconfigure-src}/groovy/template/GroovyTemplateAutoConfiguration.java[`GroovyTemplateAutoConfiguration`] for other Groovy customization options. [[howto.hotswapping.fast-application-restarts]] -=== Fast Application Restarts +== Fast Application Restarts + The `spring-boot-devtools` module includes support for automatic application restarts. While not as fast as technologies such as https://www.jrebel.com/products/jrebel[JRebel] it is usually significantly faster than a "`cold start`". You should probably give it a try before investigating some of the more complex reload options discussed later in this document. -For more details, see the <> section. +For more details, see the xref:reference:using/devtools.adoc[Developer Tools] section. [[howto.hotswapping.reload-java-classes-without-restarting]] -=== Reload Java Classes without Restarting the Container +== Reload Java Classes without Restarting the Container + Many modern IDEs (Eclipse, IDEA, and others) support hot swapping of bytecode. Consequently, if you make a change that does not affect class or method signatures, it should reload cleanly with no side effects. 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/antora/modules/how-to/pages/http-clients.adoc similarity index 70% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/http-clients.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/http-clients.adoc index 7d809dc9d9..27d80e6fde 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/http-clients.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/http-clients.adoc @@ -1,13 +1,15 @@ [[howto.http-clients]] -== HTTP Clients += HTTP Clients + Spring Boot offers a number of starters that work with HTTP clients. This section answers questions related to using them. [[howto.http-clients.rest-template-proxy-configuration]] -=== Configure RestTemplate to Use a Proxy -As described in <>, you can use a `RestTemplateCustomizer` with `RestTemplateBuilder` to build a customized `RestTemplate`. +== Configure RestTemplate to Use a Proxy + +As described in xref:reference:io/rest-client.adoc#io.rest-client.resttemplate.customization[RestTemplate Customization], you can use a `RestTemplateCustomizer` with `RestTemplateBuilder` to build a customized `RestTemplate`. This is the recommended approach for creating a `RestTemplate` configured to use a proxy. The exact details of the proxy configuration depend on the underlying client request factory that is being used. @@ -15,12 +17,13 @@ The exact details of the proxy configuration depend on the underlying client req [[howto.http-clients.webclient-reactor-netty-customization]] -=== Configure the TcpClient used by a Reactor Netty-based WebClient +== Configure the TcpClient used by a Reactor Netty-based WebClient + When Reactor Netty is on the classpath a Reactor Netty-based `WebClient` is auto-configured. To customize the client's handling of network connections, provide a `ClientHttpConnector` bean. The following example configures a 60 second connect timeout and adds a `ReadTimeoutHandler`: -include::code:MyReactorNettyClientConfiguration[] +include-code::MyReactorNettyClientConfiguration[] TIP: Note the use of `ReactorResourceFactory` for the connection provider and event loop resources. This ensures efficient sharing of resources for the server receiving requests and the client making requests. diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/index.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/index.adoc new file mode 100644 index 0000000000..d9394c9253 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/index.adoc @@ -0,0 +1,12 @@ +[[howto]] += How-to Guides + +This section provides answers to some common '`how do I do that...`' questions that often arise when using Spring Boot. +Its coverage is not exhaustive, but it does cover quite a lot. + +If you have a specific problem that we do not cover here, you might want to check https://stackoverflow.com/tags/spring-boot[stackoverflow.com] to see if someone has already provided an answer. +This is also a great place to ask new questions (please use the `spring-boot` tag). + +We are also more than happy to extend this section. +If you want to add a '`how-to`', send us a {url-github}[pull request]. + diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/jersey.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/jersey.adoc similarity index 76% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/jersey.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/jersey.adoc index ff1246e543..317fcd54cf 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/jersey.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/jersey.adoc @@ -1,30 +1,26 @@ [[howto.jersey]] -== Jersey += Jersey [[howto.jersey.spring-security]] -=== Secure Jersey endpoints with Spring Security +== Secure Jersey endpoints with Spring Security + Spring Security can be used to secure a Jersey-based web application in much the same way as it can be used to secure a Spring MVC-based web application. However, if you want to use Spring Security's method-level security with Jersey, you must configure Jersey to use `setStatus(int)` rather `sendError(int)`. This prevents Jersey from committing the response before Spring Security has had an opportunity to report an authentication or authorization failure to the client. The `jersey.config.server.response.setStatusOverSendError` property must be set to `true` on the application's `ResourceConfig` bean, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/jersey/springsecurity/JerseySetStatusOverSendErrorConfig.java[] ----- +include-code::JerseySetStatusOverSendErrorConfig[] [[howto.jersey.alongside-another-web-framework]] -=== Use Jersey Alongside Another Web Framework +== Use Jersey Alongside Another Web Framework + To use Jersey alongside another web framework, such as Spring MVC, it should be configured so that it will allow the other framework to handle requests that it cannot handle. First, configure Jersey to use a filter rather than a servlet by configuring the configprop:spring.jersey.type[] application property with a value of `filter`. Second, configure your `ResourceConfig` to forward requests that would have resulted in a 404, as shown in the following example. -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/jersey/alongsideanotherwebframework/JerseyConfig.java[] ----- +includ-code::alongsideanotherwebframework/JerseyConfig[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/logging.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/logging.adoc similarity index 72% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/logging.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/logging.adoc index 5afd422818..cbcec7cb6a 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/logging.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/logging.adoc @@ -1,17 +1,18 @@ [[howto.logging]] -== Logging += Logging + Spring Boot has no mandatory logging dependency, except for the Commons Logging API, which is typically provided by Spring Framework's `spring-jcl` module. To use https://logback.qos.ch[Logback], you need to include it and `spring-jcl` on the classpath. The recommended way to do that is through the starters, which all depend on `spring-boot-starter-logging`. For a web application, you only need `spring-boot-starter-web`, since it depends transitively on the logging starter. If you use Maven, the following dependency adds logging for you: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - org.springframework.boot - spring-boot-starter-web - + + org.springframework.boot + spring-boot-starter-web + ---- Spring Boot has a `LoggingSystem` abstraction that attempts to configure logging based on the content of the classpath. @@ -19,12 +20,12 @@ If Logback is available, it is the first choice. If the only change you need to make to logging is to set the levels of various loggers, you can do so in `application.properties` by using the "logging.level" prefix, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - logging: - level: - org.springframework.web: "debug" - org.hibernate: "error" +logging: + level: + org.springframework.web: "debug" + org.hibernate: "error" ---- You can also set the location of a file to which the log will be written (in addition to the console) by using `logging.file.name`. @@ -35,10 +36,11 @@ By default, Spring Boot picks up the native configuration from its default locat [[howto.logging.logback]] -=== Configure Logback for Logging +== Configure Logback for Logging + If you need to apply customizations to logback beyond those that can be achieved with `application.properties`, you will need to add a standard logback configuration file. You can add a `logback.xml` file to the root of your classpath for logback to find. -You can also use `logback-spring.xml` if you want to use the <>. +You can also use `logback-spring.xml` if you want to use the xref:reference:features/logging.adoc#features.logging.logback-extensions[Spring Boot Logback extensions]. TIP: The Logback documentation has a https://logback.qos.ch/manual/configuration.html[dedicated section that covers configuration] in some detail. @@ -55,17 +57,17 @@ In addition, a legacy `base.xml` file is provided for compatibility with earlier A typical custom `logback.xml` file would look something like this: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - - - - - - - - + + + + + + + + + ---- Your logback configuration file can also make use of System properties that the `LoggingSystem` takes care of creating for you: @@ -88,35 +90,37 @@ Any `logback-spring.groovy` files will not be detected. [[howto.logging.logback.file-only-output]] -==== Configure Logback for File-only Output +=== Configure Logback for File-only Output + If you want to disable console logging and write output only to a file, you need a custom `logback-spring.xml` that imports `file-appender.xml` but not `console-appender.xml`, as shown in the following example: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - - - - - - - - + + + + + + + + + ---- You also need to add `logging.file.name` to your `application.properties` or `application.yaml`, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - logging: - file: - name: "myapplication.log" +logging: + file: + name: "myapplication.log" ---- [[howto.logging.log4j]] -=== Configure Log4j for Logging +== Configure Log4j for Logging + Spring Boot supports https://logging.apache.org/log4j/2.x/[Log4j 2] for logging configuration if it is on the classpath. If you use the starters for assembling dependencies, you have to exclude Logback and then include Log4j 2 instead. If you do not use the starters, you need to provide (at least) `spring-jcl` in addition to Log4j 2. @@ -124,42 +128,42 @@ If you do not use the starters, you need to provide (at least) `spring-jcl` in a The recommended path is through the starters, even though it requires some jiggling. The following example shows how to set up the starters in Maven: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter - - - org.springframework.boot - spring-boot-starter-logging - - - - - org.springframework.boot - spring-boot-starter-log4j2 - + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.springframework.boot + spring-boot-starter-log4j2 + ---- Gradle provides a few different ways to set up the starters. -One way is to use a {gradle-docs}/resolution_rules.html#sec:module_replacement[module replacement]. +One way is to use a {url-gradle-docs}/resolution_rules.html#sec:module_replacement[module replacement]. To do so, declare a dependency on the Log4j 2 starter and tell Gradle that any occurrences of the default logging starter should be replaced by the Log4j 2 starter, as shown in the following example: -[source,gradle,indent=0,subs="verbatim"] +[source,gradle] ---- - dependencies { - implementation "org.springframework.boot:spring-boot-starter-log4j2" - modules { - module("org.springframework.boot:spring-boot-starter-logging") { - replacedBy("org.springframework.boot:spring-boot-starter-log4j2", "Use Log4j2 instead of Logback") - } +dependencies { + implementation "org.springframework.boot:spring-boot-starter-log4j2" + modules { + module("org.springframework.boot:spring-boot-starter-logging") { + replacedBy("org.springframework.boot:spring-boot-starter-log4j2", "Use Log4j2 instead of Logback") } } +} ---- NOTE: The Log4j starters gather together the dependencies for common logging requirements (such as having Tomcat use `java.util.logging` but configuring the output using Log4j 2). @@ -169,7 +173,8 @@ NOTE: To ensure that debug logging performed using `java.util.logging` is routed [[howto.logging.log4j.yaml-or-json-config]] -==== Use YAML or JSON to Configure Log4j 2 +=== Use YAML or JSON to Configure Log4j 2 + In addition to its default XML configuration format, Log4j 2 also supports YAML and JSON configuration files. To configure Log4j 2 to use an alternative configuration file format, add the appropriate dependencies to the classpath and name your configuration files to match your chosen file format, as shown in the following example: @@ -189,7 +194,8 @@ To configure Log4j 2 to use an alternative configuration file format, add the ap [[howto.logging.log4j.composite-configuration]] -==== Use Composite Configuration to Configure Log4j 2 +=== Use Composite Configuration to Configure Log4j 2 + Log4j 2 has support for combining multiple configuration files into a single composite configuration. To use this support in Spring Boot, configure configprop:logging.log4j2.config.override[] with the locations of one or more secondary configuration files. The secondary configuration files will be merged with the primary configuration, whether the primary's source is Spring Boot's defaults, a standard location such as `log4j.xml`, or the location configured by the configprop:logging.config[] property. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/messaging.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/messaging.adoc similarity index 89% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/messaging.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/messaging.adoc index b0e8b91707..79e994b330 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/messaging.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/messaging.adoc @@ -1,16 +1,18 @@ [[howto.messaging]] -== Messaging += Messaging + Spring Boot offers a number of starters to support messaging. This section answers questions that arise from using messaging with Spring Boot. [[howto.messaging.disable-transacted-jms-session]] -=== Disable Transacted JMS Session +== Disable Transacted JMS Session + If your JMS broker does not support transacted sessions, you have to disable the support of transactions altogether. If you create your own `JmsListenerContainerFactory`, there is nothing to do, since, by default it cannot be transacted. If you want to use the `DefaultJmsListenerContainerFactoryConfigurer` to reuse Spring Boot's default, you can disable transacted sessions, as follows: -include::code:MyJmsConfiguration[] +include-code::MyJmsConfiguration[] The preceding example overrides the default factory, and it should be applied to any other factory that your application defines, if any. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/nosql.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/nosql.adoc similarity index 50% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/nosql.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/nosql.adoc index 67fc1d1677..bb1e9ef177 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/nosql.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/nosql.adoc @@ -1,45 +1,47 @@ [[howto.nosql]] -== NoSQL += NoSQL + Spring Boot offers a number of starters that support NoSQL technologies. This section answers questions that arise from using NoSQL with Spring Boot. [[howto.nosql.jedis-instead-of-lettuce]] -=== Use Jedis Instead of Lettuce +== Use Jedis Instead of Lettuce + By default, the Spring Boot starter (`spring-boot-starter-data-redis`) uses https://github.com/lettuce-io/lettuce-core/[Lettuce]. You need to exclude that dependency and include the https://github.com/xetorthio/jedis/[Jedis] one instead. Spring Boot manages both of these dependencies, allowing you to switch to Jedis without specifying a version. The following example shows how to accomplish this in Maven: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - org.springframework.boot - spring-boot-starter-data-redis - - - io.lettuce - lettuce-core - - - - - redis.clients - jedis - + + org.springframework.boot + spring-boot-starter-data-redis + + + io.lettuce + lettuce-core + + + + + redis.clients + jedis + ---- The following example shows how to accomplish this in Gradle: -[source,gradle,indent=0,subs="verbatim"] +[source,gradle] ---- - dependencies { - implementation('org.springframework.boot:spring-boot-starter-data-redis') { - exclude group: 'io.lettuce', module: 'lettuce-core' - } - implementation 'redis.clients:jedis' - // ... +dependencies { + implementation('org.springframework.boot:spring-boot-starter-data-redis') { + exclude group: 'io.lettuce', module: 'lettuce-core' } + implementation 'redis.clients:jedis' + // ... +} ---- diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/properties-and-configuration.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/properties-and-configuration.adoc similarity index 69% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/properties-and-configuration.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/properties-and-configuration.adoc index 208b3504a2..8649e6dc19 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/properties-and-configuration.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/properties-and-configuration.adoc @@ -1,27 +1,30 @@ [[howto.properties-and-configuration]] -== Properties and Configuration += Properties and Configuration + This section includes topics about setting and reading properties and configuration settings and their interaction with Spring Boot applications. [[howto.properties-and-configuration.expand-properties]] -=== Automatically Expand Properties at Build Time +== Automatically Expand Properties at Build Time + Rather than hardcoding some properties that are also specified in your project's build configuration, you can automatically expand them by instead using the existing build configuration. This is possible in both Maven and Gradle. [[howto.properties-and-configuration.expand-properties.maven]] -==== Automatic Property Expansion Using Maven +=== Automatic Property Expansion Using Maven + You can automatically expand properties from the Maven project by using resource filtering. If you use the `spring-boot-starter-parent`, you can then refer to your Maven '`project properties`' with `@..@` placeholders, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops%novalidate,yaml] ---- - app: - encoding: "@project.build.sourceEncoding@" - java: - version: "@java.version@" +app: + encoding: "@project.build.sourceEncoding@" + java: + version: "@java.version@" ---- NOTE: Only production configuration is filtered that way (in other words, no filtering is applied on `src/test/resources`). @@ -29,35 +32,35 @@ NOTE: Only production configuration is filtered that way (in other words, no fil TIP: If you enable the `addResources` flag, the `spring-boot:run` goal can add `src/main/resources` directly to the classpath (for hot reloading purposes). Doing so circumvents the resource filtering and this feature. Instead, you can use the `exec:java` goal or customize the plugin's configuration. -See the {spring-boot-maven-plugin-docs}#getting-started[plugin usage page] for more details. +See the xref:maven-plugin:using.adoc[plugin usage page] for more details. If you do not use the starter parent, you need to include the following element inside the `` element of your `pom.xml`: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - - src/main/resources - true - - + + + src/main/resources + true + + ---- You also need to include the following element inside ``: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - org.apache.maven.plugins - maven-resources-plugin - 2.7 - - - @ - - false - - + + org.apache.maven.plugins + maven-resources-plugin + 2.7 + + + @ + + false + + ---- NOTE: The `useDefaultDelimiters` property is important if you use standard Spring placeholders (such as `$\{placeholder}`) in your configuration. @@ -66,23 +69,24 @@ If that property is not set to `false`, these may be expanded by the build. [[howto.properties-and-configuration.expand-properties.gradle]] -==== Automatic Property Expansion Using Gradle +=== Automatic Property Expansion Using Gradle + You can automatically expand properties from the Gradle project by configuring the Java plugin's `processResources` task to do so, as shown in the following example: -[source,gradle,indent=0,subs="verbatim"] +[source,gradle] ---- - tasks.named('processResources') { - expand(project.properties) - } +tasks.named('processResources') { + expand(project.properties) +} ---- You can then refer to your Gradle project's properties by using placeholders, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops%novalidate,yaml] ---- - app: - name: "${name}" - description: "${description}" +app: + name: "${name}" + description: "${description}" ---- NOTE: Gradle's `expand` method uses Groovy's `SimpleTemplateEngine`, which transforms `${..}` tokens. @@ -92,17 +96,18 @@ To use Spring property placeholders together with automatic expansion, escape th [[howto.properties-and-configuration.externalize-configuration]] -=== Externalize the Configuration of SpringApplication +== Externalize the Configuration of SpringApplication + A `SpringApplication` has bean property setters, so you can use its Java API as you create the application to modify its behavior. Alternatively, you can externalize the configuration by setting properties in `+spring.main.*+`. For example, in `application.properties`, you might have the following settings: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - main: - web-application-type: "none" - banner-mode: "off" +spring: + main: + web-application-type: "none" + banner-mode: "off" ---- Then the Spring Boot banner is not printed on startup, and the application is not starting an embedded web server. @@ -110,20 +115,20 @@ Then the Spring Boot banner is not printed on startup, and the application is no Properties defined in external configuration override and replace the values specified with the Java API, with the notable exception of the primary sources. Primary sources are those provided to the `SpringApplication` constructor: -include::code:application/MyApplication[] +include-code::application/MyApplication[] Or to `sources(...)` method of a `SpringApplicationBuilder`: -include::code:builder/MyApplication[] +include-code::builder/MyApplication[] Given the examples above, if we have the following configuration: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - main: - sources: "com.example.MyDatabaseConfig,com.example.MyJmsConfig" - banner-mode: "console" +spring: + main: + sources: "com.example.MyDatabaseConfig,com.example.MyJmsConfig" + banner-mode: "console" ---- The actual application will show the banner (as overridden by configuration) and uses three sources for the `ApplicationContext`. @@ -136,8 +141,9 @@ The application sources are: [[howto.properties-and-configuration.external-properties-location]] -=== Change the Location of External Properties of an Application -By default, properties from different sources are added to the Spring `Environment` in a defined order (see "`<>`" in the '`Spring Boot features`' section for the exact order). +== Change the Location of External Properties of an Application + +By default, properties from different sources are added to the Spring `Environment` in a defined order (see "`xref:reference:features/external-config.adoc[Externalized Configuration]`" in the '`Spring Boot features`' section for the exact order). You can also provide the following System properties (or environment variables) to change the behavior: @@ -148,19 +154,20 @@ You can also provide the following System properties (or environment variables) No matter what you set in the environment, Spring Boot always loads `application.properties` as described above. By default, if YAML is used, then files with the '`.yaml`' and '`.yml`' extension are also added to the list. -TIP: If you want detailed information about the files that are being loaded you can <> of `org.springframework.boot.context.config` to `trace`. +TIP: If you want detailed information about the files that are being loaded you can xref:reference:features/logging.adoc#features.logging.log-levels[set the logging level] of `org.springframework.boot.context.config` to `trace`. [[howto.properties-and-configuration.short-command-line-arguments]] -=== Use '`Short`' Command Line Arguments +== Use '`Short`' Command Line Arguments + Some people like to use (for example) `--port=9000` instead of `--server.port=9000` to set configuration properties on the command line. You can enable this behavior by using placeholders in `application.properties`, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - server: - port: "${port:8080}" +server: + port: "${port:8080}" ---- TIP: If you inherit from the `spring-boot-starter-parent` POM, the default filter token of the `maven-resources-plugins` has been changed from `+${*}+` to `@` (that is, `@maven.token@` instead of `${maven.token}`) to prevent conflicts with Spring-style placeholders. @@ -172,19 +179,20 @@ In those two platforms, the `PORT` environment variable is set automatically and [[howto.properties-and-configuration.yaml]] -=== Use YAML for External Properties +== Use YAML for External Properties + YAML is a superset of JSON and, as such, is a convenient syntax for storing external properties in a hierarchical format, as shown in the following example: -[source,yaml,indent=0,subs="verbatim"] +[source,yaml] ---- - spring: - application: - name: "cruncher" - datasource: - driver-class-name: "com.mysql.jdbc.Driver" - url: "jdbc:mysql://localhost/test" - server: - port: 9000 +spring: + application: + name: "cruncher" + datasource: + driver-class-name: "com.mysql.jdbc.Driver" + url: "jdbc:mysql://localhost/test" +server: + port: 9000 ---- Create a file called `application.yaml` and put it in the root of your classpath. @@ -193,87 +201,90 @@ A YAML file is parsed to a Java `Map` (like a JSON object), and S The preceding example YAML corresponds to the following `application.properties` file: -[source,properties,indent=0,subs="verbatim",configprops] +[source,properties,subs="verbatim",configprops] ---- - spring.application.name=cruncher - spring.datasource.driver-class-name=com.mysql.jdbc.Driver - spring.datasource.url=jdbc:mysql://localhost/test - server.port=9000 +spring.application.name=cruncher +spring.datasource.driver-class-name=com.mysql.jdbc.Driver +spring.datasource.url=jdbc:mysql://localhost/test +server.port=9000 ---- -See "`<>`" in the '`Spring Boot features`' section for more information about YAML. +See "`xref:reference:features/external-config.adoc#features.external-config.yaml[Working With YAML]`" in the '`Spring Boot features`' section for more information about YAML. [[howto.properties-and-configuration.set-active-spring-profiles]] -=== Set the Active Spring Profiles +== Set the Active Spring Profiles + The Spring `Environment` has an API for this, but you would normally set a System property (configprop:spring.profiles.active[]) or an OS environment variable (configprop:spring.profiles.active[format=envvar]). Also, you can launch your application with a `-D` argument (remember to put it before the main class or jar archive), as follows: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ java -jar -Dspring.profiles.active=production demo-0.0.1-SNAPSHOT.jar +$ java -jar -Dspring.profiles.active=production demo-0.0.1-SNAPSHOT.jar ---- In Spring Boot, you can also set the active profile in `application.properties`, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - profiles: - active: "production" +spring: + profiles: + active: "production" ---- A value set this way is replaced by the System property or environment variable setting but not by the `SpringApplicationBuilder.profiles()` method. Thus, the latter Java API can be used to augment the profiles without changing the defaults. -See "`<>`" in the "`Spring Boot features`" section for more information. +See "`xref:reference:features/profiles.adoc[Profiles]`" in the "`Spring Boot features`" section for more information. [[howto.properties-and-configuration.set-default-spring-profile-name]] -=== Set the Default Profile Name +== Set the Default Profile Name + The default profile is a profile that is enabled if no profile is active. By default, the name of the default profile is `default`, but it could be changed using a System property (configprop:spring.profiles.default[]) or an OS environment variable (configprop:spring.profiles.default[format=envvar]). In Spring Boot, you can also set the default profile name in `application.properties`, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - profiles: - default: "dev" +spring: + profiles: + default: "dev" ---- -See "`<>`" in the "`Spring Boot features`" section for more information. +See "`xref:reference:features/profiles.adoc[Profiles]`" in the "`Spring Boot features`" section for more information. [[howto.properties-and-configuration.change-configuration-depending-on-the-environment]] -=== Change Configuration Depending on the Environment -Spring Boot supports multi-document YAML and Properties files (see <> for details) which can be activated conditionally based on the active profiles. +== Change Configuration Depending on the Environment + +Spring Boot supports multi-document YAML and Properties files (see xref:reference:features/external-config.adoc#features.external-config.files.multi-document[Working With Multi-Document Files] for details) which can be activated conditionally based on the active profiles. If a document contains a `spring.config.activate.on-profile` key, then the profiles value (a comma-separated list of profiles or a profile expression) is fed into the Spring `Environment.acceptsProfiles()` method. If the profile expression matches then that document is included in the final merge (otherwise, it is not), as shown in the following example: -[source,yaml,indent=0,subs="verbatim,attributes",configprops,configblocks] +[configprops,yaml] ---- - server: - port: 9000 - --- - spring: - config: - activate: - on-profile: "development" - server: - port: 9001 - --- - spring: - config: - activate: - on-profile: "production" - server: - port: 0 +server: + port: 9000 +--- +spring: + config: + activate: + on-profile: "development" +server: + port: 9001 +--- +spring: + config: + activate: + on-profile: "production" +server: + port: 0 ---- In the preceding example, the default port is 9000. @@ -286,12 +297,13 @@ Later values override earlier values. [[howto.properties-and-configuration.discover-build-in-options-for-external-properties]] -=== Discover Built-in Options for External Properties +== Discover Built-in Options for External Properties + Spring Boot binds external properties from `application.properties` (or YAML files and other places) into an application at runtime. There is not (and technically cannot be) an exhaustive list of all supported properties in a single location, because contributions can come from additional jar files on your classpath. A running application with the Actuator features has a `configprops` endpoint that shows all the bound and bindable properties available through `@ConfigurationProperties`. -The appendix includes an <> example with a list of the most common properties supported by Spring Boot. +The appendix includes an xref:appendix:application-properties/index.adoc[`application.properties`] example with a list of the most common properties supported by Spring Boot. The definitive list comes from searching the source code for `@ConfigurationProperties` and `@Value` annotations as well as the occasional use of `Binder`. -For more about the exact ordering of loading properties, see "<>". +For more about the exact ordering of loading properties, see "xref:reference:features/external-config.adoc[Externalized Configuration]". diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/security.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/security.adoc similarity index 77% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/security.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/security.adoc index 5f813b9c76..4593b14a99 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/security.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/security.adoc @@ -1,40 +1,44 @@ [[howto.security]] -== Security += Security + This section addresses questions about security when working with Spring Boot, including questions that arise from using Spring Security with Spring Boot. -For more about Spring Security, see the {spring-security}[Spring Security project page]. +For more about Spring Security, see the {url-spring-security-site}[Spring Security project page]. [[howto.security.switch-off-spring-boot-configuration]] -=== Switch off the Spring Boot Security Configuration +== Switch off the Spring Boot Security Configuration + If you define a `@Configuration` with a `SecurityFilterChain` bean in your application, this action switches off the default webapp security settings in Spring Boot. [[howto.security.change-user-details-service-and-add-user-accounts]] -=== Change the UserDetailsService and Add User Accounts +== Change the UserDetailsService and Add User Accounts + If you provide a `@Bean` of type `AuthenticationManager`, `AuthenticationProvider`, or `UserDetailsService`, the default `@Bean` for `InMemoryUserDetailsManager` is not created. -This means you have the full feature set of Spring Security available (such as {spring-security-docs}/servlet/authentication/index.html[various authentication options]). +This means you have the full feature set of Spring Security available (such as {url-spring-security-docs}/servlet/authentication/index.html[various authentication options]). The easiest way to add user accounts is by providing your own `UserDetailsService` bean. [[howto.security.enable-https]] -=== Enable HTTPS When Running behind a Proxy Server +== Enable HTTPS When Running behind a Proxy Server + Ensuring that all your main endpoints are only available over HTTPS is an important chore for any application. If you use Tomcat as a servlet container, then Spring Boot adds Tomcat's own `RemoteIpValve` automatically if it detects some environment settings, allowing you to rely on the `HttpServletRequest` to report whether it is secure or not (even downstream of a proxy server that handles the real SSL termination). The standard behavior is determined by the presence or absence of certain request headers (`x-forwarded-for` and `x-forwarded-proto`), whose names are conventional, so it should work with most front-end proxies. You can switch on the valve by adding some entries to `application.properties`, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - server: - tomcat: - remoteip: - remote-ip-header: "x-forwarded-for" - protocol-header: "x-forwarded-proto" +server: + tomcat: + remoteip: + remote-ip-header: "x-forwarded-for" + protocol-header: "x-forwarded-proto" ---- (The presence of either of those properties switches on the valve. @@ -42,4 +46,4 @@ Alternatively, you can add the `RemoteIpValve` by customizing the `TomcatServlet To configure Spring Security to require a secure channel for all (or some) requests, consider adding your own `SecurityFilterChain` bean that adds the following `HttpSecurity` configuration: -include::code:MySecurityConfig[] +include-code::MySecurityConfig[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/spring-mvc.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/spring-mvc.adoc similarity index 86% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/spring-mvc.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/spring-mvc.adoc index 1a137f05a2..4d95b559e4 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/spring-mvc.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/spring-mvc.adoc @@ -1,5 +1,6 @@ [[howto.spring-mvc]] -== Spring MVC += Spring MVC + Spring Boot has a number of starters that include Spring MVC. Note that some starters include a dependency on Spring MVC rather than include it directly. This section answers common questions about Spring MVC and Spring Boot. @@ -7,10 +8,11 @@ This section answers common questions about Spring MVC and Spring Boot. [[howto.spring-mvc.write-json-rest-service]] -=== Write a JSON REST Service +== Write a JSON REST Service + Any Spring `@RestController` in a Spring Boot application should render JSON response by default as long as Jackson2 is on the classpath, as shown in the following example: -include::code:MyController[] +include-code::MyController[] As long as `MyThing` can be serialized by Jackson2 (true for a normal POJO or Groovy object), then `http://localhost:8080/thing` serves a JSON representation of it by default. Note that, in a browser, you might sometimes see XML responses, because browsers tend to send accept headers that prefer XML. @@ -18,31 +20,32 @@ Note that, in a browser, you might sometimes see XML responses, because browsers [[howto.spring-mvc.write-xml-rest-service]] -=== Write an XML REST Service +== Write an XML REST Service + If you have the Jackson XML extension (`jackson-dataformat-xml`) on the classpath, you can use it to render XML responses. The previous example that we used for JSON would work. To use the Jackson XML renderer, add the following dependency to your project: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + ---- If Jackson's XML extension is not available and JAXB is available, XML can be rendered with the additional requirement of having `MyThing` annotated as `@XmlRootElement`, as shown in the following example: -include::code:MyThing[] +include-code::MyThing[] You will need to ensure that the JAXB library is part of your project, for example by adding: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - org.glassfish.jaxb - jaxb-runtime - + + org.glassfish.jaxb + jaxb-runtime + ---- NOTE: To get the server to render XML instead of JSON, you might have to send an `Accept: text/xml` header (or use a browser). @@ -50,7 +53,8 @@ NOTE: To get the server to render XML instead of JSON, you might have to send an [[howto.spring-mvc.customize-jackson-objectmapper]] -=== Customize the Jackson ObjectMapper +== Customize the Jackson ObjectMapper + Spring MVC (client and server side) uses `HttpMessageConverters` to negotiate content conversion in an HTTP exchange. If Jackson is on the classpath, you already get the default converter(s) provided by `Jackson2ObjectMapperBuilder`, an instance of which is auto-configured for you. @@ -104,7 +108,7 @@ These features are described in several enums (in Jackson) that map onto propert |=== For example, to enable pretty print, set `spring.jackson.serialization.indent_output=true`. -Note that, thanks to the use of <>, the case of `indent_output` does not have to match the case of the corresponding enum constant, which is `INDENT_OUTPUT`. +Note that, thanks to the use of xref:reference:features/external-config.adoc#features.external-config.typesafe-configuration-properties.relaxed-binding[relaxed binding], the case of `indent_output` does not have to match the case of the corresponding enum constant, which is `INDENT_OUTPUT`. This environment-based configuration is applied to the auto-configured `Jackson2ObjectMapperBuilder` bean and applies to any mappers created by using the builder, including the auto-configured `ObjectMapper` bean. @@ -121,12 +125,13 @@ If you provide any `@Beans` of type `MappingJackson2HttpMessageConverter`, they Also, a convenience bean of type `HttpMessageConverters` is provided (and is always available if you use the default MVC configuration). It has some useful methods to access the default and user-enhanced message converters. -See the "`<>`" section and the {spring-boot-autoconfigure-module-code}/web/servlet/WebMvcAutoConfiguration.java[`WebMvcAutoConfiguration`] source code for more details. +See the "`xref:spring-mvc.adoc#howto.spring-mvc.customize-responsebody-rendering[Customize the @ResponseBody Rendering]`" section and the {code-spring-boot-autoconfigure-src}/web/servlet/WebMvcAutoConfiguration.java[`WebMvcAutoConfiguration`] source code for more details. [[howto.spring-mvc.customize-responsebody-rendering]] -=== Customize the @ResponseBody Rendering +== Customize the @ResponseBody Rendering + Spring uses `HttpMessageConverters` to render `@ResponseBody` (or responses from `@RestController`). You can contribute additional converters by adding beans of the appropriate type in a Spring Boot context. If a bean you add is of a type that would have been included by default anyway (such as `MappingJackson2HttpMessageConverter` for JSON conversions), it replaces the default value. @@ -137,12 +142,13 @@ As in normal MVC usage, any `WebMvcConfigurer` beans that you provide can also c However, unlike with normal MVC, you can supply only additional converters that you need (because Spring Boot uses the same mechanism to contribute its defaults). Finally, if you opt out of the Spring Boot default MVC configuration by providing your own `@EnableWebMvc` configuration, you can take control completely and do everything manually by using `getMessageConverters` from `WebMvcConfigurationSupport`. -See the {spring-boot-autoconfigure-module-code}/web/servlet/WebMvcAutoConfiguration.java[`WebMvcAutoConfiguration`] source code for more details. +See the {code-spring-boot-autoconfigure-src}/web/servlet/WebMvcAutoConfiguration.java[`WebMvcAutoConfiguration`] source code for more details. [[howto.spring-mvc.multipart-file-uploads]] -=== Handling Multipart File Uploads +== Handling Multipart File Uploads + Spring Boot embraces the servlet 5 `jakarta.servlet.http.Part` API to support uploading files. By default, Spring Boot configures Spring MVC with a maximum size of 1MB per file and a maximum of 10MB of file data in a single request. You may override these values, the location to which intermediate data is stored (for example, to the `/tmp` directory), and the threshold past which data is flushed to disk by using the properties exposed in the `MultipartProperties` class. @@ -150,23 +156,24 @@ For example, if you want to specify that files be unlimited, set the configprop: The multipart support is helpful when you want to receive multipart encoded file data as a `@RequestParam`-annotated parameter of type `MultipartFile` in a Spring MVC controller handler method. -See the {spring-boot-autoconfigure-module-code}/web/servlet/MultipartAutoConfiguration.java[`MultipartAutoConfiguration`] source for more details. +See the {code-spring-boot-autoconfigure-src}/web/servlet/MultipartAutoConfiguration.java[`MultipartAutoConfiguration`] source for more details. NOTE: It is recommended to use the container's built-in support for multipart uploads rather than introducing an additional dependency such as Apache Commons File Upload. [[howto.spring-mvc.switch-off-dispatcherservlet]] -=== Switch Off the Spring MVC DispatcherServlet +== Switch Off the Spring MVC DispatcherServlet + By default, all content is served from the root of your application (`/`). If you would rather map to a different path, you can configure one as follows: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - mvc: - servlet: - path: "/mypath" +spring: + mvc: + servlet: + path: "/mypath" ---- If you have additional servlets you can declare a `@Bean` of type `Servlet` or `ServletRegistrationBean` for each and Spring Boot will register them transparently to the container. @@ -177,14 +184,16 @@ Configuring the `DispatcherServlet` yourself is unusual but if you really need t [[howto.spring-mvc.switch-off-default-configuration]] -=== Switch off the Default MVC Configuration +== Switch off the Default MVC Configuration + The easiest way to take complete control over MVC configuration is to provide your own `@Configuration` with the `@EnableWebMvc` annotation. Doing so leaves all MVC configuration in your hands. [[howto.spring-mvc.customize-view-resolvers]] -=== Customize ViewResolvers +== Customize ViewResolvers + A `ViewResolver` is a core component of Spring MVC, translating view names in `@Controller` to actual `View` implementations. Note that `ViewResolvers` are mainly used in UI applications, rather than REST-style services (a `View` is not used to render a `@ResponseBody`). There are many implementations of `ViewResolver` to choose from, and Spring on its own is not opinionated about which ones you should use. @@ -227,7 +236,7 @@ If you add your own, you have to be aware of the order and in which position you For more detail, see the following sections: -* {spring-boot-autoconfigure-module-code}/web/servlet/WebMvcAutoConfiguration.java[`WebMvcAutoConfiguration`] -* {spring-boot-autoconfigure-module-code}/thymeleaf/ThymeleafAutoConfiguration.java[`ThymeleafAutoConfiguration`] -* {spring-boot-autoconfigure-module-code}/freemarker/FreeMarkerAutoConfiguration.java[`FreeMarkerAutoConfiguration`] -* {spring-boot-autoconfigure-module-code}/groovy/template/GroovyTemplateAutoConfiguration.java[`GroovyTemplateAutoConfiguration`] +* {code-spring-boot-autoconfigure-src}/web/servlet/WebMvcAutoConfiguration.java[`WebMvcAutoConfiguration`] +* {code-spring-boot-autoconfigure-src}/thymeleaf/ThymeleafAutoConfiguration.java[`ThymeleafAutoConfiguration`] +* {code-spring-boot-autoconfigure-src}/freemarker/FreeMarkerAutoConfiguration.java[`FreeMarkerAutoConfiguration`] +* {code-spring-boot-autoconfigure-src}/groovy/template/GroovyTemplateAutoConfiguration.java[`GroovyTemplateAutoConfiguration`] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/testing.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/testing.adoc similarity index 77% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/testing.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/testing.adoc index f0a1a1f923..501002aa4c 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/testing.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/testing.adoc @@ -1,34 +1,34 @@ [[howto.testing]] -== Testing += Testing + Spring Boot includes a number of testing utilities and support classes as well as a dedicated starter that provides common test dependencies. This section answers common questions about testing. [[howto.testing.with-spring-security]] -=== Testing With Spring Security +== Testing With Spring Security + Spring Security provides support for running tests as a specific user. For example, the test in the snippet below will run with an authenticated user that has the `ADMIN` role. -include::code:MySecurityTests[] +include-code::MySecurityTests[] Spring Security provides comprehensive integration with Spring MVC Test, and this can also be used when testing controllers using the `@WebMvcTest` slice and `MockMvc`. -For additional details on Spring Security's testing support, see Spring Security's {spring-security-docs}/servlet/test/index.html[reference documentation]. +For additional details on Spring Security's testing support, see Spring Security's {url-spring-security-docs}/servlet/test/index.html[reference documentation]. [[howto.testing.slice-tests]] -=== Structure `@Configuration` classes for inclusion in slice tests +== Structure `@Configuration` classes for inclusion in slice tests + Slice tests work by restricting Spring Framework's component scanning to a limited set of components based on their type. For any beans that are not created through component scanning, for example, beans that are created using the `@Bean` annotation, slice tests will not be able to include/exclude them from the application context. Consider this example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/testing/slicetests/MyConfiguration.java[] ----- +include-code::MyConfiguration[] For a `@WebMvcTest` for an application with the above `@Configuration` class, you might expect to have the `SecurityFilterChain` bean in the application context so that you can test if your controller endpoints are secured properly. However, `MyConfiguration` is not picked up by @WebMvcTest's component scanning filter because it doesn't match any of the types specified by the filter. @@ -36,15 +36,9 @@ You can include the configuration explicitly by annotating the test class with ` This will load all the beans in `MyConfiguration` including the `BasicDataSource` bean which isn't required when testing the web tier. Splitting the configuration class into two will enable importing just the security configuration. -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/testing/slicetests/MySecurityConfiguration.java[] ----- +include-code::MySecurityConfiguration[] -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/howto/testing/slicetests/MyDatasourceConfiguration.java[] ----- +include-code::MyDatasourceConfiguration[] Having a single configuration class can be inefficient when beans of a certain domain need to be included in slice tests. Instead, structuring the application's configuration as multiple granular classes with beans for a specific domain can enable importing them only for specific slice tests. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/traditional-deployment.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/traditional-deployment.adoc similarity index 78% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/traditional-deployment.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/traditional-deployment.adoc index a9a29e7c59..fd739403f5 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/traditional-deployment.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/traditional-deployment.adoc @@ -1,12 +1,13 @@ [[howto.traditional-deployment]] -== Traditional Deployment += Traditional Deployment + Spring Boot supports traditional deployment as well as more modern forms of deployment. This section answers common questions about traditional deployment. [[howto.traditional-deployment.war]] -=== Create a Deployable War File +== Create a Deployable War File WARNING: Because Spring WebFlux does not strictly depend on the servlet API and applications are deployed by default on an embedded Reactor Netty server, War deployment is not supported for WebFlux applications. @@ -14,21 +15,21 @@ The first step in producing a deployable war file is to provide a `SpringBootSer Doing so makes use of Spring Framework's servlet 3.0 support and lets you configure your application when it is launched by the servlet container. Typically, you should update your application's main class to extend `SpringBootServletInitializer`, as shown in the following example: -include::code:MyApplication[] +include-code::MyApplication[] The next step is to update your build configuration such that your project produces a war file rather than a jar file. If you use Maven and `spring-boot-starter-parent` (which configures Maven's war plugin for you), all you need to do is to modify `pom.xml` to change the packaging to war, as follows: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - war +war ---- If you use Gradle, you need to modify `build.gradle` to apply the war plugin to the project, as follows: -[source,gradle,indent=0,subs="verbatim"] +[source,gradle] ---- - apply plugin: 'war' +apply plugin: 'war' ---- The final step in the process is to ensure that the embedded servlet container does not interfere with the servlet container to which the war file is deployed. @@ -36,47 +37,48 @@ To do so, you need to mark the embedded servlet container dependency as being pr If you use Maven, the following example marks the servlet container (Tomcat, in this case) as being provided: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - - - org.springframework.boot - spring-boot-starter-tomcat - provided - - - + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + ---- If you use Gradle, the following example marks the servlet container (Tomcat, in this case) as being provided: -[source,gradle,indent=0,subs="verbatim"] +[source,gradle] ---- - dependencies { - // ... - providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat' - // ... - } +dependencies { + // ... + providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat' + // ... +} ---- TIP: `providedRuntime` is preferred to Gradle's `compileOnly` configuration. Among other limitations, `compileOnly` dependencies are not on the test classpath, so any web-based integration tests fail. -If you use the <>, marking the embedded servlet container dependency as provided produces an executable war file with the provided dependencies packaged in a `lib-provided` directory. +If you use the xref:build-tool-plugin:index.adoc[Spring Boot build tools], marking the embedded servlet container dependency as provided produces an executable war file with the provided dependencies packaged in a `lib-provided` directory. This means that, in addition to being deployable to a servlet container, you can also run your application by using `java -jar` on the command line. [[howto.traditional-deployment.convert-existing-application]] -=== Convert an Existing Application to Spring Boot +== Convert an Existing Application to Spring Boot + To convert an existing non-web Spring application to a Spring Boot application, replace the code that creates your `ApplicationContext` and replace it with calls to `SpringApplication` or `SpringApplicationBuilder`. Spring MVC web applications are generally amenable to first creating a deployable war application and then migrating it later to an executable war or jar. See the https://spring.io/guides/gs/convert-jar-to-war/[Getting Started Guide on Converting a jar to a war]. To create a deployable war by extending `SpringBootServletInitializer` (for example, in a class called `Application`) and adding the Spring Boot `@SpringBootApplication` annotation, use code similar to that shown in the following example: -include::code:MyApplication[tag=!main] +include-code::MyApplication[tag=!main] Remember that, whatever you put in the `sources` is merely a Spring `ApplicationContext`. Normally, anything that already works should work here. @@ -95,13 +97,13 @@ If you have other features in your application (for instance, using other servle Once the war file is working, you can make it executable by adding a `main` method to your `Application`, as shown in the following example: -include::code:MyApplication[tag=main] +include-code::MyApplication[tag=main] [NOTE] ==== If you intend to start your application as a war or as an executable application, you need to share the customizations of the builder in a method that is both available to the `SpringBootServletInitializer` callback and in the `main` method in a class similar to the following: -include::code:both/MyApplication[] +include-code::both/MyApplication[] ==== Applications can fall into more than one category: @@ -117,7 +119,7 @@ Servlet 3.0+ applications might translate pretty easily if they already use the Normally, all the code from an existing `WebApplicationInitializer` can be moved into a `SpringBootServletInitializer`. If your existing application has more than one `ApplicationContext` (for example, if it uses `AbstractDispatcherServletInitializer`) then you might be able to combine all your context sources into a single `SpringApplication`. The main complication you might encounter is if combining does not work and you need to maintain the context hierarchy. -See the <> for examples. +See the xref:application.adoc#howto.application.context-hierarchy[entry on building a hierarchy] for examples. An existing parent context that contains web-specific features usually needs to be broken up so that all the `ServletContextAware` components are in the child context. Applications that are not already Spring applications might be convertible to Spring Boot applications, and the previously mentioned guidance may help. @@ -127,30 +129,31 @@ In that case, we suggest https://stackoverflow.com/questions/tagged/spring-boot[ [[howto.traditional-deployment.weblogic]] -=== Deploying a WAR to WebLogic +== Deploying a WAR to WebLogic + To deploy a Spring Boot application to WebLogic, you must ensure that your servlet initializer *directly* implements `WebApplicationInitializer` (even if you extend from a base class that already implements it). A typical initializer for WebLogic should resemble the following example: -include::code:MyApplication[] +include-code::MyApplication[] If you use Logback, you also need to tell WebLogic to prefer the packaged version rather than the version that was pre-installed with the server. You can do so by adding a `WEB-INF/weblogic.xml` file with the following contents: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - - - - org.slf4j - - - + + + + + org.slf4j + + + ---- diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/webserver.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/webserver.adoc similarity index 73% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/webserver.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/webserver.adoc index 0b9f33e7ed..d564517df7 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/webserver.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/pages/webserver.adoc @@ -1,5 +1,6 @@ [[howto.webserver]] -== Embedded Web Servers += Embedded Web Servers + Each Spring Boot web application includes an embedded web server. This feature leads to a number of how-to questions, including how to change the embedded server and how to configure the embedded server. This section answers those questions. @@ -7,7 +8,8 @@ This section answers those questions. [[howto.webserver.use-another]] -=== Use Another Web Server +== Use Another Web Server + Many Spring Boot starters include default embedded containers. * For servlet stack applications, the `spring-boot-starter-web` includes Tomcat by including `spring-boot-starter-tomcat`, but you can use `spring-boot-starter-jetty` or `spring-boot-starter-undertow` instead. @@ -18,39 +20,39 @@ To help with this process, Spring Boot provides a separate starter for each of t The following Maven example shows how to exclude Tomcat and include Jetty for Spring MVC: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - - org.springframework.boot - spring-boot-starter-jetty - + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + + org.springframework.boot + spring-boot-starter-jetty + ---- -The following Gradle example configures the necessary dependencies and a {gradle-docs}/resolution_rules.html#sec:module_replacement[module replacement] to use Undertow in place of Reactor Netty for Spring WebFlux: +The following Gradle example configures the necessary dependencies and a {url-gradle-docs}/resolution_rules.html#sec:module_replacement[module replacement] to use Undertow in place of Reactor Netty for Spring WebFlux: -[source,gradle,indent=0,subs="verbatim"] +[source,gradle] ---- - dependencies { - implementation "org.springframework.boot:spring-boot-starter-undertow" - implementation "org.springframework.boot:spring-boot-starter-webflux" - modules { - module("org.springframework.boot:spring-boot-starter-reactor-netty") { - replacedBy("org.springframework.boot:spring-boot-starter-undertow", "Use Undertow instead of Reactor Netty") - } +dependencies { + implementation "org.springframework.boot:spring-boot-starter-undertow" + implementation "org.springframework.boot:spring-boot-starter-webflux" + modules { + module("org.springframework.boot:spring-boot-starter-reactor-netty") { + replacedBy("org.springframework.boot:spring-boot-starter-undertow", "Use Undertow instead of Reactor Netty") } } +} ---- NOTE: `spring-boot-starter-reactor-netty` is required to use the `WebClient` class, so you may need to keep a dependency on Netty even when you need to include a different HTTP server. @@ -58,44 +60,48 @@ NOTE: `spring-boot-starter-reactor-netty` is required to use the `WebClient` cla [[howto.webserver.disable]] -=== Disabling the Web Server +== Disabling the Web Server + If your classpath contains the necessary bits to start a web server, Spring Boot will automatically start it. To disable this behavior configure the `WebApplicationType` in your `application.properties`, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - main: - web-application-type: "none" +spring: + main: + web-application-type: "none" ---- [[howto.webserver.change-port]] -=== Change the HTTP Port +== Change the HTTP Port + In a standalone application, the main HTTP port defaults to `8080` but can be set with configprop:server.port[] (for example, in `application.properties` or as a System property). Thanks to relaxed binding of `Environment` values, you can also use configprop:server.port[format=envvar] (for example, as an OS environment variable). 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 "`xref:reference:web/servlet.adoc#web.servlet.embedded-container.customizing[Customizing Embedded Servlet Containers]`" in the '`Spring Boot Features`' section, or the {code-spring-boot-autoconfigure-src}/web/ServerProperties.java[`ServerProperties`] source code. [[howto.webserver.use-random-port]] -=== Use a Random Unassigned HTTP Port +== Use a Random Unassigned HTTP Port + To scan for a free port (using OS natives to prevent clashes) use `server.port=0`. [[howto.webserver.discover-port]] -=== Discover the HTTP Port at Runtime +== Discover the HTTP Port at Runtime + You can access the port the server is running on from log output or from the `WebServerApplicationContext` through its `WebServer`. The best way to get that and be sure it has been initialized is to add a `@Bean` of type `ApplicationListener` and pull the container out of the event when it is published. Tests that use `@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)` can also inject the actual port into a field by using the `@LocalServerPort` annotation, as shown in the following example: -include::code:MyWebIntegrationTests[] +include-code::MyWebIntegrationTests[] [NOTE] ==== @@ -108,15 +114,16 @@ Contrary to a test, application code callbacks are processed early (before the v [[howto.webserver.enable-response-compression]] -=== Enable HTTP Response Compression +== Enable HTTP Response Compression + HTTP response compression is supported by Jetty, Tomcat, Reactor Netty, and Undertow. It can be enabled in `application.properties`, as follows: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - server: - compression: - enabled: true +server: + compression: + enabled: true ---- By default, responses must be at least 2048 bytes in length for compression to be performed. @@ -138,18 +145,19 @@ You can configure this behavior by setting the configprop:server.compression.mim [[howto.webserver.configure-ssl]] -=== Configure SSL +== Configure SSL + SSL can be configured declaratively by setting the various `+server.ssl.*+` properties, typically in `application.properties` or `application.yaml`. The following example shows setting SSL properties using a Java KeyStore file: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - server: - port: 8443 - ssl: - key-store: "classpath:keystore.jks" - key-store-password: "secret" - key-password: "another-secret" +server: + port: 8443 + ssl: + key-store: "classpath:keystore.jks" + key-store-password: "secret" + key-password: "another-secret" ---- Using configuration such as the preceding example means the application no longer supports a plain HTTP connector at port 8080. @@ -160,69 +168,73 @@ We recommend using `application.properties` to configure HTTPS, as the HTTP conn [[howto.webserver.configure-ssl.pem-files]] -==== Using PEM-encoded files +=== Using PEM-encoded files + You can use PEM-encoded files instead of Java KeyStore files. You should use PKCS#8 key files wherever possible. PEM-encoded PKCS#8 key files start with a `-----BEGIN PRIVATE KEY-----` or `-----BEGIN ENCRYPTED PRIVATE KEY-----` header. If you have files in other formats, e.g., PKCS#1 (`-----BEGIN RSA PRIVATE KEY-----`) or SEC 1 (`-----BEGIN EC PRIVATE KEY-----`), you can convert them to PKCS#8 using OpenSSL: -[source,shell,indent=0,subs="verbatim,attributes"] +[source,shell,subs="verbatim,attributes"] ---- openssl pkcs8 -topk8 -nocrypt -in -out ---- The following example shows setting SSL properties using PEM-encoded certificate and private key files: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - server: - port: 8443 - ssl: - certificate: "classpath:my-cert.crt" - certificate-private-key: "classpath:my-cert.key" - trust-certificate: "classpath:ca-cert.crt" +server: + port: 8443 + ssl: + certificate: "classpath:my-cert.crt" + certificate-private-key: "classpath:my-cert.key" + trust-certificate: "classpath:ca-cert.crt" ---- -Alternatively, the SSL trust material can be configured in an <> and applied to the web server as shown in this example: +Alternatively, the SSL trust material can be configured in an xref:reference:features/ssl.adoc[SSL bundle] and applied to the web server as shown in this example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - server: - port: 8443 - ssl: - bundle: "example" +server: + port: 8443 + ssl: + bundle: "example" ---- NOTE: The `server.ssl.bundle` property can not be combined with the discrete Java KeyStore or PEM property options under `server.ssl`. -See {spring-boot-module-code}/web/server/Ssl.java[`Ssl`] for details of all of the supported properties. +See {code-spring-boot-src}/web/server/Ssl.java[`Ssl`] for details of all of the supported properties. [[howto.webserver.configure-http2]] -=== Configure HTTP/2 +== Configure HTTP/2 + You can enable HTTP/2 support in your Spring Boot application with the configprop:server.http2.enabled[] configuration property. Both `h2` (HTTP/2 over TLS) and `h2c` (HTTP/2 over TCP) are supported. To use `h2`, SSL must also be enabled. When SSL is not enabled, `h2c` will be used. -You may, for example, want to use `h2c` when your application is <> that is performing TLS termination. +You may, for example, want to use `h2c` when your application is xref:webserver.adoc#howto.webserver.use-behind-a-proxy-server[running behind a proxy server] that is performing TLS termination. [[howto.webserver.configure-http2.tomcat]] -==== HTTP/2 With Tomcat +=== HTTP/2 With Tomcat + Spring Boot ships by default with Tomcat 10.1.x which supports `h2c` and `h2` out of the box. Alternatively, you can use `libtcnative` for `h2` support if the library and its dependencies are installed on the host operating system. The library directory must be made available, if not already, to the JVM library path. You can do so with a JVM argument such as `-Djava.library.path=/usr/local/opt/tomcat-native/lib`. -More on this in the {tomcat-docs}/apr.html[official Tomcat documentation]. +More on this in the {url-tomcat-docs}/apr.html[official Tomcat documentation]. [[howto.webserver.configure-http2.jetty]] -==== HTTP/2 With Jetty +=== HTTP/2 With Jetty + For HTTP/2 support, Jetty requires the additional `org.eclipse.jetty.http2:jetty-http2-server` dependency. To use `h2c` no other dependencies are required. To use `h2`, you also need to choose one of the following dependencies, depending on your deployment: @@ -233,7 +245,8 @@ To use `h2`, you also need to choose one of the following dependencies, dependin [[howto.webserver.configure-http2.netty]] -==== HTTP/2 With Reactor Netty +=== HTTP/2 With Reactor Netty + The `spring-boot-webflux-starter` is using by default Reactor Netty as a server. Reactor Netty supports `h2c` and `h2` out of the box. For optimal runtime performance, this server also supports `h2` with native libraries. @@ -245,25 +258,27 @@ Developers can choose to import only the required dependencies using a classifie [[howto.webserver.configure-http2.undertow]] -==== HTTP/2 With Undertow +=== HTTP/2 With Undertow + Undertow supports `h2c` and `h2` out of the box. [[howto.webserver.configure]] -=== Configure the Web Server +== Configure the Web Server + Generally, you should first consider using one of the many available configuration keys and customize your web server by adding new entries in your `application.properties` or `application.yaml` file. -See "`<>`"). +See "`xref:properties-and-configuration.adoc#howto.properties-and-configuration.discover-build-in-options-for-external-properties[Discover Built-in Options for External Properties]`"). The `server.{asterisk}` namespace is quite useful here, and it includes namespaces like `server.tomcat.{asterisk}`, `server.jetty.{asterisk}` and others, for server-specific features. -See the list of <>. +See the list of xref:appendix:application-properties/index.adoc[Common Application Properties]. The previous sections covered already many common use cases, such as compression, SSL or HTTP/2. -However, if a configuration key does not exist for your use case, you should then look at {spring-boot-module-api}/web/server/WebServerFactoryCustomizer.html[`WebServerFactoryCustomizer`]. +However, if a configuration key does not exist for your use case, you should then look at xref:api:java/org/springframework/boot/web/server/WebServerFactoryCustomizer.html[`WebServerFactoryCustomizer`]. You can declare such a component and get access to the server factory relevant to your choice: you should select the variant for the chosen Server (Tomcat, Jetty, Reactor Netty, Undertow) and the chosen web stack (servlet or reactive). The example below is for Tomcat with the `spring-boot-starter-web` (servlet stack): -include::code:MyTomcatWebServerCustomizer[] +include-code::MyTomcatWebServerCustomizer[] NOTE: Spring Boot uses that infrastructure internally to auto-configure the server. Auto-configured `WebServerFactoryCustomizer` beans have an order of `0` and will be processed before any user-defined customizers, unless it has an explicit order that states otherwise. @@ -300,16 +315,18 @@ When you do so, auto-configured customizers are still applied on your custom fac [[howto.webserver.add-servlet-filter-listener]] -=== Add a Servlet, Filter, or Listener to an Application +== Add a Servlet, Filter, or Listener to an Application + In a servlet stack application, that is with the `spring-boot-starter-web`, there are two ways to add `Servlet`, `Filter`, `ServletContextListener`, and the other listeners supported by the Servlet API to your application: -* <> -* <> +* xref:webserver.adoc#howto.webserver.add-servlet-filter-listener.spring-bean[Add a Servlet, Filter, or Listener by Using a Spring Bean] +* xref:webserver.adoc#howto.webserver.add-servlet-filter-listener.using-scanning[Add Servlets, Filters, and Listeners by Using Classpath Scanning] [[howto.webserver.add-servlet-filter-listener.spring-bean]] -==== Add a Servlet, Filter, or Listener by Using a Spring Bean +=== Add a Servlet, Filter, or Listener by Using a Spring Bean + To add a `Servlet`, `Filter`, or servlet `*Listener` by using a Spring bean, you must provide a `@Bean` definition for it. Doing so can be very useful when you want to inject configuration or dependencies. However, you must be very careful that they do not cause eager initialization of too many other beans, because they have to be installed in the container very early in the application lifecycle. @@ -324,40 +341,43 @@ 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 "`xref:reference:web/servlet.adoc#web.servlet.embedded-container.servlets-filters-listeners.beans[Registering Servlets, Filters, and Listeners as Spring Beans]`" section. [[howto.webserver.add-servlet-filter-listener.spring-bean.disable]] -===== Disable Registration of a Servlet or Filter -As <>, any `Servlet` or `Filter` beans are registered with the servlet container automatically. +==== Disable Registration of a Servlet or Filter + +As xref:webserver.adoc#howto.webserver.add-servlet-filter-listener.spring-bean[described earlier], any `Servlet` or `Filter` beans are registered with the servlet container automatically. To disable registration of a particular `Filter` or `Servlet` bean, create a registration bean for it and mark it as disabled, as shown in the following example: -include::code:MyFilterConfiguration[] +include-code::MyFilterConfiguration[] [[howto.webserver.add-servlet-filter-listener.using-scanning]] -==== Add Servlets, Filters, and Listeners by Using Classpath Scanning +=== Add Servlets, Filters, and Listeners by Using Classpath Scanning + `@WebServlet`, `@WebFilter`, and `@WebListener` annotated classes can be automatically registered with an embedded servlet container by annotating a `@Configuration` class with `@ServletComponentScan` and specifying the package(s) containing the components that you want to register. By default, `@ServletComponentScan` scans from the package of the annotated class. [[howto.webserver.configure-access-logs]] -=== Configure Access Logging +== Configure Access Logging + Access logs can be configured for Tomcat, Undertow, and Jetty through their respective namespaces. -For instance, the following settings log access on Tomcat with a {tomcat-docs}/config/valve.html#Access_Logging[custom pattern]. +For instance, the following settings log access on Tomcat with a {url-tomcat-docs}/config/valve.html#Access_Logging[custom pattern]. -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - server: - tomcat: - basedir: "my-tomcat" - accesslog: - enabled: true - pattern: "%t %a %r %s (%D microseconds)" +server: + tomcat: + basedir: "my-tomcat" + accesslog: + enabled: true + pattern: "%t %a %r %s (%D microseconds)" ---- NOTE: The default location for logs is a `logs` directory relative to the Tomcat base directory. @@ -366,16 +386,16 @@ In the preceding example, the logs are available in `my-tomcat/logs` relative to Access logging for Undertow can be configured in a similar fashion, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - server: - undertow: - accesslog: - enabled: true - pattern: "%t %a %r %s (%D milliseconds)" - options: - server: - record-request-start-time: true +server: + undertow: + accesslog: + enabled: true + pattern: "%t %a %r %s (%D milliseconds)" + options: + server: + record-request-start-time: true ---- Note that, in addition to enabling access logging and configuring its pattern, recording request start times has also been enabled. @@ -385,13 +405,13 @@ You can customize this location by setting the configprop:server.undertow.access Finally, access logging for Jetty can also be configured as follows: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - server: - jetty: - accesslog: - enabled: true - filename: "/var/log/jetty-access.log" +server: + jetty: + accesslog: + enabled: true + filename: "/var/log/jetty-access.log" ---- By default, logs are redirected to `System.err`. @@ -400,7 +420,8 @@ For more details, see the Jetty documentation. [[howto.webserver.use-behind-a-proxy-server]] -=== Running Behind a Front-end Proxy Server +== Running Behind a Front-end Proxy Server + If your application is running behind a proxy, a load-balancer or in the cloud, the request information (like the host, port, scheme...) might change along the way. Your application may be running on `10.10.10.10:8080`, but HTTP clients should only see `example.org`. @@ -411,7 +432,7 @@ There are also non-standard headers, like `X-Forwarded-Host`, `X-Forwarded-Port` If the proxy adds the commonly used `X-Forwarded-For` and `X-Forwarded-Proto` headers, setting `server.forward-headers-strategy` to `NATIVE` is enough to support those. With this option, the Web servers themselves natively support this feature; you can check their specific documentation to learn about specific behavior. -If this is not enough, Spring Framework provides a {spring-framework-docs}/web/webmvc/filters.html#filters-forwarded-headers[ForwardedHeaderFilter] for the servlet stack and a {spring-framework-docs}/web/webflux/reactive-spring.html#webflux-forwarded-headers[ForwardedHeaderTransformer] for the reactive stack. +If this is not enough, Spring Framework provides a {url-spring-framework-docs}/web/webmvc/filters.html#filters-forwarded-headers[ForwardedHeaderFilter] for the servlet stack and a {url-spring-framework-docs}/web/webflux/reactive-spring.html#webflux-forwarded-headers[ForwardedHeaderTransformer] for the reactive stack. You can use them in your application by setting configprop:server.forward-headers-strategy[] to `FRAMEWORK`. TIP: If you are using Tomcat and terminating SSL at the proxy, configprop:server.tomcat.redirect-context-root[] should be set to `false`. @@ -423,28 +444,29 @@ In all other instances, it defaults to `NONE`. [[howto.webserver.use-behind-a-proxy-server.tomcat]] -==== Customize Tomcat's Proxy Configuration +=== Customize Tomcat's Proxy Configuration + If you use Tomcat, you can additionally configure the names of the headers used to carry "`forwarded`" information, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - server: - tomcat: - remoteip: - remote-ip-header: "x-your-remote-ip-header" - protocol-header: "x-your-protocol-header" +server: + tomcat: + remoteip: + remote-ip-header: "x-your-remote-ip-header" + protocol-header: "x-your-protocol-header" ---- Tomcat is also configured with a regular expression that matches internal proxies that are to be trusted. -See the <> for its default value. +See the xref:appendix:application-properties/index.adoc#application-properties.server.server.tomcat.remoteip.internal-proxies[configprop:server.tomcat.remoteip.internal-proxies[] entry in the appendix] for its default value. You can customize the valve's configuration by adding an entry to `application.properties`, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - server: - tomcat: - remoteip: - internal-proxies: "192\\.168\\.\\d{1,3}\\.\\d{1,3}" +server: + tomcat: + remoteip: + internal-proxies: "192\\.168\\.\\d{1,3}\\.\\d{1,3}" ---- NOTE: You can trust all proxies by setting the `internal-proxies` to empty (but do not do so in production). @@ -454,20 +476,22 @@ You can take complete control of the configuration of Tomcat's `RemoteIpValve` b [[howto.webserver.enable-multiple-connectors-in-tomcat]] -=== Enable Multiple Connectors with Tomcat +== Enable Multiple Connectors with Tomcat + You can add an `org.apache.catalina.connector.Connector` to the `TomcatServletWebServerFactory`, which can allow multiple connectors, including HTTP and HTTPS connectors, as shown in the following example: -include::code:MyTomcatConfiguration[] +include-code::MyTomcatConfiguration[] [[howto.webserver.enable-tomcat-mbean-registry]] -=== Enable Tomcat's MBean Registry +== Enable Tomcat's MBean Registry + Embedded Tomcat's MBean registry is disabled by default. This minimizes Tomcat's memory footprint. If you want to use Tomcat's MBeans, for example so that they can be used by Micrometer to expose metrics, you must use the configprop:server.tomcat.mbeanregistry.enabled[] property to do so, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- server: tomcat: @@ -478,18 +502,20 @@ server: [[howto.webserver.enable-multiple-listeners-in-undertow]] -=== Enable Multiple Listeners with Undertow +== Enable Multiple Listeners with Undertow + Add an `UndertowBuilderCustomizer` to the `UndertowServletWebServerFactory` and add a listener to the `Builder`, as shown in the following example: -include::code:MyUndertowConfiguration[] +include-code::MyUndertowConfiguration[] [[howto.webserver.create-websocket-endpoints-using-serverendpoint]] -=== Create WebSocket Endpoints Using @ServerEndpoint +== Create WebSocket Endpoints Using @ServerEndpoint + If you want to use `@ServerEndpoint` in a Spring Boot application that used an embedded container, you must declare a single `ServerEndpointExporter` `@Bean`, as shown in the following example: -include::code:MyWebSocketConfiguration[] +include-code::MyWebSocketConfiguration[] The bean shown in the preceding example registers any `@ServerEndpoint` annotated beans with the underlying WebSocket container. When deployed to a standalone servlet container, this role is performed by a servlet container initializer, and the `ServerEndpointExporter` bean is not required. diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/partials/nav-how-to.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/partials/nav-how-to.adoc new file mode 100644 index 0000000000..07576beabf --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/how-to/partials/nav-how-to.adoc @@ -0,0 +1,22 @@ +* xref:how-to:index.adoc[] + +** xref:how-to:application.adoc[] +** xref:how-to:properties-and-configuration.adoc[] +** xref:how-to:webserver.adoc[] +** xref:how-to:spring-mvc.adoc[] +** xref:how-to:jersey.adoc[] +** xref:how-to:http-clients.adoc[] +** xref:how-to:logging.adoc[] +** xref:how-to:data-access.adoc[] +** xref:how-to:data-initialization.adoc[] +** xref:how-to:nosql.adoc[] +** xref:how-to:messaging.adoc[] +** xref:how-to:batch.adoc[] +** xref:how-to:actuator.adoc[] +** xref:how-to:security.adoc[] +** xref:how-to:hotswapping.adoc[] +** xref:how-to:testing.adoc[] +** xref:how-to:build.adoc[] +** xref:how-to:aot.adoc[] +** xref:how-to:traditional-deployment.adoc[] +** xref:how-to:docker-compose.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/auditing.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/auditing.adoc similarity index 97% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/auditing.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/auditing.adoc index bac2395df0..7c366cb29b 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/auditing.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/auditing.adoc @@ -1,5 +1,6 @@ [[actuator.auditing]] -== Auditing += Auditing + Once Spring Security is in play, Spring Boot Actuator has a flexible audit framework that publishes events (by default, "`authentication success`", "`failure`" and "`access denied`" exceptions). This feature can be very useful for reporting and for implementing a lock-out policy based on authentication failures. @@ -11,7 +12,8 @@ For production environments, consider creating your own alternative `AuditEventR [[actuator.auditing.custom]] -=== Custom Auditing +== Custom Auditing + To customize published security events, you can provide your own implementations of `AbstractAuthenticationAuditListener` and `AbstractAuthorizationAuditListener`. You can also use the audit services for your own business events. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/cloud-foundry.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/cloud-foundry.adoc similarity index 80% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/cloud-foundry.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/cloud-foundry.adoc index 97e81386fd..a5e940dfe7 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/cloud-foundry.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/cloud-foundry.adoc @@ -1,5 +1,6 @@ [[actuator.cloud-foundry]] -== Cloud Foundry Support += Cloud Foundry Support + Spring Boot's actuator module includes additional support that is activated when you deploy to a compatible Cloud Foundry instance. The `/cloudfoundryapplication` path provides an alternative secured route to all `@Endpoint` beans. @@ -12,34 +13,37 @@ To use the endpoint, you must pass a valid UAA token with the request. [[actuator.cloud-foundry.disable]] -=== Disabling Extended Cloud Foundry Actuator Support +== Disabling Extended Cloud Foundry Actuator Support + If you want to fully disable the `/cloudfoundryapplication` endpoints, you can add the following setting to your `application.properties` file: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - cloudfoundry: - enabled: false +management: + cloudfoundry: + enabled: false ---- [[actuator.cloud-foundry.ssl]] -=== Cloud Foundry Self-signed Certificates +== Cloud Foundry Self-signed Certificates + By default, the security verification for `/cloudfoundryapplication` endpoints makes SSL calls to various Cloud Foundry services. If your Cloud Foundry UAA or Cloud Controller services use self-signed certificates, you need to set the following property: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - cloudfoundry: - skip-ssl-validation: true +management: + cloudfoundry: + skip-ssl-validation: true ---- [[actuator.cloud-foundry.custom-context-path]] -=== Custom Context Path +== Custom Context Path + If the server's context-path has been configured to anything other than `/`, the Cloud Foundry endpoints are not available at the root of the application. For example, if `server.servlet.context-path=/app`, Cloud Foundry endpoints are available at `/app/cloudfoundryapplication/*`. @@ -47,8 +51,8 @@ If you expect the Cloud Foundry endpoints to always be available at `/cloudfound The configuration differs, depending on the web server in use. For Tomcat, you can add the following configuration: -include::code:MyCloudFoundryConfiguration[] +include-code::MyCloudFoundryConfiguration[] If you're using a Webflux based application, you can use the following configuration: -include::code:MyReactiveCloudFoundryConfiguration[] +include-code::MyReactiveCloudFoundryConfiguration[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/enabling.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/enabling.adoc similarity index 57% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/enabling.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/enabling.adoc index 4de5a85035..17a3526fd4 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/enabling.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/enabling.adoc @@ -1,6 +1,7 @@ [[actuator.enabling]] -== Enabling Production-ready Features -The {spring-boot-code}/spring-boot-project/spring-boot-actuator[`spring-boot-actuator`] module provides all of Spring Boot's production-ready features. += Enabling Production-ready Features + +The {code-spring-boot}/spring-boot-project/spring-boot-actuator[`spring-boot-actuator`] module provides all of Spring Boot's production-ready features. The recommended way to enable the features is to add a dependency on the `spring-boot-starter-actuator` "`Starter`". .Definition of Actuator @@ -11,21 +12,21 @@ Actuators can generate a large amount of motion from a small change. To add the actuator to a Maven-based project, add the following "`Starter`" dependency: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - - org.springframework.boot - spring-boot-starter-actuator - - + + + org.springframework.boot + spring-boot-starter-actuator + + ---- For Gradle, use the following declaration: -[source,gradle,indent=0,subs="verbatim"] +[source,gradle] ---- - dependencies { - implementation 'org.springframework.boot:spring-boot-starter-actuator' - } +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-actuator' +} ---- diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/endpoints.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/endpoints.adoc similarity index 74% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/endpoints.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/endpoints.adoc index df503b59aa..f05d3e3ac2 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/endpoints.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/endpoints.adoc @@ -1,16 +1,17 @@ [[actuator.endpoints]] -== Endpoints += Endpoints + Actuator endpoints let you monitor and interact with your application. Spring Boot includes a number of built-in endpoints and lets you add your own. For example, the `health` endpoint provides basic application health information. -You can <> each individual endpoint and <>. +You can xref:actuator/endpoints.adoc#actuator.endpoints.enabling[enable or disable] each individual endpoint and xref:actuator/endpoints.adoc#actuator.endpoints.exposing[expose them (make them remotely accessible) over HTTP or JMX]. An endpoint is considered to be available when it is both enabled and exposed. The built-in endpoints are auto-configured only when they are available. Most applications choose exposure over HTTP, where the ID of the endpoint and a prefix of `/actuator` is mapped to a URL. For example, by default, the `health` endpoint is mapped to `/actuator/health`. -TIP: To learn more about the Actuator's endpoints and their request and response formats, see the separate API documentation ({spring-boot-actuator-restapi-docs}[HTML] or {spring-boot-actuator-restapi-pdfdocs}[PDF]). +TIP: To learn more about the Actuator's endpoints and their request and response formats, see the xref:api:rest/actuator/index.adoc[API documentation]. The following technology-agnostic endpoints are available: @@ -33,11 +34,11 @@ The following technology-agnostic endpoints are available: | `configprops` | Displays a collated list of all `@ConfigurationProperties`. -Subject to <>. +Subject to xref:actuator/endpoints.adoc#actuator.endpoints.sanitization[sanitization]. | `env` | Exposes properties from Spring's `ConfigurableEnvironment`. -Subject to <>. +Subject to xref:actuator/endpoints.adoc#actuator.endpoints.sanitization[sanitization]. | `flyway` | Shows any Flyway database migrations that have been applied. @@ -72,7 +73,7 @@ Subject to <>. |`quartz` |Shows information about Quartz Scheduler jobs. -Subject to <>. +Subject to xref:actuator/endpoints.adoc#actuator.endpoints.sanitization[sanitization]. | `scheduledtasks` | Displays the scheduled tasks in your application. @@ -87,7 +88,7 @@ Subject to <>. Disabled by default. | `startup` -| Shows the <> collected by the `ApplicationStartup`. +| Shows the xref:features/spring-application.adoc#features.spring-application.startup-tracking[startup steps data] collected by the `ApplicationStartup`. Requires the `SpringApplication` to be configured with a `BufferingApplicationStartup`. | `threaddump` @@ -117,39 +118,41 @@ If your application is a web application (Spring MVC, Spring WebFlux, or Jersey) [[actuator.endpoints.enabling]] -=== Enabling Endpoints +== Enabling Endpoints + By default, all endpoints except for `shutdown` are enabled. To configure the enablement of an endpoint, use its `management.endpoint..enabled` property. The following example enables the `shutdown` endpoint: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - endpoint: - shutdown: - enabled: true +management: + endpoint: + shutdown: + enabled: true ---- If you prefer endpoint enablement to be opt-in rather than opt-out, set the configprop:management.endpoints.enabled-by-default[] property to `false` and use individual endpoint `enabled` properties to opt back in. The following example enables the `info` endpoint and disables all other endpoints: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - endpoints: - enabled-by-default: false - endpoint: - info: - enabled: true +management: + endpoints: + enabled-by-default: false + endpoint: + info: + enabled: true ---- NOTE: Disabled endpoints are removed entirely from the application context. -If you want to change only the technologies over which an endpoint is exposed, use the <> instead. +If you want to change only the technologies over which an endpoint is exposed, use the xref:actuator/endpoints.adoc#actuator.endpoints.exposing[`include` and `exclude` properties] instead. [[actuator.endpoints.exposing]] -=== Exposing Endpoints +== Exposing Endpoints + By default, only the health endpoint is exposed over HTTP and JMX. Since Endpoints may contain sensitive information, you should carefully consider when to expose them. @@ -179,38 +182,39 @@ You can configure both the `include` and the `exclude` properties with a list of For example, to only expose the `health` and `info` endpoints over JMX, use the following property: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - endpoints: - jmx: - exposure: - include: "health,info" +management: + endpoints: + jmx: + exposure: + include: "health,info" ---- `*` can be used to select all endpoints. For example, to expose everything over HTTP except the `env` and `beans` endpoints, use the following properties: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - endpoints: - web: - exposure: - include: "*" - exclude: "env,beans" +management: + endpoints: + web: + exposure: + include: "*" + exclude: "env,beans" ---- NOTE: `*` has a special meaning in YAML, so be sure to add quotation marks if you want to include (or exclude) all endpoints. -NOTE: If your application is exposed publicly, we strongly recommend that you also <>. +NOTE: If your application is exposed publicly, we strongly recommend that you also xref:actuator/endpoints.adoc#actuator.endpoints.security[secure your endpoints]. TIP: If you want to implement your own strategy for when endpoints are exposed, you can register an `EndpointFilter` bean. [[actuator.endpoints.security]] -=== Security +== Security + For security purposes, only the `/health` endpoint is exposed over HTTP by default. You can use the configprop:management.endpoints.web.exposure.include[] property to configure the endpoints that are exposed. @@ -223,27 +227,27 @@ If you wish to configure custom security for HTTP endpoints (for example, to all A typical Spring Security configuration might look something like the following example: -include::code:typical/MySecurityConfiguration[] +include-code::typical/MySecurityConfiguration[] The preceding example uses `EndpointRequest.toAnyEndpoint()` to match a request to any endpoint and then ensures that all have the `ENDPOINT_ADMIN` role. Several other matcher methods are also available on `EndpointRequest`. -See the API documentation ({spring-boot-actuator-restapi-docs}[HTML] or {spring-boot-actuator-restapi-pdfdocs}[PDF]) for details. +See the xref:api:rest/actuator/index.adoc[API documentation] for details. If you deploy applications behind a firewall, you may prefer that all your actuator endpoints can be accessed without requiring authentication. You can do so by changing the configprop:management.endpoints.web.exposure.include[] property, as follows: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - endpoints: - web: - exposure: - include: "*" +management: + endpoints: + web: + exposure: + include: "*" ---- Additionally, if Spring Security is present, you would need to add custom security configuration that allows unauthenticated access to the endpoints, as the following example shows: -include::code:exposeall/MySecurityConfiguration[] +include-code::exposeall/MySecurityConfiguration[] NOTE: In both of the preceding examples, the configuration applies only to the actuator endpoints. Since Spring Boot's security configuration backs off completely in the presence of any `SecurityFilterChain` bean, you need to configure an additional `SecurityFilterChain` bean with rules that apply to the rest of the application. @@ -251,29 +255,31 @@ Since Spring Boot's security configuration backs off completely in the presence [[actuator.endpoints.security.csrf]] -==== Cross Site Request Forgery Protection +=== Cross Site Request Forgery Protection + Since Spring Boot relies on Spring Security's defaults, CSRF protection is turned on by default. This means that the actuator endpoints that require a `POST` (shutdown and loggers endpoints), a `PUT`, or a `DELETE` get a 403 (forbidden) error when the default security configuration is in use. NOTE: We recommend disabling CSRF protection completely only if you are creating a service that is used by non-browser clients. -You can find additional information about CSRF protection in the {spring-security-docs}/features/exploits/csrf.html[Spring Security Reference Guide]. +You can find additional information about CSRF protection in the {url-spring-security-docs}/features/exploits/csrf.html[Spring Security Reference Guide]. [[actuator.endpoints.caching]] -=== Configuring Endpoints +== Configuring Endpoints + Endpoints automatically cache responses to read operations that do not take any parameters. To configure the amount of time for which an endpoint caches a response, use its `cache.time-to-live` property. The following example sets the time-to-live of the `beans` endpoint's cache to 10 seconds: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - endpoint: - beans: - cache: - time-to-live: "10s" +management: + endpoint: + beans: + cache: + time-to-live: "10s" ---- NOTE: The `management.endpoint.` prefix uniquely identifies the endpoint that is being configured. @@ -281,13 +287,14 @@ NOTE: The `management.endpoint.` prefix uniquely identifies the endpoint t [[actuator.endpoints.sanitization]] -=== Sanitize Sensitive Values +== Sanitize Sensitive Values + Information returned by the `/env`, `/configprops` and `/quartz` endpoints can be sensitive, so by default values are always fully sanitized (replaced by `+******+`). Values can only be viewed in an unsanitized form when: - The `show-values` property has been set to something other than `NEVER` -- No custom `<>` beans apply +- No custom `xref:how-to:actuator.adoc#howto.actuator.customizing-sanitization[SanitizingFunction]` beans apply The `show-values` property can be configured for sanitizable endpoints to one of the following values: @@ -303,33 +310,34 @@ For JMX endpoints, all users are always authorized. The following example allows all users with the `admin` role to view values from the `/env` endpoint in their original form. Unauthorized users, or users without the `admin` role, will see only sanitized values. -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - endpoint: - env: - show-values: WHEN_AUTHORIZED - roles: "admin" +management: + endpoint: + env: + show-values: WHEN_AUTHORIZED + roles: "admin" ---- -NOTE: This example assumes that no `<>` beans have been defined. +NOTE: This example assumes that no `xref:how-to:actuator.adoc#howto.actuator.customizing-sanitization[SanitizingFunction]` beans have been defined. [[actuator.endpoints.hypermedia]] -=== Hypermedia for Actuator Web Endpoints +== Hypermedia for Actuator Web Endpoints + A "`discovery page`" is added with links to all the endpoints. The "`discovery page`" is available on `/actuator` by default. To disable the "`discovery page`", add the following property to your application properties: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - endpoints: - web: - discovery: - enabled: false +management: + endpoints: + web: + discovery: + enabled: false ---- When a custom management context path is configured, the "`discovery page`" automatically moves from `/actuator` to the root of the management context. @@ -339,36 +347,38 @@ When the management context path is set to `/`, the discovery page is disabled t [[actuator.endpoints.cors]] -=== CORS Support +== 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] that lets you specify in a flexible way what kind of cross-domain requests are authorized. If you use Spring MVC or Spring WebFlux, you can configure Actuator's web endpoints to support such scenarios. CORS support is disabled by default and is only enabled once you have set the configprop:management.endpoints.web.cors.allowed-origins[] property. The following configuration permits `GET` and `POST` calls from the `example.com` domain: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - endpoints: - web: - cors: - allowed-origins: "https://example.com" - allowed-methods: "GET,POST" +management: + endpoints: + web: + cors: + allowed-origins: "https://example.com" + allowed-methods: "GET,POST" ---- -TIP: See {spring-boot-actuator-autoconfigure-module-code}/endpoint/web/CorsEndpointProperties.java[`CorsEndpointProperties`] for a complete list of options. +TIP: See {code-spring-boot-actuator-autoconfigure-src}/endpoint/web/CorsEndpointProperties.java[`CorsEndpointProperties`] for a complete list of options. [[actuator.endpoints.implementing-custom]] -=== Implementing Custom Endpoints +== Implementing Custom Endpoints + If you add a `@Bean` annotated with `@Endpoint`, any methods annotated with `@ReadOperation`, `@WriteOperation`, or `@DeleteOperation` are automatically exposed over JMX and, in a web application, over HTTP as well. Endpoints can be exposed over HTTP by using Jersey, Spring MVC, or Spring WebFlux. If both Jersey and Spring MVC are available, Spring MVC is used. The following example exposes a read operation that returns a custom object: -include::code:MyEndpoint[tag=read] +include-code::MyEndpoint[tag=read] You can also write technology-specific endpoints by using `@JmxEndpoint` or `@WebEndpoint`. These endpoints are restricted to their respective technologies. @@ -382,7 +392,8 @@ Finally, if you need access to web-framework-specific functionality, you can imp [[actuator.endpoints.implementing-custom.input]] -==== Receiving Input +=== Receiving Input + Operations on an endpoint receive input through their parameters. When exposed over the web, the values for these parameters are taken from the URL's query parameters and from the JSON request body. When exposed over JMX, the parameters are mapped to the parameters of the MBean's operations. @@ -392,17 +403,17 @@ They can be made optional by annotating them with either `@javax.annotation.Null You can map each root property in the JSON request body to a parameter of the endpoint. Consider the following JSON request body: -[source,json,indent=0,subs="verbatim"] +[source,json] ---- - { - "name": "test", - "counter": 42 - } +{ + "name": "test", + "counter": 42 +} ---- You can use this to invoke a write operation that takes `String name` and `int counter` parameters, as the following example shows: -include::code:../MyEndpoint[tag=write] +include-code::../MyEndpoint[tag=write] TIP: Because endpoints are technology agnostic, only simple types can be specified in the method signature. In particular, declaring a single parameter with a `CustomData` type that defines a `name` and `counter` properties is not supported. @@ -413,27 +424,31 @@ This will happen automatically if you use Spring Boot's Gradle plugin or if you [[actuator.endpoints.implementing-custom.input.conversion]] -===== Input Type Conversion +==== Input Type Conversion + The parameters passed to endpoint operation methods are, if necessary, automatically converted to the required type. Before calling an operation method, the input received over JMX or HTTP is converted to the required types by using an instance of `ApplicationConversionService` as well as any `Converter` or `GenericConverter` beans qualified with `@EndpointConverter`. [[actuator.endpoints.implementing-custom.web]] -==== Custom Web Endpoints +=== Custom Web Endpoints + Operations on an `@Endpoint`, `@WebEndpoint`, or `@EndpointWebExtension` are automatically exposed over HTTP using Jersey, Spring MVC, or Spring WebFlux. If both Jersey and Spring MVC are available, Spring MVC is used. [[actuator.endpoints.implementing-custom.web.request-predicates]] -===== Web Endpoint Request Predicates +==== Web Endpoint Request Predicates + A request predicate is automatically generated for each operation on a web-exposed endpoint. [[actuator.endpoints.implementing-custom.web.path-predicates]] -===== Path +==== Path + The path of the predicate is determined by the ID of the endpoint and the base path of the web-exposed endpoints. The default base path is `/actuator`. For example, an endpoint with an ID of `sessions` uses `/actuator/sessions` as its path in the predicate. @@ -446,7 +461,8 @@ If you want to capture all remaining path elements, you can add `@Selector(Match [[actuator.endpoints.implementing-custom.web.method-predicates]] -===== HTTP method +==== HTTP method + The HTTP method of the predicate is determined by the operation type, as shown in the following table: [cols="3, 1"] @@ -466,14 +482,16 @@ The HTTP method of the predicate is determined by the operation type, as shown i [[actuator.endpoints.implementing-custom.web.consumes-predicates]] -===== Consumes +==== Consumes + For a `@WriteOperation` (HTTP `POST`) that uses the request body, the `consumes` clause of the predicate is `application/vnd.spring-boot.actuator.v2+json, application/json`. For all other operations, the `consumes` clause is empty. [[actuator.endpoints.implementing-custom.web.produces-predicates]] -===== Produces +==== Produces + The `produces` clause of the predicate can be determined by the `produces` attribute of the `@DeleteOperation`, `@ReadOperation`, and `@WriteOperation` annotations. The attribute is optional. If it is not used, the `produces` clause is determined automatically. @@ -485,7 +503,8 @@ For all other operations, the `produces` clause is `application/vnd.spring-boot. [[actuator.endpoints.implementing-custom.web.response-status]] -===== Web Endpoint Response Status +==== Web Endpoint Response Status + The default response status for an endpoint operation depends on the operation type (read, write, or delete) and what, if anything, the operation returns. If a `@ReadOperation` returns a value, the response status will be 200 (OK). @@ -499,7 +518,8 @@ If an operation is invoked without a required parameter or with a parameter that [[actuator.endpoints.implementing-custom.web.range-requests]] -===== Web Endpoint Range Requests +==== Web Endpoint Range Requests + You can use an HTTP range request to request part of an HTTP resource. When using Spring MVC or Spring Web Flux, operations that return a `org.springframework.core.io.Resource` automatically support range requests. @@ -508,7 +528,8 @@ NOTE: Range requests are not supported when using Jersey. [[actuator.endpoints.implementing-custom.web.security]] -===== Web Endpoint Security +==== Web Endpoint Security + An operation on a web endpoint or a web-specific endpoint extension can receive the current `java.security.Principal` or `org.springframework.boot.actuate.endpoint.SecurityContext` as a method parameter. The former is typically used in conjunction with `@Nullable` to provide different behavior for authenticated and unauthenticated users. The latter is typically used to perform authorization checks by using its `isUserInRole(String)` method. @@ -516,7 +537,8 @@ The latter is typically used to perform authorization checks by using its `isUse [[actuator.endpoints.implementing-custom.servlet]] -==== Servlet Endpoints +=== Servlet Endpoints + A servlet can be exposed as an endpoint by implementing a class annotated with `@ServletEndpoint` that also implements `Supplier`. Servlet endpoints provide deeper integration with the servlet container but at the expense of portability. They are intended to be used to expose an existing servlet as an endpoint. @@ -525,7 +547,8 @@ For new endpoints, the `@Endpoint` and `@WebEndpoint` annotations should be pref [[actuator.endpoints.implementing-custom.controller]] -==== Controller Endpoints +=== Controller Endpoints + You can use `@ControllerEndpoint` and `@RestControllerEndpoint` to implement an endpoint that is exposed only by Spring MVC or Spring WebFlux. Methods are mapped by using the standard annotations for Spring MVC and Spring WebFlux, such as `@RequestMapping` and `@GetMapping`, with the endpoint's ID being used as a prefix for the path. Controller endpoints provide deeper integration with Spring's web frameworks but at the expense of portability. @@ -534,7 +557,8 @@ The `@Endpoint` and `@WebEndpoint` annotations should be preferred whenever poss [[actuator.endpoints.health]] -=== Health Information +== Health Information + You can use health information to check the status of your running application. It is often used by monitoring software to alert someone when a production system goes down. The information exposed by the `health` endpoint depends on the configprop:management.endpoint.health.show-details[] and configprop:management.endpoint.health.show-components[] properties, which can be configured with one of the following values: @@ -561,7 +585,7 @@ You can configure the roles by using the configprop:management.endpoint.health.r NOTE: If you have secured your application and wish to use `always`, your security configuration must permit access to the health endpoint for both authenticated and unauthenticated users. -Health information is collected from the content of a {spring-boot-actuator-module-code}/health/HealthContributorRegistry.java[`HealthContributorRegistry`] (by default, all {spring-boot-actuator-module-code}/health/HealthContributor.java[`HealthContributor`] instances defined in your `ApplicationContext`). +Health information is collected from the content of a {code-spring-boot-actuator-src}/health/HealthContributorRegistry.java[`HealthContributorRegistry`] (by default, all {code-spring-boot-actuator-src}/health/HealthContributor.java[`HealthContributor`] instances defined in your `ApplicationContext`). Spring Boot includes a number of auto-configured `HealthContributors`, and you can also write your own. A `HealthContributor` can be either a `HealthIndicator` or a `CompositeHealthContributor`. @@ -578,7 +602,8 @@ TIP: You can use the `HealthContributorRegistry` to register and unregister heal [[actuator.endpoints.health.auto-configured-health-indicators]] -==== Auto-configured HealthIndicators +=== Auto-configured HealthIndicators + When appropriate, Spring Boot auto-configures the `HealthIndicators` listed in the following table. You can also enable or disable selected indicators by configuring `management.health.key.enabled`, with the `key` listed in the following table: @@ -588,63 +613,63 @@ with the `key` listed in the following table: | Key | Name | Description | `cassandra` -| {spring-boot-actuator-module-code}/cassandra/CassandraDriverHealthIndicator.java[`CassandraDriverHealthIndicator`] +| {code-spring-boot-actuator-src}/cassandra/CassandraDriverHealthIndicator.java[`CassandraDriverHealthIndicator`] | Checks that a Cassandra database is up. | `couchbase` -| {spring-boot-actuator-module-code}/couchbase/CouchbaseHealthIndicator.java[`CouchbaseHealthIndicator`] +| {code-spring-boot-actuator-src}/couchbase/CouchbaseHealthIndicator.java[`CouchbaseHealthIndicator`] | Checks that a Couchbase cluster is up. | `db` -| {spring-boot-actuator-module-code}/jdbc/DataSourceHealthIndicator.java[`DataSourceHealthIndicator`] +| {code-spring-boot-actuator-src}/jdbc/DataSourceHealthIndicator.java[`DataSourceHealthIndicator`] | Checks that a connection to `DataSource` can be obtained. | `diskspace` -| {spring-boot-actuator-module-code}/system/DiskSpaceHealthIndicator.java[`DiskSpaceHealthIndicator`] +| {code-spring-boot-actuator-src}/system/DiskSpaceHealthIndicator.java[`DiskSpaceHealthIndicator`] | Checks for low disk space. | `elasticsearch` -| {spring-boot-actuator-module-code}/elasticsearch/ElasticsearchRestClientHealthIndicator.java[`ElasticsearchRestClientHealthIndicator`] +| {code-spring-boot-actuator-src}/elasticsearch/ElasticsearchRestClientHealthIndicator.java[`ElasticsearchRestClientHealthIndicator`] | Checks that an Elasticsearch cluster is up. | `hazelcast` -| {spring-boot-actuator-module-code}/hazelcast/HazelcastHealthIndicator.java[`HazelcastHealthIndicator`] +| {code-spring-boot-actuator-src}/hazelcast/HazelcastHealthIndicator.java[`HazelcastHealthIndicator`] | Checks that a Hazelcast server is up. | `influxdb` -| {spring-boot-actuator-module-code}/influx/InfluxDbHealthIndicator.java[`InfluxDbHealthIndicator`] +| {code-spring-boot-actuator-src}/influx/InfluxDbHealthIndicator.java[`InfluxDbHealthIndicator`] | Checks that an InfluxDB server is up. | `jms` -| {spring-boot-actuator-module-code}/jms/JmsHealthIndicator.java[`JmsHealthIndicator`] +| {code-spring-boot-actuator-src}/jms/JmsHealthIndicator.java[`JmsHealthIndicator`] | Checks that a JMS broker is up. | `ldap` -| {spring-boot-actuator-module-code}/ldap/LdapHealthIndicator.java[`LdapHealthIndicator`] +| {code-spring-boot-actuator-src}/ldap/LdapHealthIndicator.java[`LdapHealthIndicator`] | Checks that an LDAP server is up. | `mail` -| {spring-boot-actuator-module-code}/mail/MailHealthIndicator.java[`MailHealthIndicator`] +| {code-spring-boot-actuator-src}/mail/MailHealthIndicator.java[`MailHealthIndicator`] | Checks that a mail server is up. | `mongo` -| {spring-boot-actuator-module-code}/data/mongo/MongoHealthIndicator.java[`MongoHealthIndicator`] +| {code-spring-boot-actuator-src}/data/mongo/MongoHealthIndicator.java[`MongoHealthIndicator`] | Checks that a Mongo database is up. | `neo4j` -| {spring-boot-actuator-module-code}/neo4j/Neo4jHealthIndicator.java[`Neo4jHealthIndicator`] +| {code-spring-boot-actuator-src}/neo4j/Neo4jHealthIndicator.java[`Neo4jHealthIndicator`] | Checks that a Neo4j database is up. | `ping` -| {spring-boot-actuator-module-code}/health/PingHealthIndicator.java[`PingHealthIndicator`] +| {code-spring-boot-actuator-src}/health/PingHealthIndicator.java[`PingHealthIndicator`] | Always responds with `UP`. | `rabbit` -| {spring-boot-actuator-module-code}/amqp/RabbitHealthIndicator.java[`RabbitHealthIndicator`] +| {code-spring-boot-actuator-src}/amqp/RabbitHealthIndicator.java[`RabbitHealthIndicator`] | Checks that a Rabbit server is up. | `redis` -| {spring-boot-actuator-module-code}/data/redis/RedisHealthIndicator.java[`RedisHealthIndicator`] +| {code-spring-boot-actuator-src}/data/redis/RedisHealthIndicator.java[`RedisHealthIndicator`] | Checks that a Redis server is up. |=== @@ -657,24 +682,25 @@ Additional `HealthIndicators` are available but are not enabled by default: | Key | Name | Description | `livenessstate` -| {spring-boot-actuator-module-code}/availability/LivenessStateHealthIndicator.java[`LivenessStateHealthIndicator`] +| {code-spring-boot-actuator-src}/availability/LivenessStateHealthIndicator.java[`LivenessStateHealthIndicator`] | Exposes the "`Liveness`" application availability state. | `readinessstate` -| {spring-boot-actuator-module-code}/availability/ReadinessStateHealthIndicator.java[`ReadinessStateHealthIndicator`] +| {code-spring-boot-actuator-src}/availability/ReadinessStateHealthIndicator.java[`ReadinessStateHealthIndicator`] | Exposes the "`Readiness`" application availability state. |=== [[actuator.endpoints.health.writing-custom-health-indicators]] -==== Writing Custom HealthIndicators -To provide custom health information, you can register Spring beans that implement the {spring-boot-actuator-module-code}/health/HealthIndicator.java[`HealthIndicator`] interface. +=== Writing Custom HealthIndicators + +To provide custom health information, you can register Spring beans that implement the {code-spring-boot-actuator-src}/health/HealthIndicator.java[`HealthIndicator`] interface. You need to provide an implementation of the `health()` method and return a `Health` response. The `Health` response should include a status and can optionally include additional details to be displayed. The following code shows a sample `HealthIndicator` implementation: -include::code:MyHealthIndicator[] +include-code::MyHealthIndicator[] NOTE: The identifier for a given `HealthIndicator` is the name of the bean without the `HealthIndicator` suffix, if it exists. In the preceding example, the health information is available in an entry named `my`. @@ -683,19 +709,19 @@ TIP: Health indicators are usually called over HTTP and need to respond before a Spring Boot will log a warning message for any health indicator that takes longer than 10 seconds to respond. If you want to configure this threshold, you can use the configprop:management.endpoint.health.logging.slow-indicator-threshold[] property. -In addition to Spring Boot's predefined {spring-boot-actuator-module-code}/health/Status.java[`Status`] types, `Health` can return a custom `Status` that represents a new system state. -In such cases, you also need to provide a custom implementation of the {spring-boot-actuator-module-code}/health/StatusAggregator.java[`StatusAggregator`] interface, or you must configure the default implementation by using the configprop:management.endpoint.health.status.order[] configuration property. +In addition to Spring Boot's predefined {code-spring-boot-actuator-src}/health/Status.java[`Status`] types, `Health` can return a custom `Status` that represents a new system state. +In such cases, you also need to provide a custom implementation of the {code-spring-boot-actuator-src}/health/StatusAggregator.java[`StatusAggregator`] interface, or you must configure the default implementation by using the configprop:management.endpoint.health.status.order[] configuration property. For example, assume a new `Status` with a code of `FATAL` is being used in one of your `HealthIndicator` implementations. To configure the severity order, add the following property to your application properties: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - endpoint: - health: - status: - order: "fatal,down,out-of-service,unknown,up" +management: + endpoint: + health: + status: + order: "fatal,down,out-of-service,unknown,up" ---- The HTTP status code in the response reflects the overall health status. @@ -706,16 +732,16 @@ Configuring a custom mapping disables the defaults mappings for `DOWN` and `OUT_ If you want to retain the default mappings, you must explicitly configure them, alongside any custom mappings. For example, the following property maps `FATAL` to 503 (service unavailable) and retains the default mappings for `DOWN` and `OUT_OF_SERVICE`: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - endpoint: - health: - status: - http-mapping: - down: 503 - fatal: 503 - out-of-service: 503 +management: + endpoint: + health: + status: + http-mapping: + down: 503 + fatal: 503 + out-of-service: 503 ---- TIP: If you need more control, you can define your own `HttpCodeStatusMapper` bean. @@ -742,25 +768,27 @@ The following table shows the default status mappings for the built-in statuses: [[actuator.endpoints.health.reactive-health-indicators]] -==== Reactive Health Indicators +=== Reactive Health Indicators + For reactive applications, such as those that use Spring WebFlux, `ReactiveHealthContributor` provides a non-blocking contract for getting application health. -Similar to a traditional `HealthContributor`, health information is collected from the content of a {spring-boot-actuator-module-code}/health/ReactiveHealthContributorRegistry.java[`ReactiveHealthContributorRegistry`] (by default, all {spring-boot-actuator-module-code}/health/HealthContributor.java[`HealthContributor`] and {spring-boot-actuator-module-code}/health/ReactiveHealthContributor.java[`ReactiveHealthContributor`] instances defined in your `ApplicationContext`). +Similar to a traditional `HealthContributor`, health information is collected from the content of a {code-spring-boot-actuator-src}/health/ReactiveHealthContributorRegistry.java[`ReactiveHealthContributorRegistry`] (by default, all {code-spring-boot-actuator-src}/health/HealthContributor.java[`HealthContributor`] and {code-spring-boot-actuator-src}/health/ReactiveHealthContributor.java[`ReactiveHealthContributor`] instances defined in your `ApplicationContext`). Regular `HealthContributors` that do not check against a reactive API are executed on the elastic scheduler. TIP: In a reactive application, you should use the `ReactiveHealthContributorRegistry` to register and unregister health indicators at runtime. If you need to register a regular `HealthContributor`, you should wrap it with `ReactiveHealthContributor#adapt`. -To provide custom health information from a reactive API, you can register Spring beans that implement the {spring-boot-actuator-module-code}/health/ReactiveHealthIndicator.java[`ReactiveHealthIndicator`] interface. +To provide custom health information from a reactive API, you can register Spring beans that implement the {code-spring-boot-actuator-src}/health/ReactiveHealthIndicator.java[`ReactiveHealthIndicator`] interface. The following code shows a sample `ReactiveHealthIndicator` implementation: -include::code:MyReactiveHealthIndicator[] +include-code::MyReactiveHealthIndicator[] TIP: To handle the error automatically, consider extending from `AbstractReactiveHealthIndicator`. [[actuator.endpoints.health.auto-configured-reactive-health-indicators]] -==== Auto-configured ReactiveHealthIndicators +=== Auto-configured ReactiveHealthIndicators + When appropriate, Spring Boot auto-configures the following `ReactiveHealthIndicators`: [cols="2,4,6"] @@ -768,27 +796,27 @@ When appropriate, Spring Boot auto-configures the following `ReactiveHealthIndic | Key | Name | Description | `cassandra` -| {spring-boot-actuator-module-code}/cassandra/CassandraDriverReactiveHealthIndicator.java[`CassandraDriverReactiveHealthIndicator`] +| {code-spring-boot-actuator-src}/cassandra/CassandraDriverReactiveHealthIndicator.java[`CassandraDriverReactiveHealthIndicator`] | Checks that a Cassandra database is up. | `couchbase` -| {spring-boot-actuator-module-code}/couchbase/CouchbaseReactiveHealthIndicator.java[`CouchbaseReactiveHealthIndicator`] +| {code-spring-boot-actuator-src}/couchbase/CouchbaseReactiveHealthIndicator.java[`CouchbaseReactiveHealthIndicator`] | Checks that a Couchbase cluster is up. | `elasticsearch` -| {spring-boot-actuator-module-code}/data/elasticsearch/ElasticsearchReactiveHealthIndicator.java[`ElasticsearchReactiveHealthIndicator`] +| {code-spring-boot-actuator-src}/data/elasticsearch/ElasticsearchReactiveHealthIndicator.java[`ElasticsearchReactiveHealthIndicator`] | Checks that an Elasticsearch cluster is up. | `mongo` -| {spring-boot-actuator-module-code}/data/mongo/MongoReactiveHealthIndicator.java[`MongoReactiveHealthIndicator`] +| {code-spring-boot-actuator-src}/data/mongo/MongoReactiveHealthIndicator.java[`MongoReactiveHealthIndicator`] | Checks that a Mongo database is up. | `neo4j` -| {spring-boot-actuator-module-code}/neo4j/Neo4jReactiveHealthIndicator.java[`Neo4jReactiveHealthIndicator`] +| {code-spring-boot-actuator-src}/neo4j/Neo4jReactiveHealthIndicator.java[`Neo4jReactiveHealthIndicator`] | Checks that a Neo4j database is up. | `redis` -| {spring-boot-actuator-module-code}/data/redis/RedisReactiveHealthIndicator.java[`RedisReactiveHealthIndicator`] +| {code-spring-boot-actuator-src}/data/redis/RedisReactiveHealthIndicator.java[`RedisReactiveHealthIndicator`] | Checks that a Redis server is up. |=== @@ -798,34 +826,35 @@ Also, any `HealthIndicator` that is not handled explicitly is wrapped automatica [[actuator.endpoints.health.groups]] -==== Health Groups +=== Health Groups + It is sometimes useful to organize health indicators into groups that you can use for different purposes. To create a health indicator group, you can use the `management.endpoint.health.group.` property and specify a list of health indicator IDs to `include` or `exclude`. For example, to create a group that includes only database indicators you can define the following: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - endpoint: - health: - group: - custom: - include: "db" +management: + endpoint: + health: + group: + custom: + include: "db" ---- You can then check the result by hitting `http://localhost:8080/actuator/health/custom`. Similarly, to create a group that excludes the database indicators from the group and includes all the other indicators, you can define the following: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - endpoint: - health: - group: - custom: - exclude: "db" +management: + endpoint: + health: + group: + custom: + exclude: "db" ---- By default, startup will fail if a health group includes or excludes a health indicator that does not exist. @@ -835,20 +864,20 @@ By default, groups inherit the same `StatusAggregator` and `HttpCodeStatusMapper However, you can also define these on a per-group basis. You can also override the `show-details` and `roles` properties if required: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - endpoint: - health: - group: - custom: - show-details: "when-authorized" - roles: "admin" - status: - order: "fatal,up" - http-mapping: - fatal: 500 - out-of-service: 500 +management: + endpoint: + health: + group: + custom: + show-details: "when-authorized" + roles: "admin" + status: + order: "fatal,up" + http-mapping: + fatal: 500 + out-of-service: 500 ---- TIP: You can use `@Qualifier("groupname")` if you need to register custom `StatusAggregator` or `HttpCodeStatusMapper` beans for use with the group. @@ -857,10 +886,10 @@ A health group can also include/exclude a `CompositeHealthContributor`. You can also include/exclude only a certain component of a `CompositeHealthContributor`. This can be done using the fully qualified name of the component as follows: -[source,properties,indent=0,subs="verbatim"] +[source,properties] ---- - management.endpoint.health.group.custom.include="test/primary" - management.endpoint.health.group.custom.exclude="test/primary/b" +management.endpoint.health.group.custom.include="test/primary" +management.endpoint.health.group.custom.exclude="test/primary/b" ---- In the example above, the `custom` group will include the `HealthContributor` with the name `primary` which is a component of the composite `test`. @@ -872,9 +901,9 @@ This is useful in cloud environments such as Kubernetes, where it is quite commo Having a separate port could lead to unreliable health checks because the main application might not work properly even if the health check is successful. The health group can be configured with an additional path as follows: -[source,properties,indent=0,subs="verbatim"] +[source,properties] ---- - management.endpoint.health.group.live.additional-path="server:/healthz" +management.endpoint.health.group.live.additional-path="server:/healthz" ---- This would make the `live` health group available on the main server port at `/healthz`. @@ -884,7 +913,8 @@ The path must be a single path segment. [[actuator.endpoints.health.datasource]] -==== DataSource Health +=== DataSource Health + The `DataSource` health indicator shows the health of both standard data sources and routing data source beans. The health of a routing data source includes the health of each of its target data sources. In the health endpoint's response, each of a routing data source's targets is named by using its routing key. @@ -893,86 +923,88 @@ If you prefer not to include routing data sources in the indicator's output, set [[actuator.endpoints.kubernetes-probes]] -=== Kubernetes Probes +== Kubernetes Probes + Applications deployed on Kubernetes can provide information about their internal state with https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#container-probes[Container Probes]. Depending on https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/[your Kubernetes configuration], the kubelet calls those probes and reacts to the result. -By default, Spring Boot manages your <>. -If deployed in a Kubernetes environment, actuator gathers the "`Liveness`" and "`Readiness`" information from the `ApplicationAvailability` interface and uses that information in dedicated <>: `LivenessStateHealthIndicator` and `ReadinessStateHealthIndicator`. +By default, Spring Boot manages your xref:features/spring-application.adoc#features.spring-application.application-availability[Application Availability State]. +If deployed in a Kubernetes environment, actuator gathers the "`Liveness`" and "`Readiness`" information from the `ApplicationAvailability` interface and uses that information in dedicated xref:actuator/endpoints.adoc#actuator.endpoints.health.auto-configured-health-indicators[health indicators]: `LivenessStateHealthIndicator` and `ReadinessStateHealthIndicator`. These indicators are shown on the global health endpoint (`"/actuator/health"`). -They are also exposed as separate HTTP Probes by using <>: `"/actuator/health/liveness"` and `"/actuator/health/readiness"`. +They are also exposed as separate HTTP Probes by using xref:actuator/endpoints.adoc#actuator.endpoints.health.groups[health groups]: `"/actuator/health/liveness"` and `"/actuator/health/readiness"`. You can then configure your Kubernetes infrastructure with the following endpoint information: -[source,yaml,indent=0,subs="verbatim"] +[source,yaml] ---- - livenessProbe: - httpGet: - path: "/actuator/health/liveness" - port: - failureThreshold: ... - periodSeconds: ... +livenessProbe: + httpGet: + path: "/actuator/health/liveness" + port: + failureThreshold: ... + periodSeconds: ... - readinessProbe: - httpGet: - path: "/actuator/health/readiness" - port: - failureThreshold: ... - periodSeconds: ... +readinessProbe: + httpGet: + path: "/actuator/health/readiness" + port: + failureThreshold: ... + periodSeconds: ... ---- NOTE: `` should be set to the port that the actuator endpoints are available on. It could be the main web server port or a separate management port if the `"management.server.port"` property has been set. -These health groups are automatically enabled only if the application <>. +These health groups are automatically enabled only if the application xref:deployment/cloud.adoc#deployment.cloud.kubernetes[runs in a Kubernetes environment]. You can enable them in any environment by using the configprop:management.endpoint.health.probes.enabled[] configuration property. NOTE: If an application takes longer to start than the configured liveness period, Kubernetes mentions the `"startupProbe"` as a possible solution. Generally speaking, the `"startupProbe"` is not necessarily needed here, as the `"readinessProbe"` fails until all startup tasks are done. This means your application will not receive traffic until it is ready. However, if your application takes a long time to start, consider using a `"startupProbe"` to make sure that Kubernetes won't kill your application while it is in the process of starting. -See the section that describes <>. +See the section that describes xref:actuator/endpoints.adoc#actuator.endpoints.kubernetes-probes.lifecycle[how probes behave during the application lifecycle]. If your Actuator endpoints are deployed on a separate management context, the endpoints do not use the same web infrastructure (port, connection pools, framework components) as the main application. In this case, a probe check could be successful even if the main application does not work properly (for example, it cannot accept new connections). For this reason, it is a good idea to make the `liveness` and `readiness` health groups available on the main server port. This can be done by setting the following property: -[source,properties,indent=0,subs="verbatim"] +[source,properties] ---- - management.endpoint.health.probes.add-additional-paths=true +management.endpoint.health.probes.add-additional-paths=true ---- This would make the `liveness` group available at `/livez` and the `readiness` group available at `/readyz` on the main server port. -Paths can be customized using the `additional-path` property on each group, see <> for details. +Paths can be customized using the `additional-path` property on each group, see xref:actuator/endpoints.adoc#actuator.endpoints.health.groups[health groups] for details. [[actuator.endpoints.kubernetes-probes.external-state]] -==== Checking External State With Kubernetes Probes +=== Checking External State With Kubernetes Probes + Actuator configures the "`liveness`" and "`readiness`" probes as Health Groups. -This means that all the <> are available for them. +This means that all the xref:actuator/endpoints.adoc#actuator.endpoints.health.groups[health groups features] are available for them. You can, for example, configure additional Health Indicators: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - endpoint: - health: - group: - readiness: - include: "readinessState,customCheck" +management: + endpoint: + health: + group: + readiness: + include: "readinessState,customCheck" ---- By default, Spring Boot does not add other health indicators to these groups. The "`liveness`" probe should not depend on health checks for external systems. -If the <> is broken, Kubernetes tries to solve that problem by restarting the application instance. +If the xref:features/spring-application.adoc#features.spring-application.application-availability.liveness[liveness state of an application] is broken, Kubernetes tries to solve that problem by restarting the application instance. This means that if an external system (such as a database, a Web API, or an external cache) fails, Kubernetes might restart all application instances and create cascading failures. As for the "`readiness`" probe, the choice of checking external systems must be made carefully by the application developers. For this reason, Spring Boot does not include any additional health checks in the readiness probe. -If the <> is unready, Kubernetes does not route traffic to that instance. +If the xref:features/spring-application.adoc#features.spring-application.application-availability.readiness[readiness state of an application instance] is unready, Kubernetes does not route traffic to that instance. Some external systems might not be shared by application instances, in which case they could be included in a readiness probe. Other external systems might not be essential to the application (the application could have circuit breakers and fallbacks), in which case they definitely should not be included. Unfortunately, an external system that is shared by all application instances is common, and you have to make a judgement call: Include it in the readiness probe and expect that the application is taken out of service when the external service is down or leave it out and deal with failures higher up the stack, perhaps by using a circuit breaker in the caller. @@ -988,13 +1020,14 @@ Also, if an application uses Kubernetes https://kubernetes.io/docs/tasks/run-app [[actuator.endpoints.kubernetes-probes.lifecycle]] -==== Application Lifecycle and Probe States +=== Application Lifecycle and Probe States + An important aspect of the Kubernetes Probes support is its consistency with the application lifecycle. There is a significant difference between the `AvailabilityState` (which is the in-memory, internal state of the application) and the actual probe (which exposes that state). Depending on the phase of application lifecycle, the probe might not be available. -Spring Boot publishes <>, +Spring Boot publishes xref:features/spring-application.adoc#features.spring-application.application-events-and-listeners[application events during startup and shutdown], and probes can listen to such events and expose the `AvailabilityState` information. The following tables show the `AvailabilityState` and the state of HTTP connectors at different stages. @@ -1040,7 +1073,7 @@ When a Spring Boot application shuts down: |`CORRECT` |`REFUSING_TRAFFIC` |New requests are rejected -|If enabled, <>. +|If enabled, xref:web/graceful-shutdown.adoc[graceful shutdown processes in-flight requests]. |Shutdown complete |N/A @@ -1049,19 +1082,21 @@ When a Spring Boot application shuts down: |The application context is closed and the application is shut down. |=== -TIP: See <> for more information about Kubernetes deployment. +TIP: See xref:deployment/cloud.adoc#deployment.cloud.kubernetes.container-lifecycle[Kubernetes container lifecycle section] for more information about Kubernetes deployment. [[actuator.endpoints.info]] -=== Application Information -Application information exposes various information collected from all {spring-boot-actuator-module-code}/info/InfoContributor.java[`InfoContributor`] beans defined in your `ApplicationContext`. +== Application Information + +Application information exposes various information collected from all {code-spring-boot-actuator-src}/info/InfoContributor.java[`InfoContributor`] beans defined in your `ApplicationContext`. Spring Boot includes a number of auto-configured `InfoContributor` beans, and you can write your own. [[actuator.endpoints.info.auto-configured-info-contributors]] -==== Auto-configured InfoContributors +=== Auto-configured InfoContributors + When appropriate, Spring auto-configures the following `InfoContributor` beans: [cols="1,4,8,4"] @@ -1069,32 +1104,32 @@ When appropriate, Spring auto-configures the following `InfoContributor` beans: | ID | Name | Description | Prerequisites | `build` -| {spring-boot-actuator-module-code}/info/BuildInfoContributor.java[`BuildInfoContributor`] +| {code-spring-boot-actuator-src}/info/BuildInfoContributor.java[`BuildInfoContributor`] | Exposes build information. | A `META-INF/build-info.properties` resource. | `env` -| {spring-boot-actuator-module-code}/info/EnvironmentInfoContributor.java[`EnvironmentInfoContributor`] +| {code-spring-boot-actuator-src}/info/EnvironmentInfoContributor.java[`EnvironmentInfoContributor`] | Exposes any property from the `Environment` whose name starts with `info.`. | None. | `git` -| {spring-boot-actuator-module-code}/info/GitInfoContributor.java[`GitInfoContributor`] +| {code-spring-boot-actuator-src}/info/GitInfoContributor.java[`GitInfoContributor`] | Exposes git information. | A `git.properties` resource. | `java` -| {spring-boot-actuator-module-code}/info/JavaInfoContributor.java[`JavaInfoContributor`] +| {code-spring-boot-actuator-src}/info/JavaInfoContributor.java[`JavaInfoContributor`] | Exposes Java runtime information. | None. | `os` -| {spring-boot-actuator-module-code}/info/OsInfoContributor.java[`OsInfoContributor`] +| {code-spring-boot-actuator-src}/info/OsInfoContributor.java[`OsInfoContributor`] | Exposes Operating System information. | None. | `process` -| {spring-boot-actuator-module-code}/info/ProcessInfoContributor.java[`ProcessInfoContributor`] +| {code-spring-boot-actuator-src}/info/ProcessInfoContributor.java[`ProcessInfoContributor`] | Exposes process information. | None. @@ -1113,115 +1148,122 @@ Alternatively, to disable every contributor that is usually enabled by default, [[actuator.endpoints.info.custom-application-information]] -==== Custom Application Information +=== Custom Application Information + When the `env` contributor is enabled, you can customize the data exposed by the `info` endpoint by setting `+info.*+` Spring properties. All `Environment` properties under the `info` key are automatically exposed. For example, you could add the following settings to your `application.properties` file: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - info: - app: - encoding: "UTF-8" - java: - source: "17" - target: "17" +info: + app: + encoding: "UTF-8" + java: + source: "17" + target: "17" ---- [TIP] ==== -Rather than hardcoding those values, you could also <>. +Rather than hardcoding those values, you could also xref:how-to:properties-and-configuration.adoc#howto.properties-and-configuration.expand-properties[expand info properties at build time]. Assuming you use Maven, you could rewrite the preceding example as follows: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - info: - app: - encoding: "@project.build.sourceEncoding@" - java: - source: "@java.version@" - target: "@java.version@" +info: + app: + encoding: "@project.build.sourceEncoding@" + java: + source: "@java.version@" + target: "@java.version@" ---- ==== [[actuator.endpoints.info.git-commit-information]] -==== Git Commit Information +=== Git Commit Information + Another useful feature of the `info` endpoint is its ability to publish information about the state of your `git` source code repository when the project was built. If a `GitProperties` bean is available, you can use the `info` endpoint to expose these properties. TIP: A `GitProperties` bean is auto-configured if a `git.properties` file is available at the root of the classpath. -See "<>" for more detail. +See "xref:how-to:build.adoc#howto.build.generate-git-info[how to generate git information]" for more detail. By default, the endpoint exposes `git.branch`, `git.commit.id`, and `git.commit.time` properties, if present. If you do not want any of these properties in the endpoint response, they need to be excluded from the `git.properties` file. If you want to display the full git information (that is, the full content of `git.properties`), use the configprop:management.info.git.mode[] property, as follows: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - info: - git: - mode: "full" +management: + info: + git: + mode: "full" ---- To disable the git commit information from the `info` endpoint completely, set the configprop:management.info.git.enabled[] property to `false`, as follows: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - info: - git: - enabled: false +management: + info: + git: + enabled: false ---- [[actuator.endpoints.info.build-information]] -==== Build Information +=== Build Information + If a `BuildProperties` bean is available, the `info` endpoint can also publish information about your build. This happens if a `META-INF/build-info.properties` file is available in the classpath. TIP: The Maven and Gradle plugins can both generate that file. -See "<>" for more details. +See "xref:how-to:build.adoc#howto.build.generate-info[how to generate build information]" for more details. [[actuator.endpoints.info.java-information]] -==== Java Information -The `info` endpoint publishes information about your Java runtime environment, see {spring-boot-module-api}/info/JavaInfo.html[`JavaInfo`] for more details. +=== Java Information + +The `info` endpoint publishes information about your Java runtime environment, see xref:api:java/org/springframework/boot/info/JavaInfo.html[`JavaInfo`] for more details. [[actuator.endpoints.info.os-information]] -==== OS Information -The `info` endpoint publishes information about your Operating System, see {spring-boot-module-api}/info/OsInfo.html[`OsInfo`] for more details. +=== OS Information + +The `info` endpoint publishes information about your Operating System, see xref:api:java/org/springframework/boot/info/OsInfo.html[`OsInfo`] for more details. [[actuator.endpoints.info.process-information]] -==== Process Information -The `info` endpoint publishes information about your process, see {spring-boot-module-api}/info/ProcessInfo.html[`ProcessInfo`] for more details. +=== Process Information + +The `info` endpoint publishes information about your process, see xref:api:java/org/springframework/boot/info/ProcessInfo.html[`ProcessInfo`] for more details. [[actuator.endpoints.info.writing-custom-info-contributors]] -==== Writing Custom InfoContributors -To provide custom application information, you can register Spring beans that implement the {spring-boot-actuator-module-code}/info/InfoContributor.java[`InfoContributor`] interface. +=== Writing Custom InfoContributors + +To provide custom application information, you can register Spring beans that implement the {code-spring-boot-actuator-src}/info/InfoContributor.java[`InfoContributor`] interface. The following example contributes an `example` entry with a single value: -include::code:MyInfoContributor[] +include-code::MyInfoContributor[] If you reach the `info` endpoint, you should see a response that contains the following additional entry: -[source,json,indent=0,subs="verbatim"] +[source,json] ---- - { - "example": { - "key" : "value" - } +{ + "example": { + "key" : "value" } +} ---- diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/http-exchanges.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/http-exchanges.adoc similarity index 85% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/http-exchanges.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/http-exchanges.adoc index faf3c3f6b6..06b12f1e96 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/http-exchanges.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/http-exchanges.adoc @@ -1,5 +1,6 @@ [[actuator.http-exchanges]] -== Recording HTTP Exchanges += Recording HTTP Exchanges + You can enable recording of HTTP exchanges by providing a bean of type `HttpExchangeRepository` in your application's configuration. For convenience, Spring Boot offers `InMemoryHttpExchangeRepository`, which, by default, stores the last 100 request-response exchanges. `InMemoryHttpExchangeRepository` is limited compared to tracing solutions, and we recommend using it only for development environments. @@ -11,7 +12,8 @@ You can use the `httpexchanges` endpoint to obtain information about the request [[actuator.http-exchanges.custom]] -=== Custom HTTP Exchange Recording +== Custom HTTP Exchange Recording + To customize the items that are included in each recorded exchange, use the configprop:management.httpexchanges.recording.include[] configuration property. -To disable recording entirely, set configprop:management.httpexchanges.recording.enabled[] to `false`. +To disable recoding entirely, set configprop:management.httpexchanges.recording.enabled[] to `false`. diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/index.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/index.adoc new file mode 100644 index 0000000000..3c05673e87 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/index.adoc @@ -0,0 +1,8 @@ + +[[actuator]] += Production-ready Features + +Spring Boot includes a number of additional features to help you monitor and manage your application when you push it to production. +You can choose to manage and monitor your application by using HTTP endpoints or with JMX. +Auditing, health, and metrics gathering can also be automatically applied to your application. + diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/jmx.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/jmx.adoc similarity index 76% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/jmx.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/jmx.adoc index ad3a52b2a4..37f197ee73 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/jmx.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/jmx.adoc @@ -1,5 +1,6 @@ [[actuator.jmx]] -== Monitoring and Management over JMX += Monitoring and Management over JMX + Java Management Extensions (JMX) provide a standard mechanism to monitor and manage applications. By default, this feature is not enabled. You can turn it on by setting the configprop:spring.jmx.enabled[] configuration property to `true`. @@ -9,7 +10,7 @@ Any of your beans that are annotated with Spring JMX annotations (`@ManagedResou If your platform provides a standard `MBeanServer`, Spring Boot uses that and defaults to the VM `MBeanServer`, if necessary. If all that fails, a new `MBeanServer` is created. -See the {spring-boot-autoconfigure-module-code}/jmx/JmxAutoConfiguration.java[`JmxAutoConfiguration`] class for more details. +See the {code-spring-boot-autoconfigure-src}/jmx/JmxAutoConfiguration.java[`JmxAutoConfiguration`] class for more details. By default, Spring Boot also exposes management endpoints as JMX MBeans under the `org.springframework.boot` domain. To take full control over endpoint registration in the JMX domain, consider registering your own `EndpointObjectNameFactory` implementation. @@ -17,7 +18,8 @@ To take full control over endpoint registration in the JMX domain, consider regi [[actuator.jmx.custom-mbean-names]] -=== Customizing MBean Names +== Customizing MBean Names + The name of the MBean is usually generated from the `id` of the endpoint. For example, the `health` endpoint is exposed as `org.springframework.boot:type=Endpoint,name=Health`. @@ -27,28 +29,29 @@ To solve this problem, you can set the configprop:spring.jmx.unique-names[] prop You can also customize the JMX domain under which endpoints are exposed. The following settings show an example of doing so in `application.properties`: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - jmx: - unique-names: true - management: - endpoints: - jmx: - domain: "com.example.myapp" +spring: + jmx: + unique-names: true +management: + endpoints: + jmx: + domain: "com.example.myapp" ---- [[actuator.jmx.disable-jmx-endpoints]] -=== Disabling JMX Endpoints +== Disabling JMX Endpoints + If you do not want to expose endpoints over JMX, you can set the configprop:management.endpoints.jmx.exposure.exclude[] property to `*`, as the following example shows: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - endpoints: - jmx: - exposure: - exclude: "*" +management: + endpoints: + jmx: + exposure: + exclude: "*" ---- diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/loggers.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/loggers.adoc similarity index 88% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/loggers.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/loggers.adoc index 816d5acd9c..3c6e0534ac 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/loggers.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/loggers.adoc @@ -1,5 +1,6 @@ [[actuator.loggers]] -== Loggers += Loggers + Spring Boot Actuator includes the ability to view and configure the log levels of your application at runtime. You can view either the entire list or an individual logger's configuration, which is made up of both the explicitly configured logging level as well as the effective logging level given to it by the logging framework. These levels can be one of: @@ -18,14 +19,15 @@ These levels can be one of: [[actuator.loggers.configure]] -=== Configure a Logger +== Configure a Logger + To configure a given logger, `POST` a partial entity to the resource's URI, as the following example shows: -[source,json,indent=0,subs="verbatim"] +[source,json] ---- - { - "configuredLevel": "DEBUG" - } +{ + "configuredLevel": "DEBUG" +} ---- TIP: To "`reset`" the specific level of the logger (and use the default configuration instead), you can pass a value of `null` as the `configuredLevel`. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/metrics.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/metrics.adoc similarity index 66% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/metrics.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/metrics.adoc index 8ea7054c6b..06a39a25bf 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/metrics.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/metrics.adoc @@ -1,33 +1,35 @@ [[actuator.metrics]] -== Metrics -Spring Boot Actuator provides dependency management and auto-configuration for https://micrometer.io[Micrometer], an application metrics facade that supports {micrometer-docs}[numerous monitoring systems], including: += Metrics -- <> -- <> -- <> -- <> -- <> -- <> -- <> -- <> -- <> -- <> -- <> -- <> -- <> -- <> -- <> -- <> -- <> -- <> -- <> +Spring Boot Actuator provides dependency management and auto-configuration for https://micrometer.io[Micrometer], an application metrics facade that supports {url-micrometer-docs}[numerous monitoring systems], including: -TIP: To learn more about Micrometer's capabilities, see its {micrometer-docs}[reference documentation], in particular the {micrometer-concepts-docs}[concepts section]. +- xref:actuator/metrics.adoc#actuator.metrics.export.appoptics[AppOptics] +- xref:actuator/metrics.adoc#actuator.metrics.export.atlas[Atlas] +- xref:actuator/metrics.adoc#actuator.metrics.export.datadog[Datadog] +- xref:actuator/metrics.adoc#actuator.metrics.export.dynatrace[Dynatrace] +- xref:actuator/metrics.adoc#actuator.metrics.export.elastic[Elastic] +- xref:actuator/metrics.adoc#actuator.metrics.export.ganglia[Ganglia] +- xref:actuator/metrics.adoc#actuator.metrics.export.graphite[Graphite] +- xref:actuator/metrics.adoc#actuator.metrics.export.humio[Humio] +- xref:actuator/metrics.adoc#actuator.metrics.export.influx[Influx] +- xref:actuator/metrics.adoc#actuator.metrics.export.jmx[JMX] +- xref:actuator/metrics.adoc#actuator.metrics.export.kairos[KairosDB] +- xref:actuator/metrics.adoc#actuator.metrics.export.newrelic[New Relic] +- xref:actuator/metrics.adoc#actuator.metrics.export.otlp[OpenTelemetry] +- xref:actuator/metrics.adoc#actuator.metrics.export.prometheus[Prometheus] +- xref:actuator/metrics.adoc#actuator.metrics.export.signalfx[SignalFx] +- xref:actuator/metrics.adoc#actuator.metrics.export.simple[Simple (in-memory)] +- xref:actuator/metrics.adoc#actuator.metrics.export.stackdriver[Stackdriver] +- xref:actuator/metrics.adoc#actuator.metrics.export.statsd[StatsD] +- xref:actuator/metrics.adoc#actuator.metrics.export.wavefront[Wavefront] + +TIP: To learn more about Micrometer's capabilities, see its {url-micrometer-docs}[reference documentation], in particular the {url-micrometer-docs-concepts}[concepts section]. [[actuator.metrics.getting-started]] -=== Getting started +== Getting started + Spring Boot auto-configures a composite `MeterRegistry` and adds a registry to the composite for each of the supported implementations that it finds on the classpath. Having a dependency on `micrometer-registry-\{system}` in your runtime classpath is enough for Spring Boot to configure the registry. @@ -35,142 +37,147 @@ Most registries share common features. For instance, you can disable a particular registry even if the Micrometer registry implementation is on the classpath. The following example disables Datadog: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - datadog: - metrics: - export: - enabled: false +management: + datadog: + metrics: + export: + enabled: false ---- You can also disable all registries unless stated otherwise by the registry-specific property, as the following example shows: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - defaults: - metrics: - export: - enabled: false +management: + defaults: + metrics: + export: + enabled: false ---- Spring Boot also adds any auto-configured registries to the global static composite registry on the `Metrics` class, unless you explicitly tell it not to: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - metrics: - use-global-registry: false +management: + metrics: + use-global-registry: false ---- You can register any number of `MeterRegistryCustomizer` beans to further configure the registry, such as applying common tags, before any meters are registered with the registry: -include::code:commontags/MyMeterRegistryConfiguration[] +include-code::commontags/MyMeterRegistryConfiguration[] You can apply customizations to particular registry implementations by being more specific about the generic type: -include::code:specifictype/MyMeterRegistryConfiguration[] +include-code::specifictype/MyMeterRegistryConfiguration[] -Spring Boot also <> that you can control through configuration or dedicated annotation markers. +Spring Boot also xref:actuator/metrics.adoc#actuator.metrics.supported[configures built-in instrumentation] that you can control through configuration or dedicated annotation markers. [[actuator.metrics.export]] -=== Supported Monitoring Systems +== Supported Monitoring Systems + This section briefly describes each of the supported monitoring systems. [[actuator.metrics.export.appoptics]] -==== AppOptics -By default, the AppOptics registry periodically pushes metrics to `https://api.appoptics.com/v1/measurements`. -To export metrics to SaaS {micrometer-implementation-docs}/appOptics[AppOptics], your API token must be provided: +=== AppOptics -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +By default, the AppOptics registry periodically pushes metrics to `https://api.appoptics.com/v1/measurements`. +To export metrics to SaaS {url-micrometer-docs-implementations}/appOptics[AppOptics], your API token must be provided: + +[configprops,yaml] ---- - management: - appoptics: - metrics: - export: - api-token: "YOUR_TOKEN" +management: + appoptics: + metrics: + export: + api-token: "YOUR_TOKEN" ---- [[actuator.metrics.export.atlas]] -==== Atlas -By default, metrics are exported to {micrometer-implementation-docs}/atlas[Atlas] running on your local machine. +=== Atlas + +By default, metrics are exported to {url-micrometer-docs-implementations}/atlas[Atlas] running on your local machine. You can provide the location of the https://github.com/Netflix/atlas[Atlas server]: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - atlas: - metrics: - export: - uri: "https://atlas.example.com:7101/api/v1/publish" +management: + atlas: + metrics: + export: + uri: "https://atlas.example.com:7101/api/v1/publish" ---- [[actuator.metrics.export.datadog]] -==== Datadog -A Datadog registry periodically pushes metrics to https://www.datadoghq.com[datadoghq]. -To export metrics to {micrometer-implementation-docs}/datadog[Datadog], you must provide your API key: +=== Datadog -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +A Datadog registry periodically pushes metrics to https://www.datadoghq.com[datadoghq]. +To export metrics to {url-micrometer-docs-implementations}/datadog[Datadog], you must provide your API key: + +[configprops,yaml] ---- - management: - datadog: - metrics: - export: - api-key: "YOUR_KEY" +management: + datadog: + metrics: + export: + api-key: "YOUR_KEY" ---- If you additionally provide an application key (optional), then metadata such as meter descriptions, types, and base units will also be exported: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - datadog: - metrics: - export: - api-key: "YOUR_API_KEY" - application-key: "YOUR_APPLICATION_KEY" +management: + datadog: + metrics: + export: + api-key: "YOUR_API_KEY" + application-key: "YOUR_APPLICATION_KEY" ---- By default, metrics are sent to the Datadog US https://docs.datadoghq.com/getting_started/site[site] (`https://api.datadoghq.com`). If your Datadog project is hosted on one of the other sites, or you need to send metrics through a proxy, configure the URI accordingly: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - datadog: - metrics: - export: - uri: "https://api.datadoghq.eu" +management: + datadog: + metrics: + export: + uri: "https://api.datadoghq.eu" ---- You can also change the interval at which metrics are sent to Datadog: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - datadog: - metrics: - export: - step: "30s" +management: + datadog: + metrics: + export: + step: "30s" ---- [[actuator.metrics.export.dynatrace]] -==== Dynatrace -Dynatrace offers two metrics ingest APIs, both of which are implemented for {micrometer-implementation-docs}/dynatrace[Micrometer]. -You can find the Dynatrace documentation on Micrometer metrics ingest {dynatrace-docs}/micrometer-metrics-ingest[here]. -Configuration properties in the `v1` namespace apply only when exporting to the {dynatrace-docs}/api-metrics[Timeseries v1 API]. -Configuration properties in the `v2` namespace apply only when exporting to the {dynatrace-docs}/api-metrics-v2-post-datapoints[Metrics v2 API]. +=== Dynatrace + +Dynatrace offers two metrics ingest APIs, both of which are implemented for {url-micrometer-docs-implementations}/dynatrace[Micrometer]. +You can find the Dynatrace documentation on Micrometer metrics ingest {url-dynatrace-docs-shortlink}/micrometer-metrics-ingest[here]. +Configuration properties in the `v1` namespace apply only when exporting to the {url-dynatrace-docs-shortlink}/api-metrics[Timeseries v1 API]. +Configuration properties in the `v2` namespace apply only when exporting to the {url-dynatrace-docs-shortlink}/api-metrics-v2-post-datapoints[Metrics v2 API]. Note that this integration can export only to either the `v1` or `v2` version of the API at a time, with `v2` being preferred. If the `device-id` (required for v1 but not used in v2) is set in the `v1` namespace, metrics are exported to the `v1` endpoint. Otherwise, `v2` is assumed. @@ -178,16 +185,18 @@ Otherwise, `v2` is assumed. [[actuator.metrics.export.dynatrace.v2-api]] -===== v2 API +==== v2 API + You can use the v2 API in two ways. [[actuator.metrics.export.dynatrace.v2-api.auto-config]] -====== Auto-configuration +===== Auto-configuration + Dynatrace auto-configuration is available for hosts that are monitored by the OneAgent or by the Dynatrace Operator for Kubernetes. -**Local OneAgent:** If a OneAgent is running on the host, metrics are automatically exported to the {dynatrace-docs}/local-api[local OneAgent ingest endpoint]. +**Local OneAgent:** If a OneAgent is running on the host, metrics are automatically exported to the {url-dynatrace-docs-shortlink}/local-api[local OneAgent ingest endpoint]. The ingest endpoint forwards the metrics to the Dynatrace backend. **Dynatrace Kubernetes Operator:** When running in Kubernetes with the Dynatrace Operator installed, the registry will automatically pick up your endpoint URI and API token from the operator instead. @@ -197,9 +206,10 @@ This is the default behavior and requires no special setup beyond a dependency o [[actuator.metrics.export.dynatrace.v2-api.manual-config]] -====== Manual configuration -If no auto-configuration is available, the endpoint of the {dynatrace-docs}/api-metrics-v2-post-datapoints[Metrics v2 API] and an API token are required. -The {dynatrace-docs}/api-authentication[API token] must have the "`Ingest metrics`" (`metrics.ingest`) permission set. +===== Manual configuration + +If no auto-configuration is available, the endpoint of the {url-dynatrace-docs-shortlink}/api-metrics-v2-post-datapoints[Metrics v2 API] and an API token are required. +The {url-dynatrace-docs-shortlink}/api-authentication[API token] must have the "`Ingest metrics`" (`metrics.ingest`) permission set. We recommend limiting the scope of the token to this one permission. You must ensure that the endpoint URI contains the path (for example, `/api/v2/metrics/ingest`): @@ -210,17 +220,17 @@ The URL of the Metrics API v2 ingest endpoint is different according to your dep The example below configures metrics export using the `example` environment id: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - dynatrace: - metrics: - export: - uri: "https://example.live.dynatrace.com/api/v2/metrics/ingest" - api-token: "YOUR_TOKEN" +management: + dynatrace: + metrics: + export: + uri: "https://example.live.dynatrace.com/api/v2/metrics/ingest" + api-token: "YOUR_TOKEN" ---- -When using the Dynatrace v2 API, the following optional features are available (more details can be found in the {dynatrace-docs}/micrometer-metrics-ingest#dt-configuration-properties[Dynatrace documentation]): +When using the Dynatrace v2 API, the following optional features are available (more details can be found in the {url-dynatrace-docs-shortlink}/micrometer-metrics-ingest#dt-configuration-properties[Dynatrace documentation]): * Metric key prefix: Sets a prefix that is prepended to all exported metric keys. * Enrich with Dynatrace metadata: If a OneAgent or Dynatrace operator is running, enrich metrics with additional metadata (for example, about the host, process, or pod). @@ -236,41 +246,42 @@ Use the `export-meter-metadata` toggle to turn this feature off. It is possible to not specify a URI and API token, as shown in the following example. In this scenario, the automatically configured endpoint is used: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - dynatrace: - metrics: - export: - # Specify uri and api-token here if not using the local OneAgent endpoint. - v2: - metric-key-prefix: "your.key.prefix" - enrich-with-dynatrace-metadata: true - default-dimensions: - key1: "value1" - key2: "value2" - use-dynatrace-summary-instruments: true # (default: true) - export-meter-metadata: true # (default: true) +management: + dynatrace: + metrics: + export: + # Specify uri and api-token here if not using the local OneAgent endpoint. + v2: + metric-key-prefix: "your.key.prefix" + enrich-with-dynatrace-metadata: true + default-dimensions: + key1: "value1" + key2: "value2" + use-dynatrace-summary-instruments: true # (default: true) + export-meter-metadata: true # (default: true) ---- [[actuator.metrics.export.dynatrace.v1-api]] -===== v1 API (Legacy) -The Dynatrace v1 API metrics registry pushes metrics to the configured URI periodically by using the {dynatrace-docs}/api-metrics[Timeseries v1 API]. -For backwards-compatibility with existing setups, when `device-id` is set (required for v1, but not used in v2), metrics are exported to the Timeseries v1 endpoint. -To export metrics to {micrometer-implementation-docs}/dynatrace[Dynatrace], your API token, device ID, and URI must be provided: +==== v1 API (Legacy) -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +The Dynatrace v1 API metrics registry pushes metrics to the configured URI periodically by using the {url-dynatrace-docs-shortlink}/api-metrics[Timeseries v1 API]. +For backwards-compatibility with existing setups, when `device-id` is set (required for v1, but not used in v2), metrics are exported to the Timeseries v1 endpoint. +To export metrics to {url-micrometer-docs-implementations}/dynatrace[Dynatrace], your API token, device ID, and URI must be provided: + +[configprops,yaml] ---- - management: - dynatrace: - metrics: - export: - uri: "https://{your-environment-id}.live.dynatrace.com" - api-token: "YOUR_TOKEN" - v1: - device-id: "YOUR_DEVICE_ID" +management: + dynatrace: + metrics: + export: + uri: "https://{your-environment-id}.live.dynatrace.com" + api-token: "YOUR_TOKEN" + v1: + device-id: "YOUR_DEVICE_ID" ---- For the v1 API, you must specify the base environment URI without a path, as the v1 endpoint path is added automatically. @@ -278,206 +289,217 @@ For the v1 API, you must specify the base environment URI without a path, as the [[actuator.metrics.export.dynatrace.version-independent-settings]] -===== Version-independent Settings +==== Version-independent Settings + In addition to the API endpoint and token, you can also change the interval at which metrics are sent to Dynatrace. The default export interval is `60s`. The following example sets the export interval to 30 seconds: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - dynatrace: - metrics: - export: - step: "30s" +management: + dynatrace: + metrics: + export: + step: "30s" ---- -You can find more information on how to set up the Dynatrace exporter for Micrometer in the {micrometer-implementation-docs}/dynatrace[Micrometer documentation] and the {dynatrace-docs}/micrometer-metrics-ingest[Dynatrace documentation]. +You can find more information on how to set up the Dynatrace exporter for Micrometer in the {url-micrometer-docs-implementations}/dynatrace[Micrometer documentation] and the {url-dynatrace-docs-shortlink}/micrometer-metrics-ingest[Dynatrace documentation]. [[actuator.metrics.export.elastic]] -==== Elastic -By default, metrics are exported to {micrometer-implementation-docs}/elastic[Elastic] running on your local machine. +=== Elastic + +By default, metrics are exported to {url-micrometer-docs-implementations}/elastic[Elastic] running on your local machine. You can provide the location of the Elastic server to use by using the following property: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - elastic: - metrics: - export: - host: "https://elastic.example.com:8086" +management: + elastic: + metrics: + export: + host: "https://elastic.example.com:8086" ---- + + [[actuator.metrics.export.ganglia]] -==== Ganglia -By default, metrics are exported to {micrometer-implementation-docs}/ganglia[Ganglia] running on your local machine. +=== Ganglia + +By default, metrics are exported to {url-micrometer-docs-implementations}/ganglia[Ganglia] running on your local machine. You can provide the http://ganglia.sourceforge.net[Ganglia server] host and port, as the following example shows: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - ganglia: - metrics: - export: - host: "ganglia.example.com" - port: 9649 +management: + ganglia: + metrics: + export: + host: "ganglia.example.com" + port: 9649 ---- [[actuator.metrics.export.graphite]] -==== Graphite -By default, metrics are exported to {micrometer-implementation-docs}/graphite[Graphite] running on your local machine. +=== Graphite + +By default, metrics are exported to {url-micrometer-docs-implementations}/graphite[Graphite] running on your local machine. You can provide the https://graphiteapp.org[Graphite server] host and port, as the following example shows: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - graphite: - metrics: - export: - host: "graphite.example.com" - port: 9004 +management: + graphite: + metrics: + export: + host: "graphite.example.com" + port: 9004 ---- -Micrometer provides a default `HierarchicalNameMapper` that governs how a dimensional meter ID is {micrometer-implementation-docs}/graphite#_hierarchical_name_mapping[mapped to flat hierarchical names]. +Micrometer provides a default `HierarchicalNameMapper` that governs how a dimensional meter ID is {url-micrometer-docs-implementations}/graphite#_hierarchical_name_mapping[mapped to flat hierarchical names]. [TIP] ==== To take control over this behavior, define your `GraphiteMeterRegistry` and supply your own `HierarchicalNameMapper`. An auto-configured `GraphiteConfig` and `Clock` beans are provided unless you define your own: -include::code:MyGraphiteConfiguration[] +include-code::MyGraphiteConfiguration[] ==== [[actuator.metrics.export.humio]] -==== Humio -By default, the Humio registry periodically pushes metrics to https://cloud.humio.com. -To export metrics to SaaS {micrometer-implementation-docs}/humio[Humio], you must provide your API token: +=== Humio -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +By default, the Humio registry periodically pushes metrics to https://cloud.humio.com. +To export metrics to SaaS {url-micrometer-docs-implementations}/humio[Humio], you must provide your API token: + +[configprops,yaml] ---- - management: - humio: - metrics: - export: - api-token: "YOUR_TOKEN" +management: + humio: + metrics: + export: + api-token: "YOUR_TOKEN" ---- You should also configure one or more tags to identify the data source to which metrics are pushed: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - humio: - metrics: - export: - tags: - alpha: "a" - bravo: "b" +management: + humio: + metrics: + export: + tags: + alpha: "a" + bravo: "b" ---- [[actuator.metrics.export.influx]] -==== Influx -By default, metrics are exported to an {micrometer-implementation-docs}/influx[Influx] v1 instance running on your local machine with the default configuration. +=== Influx + +By default, metrics are exported to an {url-micrometer-docs-implementations}/influx[Influx] v1 instance running on your local machine with the default configuration. To export metrics to InfluxDB v2, configure the `org`, `bucket`, and authentication `token` for writing metrics. You can provide the location of the https://www.influxdata.com[Influx server] to use by using: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - influx: - metrics: - export: - uri: "https://influx.example.com:8086" +management: + influx: + metrics: + export: + uri: "https://influx.example.com:8086" ---- [[actuator.metrics.export.jmx]] -==== JMX -Micrometer provides a hierarchical mapping to {micrometer-implementation-docs}/jmx[JMX], primarily as a cheap and portable way to view metrics locally. +=== JMX + +Micrometer provides a hierarchical mapping to {url-micrometer-docs-implementations}/jmx[JMX], primarily as a cheap and portable way to view metrics locally. By default, metrics are exported to the `metrics` JMX domain. You can provide the domain to use by using: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - jmx: - metrics: - export: - domain: "com.example.app.metrics" +management: + jmx: + metrics: + export: + domain: "com.example.app.metrics" ---- -Micrometer provides a default `HierarchicalNameMapper` that governs how a dimensional meter ID is {micrometer-implementation-docs}/jmx#_hierarchical_name_mapping[mapped to flat hierarchical names]. +Micrometer provides a default `HierarchicalNameMapper` that governs how a dimensional meter ID is {url-micrometer-docs-implementations}/jmx#_hierarchical_name_mapping[mapped to flat hierarchical names]. [TIP] ==== To take control over this behavior, define your `JmxMeterRegistry` and supply your own `HierarchicalNameMapper`. An auto-configured `JmxConfig` and `Clock` beans are provided unless you define your own: -include::code:MyJmxConfiguration[] +include-code::MyJmxConfiguration[] ==== [[actuator.metrics.export.kairos]] -==== KairosDB -By default, metrics are exported to {micrometer-implementation-docs}/kairos[KairosDB] running on your local machine. +=== KairosDB + +By default, metrics are exported to {url-micrometer-docs-implementations}/kairos[KairosDB] running on your local machine. You can provide the location of the https://kairosdb.github.io/[KairosDB server] to use by using: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - kairos: - metrics: - export: - uri: "https://kairosdb.example.com:8080/api/v1/datapoints" +management: + kairos: + metrics: + export: + uri: "https://kairosdb.example.com:8080/api/v1/datapoints" ---- [[actuator.metrics.export.newrelic]] -==== New Relic -A New Relic registry periodically pushes metrics to {micrometer-implementation-docs}/new-relic[New Relic]. +=== New Relic + +A New Relic registry periodically pushes metrics to {url-micrometer-docs-implementations}/new-relic[New Relic]. To export metrics to https://newrelic.com[New Relic], you must provide your API key and account ID: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - newrelic: - metrics: - export: - api-key: "YOUR_KEY" - account-id: "YOUR_ACCOUNT_ID" +management: + newrelic: + metrics: + export: + api-key: "YOUR_KEY" + account-id: "YOUR_ACCOUNT_ID" ---- You can also change the interval at which metrics are sent to New Relic: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - newrelic: - metrics: - export: - step: "30s" +management: + newrelic: + metrics: + export: + step: "30s" ---- By default, metrics are published through REST calls, but you can also use the Java Agent API if you have it on the classpath: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - newrelic: - metrics: - export: - client-provider-type: "insights-agent" +management: + newrelic: + metrics: + export: + client-provider-type: "insights-agent" ---- Finally, you can take full control by defining your own `NewRelicClientProvider` bean. @@ -485,37 +507,39 @@ Finally, you can take full control by defining your own `NewRelicClientProvider` [[actuator.metrics.export.otlp]] -==== OpenTelemetry -By default, metrics are exported to {micrometer-implementation-docs}/otlp[OpenTelemetry] running on your local machine. +=== OpenTelemetry + +By default, metrics are exported to {url-micrometer-docs-implementations}/otlp[OpenTelemetry] running on your local machine. You can provide the location of the https://opentelemetry.io/[OpenTelemetry metric endpoint] to use by using: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - otlp: - metrics: - export: - url: "https://otlp.example.com:4318/v1/metrics" +management: + otlp: + metrics: + export: + url: "https://otlp.example.com:4318/v1/metrics" ---- [[actuator.metrics.export.prometheus]] -==== Prometheus -{micrometer-implementation-docs}/prometheus[Prometheus] expects to scrape or poll individual application instances for metrics. +=== Prometheus + +{url-micrometer-docs-implementations}/prometheus[Prometheus] expects to scrape or poll individual application instances for metrics. Spring Boot provides an actuator endpoint at `/actuator/prometheus` to present a https://prometheus.io[Prometheus scrape] with the appropriate format. -TIP: By default, the endpoint is not available and must be exposed. See <> for more details. +TIP: By default, the endpoint is not available and must be exposed. See xref:actuator/endpoints.adoc#actuator.endpoints.exposing[exposing endpoints] for more details. The following example `scrape_config` adds to `prometheus.yml`: -[source,yaml,indent=0,subs="verbatim"] +[source,yaml] ---- - scrape_configs: - - job_name: "spring" - metrics_path: "/actuator/prometheus" - static_configs: - - targets: ["HOST:PORT"] +scrape_configs: +- job_name: "spring" + metrics_path: "/actuator/prometheus" + static_configs: + - targets: ["HOST:PORT"] ---- https://prometheus.io/docs/prometheus/latest/feature_flags/#exemplars-storage[Prometheus Exemplars] are also supported. @@ -526,7 +550,7 @@ Please check the https://prometheus.io/docs/prometheus/latest/feature_flags/#exe For ephemeral or batch jobs that may not exist long enough to be scraped, you can use https://github.com/prometheus/pushgateway[Prometheus Pushgateway] support to expose the metrics to Prometheus. To enable Prometheus Pushgateway support, add the following dependency to your project: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- io.prometheus @@ -543,153 +567,160 @@ For advanced configuration, you can also provide your own `PrometheusPushGateway [[actuator.metrics.export.signalfx]] -==== SignalFx -SignalFx registry periodically pushes metrics to {micrometer-implementation-docs}/signalFx[SignalFx]. +=== SignalFx + +SignalFx registry periodically pushes metrics to {url-micrometer-docs-implementations}/signalFx[SignalFx]. To export metrics to https://www.signalfx.com[SignalFx], you must provide your access token: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - signalfx: - metrics: - export: - access-token: "YOUR_ACCESS_TOKEN" +management: + signalfx: + metrics: + export: + access-token: "YOUR_ACCESS_TOKEN" ---- You can also change the interval at which metrics are sent to SignalFx: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - signalfx: - metrics: - export: - step: "30s" +management: + signalfx: + metrics: + export: + step: "30s" ---- [[actuator.metrics.export.simple]] -==== Simple +=== Simple + Micrometer ships with a simple, in-memory backend that is automatically used as a fallback if no other registry is configured. -This lets you see what metrics are collected in the <>. +This lets you see what metrics are collected in the xref:actuator/metrics.adoc#actuator.metrics.endpoint[metrics endpoint]. The in-memory backend disables itself as soon as you use any other available backend. You can also disable it explicitly: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - simple: - metrics: - export: - enabled: false +management: + simple: + metrics: + export: + enabled: false ---- [[actuator.metrics.export.stackdriver]] -==== Stackdriver -The Stackdriver registry periodically pushes metrics to https://cloud.google.com/stackdriver/[Stackdriver]. -To export metrics to SaaS {micrometer-implementation-docs}/stackdriver[Stackdriver], you must provide your Google Cloud project ID: +=== Stackdriver -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +The Stackdriver registry periodically pushes metrics to https://cloud.google.com/stackdriver/[Stackdriver]. +To export metrics to SaaS {url-micrometer-docs-implementations}/stackdriver[Stackdriver], you must provide your Google Cloud project ID: + +[configprops,yaml] ---- - management: - stackdriver: - metrics: - export: - project-id: "my-project" +management: + stackdriver: + metrics: + export: + project-id: "my-project" ---- You can also change the interval at which metrics are sent to Stackdriver: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - stackdriver: - metrics: - export: - step: "30s" +management: + stackdriver: + metrics: + export: + step: "30s" ---- [[actuator.metrics.export.statsd]] -==== StatsD +=== StatsD + The StatsD registry eagerly pushes metrics over UDP to a StatsD agent. -By default, metrics are exported to a {micrometer-implementation-docs}/statsD[StatsD] agent running on your local machine. +By default, metrics are exported to a {url-micrometer-docs-implementations}/statsD[StatsD] agent running on your local machine. You can provide the StatsD agent host, port, and protocol to use by using: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - statsd: - metrics: - export: - host: "statsd.example.com" - port: 9125 - protocol: "udp" +management: + statsd: + metrics: + export: + host: "statsd.example.com" + port: 9125 + protocol: "udp" ---- You can also change the StatsD line protocol to use (it defaults to Datadog): -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - statsd: - metrics: - export: - flavor: "etsy" +management: + statsd: + metrics: + export: + flavor: "etsy" ---- [[actuator.metrics.export.wavefront]] -==== Wavefront -The Wavefront registry periodically pushes metrics to {micrometer-implementation-docs}/wavefront[Wavefront]. +=== Wavefront + +The Wavefront registry periodically pushes metrics to {url-micrometer-docs-implementations}/wavefront[Wavefront]. If you are exporting metrics to https://www.wavefront.com/[Wavefront] directly, you must provide your API token: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - wavefront: - api-token: "YOUR_API_TOKEN" +management: + wavefront: + api-token: "YOUR_API_TOKEN" ---- Alternatively, you can use a Wavefront sidecar or an internal proxy in your environment to forward metrics data to the Wavefront API host: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - wavefront: - uri: "proxy://localhost:2878" +management: + wavefront: + uri: "proxy://localhost:2878" ---- NOTE: If you publish metrics to a Wavefront proxy (as described in https://docs.wavefront.com/proxies_installing.html[the Wavefront documentation]), the host must be in the `proxy://HOST:PORT` format. You can also change the interval at which metrics are sent to Wavefront: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - wavefront: - metrics: - export: - step: "30s" +management: + wavefront: + metrics: + export: + step: "30s" ---- [[actuator.metrics.supported]] -=== Supported Metrics and Meters +== Supported Metrics and Meters + Spring Boot provides automatic meter registration for a wide variety of technologies. In most situations, the defaults provide sensible metrics that can be published to any of the supported monitoring systems. [[actuator.metrics.supported.jvm]] -==== JVM Metrics +=== JVM Metrics + Auto-configuration enables JVM Metrics by using core Micrometer classes. JVM metrics are published under the `jvm.` meter name. @@ -705,7 +736,8 @@ The following JVM metrics are provided: [[actuator.metrics.supported.system]] -==== System Metrics +=== System Metrics + Auto-configuration enables system metrics by using core Micrometer classes. System metrics are published under the `system.`, `process.`, and `disk.` meter names. @@ -719,7 +751,8 @@ The following system metrics are provided: [[actuator.metrics.supported.application-startup]] -==== Application Startup Metrics +=== Application Startup Metrics + Auto-configuration exposes application startup time metrics: * `application.started.time`: time taken to start the application. @@ -730,41 +763,45 @@ Metrics are tagged by the fully qualified name of the application class. [[actuator.metrics.supported.logger]] -==== Logger Metrics +=== Logger Metrics + Auto-configuration enables the event metrics for both Logback and Log4J2. The details are published under the `log4j2.events.` or `logback.events.` meter names. [[actuator.metrics.supported.tasks]] -==== Task Execution and Scheduling Metrics +=== Task Execution and Scheduling Metrics + Auto-configuration enables the instrumentation of all available `ThreadPoolTaskExecutor` and `ThreadPoolTaskScheduler` beans, as long as the underling `ThreadPoolExecutor` is available. Metrics are tagged by the name of the executor, which is derived from the bean name. [[actuator.metrics.supported.jms]] -==== JMS Metrics +=== JMS Metrics + Auto-configuration enables the instrumentation of all available `JmsTemplate` beans and `@JmsListener` annotated methods. This will produce `"jms.message.publish"` and `"jms.message.process"` metrics respectively. -See the {spring-framework-docs}/integration/observability.html#observability.jms[Spring Framework reference documentation for more information on produced observations]. +See the {url-spring-framework-docs}/integration/observability.html#observability.jms[Spring Framework reference documentation for more information on produced observations]. + [[actuator.metrics.supported.spring-mvc]] -==== Spring MVC Metrics +=== Spring MVC Metrics Auto-configuration enables the instrumentation of all requests handled by Spring MVC controllers and functional handlers. By default, metrics are generated with the name, `http.server.requests`. You can customize the name by setting the configprop:management.observations.http.server.requests.name[] property. -See the {spring-framework-docs}/integration/observability.html#observability.http-server.servlet[Spring Framework reference documentation for more information on produced observations]. +See the {url-spring-framework-docs}/integration/observability.html#observability.http-server.servlet[Spring Framework reference documentation for more information on produced observations]. To add to the default tags, provide a `@Bean` that extends `DefaultServerRequestObservationConvention` from the `org.springframework.http.server.observation` package. To replace the default tags, provide a `@Bean` that implements `ServerRequestObservationConvention`. TIP: In some cases, exceptions handled in web controllers are not recorded as request metrics tags. -Applications can opt in and record exceptions by <>. +Applications can opt in and record exceptions by xref:web/servlet.adoc#web.servlet.spring-mvc.error-handling[setting handled exceptions as request attributes]. By default, all requests are handled. To customize the filter, provide a `@Bean` that implements `FilterRegistrationBean`. @@ -772,23 +809,25 @@ To customize the filter, provide a `@Bean` that implements `FilterRegistrationBe [[actuator.metrics.supported.spring-webflux]] -==== Spring WebFlux Metrics +=== Spring WebFlux Metrics + Auto-configuration enables the instrumentation of all requests handled by Spring WebFlux controllers and functional handlers. By default, metrics are generated with the name, `http.server.requests`. You can customize the name by setting the configprop:management.observations.http.server.requests.name[] property. -See the {spring-framework-docs}/integration/observability.html#observability.http-server.reactive[Spring Framework reference documentation for more information on produced observations]. +See the {url-spring-framework-docs}/integration/observability.html#observability.http-server.reactive[Spring Framework reference documentation for more information on produced observations]. To add to the default tags, provide a `@Bean` that extends `DefaultServerRequestObservationConvention` from the `org.springframework.http.server.reactive.observation` package. To replace the default tags, provide a `@Bean` that implements `ServerRequestObservationConvention`. TIP: In some cases, exceptions handled in controllers and handler functions are not recorded as request metrics tags. -Applications can opt in and record exceptions by <>. +Applications can opt in and record exceptions by xref:web/reactive.adoc#web.reactive.webflux.error-handling[setting handled exceptions as request attributes]. [[actuator.metrics.supported.jersey]] -==== Jersey Server Metrics +=== Jersey Server Metrics + Auto-configuration enables the instrumentation of all requests handled by the Jersey JAX-RS implementation. By default, metrics are generated with the name, `http.server.requests`. You can customize the name by setting the configprop:management.observations.http.server.requests.name[] property. @@ -820,7 +859,8 @@ To customize the tags, provide a `@Bean` that implements `JerseyObservationConve [[actuator.metrics.supported.http-clients]] -==== HTTP Client Metrics +=== HTTP Client Metrics + Spring Boot Actuator manages the instrumentation of `RestTemplate`, `WebClient` and `RestClient`. For that, you have to inject the auto-configured builder and use it to create instances: @@ -833,7 +873,7 @@ You can also manually apply the customizers responsible for this instrumentation By default, metrics are generated with the name, `http.client.requests`. You can customize the name by setting the configprop:management.observations.http.client.requests.name[] property. -See the {spring-framework-docs}/integration/observability.html#observability.http-client[Spring Framework reference documentation for more information on produced observations]. +See the {url-spring-framework-docs}/integration/observability.html#observability.http-client[Spring Framework reference documentation for more information on produced observations]. To customize the tags when using `RestTemplate` or `RestClient`, provide a `@Bean` that implements `ClientRequestObservationConvention` from the `org.springframework.http.client.observation` package. To customize the tags when using `WebClient`, provide a `@Bean` that implements `ClientRequestObservationConvention` from the `org.springframework.web.reactive.function.client` package. @@ -841,7 +881,8 @@ To customize the tags when using `WebClient`, provide a `@Bean` that implements [[actuator.metrics.supported.tomcat]] -==== Tomcat Metrics +=== Tomcat Metrics + Auto-configuration enables the instrumentation of Tomcat only when an `MBeanRegistry` is enabled. By default, the `MBeanRegistry` is disabled, but you can enable it by setting configprop:server.tomcat.mbeanregistry.enabled[] to `true`. @@ -850,7 +891,8 @@ Tomcat metrics are published under the `tomcat.` meter name. [[actuator.metrics.supported.cache]] -==== Cache Metrics +=== Cache Metrics + Auto-configuration enables the instrumentation of all available `Cache` instances on startup, with metrics prefixed with `cache`. Cache instrumentation is standardized for a basic set of metrics. Additional, cache-specific metrics are also available. @@ -872,21 +914,22 @@ A `CacheMetricsRegistrar` bean is made available to make that process easier. [[actuator.metrics.supported.spring-batch]] -==== Spring Batch Metrics +=== Spring Batch Metrics -See the {spring-batch-docs}/monitoring-and-metrics.html[Spring Batch reference documentation]. +See the {url-spring-batch-docs}/monitoring-and-metrics.html[Spring Batch reference documentation]. [[actuator.metrics.supported.spring-graphql]] -==== Spring GraphQL Metrics +=== Spring GraphQL Metrics -See the {spring-graphql-docs}/observability.html[Spring GraphQL reference documentation]. +See the {url-spring-graphql-docs}/observability.html[Spring GraphQL reference documentation]. [[actuator.metrics.supported.jdbc]] -==== DataSource Metrics +=== DataSource Metrics + Auto-configuration enables the instrumentation of all available `DataSource` objects with metrics prefixed with `jdbc.connections`. Data source instrumentation results in gauges that represent the currently active, idle, maximum allowed, and minimum allowed connections in the pool. @@ -902,7 +945,8 @@ Each metric is tagged by the name of the pool (you can control it with `spring.d [[actuator.metrics.supported.hibernate]] -==== Hibernate Metrics +=== Hibernate Metrics + If `org.hibernate.orm:hibernate-micrometer` is on the classpath, all available Hibernate `EntityManagerFactory` instances that have statistics enabled are instrumented with a metric named `hibernate`. Metrics are also tagged by the name of the `EntityManagerFactory`, which is derived from the bean name. @@ -910,18 +954,19 @@ Metrics are also tagged by the name of the `EntityManagerFactory`, which is deri To enable statistics, the standard JPA property `hibernate.generate_statistics` must be set to `true`. You can enable that on the auto-configured `EntityManagerFactory`: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - jpa: - properties: - "[hibernate.generate_statistics]": true +spring: + jpa: + properties: + "[hibernate.generate_statistics]": true ---- [[actuator.metrics.supported.spring-data-repository]] -==== Spring Data Repository Metrics +=== Spring Data Repository Metrics + Auto-configuration enables the instrumentation of all Spring Data `Repository` method invocations. By default, metrics are generated with the name, `spring.data.repository.invocations`. You can customize the name by setting the configprop:management.metrics.data.repository.metric-name[] property. @@ -955,34 +1000,39 @@ To replace the default tags, provide a `@Bean` that implements `RepositoryTagsPr [[actuator.metrics.supported.rabbitmq]] -==== RabbitMQ Metrics +=== RabbitMQ Metrics + Auto-configuration enables the instrumentation of all available RabbitMQ connection factories with a metric named `rabbitmq`. [[actuator.metrics.supported.spring-integration]] -==== Spring Integration Metrics -Spring Integration automatically provides {spring-integration-docs}/metrics.html#micrometer-integration[Micrometer support] whenever a `MeterRegistry` bean is available. +=== Spring Integration Metrics + +Spring Integration automatically provides {url-spring-integration-docs}/metrics.html#micrometer-integration[Micrometer support] whenever a `MeterRegistry` bean is available. Metrics are published under the `spring.integration.` meter name. [[actuator.metrics.supported.kafka]] -==== Kafka Metrics +=== Kafka Metrics + Auto-configuration registers a `MicrometerConsumerListener` and `MicrometerProducerListener` for the auto-configured consumer factory and producer factory, respectively. It also registers a `KafkaStreamsMicrometerListener` for `StreamsBuilderFactoryBean`. -For more detail, see the {spring-kafka-docs}kafka/micrometer.html#micrometer-native[Micrometer Native Metrics] section of the Spring Kafka documentation. +For more detail, see the {url-spring-kafka-docs}/kafka/micrometer.html#micrometer-native[Micrometer Native Metrics] section of the Spring Kafka documentation. [[actuator.metrics.supported.mongodb]] -==== MongoDB Metrics +=== MongoDB Metrics + This section briefly describes the available metrics for MongoDB. [[actuator.metrics.supported.mongodb.command]] -===== MongoDB Command Metrics +==== MongoDB Command Metrics + Auto-configuration registers a `MongoMetricsCommandListener` with the auto-configured `MongoClient`. A timer metric named `mongodb.driver.commands` is created for each command issued to the underlying MongoDB driver. @@ -1005,23 +1055,24 @@ Each metric is tagged with the following information by default: To replace the default metric tags, define a `MongoCommandTagsProvider` bean, as the following example shows: -include::code:MyCommandTagsProviderConfiguration[] +include-code::MyCommandTagsProviderConfiguration[] To disable the auto-configured command metrics, set the following property: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - metrics: - mongo: - command: - enabled: false +management: + metrics: + mongo: + command: + enabled: false ---- [[actuator.metrics.supported.mongodb.connection-pool]] -===== MongoDB Connection Pool Metrics +==== MongoDB Connection Pool Metrics + Auto-configuration registers a `MongoMetricsConnectionPoolListener` with the auto-configured `MongoClient`. The following gauge metrics are created for the connection pool: @@ -1043,51 +1094,55 @@ Each metric is tagged with the following information by default: To replace the default metric tags, define a `MongoConnectionPoolTagsProvider` bean: -include::code:MyConnectionPoolTagsProviderConfiguration[] +include-code::MyConnectionPoolTagsProviderConfiguration[] To disable the auto-configured connection pool metrics, set the following property: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - metrics: - mongo: - connectionpool: - enabled: false +management: + metrics: + mongo: + connectionpool: + enabled: false ---- [[actuator.metrics.supported.jetty]] -==== Jetty Metrics +=== Jetty Metrics + Auto-configuration binds metrics for Jetty's `ThreadPool` by using Micrometer's `JettyServerThreadPoolMetrics`. Metrics for Jetty's `Connector` instances are bound by using Micrometer's `JettyConnectionMetrics` and, when configprop:server.ssl.enabled[] is set to `true`, Micrometer's `JettySslHandshakeMetrics`. [[actuator.metrics.supported.timed-annotation]] -==== @Timed Annotation Support +=== @Timed Annotation Support + To enable scanning of `@Timed` annotations, you will need to set the configprop:management.observations.annotations.enabled[] property to `true`. -Please refer to the {micrometer-concepts-docs}#_the_timed_annotation[Micrometer documentation]. +Please refer to the {url-micrometer-docs-concepts}#_the_timed_annotation[Micrometer documentation]. [[actuator.metrics.supported.redis]] -==== Redis Metrics +=== Redis Metrics + Auto-configuration registers a `MicrometerCommandLatencyRecorder` for the auto-configured `LettuceConnectionFactory`. -For more detail, see the {lettuce-docs}#command.latency.metrics.micrometer[Micrometer Metrics section] of the Lettuce documentation. +For more detail, see the {url-lettuce-docs}#command.latency.metrics.micrometer[Micrometer Metrics section] of the Lettuce documentation. [[actuator.metrics.registering-custom]] -=== Registering Custom Metrics +== Registering Custom Metrics + To register custom metrics, inject `MeterRegistry` into your component: -include::code:MyBean[] +include-code::MyBean[] If your metrics depend on other beans, we recommend that you use a `MeterBinder` to register them: -include::code:MyMeterBinderConfiguration[] +include-code::MyMeterBinderConfiguration[] Using a `MeterBinder` ensures that the correct dependency relationships are set up and that the bean is available when the metric's value is retrieved. A `MeterBinder` implementation can also be useful if you find that you repeatedly instrument a suite of metrics across components or applications. @@ -1097,12 +1152,13 @@ NOTE: By default, metrics from all `MeterBinder` beans are automatically bound t [[actuator.metrics.customizing]] -=== Customizing Individual Metrics +== Customizing Individual Metrics + If you need to apply customizations to specific `Meter` instances, you can use the `io.micrometer.core.instrument.config.MeterFilter` interface. For example, if you want to rename the `mytag.region` tag to `mytag.area` for all meter IDs beginning with `com.example`, you can do the following: -include::code:MyMetricsFilterConfiguration[] +include-code::MyMetricsFilterConfiguration[] NOTE: By default, all `MeterFilter` beans are automatically bound to the Spring-managed `MeterRegistry`. Make sure to register your metrics by using the Spring-managed `MeterRegistry` and not any of the static methods on `Metrics`. @@ -1111,17 +1167,18 @@ These use the global registry that is not Spring-managed. [[actuator.metrics.customizing.common-tags]] -==== Common Tags +=== Common Tags + Common tags are generally used for dimensional drill-down on the operating environment, such as host, instance, region, stack, and others. Commons tags are applied to all meters and can be configured, as the following example shows: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - metrics: - tags: - region: "us-east-1" - stack: "prod" +management: + metrics: + tags: + region: "us-east-1" + stack: "prod" ---- The preceding example adds `region` and `stack` tags to all meters with a value of `us-east-1` and `prod`, respectively. @@ -1132,18 +1189,19 @@ As the order of common tags cannot be guaranteed by using this approach, Graphit [[actuator.metrics.customizing.per-meter-properties]] -==== Per-meter Properties +=== Per-meter Properties + In addition to `MeterFilter` beans, you can apply a limited set of customization on a per-meter basis using properties. Per-meter customizations are applied, using Spring Boot's `PropertiesMeterFilter`, to any meter IDs that start with the given name. The following example filters out any meters that have an ID starting with `example.remote`. -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - metrics: - enable: - example: - remote: false +management: + metrics: + enable: + example: + remote: false ---- The following properties allow per-meter customization: @@ -1173,15 +1231,16 @@ configurable buffer length. | Publish a cumulative histogram with buckets defined by your service-level objectives. |=== -For more details on the concepts behind `percentiles-histogram`, `percentiles`, and `slo`, see the {micrometer-concepts-docs}#_histograms_and_percentiles["`Histograms and percentiles`" section] of the Micrometer documentation. +For more details on the concepts behind `percentiles-histogram`, `percentiles`, and `slo`, see the {url-micrometer-docs-concepts}#_histograms_and_percentiles["`Histograms and percentiles`" section] of the Micrometer documentation. [[actuator.metrics.endpoint]] -=== Metrics Endpoint +== Metrics Endpoint + Spring Boot provides a `metrics` endpoint that you can use diagnostically to examine the metrics collected by an application. The endpoint is not available by default and must be exposed. -See <> for more details. +See xref:actuator/endpoints.adoc#actuator.endpoints.exposing[exposing endpoints] for more details. Navigating to `/actuator/metrics` displays a list of available meter names. You can drill down to view information about a particular meter by providing its name as a selector -- for example, `/actuator/metrics/jvm.memory.max`. @@ -1201,6 +1260,9 @@ In the preceding example, the returned `Value` statistic is the sum of the maxim If you wanted to see only the maximum size for the "`Metaspace`", you could add an additional `tag=id:Metaspace` -- that is, `/actuator/metrics/jvm.memory.max?tag=area:nonheap&tag=id:Metaspace`. ==== + + [[actuator.metrics.micrometer-observation]] -=== Integration with Micrometer Observation +== Integration with Micrometer Observation + A `DefaultMeterObservationHandler` is automatically registered on the `ObservationRegistry`, which creates metrics for every completed observation. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/monitoring.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/monitoring.adoc similarity index 62% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/monitoring.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/monitoring.adoc index 499ec66a13..faec2eafd4 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/monitoring.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/monitoring.adoc @@ -1,5 +1,6 @@ [[actuator.monitoring]] -== Monitoring and Management Over HTTP += Monitoring and Management Over HTTP + If you are developing a web application, Spring Boot Actuator auto-configures all enabled endpoints to be exposed over HTTP. The default convention is to use the `id` of the endpoint with a prefix of `/actuator` as the URL path. For example, `health` is exposed as `/actuator/health`. @@ -7,57 +8,59 @@ For example, `health` is exposed as `/actuator/health`. TIP: Actuator is supported natively with Spring MVC, Spring WebFlux, and Jersey. If both Jersey and Spring MVC are available, Spring MVC is used. -NOTE: Jackson is a required dependency in order to get the correct JSON responses as documented in the API documentation ({spring-boot-actuator-restapi-docs}[HTML] or {spring-boot-actuator-restapi-pdfdocs}[PDF]). +NOTE: Jackson is a required dependency in order to get the correct JSON responses as documented in the xref:api:rest/actuator/index.adoc[API documentation]. [[actuator.monitoring.customizing-management-server-context-path]] -=== Customizing the Management Endpoint Paths +== Customizing the Management Endpoint Paths + Sometimes, it is useful to customize the prefix for the management endpoints. For example, your application might already use `/actuator` for another purpose. You can use the configprop:management.endpoints.web.base-path[] property to change the prefix for your management endpoint, as the following example shows: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - endpoints: - web: - base-path: "/manage" +management: + endpoints: + web: + base-path: "/manage" ---- The preceding `application.properties` example changes the endpoint from `/actuator/\{id}` to `/manage/\{id}` (for example, `/manage/info`). -NOTE: Unless the management port has been configured to <>, `management.endpoints.web.base-path` is relative to `server.servlet.context-path` (for servlet web applications) or `spring.webflux.base-path` (for reactive web applications). +NOTE: Unless the management port has been configured to xref:actuator/monitoring.adoc#actuator.monitoring.customizing-management-server-port[expose endpoints by using a different HTTP port], `management.endpoints.web.base-path` is relative to `server.servlet.context-path` (for servlet web applications) or `spring.webflux.base-path` (for reactive web applications). If `management.server.port` is configured, `management.endpoints.web.base-path` is relative to `management.server.base-path`. If you want to map endpoints to a different path, you can use the configprop:management.endpoints.web.path-mapping[] property. The following example remaps `/actuator/health` to `/healthcheck`: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - endpoints: - web: - base-path: "/" - path-mapping: - health: "healthcheck" +management: + endpoints: + web: + base-path: "/" + path-mapping: + health: "healthcheck" ---- [[actuator.monitoring.customizing-management-server-port]] -=== Customizing the Management Server Port +== Customizing the Management Server Port + Exposing management endpoints by using the default HTTP port is a sensible choice for cloud-based deployments. If, however, your application runs inside your own data center, you may prefer to expose endpoints by using a different HTTP port. You can set the configprop:management.server.port[] property to change the HTTP port, as the following example shows: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - server: - port: 8081 +management: + server: + port: 8081 ---- NOTE: On Cloud Foundry, by default, applications receive requests only on port 8080 for both HTTP and TCP routing. @@ -66,48 +69,50 @@ If you want to use a custom management port on Cloud Foundry, you need to explic [[actuator.monitoring.management-specific-ssl]] -=== Configuring Management-specific SSL +== Configuring Management-specific SSL + When configured to use a custom port, you can also configure the management server with its own SSL by using the various `management.server.ssl.*` properties. For example, doing so lets a management server be available over HTTP while the main application uses HTTPS, as the following property settings show: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - server: - port: 8443 - ssl: - enabled: true - key-store: "classpath:store.jks" - key-password: "secret" - management: - server: - port: 8080 - ssl: - enabled: false +server: + port: 8443 + ssl: + enabled: true + key-store: "classpath:store.jks" + key-password: "secret" +management: + server: + port: 8080 + ssl: + enabled: false ---- Alternatively, both the main server and the management server can use SSL but with different key stores, as follows: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - server: - port: 8443 - ssl: - enabled: true - key-store: "classpath:main.jks" - key-password: "secret" - management: - server: - port: 8080 - ssl: - enabled: true - key-store: "classpath:management.jks" - key-password: "secret" +server: + port: 8443 + ssl: + enabled: true + key-store: "classpath:main.jks" + key-password: "secret" +management: + server: + port: 8080 + ssl: + enabled: true + key-store: "classpath:management.jks" + key-password: "secret" ---- [[actuator.monitoring.customizing-management-server-address]] -=== Customizing the Management Server Address +== Customizing the Management Server Address + You can customize the address on which the management endpoints are available by setting the configprop:management.server.address[] property. Doing so can be useful if you want to listen only on an internal or ops-facing network or to listen only for connections from `localhost`. @@ -115,34 +120,35 @@ NOTE: You can listen on a different address only when the port differs from the The following example `application.properties` does not allow remote management connections: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - server: - port: 8081 - address: "127.0.0.1" +management: + server: + port: 8081 + address: "127.0.0.1" ---- [[actuator.monitoring.disabling-http-endpoints]] -=== Disabling HTTP Endpoints +== Disabling HTTP Endpoints + If you do not want to expose endpoints over HTTP, you can set the management port to `-1`, as the following example shows: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - server: - port: -1 +management: + server: + port: -1 ---- You can also achieve this by using the configprop:management.endpoints.web.exposure.exclude[] property, as the following example shows: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - endpoints: - web: - exposure: - exclude: "*" +management: + endpoints: + web: + exposure: + exclude: "*" ---- diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/observability.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/observability.adoc similarity index 84% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/observability.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/observability.adoc index 11b641484d..36b9159fb5 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/observability.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/observability.adoc @@ -1,12 +1,13 @@ [[actuator.observability]] -== Observability += Observability + Observability is the ability to observe the internal state of a running system from the outside. It consists of the three pillars logging, metrics and traces. For metrics and traces, Spring Boot uses https://micrometer.io/docs/observation[Micrometer Observation]. To create your own observations (which will lead to metrics and traces), you can inject an `ObservationRegistry`. -include::code:MyCustomObservation[] +include-code::MyCustomObservation[] NOTE: Low cardinality tags will be added to metrics and traces, while high cardinality tags will only be added to traces. @@ -29,36 +30,39 @@ To enable it, add the `io.r2dbc:r2dbc-proxy` dependency to your project. [[actuator.observability.common-tags]] -=== Common tags +== Common tags + Common tags are generally used for dimensional drill-down on the operating environment, such as host, instance, region, stack, and others. Common tags are applied to all observations as low cardinality tags and can be configured, as the following example shows: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - observations: - key-values: - region: "us-east-1" - stack: "prod" +management: + observations: + key-values: + region: "us-east-1" + stack: "prod" ---- The preceding example adds `region` and `stack` tags to all observations with a value of `us-east-1` and `prod`, respectively. + + [[actuator.observability.preventing-observations]] -=== Preventing Observations +== Preventing Observations If you'd like to prevent some observations from being reported, you can use the configprop:management.observations.enable[] properties: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - observations: - enable: - denied: - prefix: false - another: - denied: - prefix: false +management: + observations: + enable: + denied: + prefix: false + another: + denied: + prefix: false ---- The preceding example will prevent all observations with a name starting with `denied.prefix` or `another.denied.prefix`. @@ -68,14 +72,15 @@ TIP: If you want to prevent Spring Security from reporting observations, set the If you need greater control over the prevention of observations, you can register beans of type `ObservationPredicate`. Observations are only reported if all the `ObservationPredicate` beans return `true` for that observation. -include::code:MyObservationPredicate[] +include-code::MyObservationPredicate[] The preceding example will prevent all observations whose name contains "denied". [[actuator.observability.opentelemetry]] -=== OpenTelemetry Support +== OpenTelemetry Support + Spring Boot's actuator module includes basic support for https://opentelemetry.io/[OpenTelemetry]. It provides a bean of type `OpenTelemetry`, and if there are beans of type `SdkTracerProvider`, `ContextPropagators`, `SdkLoggerProvider` or `SdkMeterProvider` in the application context, they automatically get registered. @@ -84,13 +89,14 @@ The attributes of the auto-configured `Resource` can be configured via the confi If you have defined your own `Resource` bean, this will no longer be the case. NOTE: Spring Boot does not provide auto-configuration for OpenTelemetry metrics or logging. -OpenTelemetry tracing is only auto-configured when used together with <>. +OpenTelemetry tracing is only auto-configured when used together with xref:actuator/tracing.adoc[Micrometer Tracing]. The next sections will provide more details about logging, metrics and traces. [[actuator.observability.annotations]] -=== Micrometer Observation Annotations support +== Micrometer Observation Annotations support + To enable scanning of metrics and tracing annotations like `@Timed`, `@Counted`, `@MeterTag` and `@NewSpan` annotations, you will need to set the configprop:management.observations.annotations.enabled[] property to `true`. -This feature is supported Micrometer directly, please refer to the {micrometer-concepts-docs}#_the_timed_annotation[Micrometer] and {micrometer-tracing-docs}/api.html#_aspect_oriented_programming[Micrometer Tracing] reference docs. +This feature is supported Micrometer directly, please refer to the {url-micrometer-docs-concepts}#_the_timed_annotation[Micrometer] and {url-micrometer-tracing-docs}/api.html#_aspect_oriented_programming[Micrometer Tracing] reference docs. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/process-monitoring.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/process-monitoring.adoc similarity index 66% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/process-monitoring.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/process-monitoring.adoc index 5b877bd10a..34f6b9f876 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/process-monitoring.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/process-monitoring.adoc @@ -1,5 +1,6 @@ [[actuator.process-monitoring]] -== Process Monitoring += Process Monitoring + In the `spring-boot` module, you can find two classes to create files that are often useful for process monitoring: * `ApplicationPidFileWriter` creates a file that contains the application PID (by default, in the application directory with a file name of `application.pid`). @@ -7,25 +8,27 @@ In the `spring-boot` module, you can find two classes to create files that are o By default, these writers are not activated, but you can enable them: -* <> -* <> +* xref:actuator/process-monitoring.adoc#actuator.process-monitoring.configuration[By Extending Configuration] +* xref:actuator/process-monitoring.adoc#actuator.process-monitoring.programmatically[Programmatically Enabling Process Monitoring] [[actuator.process-monitoring.configuration]] -=== Extending Configuration +== Extending Configuration + In the `META-INF/spring.factories` file, you can activate the listener (or listeners) that writes a PID file: -[indent=0] +[source] ---- - org.springframework.context.ApplicationListener=\ - org.springframework.boot.context.ApplicationPidFileWriter,\ - org.springframework.boot.web.context.WebServerPortFileWriter +org.springframework.context.ApplicationListener=\ +org.springframework.boot.context.ApplicationPidFileWriter,\ +org.springframework.boot.web.context.WebServerPortFileWriter ---- [[actuator.process-monitoring.programmatically]] -=== Programmatically Enabling Process Monitoring +== Programmatically Enabling Process Monitoring + You can also activate a listener by invoking the `SpringApplication.addListeners(...)` method and passing the appropriate `Writer` object. This method also lets you customize the file name and path in the `Writer` constructor. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/tracing.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/tracing.adoc similarity index 87% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/tracing.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/tracing.adoc index e4e9189b24..e7ffa8387a 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/tracing.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/tracing.adoc @@ -1,5 +1,6 @@ [[actuator.micrometer-tracing]] -== Tracing += Tracing + Spring Boot Actuator provides dependency management and auto-configuration for https://micrometer.io/docs/tracing[Micrometer Tracing], a facade for popular tracer libraries. TIP: To learn more about Micrometer Tracing capabilities, see its https://micrometer.io/docs/tracing[reference documentation]. @@ -7,7 +8,8 @@ TIP: To learn more about Micrometer Tracing capabilities, see its https://microm [[actuator.micrometer-tracing.tracers]] -=== Supported Tracers +== Supported Tracers + Spring Boot ships auto-configuration for the following tracers: * https://opentelemetry.io/[OpenTelemetry] with https://zipkin.io/[Zipkin], https://docs.wavefront.com/[Wavefront], or https://opentelemetry.io/docs/reference/specification/protocol/[OTLP] @@ -16,14 +18,15 @@ Spring Boot ships auto-configuration for the following tracers: [[actuator.micrometer-tracing.getting-started]] -=== Getting Started +== Getting Started + We need an example application that we can use to get started with tracing. -For our purposes, the simple "`Hello World!`" web application that's covered in the "`<>`" section will suffice. +For our purposes, the simple "`Hello World!`" web application that's covered in the "`xref:tutorial:first-application/index.adoc[Developing Your First Spring Boot Application]`" section will suffice. We're going to use the OpenTelemetry tracer with Zipkin as trace backend. To recap, our main application code looks like this: -include::code:MyApplication[] +include-code::MyApplication[] NOTE: There's an added logger statement in the `home()` method, which will be important later. @@ -35,12 +38,12 @@ Now we have to add the following dependencies: Add the following application properties: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - management: - tracing: - sampling: - probability: 1.0 +management: + tracing: + sampling: + probability: 1.0 ---- By default, Spring Boot samples only 10% of requests to prevent overwhelming the trace backend. @@ -54,9 +57,9 @@ After Zipkin is running, you can start your application. If you open a web browser to `http://localhost:8080`, you should see the following output: -[indent=0] +[source] ---- - Hello World! +Hello World! ---- Behind the scenes, an observation has been created for the HTTP request, which in turn gets bridged to OpenTelemetry, which reports a new trace to Zipkin. @@ -68,7 +71,8 @@ Press the "Show" button to see the details of that trace. [[actuator.micrometer-tracing.logging]] -=== Logging Correlation IDs +== Logging Correlation IDs + Correlation IDs provide a helpful way to link lines in your log files to spans/traces. If you are using Micrometer Tracing, Spring Boot will include correlation IDs in your logs by default. @@ -78,12 +82,12 @@ For example, if Micrometer Tracing has added an MDC `traceId` of `803B448A0489F8 If you prefer to use a different format for your correlation ID, you can use the configprop:logging.pattern.correlation[] property to define one. For example, the following will provide a correlation ID for Logback in format previously used by Spring Cloud Sleuth: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - logging: - pattern: - correlation: "[${spring.application.name:},%X{traceId:-},%X{spanId:-}] " - include-application-name: false +logging: + pattern: + correlation: "[${spring.application.name:},%X{traceId:-},%X{spanId:-}] " + include-application-name: false ---- NOTE: In the example above, configprop:logging.include-application-name[] is set to `false` to avoid the application name being duplicated in the log messages (configprop:logging.pattern.correlation[] already contains it). @@ -92,15 +96,17 @@ It's also worth mentioning that configprop:logging.pattern.correlation[] contain [[actuator.micrometer-tracing.propagating-traces]] -=== Propagating Traces -To automatically propagate traces over the network, use the auto-configured <> or <> to construct the client. +== Propagating Traces + +To automatically propagate traces over the network, use the auto-configured xref:io/rest-client.adoc#io.rest-client.resttemplate[`RestTemplateBuilder`] or xref:io/rest-client.adoc#io.rest-client.webclient[`WebClient.Builder`] to construct the client. WARNING: If you create the `WebClient` or the `RestTemplate` without using the auto-configured builders, automatic trace propagation won't work! [[actuator.micrometer-tracing.tracer-implementations]] -=== Tracer Implementations +== Tracer Implementations + As Micrometer Tracer supports multiple tracer implementations, there are multiple dependency combinations possible with Spring Boot. All tracer implementations need the `org.springframework.boot:spring-boot-starter-actuator` dependency. @@ -108,7 +114,8 @@ All tracer implementations need the `org.springframework.boot:spring-boot-starte [[actuator.micrometer-tracing.tracer-implementations.otel-zipkin]] -==== OpenTelemetry With Zipkin +=== OpenTelemetry With Zipkin + Tracing with OpenTelemetry and reporting to Zipkin requires the following dependencies: * `io.micrometer:micrometer-tracing-bridge-otel` - bridges the Micrometer Observation API to OpenTelemetry. @@ -119,7 +126,8 @@ Use the `management.zipkin.tracing.*` configuration properties to configure repo [[actuator.micrometer-tracing.tracer-implementations.otel-wavefront]] -==== OpenTelemetry With Wavefront +=== OpenTelemetry With Wavefront + Tracing with OpenTelemetry and reporting to Wavefront requires the following dependencies: * `io.micrometer:micrometer-tracing-bridge-otel` - bridges the Micrometer Observation API to OpenTelemetry. @@ -130,7 +138,8 @@ Use the `management.wavefront.*` configuration properties to configure reporting [[actuator.micrometer-tracing.tracer-implementations.otel-otlp]] -==== OpenTelemetry With OTLP +=== OpenTelemetry With OTLP + Tracing with OpenTelemetry and reporting using OTLP requires the following dependencies: * `io.micrometer:micrometer-tracing-bridge-otel` - bridges the Micrometer Observation API to OpenTelemetry. @@ -141,7 +150,8 @@ Use the `management.otlp.tracing.*` configuration properties to configure report [[actuator.micrometer-tracing.tracer-implementations.brave-zipkin]] -==== OpenZipkin Brave With Zipkin +=== OpenZipkin Brave With Zipkin + Tracing with OpenZipkin Brave and reporting to Zipkin requires the following dependencies: * `io.micrometer:micrometer-tracing-bridge-brave` - bridges the Micrometer Observation API to Brave. @@ -154,7 +164,8 @@ Use the `management.zipkin.tracing.*` configuration properties to configure repo [[actuator.micrometer-tracing.tracer-implementations.brave-wavefront]] -==== OpenZipkin Brave With Wavefront +=== OpenZipkin Brave With Wavefront + Tracing with OpenZipkin Brave and reporting to Wavefront requires the following dependencies: * `io.micrometer:micrometer-tracing-bridge-brave` - bridges the Micrometer Observation API to Brave. @@ -165,16 +176,19 @@ Use the `management.wavefront.*` configuration properties to configure reporting [[actuator.micrometer-tracing.micrometer-observation]] -=== Integration with Micrometer Observation +== Integration with Micrometer Observation A `TracingAwareMeterObservationHandler` is automatically registered on the `ObservationRegistry`, which creates spans for every completed observation. + + [[actuator.micrometer-tracing.creating-spans]] -=== Creating Custom Spans +== Creating Custom Spans + You can create your own spans by starting an observation. For this, inject `ObservationRegistry` into your component: -include::code:CustomObservation[] +include-code::CustomObservation[] This will create an observation named "some-operation" with the tag "some-tag=some-value". @@ -183,10 +197,11 @@ TIP: If you want to create a span without creating a metric, you need to use the [[actuator.micrometer-tracing.baggage]] -=== Baggage +== Baggage + You can create baggage with the `Tracer` API: -include::code:CreatingBaggage[] +include-code::CreatingBaggage[] This example creates baggage named `baggage1` with the value `value1`. The baggage is automatically propagated over the network if you're using W3C propagation. @@ -200,7 +215,7 @@ For the example above, setting this property to `baggage1` results in an MDC ent [[actuator.micrometer-tracing.tests]] -=== Tests +== Tests Tracing components which are reporting data are not auto-configured when using `@SpringBootTest`. -See <> for more details. +See xref:features/testing.adoc#features.testing.spring-boot-applications.tracing[the testing section] for more details. 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/antora/modules/reference/pages/container-images/cloud-native-buildpacks.adoc similarity index 91% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images/cloud-native-buildpacks.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/container-images/cloud-native-buildpacks.adoc index 020eac3832..15d47e930f 100644 --- 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/antora/modules/reference/pages/container-images/cloud-native-buildpacks.adoc @@ -1,5 +1,6 @@ [[container-images.buildpacks]] -== Cloud Native 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. @@ -10,7 +11,7 @@ With Cloud Native Buildpacks, you can create Docker compatible images that you c Spring Boot includes buildpack support directly for both Maven and Gradle. This means you can just type a single command and quickly get a sensible image into your locally running Docker daemon. -See the individual plugin documentation on how to use buildpacks with {spring-boot-maven-plugin-docs}#build-image[Maven] and {spring-boot-gradle-plugin-docs}#build-image[Gradle]. +See the individual plugin documentation on how to use buildpacks with xref:maven-plugin:build-image.adoc#build-image[Maven] and xref:gradle-plugin:packaging-oci-image.adoc[Gradle]. NOTE: The https://github.com/paketo-buildpacks/spring-boot[Paketo Spring Boot buildpack] supports the `layers.idx` file, so any customization that is applied to it will be reflected in the image created by the buildpack. 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/antora/modules/reference/pages/container-images/dockerfiles.adoc similarity index 82% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images/dockerfiles.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/container-images/dockerfiles.adoc index 1956cc4a31..50caeef07f 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images/dockerfiles.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/container-images/dockerfiles.adoc @@ -1,15 +1,16 @@ [[container-images.dockerfiles]] -== Dockerfiles -While it is possible to convert a Spring Boot uber jar into a docker image with just a few lines in the Dockerfile, we will use the <> to create an optimized docker image. += Dockerfiles + +While it is possible to convert a Spring Boot uber jar into a docker image with just a few lines in the Dockerfile, we will use the xref:container-images/efficient-images.adoc#container-images.efficient-images.layering[layering feature] to create an optimized docker image. When you create a jar containing the layers index file, the `spring-boot-jarmode-layertools` jar will be added as a dependency to your jar. With this jar on the classpath, you can launch your application in a special mode which allows the bootstrap code to run something entirely different from your application, for example, something that extracts the layers. -CAUTION: The `layertools` mode can not be used with a <> that includes a launch script. +CAUTION: The `layertools` mode can not be used with a xref:deployment/installing.adoc[fully executable Spring Boot archive] that includes a launch script. Disable launch script configuration when building a jar file that is intended to be used with `layertools`. Here’s how you can launch your jar with a `layertools` jar mode: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- $ java -Djarmode=layertools -jar my-app.jar ---- @@ -30,7 +31,7 @@ Available commands: The `extract` command can be used to easily split the application into layers to be added to the dockerfile. Here is an example of a Dockerfile using `jarmode`. -[source,dockerfile,indent=0,subs="verbatim"] +[source,dockerfile] ---- FROM eclipse-temurin:17-jre as builder WORKDIR application @@ -49,9 +50,9 @@ ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"] Assuming the above `Dockerfile` is in the current directory, your docker image can be built with `docker build .`, or optionally specifying the path to your application jar, as shown in the following example: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ docker build --build-arg JAR_FILE=path/to/myapp.jar . +$ docker build --build-arg JAR_FILE=path/to/myapp.jar . ---- This is a multi-stage dockerfile. 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/antora/modules/reference/pages/container-images/efficient-images.adoc similarity index 72% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images/efficient-images.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/container-images/efficient-images.adoc index d06327bb05..8de3bf39ae 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images/efficient-images.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/container-images/efficient-images.adoc @@ -1,5 +1,6 @@ [[container-images.efficient-images]] -== Efficient Container Images += Efficient Container Images + It is easily possible to package a Spring Boot uber jar as a docker image. However, there are various downsides to copying and running the uber jar as is in the docker image. There’s always a certain amount of overhead when running a uber jar without unpacking it, and in a containerized environment this can be noticeable. @@ -8,8 +9,10 @@ Since you probably recompile your code more often than you upgrade the version o If you put jar files in the layer before your application classes, Docker often only needs to change the very bottom layer and can pick others up from its cache. + [[container-images.efficient-images.layering]] -=== Layering Docker Images +== 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. @@ -22,19 +25,19 @@ Out-of-the-box, the following layers are supported: The following shows an example of a `layers.idx` file: -[source,yaml,indent=0,subs="verbatim"] +[source,yaml] ---- - - "dependencies": - - BOOT-INF/lib/library1.jar - - BOOT-INF/lib/library2.jar - - "spring-boot-loader": - - org/springframework/boot/loader/launch/JarLauncher.class - - ... - - "snapshot-dependencies": - - BOOT-INF/lib/library3-SNAPSHOT.jar - - "application": - - META-INF/MANIFEST.MF - - BOOT-INF/classes/a/b/C.class +- "dependencies": + - BOOT-INF/lib/library1.jar + - BOOT-INF/lib/library2.jar +- "spring-boot-loader": + - org/springframework/boot/loader/launch/JarLauncher.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. @@ -43,5 +46,5 @@ Application code is more likely to change between builds so it is isolated in a Spring Boot also supports layering for war files with the help of a `layers.idx`. -For Maven, see 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, see the {spring-boot-gradle-plugin-docs}#packaging-layered-archives[packaging layered jar or war section] of the Gradle plugin documentation. +For Maven, see the xref:maven-plugin:packaging.adoc#packaging.layers[packaging layered jar or war section] for more details on adding a layer index to the archive. +For Gradle, see the xref:gradle-plugin:packaging.adoc#packaging-executable.configuring.layered-archives[packaging layered jar or war section] of the Gradle plugin documentation. diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/container-images/index.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/container-images/index.adoc new file mode 100644 index 0000000000..0c91ca29ff --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/container-images/index.adoc @@ -0,0 +1,4 @@ +[[container-images]] += Container Images + +Spring Boot applications can be containerized xref:container-images/dockerfiles.adoc[using Dockerfiles], or by xref:container-images/cloud-native-buildpacks.adoc[using Cloud Native Buildpacks to create optimized docker compatible container images that you can run anywhere]. diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/data/index.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/data/index.adoc new file mode 100644 index 0000000000..b6e87cc5fd --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/data/index.adoc @@ -0,0 +1,4 @@ +[[data]] += Data + +Spring Boot integrates with a number of data technologies, both SQL and NoSQL. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data/nosql.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/data/nosql.adoc similarity index 75% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/data/nosql.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/data/nosql.adoc index c1816b18d9..9a6e80173d 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data/nosql.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/data/nosql.adoc @@ -1,27 +1,29 @@ [[data.nosql]] -== Working with NoSQL Technologies += Working with NoSQL Technologies + Spring Data provides additional projects that help you access a variety of NoSQL technologies, including: -* {spring-data-cassandra}[Cassandra] -* {spring-data-couchbase}[Couchbase] -* {spring-data-elasticsearch}[Elasticsearch] -* {spring-data-gemfire}[GemFire] or {spring-data-geode}[Geode] -* {spring-data-ldap}[LDAP] -* {spring-data-mongodb}[MongoDB] -* {spring-data-neo4j}[Neo4J] -* {spring-data-redis}[Redis] +* {url-spring-data-cassandra-site}[Cassandra] +* {url-spring-data-couchbase-site}[Couchbase] +* {url-spring-data-elasticsearch-site}[Elasticsearch] +* {url-spring-data-gemfire-site}[GemFire] or {url-spring-data-geode-site}[Geode] +* {url-spring-data-ldap-site}[LDAP] +* {url-spring-data-mongodb-site}[MongoDB] +* {url-spring-data-neo4j-site}[Neo4J] +* {url-spring-data-redis-site}[Redis] Of these, Spring Boot provides auto-configuration for Cassandra, Couchbase, Elasticsearch, LDAP, MongoDB, Neo4J and Redis. -Additionally, {spring-boot-for-apache-geode}[Spring Boot for Apache Geode] provides {spring-boot-for-apache-geode-docs}#geode-repositories[auto-configuration for Apache Geode]. +Additionally, {url-spring-boot-for-apache-geode-site}[Spring Boot for Apache Geode] provides {url-spring-boot-for-apache-geode-docs}#geode-repositories[auto-configuration for Apache Geode]. You can make use of the other projects, but you must configure them yourself. -See the appropriate reference documentation at {spring-data}. +See the appropriate reference documentation at {url-spring-data-site}. Spring Boot also provides auto-configuration for the InfluxDB client but it is deprecated in favor of https://github.com/influxdata/influxdb-client-java[the new InfluxDB Java client] that provides its own Spring Boot integration. [[data.nosql.redis]] -=== Redis +== 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]. @@ -34,25 +36,26 @@ TIP: We also provide a `spring-boot-starter-data-redis-reactive` "`Starter`" for [[data.nosql.redis.connecting]] -==== Connecting to Redis +=== Connecting to Redis + You can inject an auto-configured `RedisConnectionFactory`, `StringRedisTemplate`, or vanilla `RedisTemplate` instance as you would any other Spring Bean. The following listing shows an example of such a bean: -include::code:MyBean[] +include-code::MyBean[] By default, the instance tries to connect to a Redis server at `localhost:6379`. You can specify custom connection details using `spring.data.redis.*` properties, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - data: - redis: - host: "localhost" - port: 6379 - database: 0 - username: "user" - password: "secret" +spring: + data: + redis: + host: "localhost" + port: 6379 + database: 0 + username: "user" + password: "secret" ---- TIP: You can also register an arbitrary number of beans that implement `LettuceClientConfigurationBuilderCustomizer` for more advanced customizations. @@ -66,41 +69,44 @@ By default, a pooled connection factory is auto-configured if `commons-pool2` is The auto-configured `RedisConnectionFactory` can be configured to use SSL for communication with the server by setting the properties as shown in this example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - data: - redis: - ssl: - enabled: true +spring: + data: + redis: + ssl: + enabled: true ---- -Custom SSL trust material can be configured in an <> and applied to the `RedisConnectionFactory` as shown in this example: +Custom SSL trust material can be configured in an xref:features/ssl.adoc[SSL bundle] and applied to the `RedisConnectionFactory` as shown in this example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - data: - redis: - ssl: - bundle: "example" +spring: + data: + redis: + ssl: + bundle: "example" ---- + [[data.nosql.mongodb]] -=== MongoDB +== MongoDB + https://www.mongodb.com/[MongoDB] is an open-source NoSQL document database that uses a JSON-like schema instead of traditional table-based relational data. Spring Boot offers several conveniences for working with MongoDB, including the `spring-boot-starter-data-mongodb` and `spring-boot-starter-data-mongodb-reactive` "`Starters`". [[data.nosql.mongodb.connecting]] -==== Connecting to a MongoDB Database +=== Connecting to a MongoDB Database + To access MongoDB databases, you can inject an auto-configured `org.springframework.data.mongodb.MongoDatabaseFactory`. By default, the instance tries to connect to a MongoDB server at `mongodb://localhost/test`. The following example shows how to connect to a MongoDB database: -include::code:MyBean[] +include-code::MyBean[] If you have defined your own `MongoClient`, it will be used to auto-configure a suitable `MongoDatabaseFactory`. @@ -112,53 +118,53 @@ Each will be called in order with the `MongoClientSettings.Builder` that is used You can set the configprop:spring.data.mongodb.uri[] property to change the URL and configure additional settings such as the _replica set_, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - data: - mongodb: - uri: "mongodb://user:secret@mongoserver1.example.com:27017,mongoserver2.example.com:23456/test" +spring: + data: + mongodb: + uri: "mongodb://user:secret@mongoserver1.example.com:27017,mongoserver2.example.com:23456/test" ---- Alternatively, you can specify connection details using discrete properties. For example, you might declare the following settings in your `application.properties`: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - data: - mongodb: - host: "mongoserver1.example.com" - port: 27017 - additional-hosts: - - "mongoserver2.example.com:23456" - database: "test" - username: "user" - password: "secret" +spring: + data: + mongodb: + host: "mongoserver1.example.com" + port: 27017 + additional-hosts: + - "mongoserver2.example.com:23456" + database: "test" + username: "user" + password: "secret" ---- The auto-configured `MongoClient` can be configured to use SSL for communication with the server by setting the properties as shown in this example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - data: - mongodb: - uri: "mongodb://user:secret@mongoserver1.example.com:27017,mongoserver2.example.com:23456/test" - ssl: - enabled: true +spring: + data: + mongodb: + uri: "mongodb://user:secret@mongoserver1.example.com:27017,mongoserver2.example.com:23456/test" + ssl: + enabled: true ---- -Custom SSL trust material can be configured in an <> and applied to the `MongoClient` as shown in this example: +Custom SSL trust material can be configured in an xref:features/ssl.adoc[SSL bundle] and applied to the `MongoClient` as shown in this example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - data: - mongodb: - uri: "mongodb://user:secret@mongoserver1.example.com:27017,mongoserver2.example.com:23456/test" - ssl: - bundle: "example" +spring: + data: + mongodb: + uri: "mongodb://user:secret@mongoserver1.example.com:27017,mongoserver2.example.com:23456/test" + ssl: + bundle: "example" ---- @@ -180,60 +186,64 @@ The auto-configuration configures this factory automatically if Netty is availab [[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`. +=== MongoTemplate + +{url-spring-data-mongodb-site}[Spring Data MongoDB] provides a {url-spring-data-mongodb-javadoc}/org/springframework/data/mongodb/core/MongoTemplate.html[`MongoTemplate`] class that is very similar in its design to Spring's `JdbcTemplate`. As with `JdbcTemplate`, Spring Boot auto-configures a bean for you to inject the template, as follows: -include::code:MyBean[] +include-code::MyBean[] -See the {spring-data-mongodb-api}/core/MongoOperations.html[`MongoOperations` Javadoc] for complete details. +See the {url-spring-data-mongodb-javadoc}/org/springframework/data/mongodb/core/MongoOperations.html[`MongoOperations` Javadoc] for complete details. [[data.nosql.mongodb.repositories]] -==== Spring Data MongoDB Repositories +=== Spring Data MongoDB Repositories + Spring Data includes repository support for MongoDB. As with the JPA repositories discussed earlier, the basic principle is that queries are constructed automatically, based on method names. In fact, both Spring Data JPA and Spring Data MongoDB share the same common infrastructure. You could take the JPA example from earlier and, assuming that `City` is now a MongoDB data class rather than a JPA `@Entity`, it works in the same way, as shown in the following example: -include::code:CityRepository[] +include-code::CityRepository[] Repositories and documents are found through scanning. -By default, the <> are scanned. +By default, the xref:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages] are scanned. You can customize the locations to look for repositories and documents by using `@EnableMongoRepositories` and `@EntityScan` respectively. -TIP: For complete details of Spring Data MongoDB, including its rich object mapping technologies, see its {spring-data-mongodb}[reference documentation]. +TIP: For complete details of Spring Data MongoDB, including its rich object mapping technologies, see its {url-spring-data-mongodb-docs}[reference documentation]. [[data.nosql.neo4j]] -=== Neo4j +== Neo4j + https://neo4j.com/[Neo4j] is an open-source NoSQL graph database that uses a rich data model of nodes connected by first class relationships, which is better suited for connected big data than traditional RDBMS approaches. Spring Boot offers several conveniences for working with Neo4j, including the `spring-boot-starter-data-neo4j` "`Starter`". [[data.nosql.neo4j.connecting]] -==== Connecting to a Neo4j Database +=== Connecting to a Neo4j Database + To access a Neo4j server, you can inject an auto-configured `org.neo4j.driver.Driver`. By default, the instance tries to connect to a Neo4j server at `localhost:7687` using the Bolt protocol. The following example shows how to inject a Neo4j `Driver` that gives you access, amongst other things, to a `Session`: -include::code:MyBean[] +include-code::MyBean[] You can configure various aspects of the driver using `spring.neo4j.*` properties. The following example shows how to configure the uri and credentials to use: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - neo4j: - uri: "bolt://my-server:7687" - authentication: - username: "neo4j" - password: "secret" +spring: + neo4j: + uri: "bolt://my-server:7687" + authentication: + username: "neo4j" + password: "secret" ---- The auto-configured `Driver` is created using `ConfigBuilder`. @@ -243,21 +253,22 @@ Each will be called in order with the `ConfigBuilder` that is used to build the [[data.nosql.neo4j.repositories]] -==== Spring Data Neo4j Repositories +=== Spring Data Neo4j Repositories + Spring Data includes repository support for Neo4j. -For complete details of Spring Data Neo4j, see the {spring-data-neo4j-docs}[reference documentation]. +For complete details of Spring Data Neo4j, see the {url-spring-data-neo4j-docs}[reference documentation]. Spring Data Neo4j shares the common infrastructure with Spring Data JPA as many other Spring Data modules do. You could take the JPA example from earlier and define `City` as Spring Data Neo4j `@Node` rather than JPA `@Entity` and the repository abstraction works in the same way, as shown in the following example: -include::code:CityRepository[] +include-code::CityRepository[] The `spring-boot-starter-data-neo4j` "`Starter`" enables the repository support as well as transaction management. Spring Boot supports both classic and reactive Neo4j repositories, using the `Neo4jTemplate` or `ReactiveNeo4jTemplate` beans. When Project Reactor is available on the classpath, the reactive style is also auto-configured. Repositories and entities are found through scanning. -By default, the <> are scanned. +By default, the xref:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages] are scanned. You can customize the locations to look for repositories and entities by using `@EnableNeo4jRepositories` and `@EntityScan` respectively. [NOTE] @@ -265,13 +276,14 @@ You can customize the locations to look for repositories and entities by using ` In an application using the reactive style, a `ReactiveTransactionManager` is not auto-configured. To enable transaction management, the following bean must be defined in your configuration: -include::code:MyNeo4jConfiguration[] +include-code::MyNeo4jConfiguration[] ==== [[data.nosql.elasticsearch]] -=== Elasticsearch +== Elasticsearch + https://www.elastic.co/products/elasticsearch[Elasticsearch] is an open source, distributed, RESTful search and analytics engine. Spring Boot offers basic auto-configuration for Elasticsearch clients. @@ -286,24 +298,28 @@ Spring Boot provides a dedicated "`Starter`", `spring-boot-starter-data-elastics [[data.nosql.elasticsearch.connecting-using-rest]] -==== Connecting to Elasticsearch Using REST clients +=== Connecting to Elasticsearch Using REST clients + Elasticsearch ships two different REST clients that you can use to query a cluster: the https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/java-rest-low.html[low-level client] from the `org.elasticsearch.client:elasticsearch-rest-client` module and the https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/index.html[Java API client] from the `co.elastic.clients:elasticsearch-java` module. Additionally, Spring Boot provides support for a reactive client from the `org.springframework.data:spring-data-elasticsearch` module. By default, the clients will target `http://localhost:9200`. You can use `spring.elasticsearch.*` properties to further tune how the clients are configured, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - elasticsearch: - uris: "https://search.example.com:9200" - socket-timeout: "10s" - username: "user" - password: "secret" +spring: + elasticsearch: + uris: "https://search.example.com:9200" + socket-timeout: "10s" + username: "user" + password: "secret" ---- + + [[data.nosql.elasticsearch.connecting-using-rest.restclient]] -===== Connecting to Elasticsearch Using RestClient +==== Connecting to Elasticsearch Using RestClient + If you have `elasticsearch-rest-client` on the classpath, Spring Boot will auto-configure and register a `RestClient` bean. In addition to the properties described previously, to fine-tune the `RestClient` you can register an arbitrary number of beans that implement `RestClientBuilderCustomizer` for more advanced customizations. To take full control over the clients' configuration, define a `RestClientBuilder` bean. @@ -313,19 +329,21 @@ To take full control over the clients' configuration, define a `RestClientBuilde Additionally, if `elasticsearch-rest-client-sniffer` is on the classpath, a `Sniffer` is auto-configured to automatically discover nodes from a running Elasticsearch cluster and set them on the `RestClient` bean. You can further tune how `Sniffer` is configured, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - elasticsearch: - restclient: - sniffer: - interval: "10m" - delay-after-failure: "30s" +spring: + elasticsearch: + restclient: + sniffer: + interval: "10m" + delay-after-failure: "30s" ---- + [[data.nosql.elasticsearch.connecting-using-rest.javaapiclient]] -===== Connecting to Elasticsearch Using ElasticsearchClient +==== Connecting to Elasticsearch Using ElasticsearchClient + If you have `co.elastic.clients:elasticsearch-java` on the classpath, Spring Boot will auto-configure and register an `ElasticsearchClient` bean. The `ElasticsearchClient` uses a transport that depends upon the previously described `RestClient`. @@ -335,8 +353,9 @@ Furthermore, you can define a `RestClientOptions` bean to take further control o [[data.nosql.elasticsearch.connecting-using-rest.reactiveclient]] -===== Connecting to Elasticsearch using ReactiveElasticsearchClient -{spring-data-elasticsearch}[Spring Data Elasticsearch] ships `ReactiveElasticsearchClient` for querying Elasticsearch instances in a reactive fashion. +==== Connecting to Elasticsearch using ReactiveElasticsearchClient + +{url-spring-data-elasticsearch-site}[Spring Data Elasticsearch] ships `ReactiveElasticsearchClient` for querying Elasticsearch instances in a reactive fashion. If you have Spring Data Elasticsearch and Reactor on the classpath, Spring Boot will auto-configure and register a `ReactiveElasticsearchClient`. The `ReactiveElasticsearchclient` uses a transport that depends upon the previously described `RestClient`. @@ -346,22 +365,24 @@ Furthermore, you can define a `RestClientOptions` bean to take further control o [[data.nosql.elasticsearch.connecting-using-spring-data]] -==== Connecting to Elasticsearch by Using Spring Data +=== Connecting to Elasticsearch by Using Spring Data + To connect to Elasticsearch, an `ElasticsearchClient` bean must be defined, auto-configured by Spring Boot or manually provided by the application (see previous sections). With this configuration in place, an `ElasticsearchTemplate` can be injected like any other Spring bean, as shown in the following example: -include::code:MyBean[] +include-code::MyBean[] -In the presence of `spring-data-elasticsearch` and Reactor, Spring Boot can also auto-configure a <> and a `ReactiveElasticsearchTemplate` as beans. +In the presence of `spring-data-elasticsearch` and Reactor, Spring Boot can also auto-configure a xref:data/nosql.adoc#data.nosql.elasticsearch.connecting-using-rest.reactiveclient[ReactiveElasticsearchClient] and a `ReactiveElasticsearchTemplate` as beans. They are the reactive equivalent of the other REST clients. [[data.nosql.elasticsearch.repositories]] -==== Spring Data 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. @@ -369,10 +390,10 @@ In fact, both Spring Data JPA and Spring Data Elasticsearch share the same commo You could take the JPA example from earlier and, assuming that `City` is now an Elasticsearch `@Document` class rather than a JPA `@Entity`, it works in the same way. Repositories and documents are found through scanning. -By default, the <> are scanned. +By default, the xref:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages] are scanned. You can customize the locations to look for repositories and documents by using `@EnableElasticsearchRepositories` and `@EntityScan` respectively. -TIP: For complete details of Spring Data Elasticsearch, see the {spring-data-elasticsearch-docs}[reference documentation]. +TIP: For complete details of Spring Data Elasticsearch, see the {url-spring-data-elasticsearch-docs}[reference documentation]. Spring Boot supports both classic and reactive Elasticsearch repositories, using the `ElasticsearchRestTemplate` or `ReactiveElasticsearchTemplate` beans. Most likely those beans are auto-configured by Spring Boot given the required dependencies are present. @@ -382,7 +403,7 @@ Same applies to `ReactiveElasticsearchTemplate` and `ReactiveElasticsearchOperat You can choose to disable the repositories support with the following property: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- spring: data: @@ -394,37 +415,39 @@ You can choose to disable the repositories support with the following property: [[data.nosql.cassandra]] -=== 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]. +Spring Boot offers auto-configuration for Cassandra and the abstractions on top of it provided by {url-spring-data-cassandra-site}[Spring Data Cassandra]. There is a `spring-boot-starter-data-cassandra` "`Starter`" for collecting the dependencies in a convenient way. [[data.nosql.cassandra.connecting]] -==== Connecting to Cassandra +=== Connecting to Cassandra + You can inject an auto-configured `CassandraTemplate` or a Cassandra `CqlSession` instance as you would with any other Spring Bean. The `spring.cassandra.*` properties can be used to customize the connection. Generally, you provide `keyspace-name` and `contact-points` as well the local datacenter name, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - cassandra: - keyspace-name: "mykeyspace" - contact-points: "cassandrahost1:9042,cassandrahost2:9042" - local-datacenter: "datacenter1" +spring: + cassandra: + keyspace-name: "mykeyspace" + contact-points: "cassandrahost1:9042,cassandrahost2:9042" + local-datacenter: "datacenter1" ---- If the port is the same for all your contact points you can use a shortcut and only specify the host names, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - cassandra: - keyspace-name: "mykeyspace" - contact-points: "cassandrahost1,cassandrahost2" - local-datacenter: "datacenter1" +spring: + cassandra: + keyspace-name: "mykeyspace" + contact-points: "cassandrahost1,cassandrahost2" + local-datacenter: "datacenter1" ---- TIP: Those two examples are identical as the port default to `9042`. @@ -432,28 +455,28 @@ If you need to configure the port, use `spring.cassandra.port`. The auto-configured `CqlSession` can be configured to use SSL for communication with the server by setting the properties as shown in this example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - cassandra: - keyspace-name: "mykeyspace" - contact-points: "cassandrahost1,cassandrahost2" - local-datacenter: "datacenter1" - ssl: - enabled: true +spring: + cassandra: + keyspace-name: "mykeyspace" + contact-points: "cassandrahost1,cassandrahost2" + local-datacenter: "datacenter1" + ssl: + enabled: true ---- -Custom SSL trust material can be configured in an <> and applied to the `CqlSession` as shown in this example: +Custom SSL trust material can be configured in an xref:features/ssl.adoc[SSL bundle] and applied to the `CqlSession` as shown in this example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - cassandra: - keyspace-name: "mykeyspace" - contact-points: "cassandrahost1,cassandrahost2" - local-datacenter: "datacenter1" - ssl: - bundle: "example" +spring: + cassandra: + keyspace-name: "mykeyspace" + contact-points: "cassandrahost1,cassandrahost2" + local-datacenter: "datacenter1" + ssl: + bundle: "example" ---- @@ -472,19 +495,20 @@ NOTE: If you use `CqlSessionBuilder` to create multiple `CqlSession` beans, keep The following code listing shows how to inject a Cassandra bean: -include::code:MyBean[] +include-code::MyBean[] If you add your own `@Bean` of type `CassandraTemplate`, it replaces the default. [[data.nosql.cassandra.repositories]] -==== Spring Data Cassandra Repositories +=== Spring Data Cassandra Repositories + Spring Data includes basic repository support for Cassandra. Currently, this is more limited than the JPA repositories discussed earlier and needs `@Query` annotated finder methods. Repositories and entities are found through scanning. -By default, the <> are scanned. +By default, the xref:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages] are scanned. You can customize the locations to look for repositories and entities by using `@EnableCassandraRepositories` and `@EntityScan` respectively. TIP: For complete details of Spring Data Cassandra, see the https://docs.spring.io/spring-data/cassandra/docs/[reference documentation]. @@ -492,7 +516,8 @@ TIP: For complete details of Spring Data Cassandra, see the https://docs.spring. [[data.nosql.couchbase]] -=== Couchbase +== Couchbase + https://www.couchbase.com/[Couchbase] is an open-source, distributed, multi-model NoSQL document-oriented database that is optimized for interactive applications. Spring Boot offers auto-configuration for Couchbase and the abstractions on top of it provided by https://github.com/spring-projects/spring-data-couchbase[Spring Data Couchbase]. There are `spring-boot-starter-data-couchbase` and `spring-boot-starter-data-couchbase-reactive` "`Starters`" for collecting the dependencies in a convenient way. @@ -500,32 +525,33 @@ There are `spring-boot-starter-data-couchbase` and `spring-boot-starter-data-cou [[data.nosql.couchbase.connecting]] -==== Connecting to Couchbase +=== Connecting to Couchbase + You can get a `Cluster` by adding the Couchbase SDK and some configuration. The `spring.couchbase.*` properties can be used to customize the connection. Generally, you provide the https://github.com/couchbaselabs/sdk-rfcs/blob/master/rfc/0011-connection-string.md[connection string], username, and password, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - couchbase: - connection-string: "couchbase://192.168.1.123" - username: "user" - password: "secret" +spring: + couchbase: + connection-string: "couchbase://192.168.1.123" + username: "user" + password: "secret" ---- It is also possible to customize some of the `ClusterEnvironment` settings. -For instance, the following configuration changes the timeout to open a new `Bucket` and enables SSL support with a reference to a configured <>: +For instance, the following configuration changes the timeout to open a new `Bucket` and enables SSL support with a reference to a configured xref:features/ssl.adoc[SSL bundle]: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - couchbase: - env: - timeouts: - connect: "3s" - ssl: - bundle: "example" +spring: + couchbase: + env: + timeouts: + connect: "3s" + ssl: + bundle: "example" ---- TIP: Check the `spring.couchbase.env.*` properties for more details. @@ -534,29 +560,30 @@ To take more control, one or more `ClusterEnvironmentBuilderCustomizer` beans ca [[data.nosql.couchbase.repositories]] -==== Spring Data Couchbase Repositories +=== Spring Data Couchbase Repositories + Spring Data includes repository support for Couchbase. Repositories and documents are found through scanning. -By default, the <> are scanned. +By default, the xref:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages] are scanned. You can customize the locations to look for repositories and documents by using `@EnableCouchbaseRepositories` and `@EntityScan` respectively. -For complete details of Spring Data Couchbase, see the {spring-data-couchbase-docs}[reference documentation]. +For complete details of Spring Data Couchbase, see the {url-spring-data-couchbase-docs}[reference documentation]. You can inject an auto-configured `CouchbaseTemplate` instance as you would with any other Spring Bean, provided a `CouchbaseClientFactory` bean is available. This happens when a `Cluster` is available, as described above, and a bucket name has been specified: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - data: - couchbase: - bucket-name: "my-bucket" +spring: + data: + couchbase: + bucket-name: "my-bucket" ---- The following examples shows how to inject a `CouchbaseTemplate` bean: -include::code:MyBean[] +include-code::MyBean[] There are a few beans that you can define in your own configuration to override those provided by the auto-configuration: @@ -567,12 +594,13 @@ There are a few beans that you can define in your own configuration to override To avoid hard-coding those names in your own config, you can reuse `BeanNames` provided by Spring Data Couchbase. For instance, you can customize the converters to use, as follows: -include::code:MyCouchbaseConfiguration[] +include-code::MyCouchbaseConfiguration[] [[data.nosql.ldap]] -=== 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]. @@ -582,16 +610,17 @@ There is a `spring-boot-starter-data-ldap` "`Starter`" for collecting the depend [[data.nosql.ldap.connecting]] -==== Connecting to an LDAP Server +=== 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: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - ldap: - urls: "ldap://myserver:1235" - username: "admin" - password: "secret" +spring: + ldap: + urls: "ldap://myserver:1235" + username: "admin" + password: "secret" ---- If you need to customize connection settings, you can use the `spring.ldap.base` and `spring.ldap.base-environment` properties. @@ -604,11 +633,12 @@ Make sure to flag your customized `ContextSource` as `@Primary` so that the auto [[data.nosql.ldap.repositories]] -==== Spring Data LDAP Repositories +=== Spring Data LDAP Repositories + Spring Data includes repository support for LDAP. Repositories and documents are found through scanning. -By default, the <> are scanned. +By default, the xref:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages] are scanned. You can customize the locations to look for repositories and documents by using `@EnableLdapRepositories` and `@EntityScan` respectively. For complete details of Spring Data LDAP, see the https://docs.spring.io/spring-data/ldap/docs/1.0.x/reference/html/[reference documentation]. @@ -616,21 +646,22 @@ For complete details of Spring Data LDAP, see the https://docs.spring.io/spring- You can also inject an auto-configured `LdapTemplate` instance as you would with any other Spring Bean, as shown in the following example: -include::code:MyBean[] +include-code::MyBean[] [[data.nosql.ldap.embedded]] -==== Embedded In-memory LDAP Server +=== 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: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - ldap: - embedded: - base-dn: "dc=spring,dc=io" +spring: + ldap: + embedded: + base-dn: "dc=spring,dc=io" ---- [NOTE] @@ -639,11 +670,11 @@ It is possible to define multiple base-dn values, however, since distinguished n In yaml files, you can use the yaml list notation. In properties files, you must include the index as part of the property name: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring.ldap.embedded.base-dn: - - "dc=spring,dc=io" - - "dc=vmware,dc=com" +spring.ldap.embedded.base-dn: +- "dc=spring,dc=io" +- "dc=vmware,dc=com" ---- ==== @@ -660,7 +691,8 @@ If you have custom attributes, you can use configprop:spring.ldap.embedded.valid [[data.nosql.influxdb]] -=== InfluxDB +== InfluxDB + WARNING: Auto-configuration for InfluxDB is deprecated and scheduled for removal in Spring Boot 3.4 in favor of https://github.com/influxdata/influxdb-client-java[the new InfluxDB Java client] that provides its own Spring Boot integration. https://www.influxdata.com/[InfluxDB] is an open-source time series database optimized for fast, high-availability storage and retrieval of time series data in fields such as operations monitoring, application metrics, Internet-of-Things sensor data, and real-time analytics. @@ -668,7 +700,8 @@ https://www.influxdata.com/[InfluxDB] is an open-source time series database opt [[data.nosql.influxdb.connecting]] -==== Connecting to InfluxDB +=== Connecting to InfluxDB + Spring Boot auto-configures an `InfluxDB` instance, provided the `influxdb-java` client is on the classpath and the URL of the database is set using configprop:spring.influx.url[deprecated]. If the connection to InfluxDB requires a user and password, you can set the configprop:spring.influx.user[deprecated] and configprop:spring.influx.password[deprecated] properties accordingly. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data/sql.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/data/sql.adoc similarity index 71% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/data/sql.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/data/sql.adoc index 17e506da15..a0e50dbb3b 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data/sql.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/data/sql.adoc @@ -1,26 +1,29 @@ [[data.sql]] -== SQL Databases -The {spring-framework}[Spring Framework] provides extensive support for working with SQL databases, from direct JDBC access using `JdbcClient` or `JdbcTemplate` to complete "`object relational mapping`" technologies such as Hibernate. -{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. += SQL Databases + +The {url-spring-framework-site}[Spring Framework] provides extensive support for working with SQL databases, from direct JDBC access using `JdbcClient` or `JdbcTemplate` to complete "`object relational mapping`" technologies such as Hibernate. +{url-spring-data-site}[Spring Data] provides an additional level of functionality: creating `Repository` implementations directly from interfaces and using conventions to generate queries from your method names. [[data.sql.datasource]] -=== Configure a DataSource +== Configure a DataSource + Java's `javax.sql.DataSource` interface provides a standard method of working with database connections. Traditionally, a `DataSource` uses a `URL` along with some credentials to establish a database connection. -TIP: See <> for more advanced examples, typically to take full control over the configuration of the DataSource. +TIP: See xref:how-to:data-access.adoc#howto.data-access.configure-custom-datasource[the "`How-to`" section] for more advanced examples, typically to take full control over the configuration of the DataSource. [[data.sql.datasource.embedded]] -==== Embedded Database Support +=== Embedded Database Support + It is often convenient to develop applications by using an in-memory embedded database. Obviously, in-memory databases do not provide persistent storage. You need to populate your database when your application starts and be prepared to throw away data when your application ends. -TIP: The "`How-to`" section includes a <>. +TIP: The "`How-to`" section includes a xref:how-to:data-initialization.adoc[section on how to initialize a database]. Spring Boot can auto-configure embedded https://www.h2database.com[H2], https://hsqldb.org/[HSQL], and https://db.apache.org/derby/[Derby] databases. You need not provide any connection URLs. @@ -36,17 +39,17 @@ If you want to make sure that each context has a separate embedded database, you For example, the typical POM dependencies would be as follows: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.hsqldb - hsqldb - runtime - + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.hsqldb + hsqldb + runtime + ---- NOTE: You need a dependency on `spring-jdbc` for an embedded database to be auto-configured. @@ -60,23 +63,25 @@ Disabling the database's automatic shutdown lets Spring Boot control when the da [[data.sql.datasource.production]] -==== Connection to a Production Database +=== Connection to a Production Database + Production database connections can also be auto-configured by using a pooling `DataSource`. [[data.sql.datasource.configuration]] -==== DataSource Configuration +=== DataSource Configuration + DataSource configuration is controlled by external configuration properties in `+spring.datasource.*+`. For example, you might declare the following section in `application.properties`: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - datasource: - url: "jdbc:mysql://localhost/test" - username: "dbuser" - password: "dbpass" +spring: + datasource: + url: "jdbc:mysql://localhost/test" + username: "dbuser" + password: "dbpass" ---- NOTE: You should at least specify the URL by setting the configprop:spring.datasource.url[] property. @@ -88,21 +93,21 @@ If you need to specify a specific class, you can use the configprop:spring.datas NOTE: For a pooling `DataSource` to be created, we need to be able to verify that a valid `Driver` class is available, so we check for that before doing anything. In other words, if you set `spring.datasource.driver-class-name=com.mysql.jdbc.Driver`, then that class has to be loadable. -See {spring-boot-autoconfigure-module-code}/jdbc/DataSourceProperties.java[`DataSourceProperties`] for more of the supported options. -These are the standard options that work regardless of <>. +See {code-spring-boot-autoconfigure-src}/jdbc/DataSourceProperties.java[`DataSourceProperties`] for more of the supported options. +These are the standard options that work regardless of xref:data/sql.adoc#data.sql.datasource.connection-pool[the actual implementation]. It is also possible to fine-tune implementation-specific settings by using their respective prefix (`+spring.datasource.hikari.*+`, `+spring.datasource.tomcat.*+`, `+spring.datasource.dbcp2.*+`, and `+spring.datasource.oracleucp.*+`). See the documentation of the connection pool implementation you are using for more details. -For instance, if you use the {tomcat-docs}/jdbc-pool.html#Common_Attributes[Tomcat connection pool], you could customize many additional settings, as shown in the following example: +For instance, if you use the {url-tomcat-docs}/jdbc-pool.html#Common_Attributes[Tomcat connection pool], you could customize many additional settings, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - datasource: - tomcat: - max-wait: 10000 - max-active: 50 - test-on-borrow: true +spring: + datasource: + tomcat: + max-wait: 10000 + max-active: 50 + test-on-borrow: true ---- This will set the pool to wait 10000ms before throwing an exception if no connection is available, limit the maximum number of connections to 50 and validate the connection before borrowing it from the pool. @@ -110,7 +115,8 @@ This will set the pool to wait 10000ms before throwing an exception if no connec [[data.sql.datasource.connection-pool]] -==== Supported Connection Pools +=== Supported Connection Pools + Spring Boot uses the following algorithm for choosing a specific implementation: . We prefer https://github.com/brettwooldridge/HikariCP[HikariCP] for its performance and concurrency. @@ -140,35 +146,37 @@ The following connection pools are supported by `DataSourceBuilder`: [[data.sql.datasource.jndi]] -==== Connection to a JNDI DataSource +=== Connection to a JNDI DataSource + If you deploy your Spring Boot application to an Application Server, you might want to configure and manage your DataSource by using your Application Server's built-in features and access it by using JNDI. The configprop:spring.datasource.jndi-name[] property can be used as an alternative to the configprop:spring.datasource.url[], configprop:spring.datasource.username[], and configprop:spring.datasource.password[] properties to access the `DataSource` from a specific JNDI location. For example, the following section in `application.properties` shows how you can access a JBoss AS defined `DataSource`: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - datasource: - jndi-name: "java:jboss/datasources/customers" +spring: + datasource: + jndi-name: "java:jboss/datasources/customers" ---- [[data.sql.jdbc-template]] -=== Using JdbcTemplate +== Using JdbcTemplate + Spring's `JdbcTemplate` and `NamedParameterJdbcTemplate` classes are auto-configured, and you can `@Autowire` them directly into your own beans, as shown in the following example: -include::code:MyBean[] +include-code::MyBean[] You can customize some properties of the template by using the `spring.jdbc.template.*` properties, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - jdbc: - template: - max-rows: 500 +spring: + jdbc: + template: + max-rows: 500 ---- NOTE: The `NamedParameterJdbcTemplate` reuses the same `JdbcTemplate` instance behind the scenes. @@ -177,18 +185,20 @@ If more than one `JdbcTemplate` is defined and no primary candidate exists, the [[data.sql.jdbc-client]] -=== Using JdbcClient +== Using JdbcClient + Spring's `JdbcClient` is auto-configured based on the presence of a `NamedParameterJdbcTemplate`. You can inject it directly in your own beans as well, as shown in the following example: -include::code:MyBean[] +include-code::MyBean[] If you rely on auto-configuration to create the underlying `JdbcTemplate`, any customization using `spring.jdbc.template.*` properties is taken into account in the client as well. [[data.sql.jpa-and-spring-data]] -=== JPA and Spring Data JPA +== JPA and Spring Data JPA + The Java Persistence API is a standard technology that lets you "`map`" objects to relational databases. The `spring-boot-starter-data-jpa` POM provides a quick way to get started. It provides the following key dependencies: @@ -197,43 +207,45 @@ It provides the following key dependencies: * Spring Data JPA: Helps you to implement JPA-based repositories. * Spring ORM: Core ORM support from the Spring Framework. -TIP: We do not go into too many details of JPA or {spring-data}[Spring Data] here. -You can follow the https://spring.io/guides/gs/accessing-data-jpa/["`Accessing Data with JPA`"] guide from https://spring.io and read the {spring-data-jpa}[Spring Data JPA] and https://hibernate.org/orm/documentation/[Hibernate] reference documentation. +TIP: We do not go into too many details of JPA or {url-spring-data-site}[Spring Data] here. +You can follow the https://spring.io/guides/gs/accessing-data-jpa/["`Accessing Data with JPA`"] guide from https://spring.io and read the {url-spring-data-jpa-site}[Spring Data JPA] and https://hibernate.org/orm/documentation/[Hibernate] reference documentation. [[data.sql.jpa-and-spring-data.entity-classes]] -==== Entity Classes +=== Entity Classes + Traditionally, JPA "`Entity`" classes are specified in a `persistence.xml` file. With Spring Boot, this file is not necessary and "`Entity Scanning`" is used instead. -By default the <> are scanned. +By default the xref:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages] are scanned. Any classes annotated with `@Entity`, `@Embeddable`, or `@MappedSuperclass` are considered. A typical entity class resembles the following example: -include::code:City[] +include-code::City[] TIP: You can customize entity scanning locations by using the `@EntityScan` annotation. -See the "`<>`" how-to. +See the "`xref:how-to:data-access.adoc#howto.data-access.separate-entity-definitions-from-spring-configuration[Separate @Entity Definitions from Spring Configuration]`" how-to. [[data.sql.jpa-and-spring-data.repositories]] -==== Spring Data JPA Repositories -{spring-data-jpa}[Spring Data JPA] repositories are interfaces that you can define to access data. +=== Spring Data JPA Repositories + +{url-spring-data-jpa-site}[Spring Data JPA] repositories are interfaces that you can define to access data. JPA queries are created automatically from your method names. For example, a `CityRepository` interface might declare a `findAllByState(String state)` method to find all the cities in a given state. -For more complex queries, you can annotate your method with Spring Data's {spring-data-jpa-api}/repository/Query.html[`Query`] annotation. +For more complex queries, you can annotate your method with Spring Data's {url-spring-data-jpa-javadoc}/org/springframework/data/jpa/repository/Query.html[`Query`] annotation. -Spring Data repositories usually extend from the {spring-data-commons-api}/repository/Repository.html[`Repository`] or {spring-data-commons-api}/repository/CrudRepository.html[`CrudRepository`] interfaces. -If you use auto-configuration, the <> are searched for repositories. +Spring Data repositories usually extend from the {url-spring-data-commons-javadoc}/org/springframework/data/repository/Repository.html[`Repository`] or {url-spring-data-commons-javadoc}/org/springframework/data/repository/CrudRepository.html[`CrudRepository`] interfaces. +If you use auto-configuration, the xref:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages] are searched for repositories. TIP: You can customize the locations to look for repositories using `@EnableJpaRepositories`. The following example shows a typical Spring Data repository interface definition: -include::code:CityRepository[] +include-code::CityRepository[] Spring Data JPA repositories support three different modes of bootstrapping: default, deferred, and lazy. To enable deferred or lazy bootstrapping, set the configprop:spring.data.jpa.repositories.bootstrap-mode[] property to `deferred` or `lazy` respectively. @@ -248,46 +260,48 @@ For JPA components (such as converters) that are created as Spring beans, use `O ==== TIP: We have barely scratched the surface of Spring Data JPA. -For complete details, see the {spring-data-jpa-docs}[Spring Data JPA reference documentation]. +For complete details, see the {url-spring-data-jpa-docs}[Spring Data JPA reference documentation]. [[data.sql.jpa-and-spring-data.envers-repositories]] -==== Spring Data Envers Repositories -If {spring-data-envers}[Spring Data Envers] is available, JPA repositories are auto-configured to support typical Envers queries. +=== Spring Data Envers Repositories + +If {url-spring-data-envers-site}[Spring Data Envers] is available, JPA repositories are auto-configured to support typical Envers queries. To use Spring Data Envers, make sure your repository extends from `RevisionRepository` as shown in the following example: -include::code:CountryRepository[] +include-code::CountryRepository[] -NOTE: For more details, check the {spring-data-jpa-docs}/#envers[Spring Data Envers reference documentation]. +NOTE: For more details, check the {url-spring-data-jpa-docs}/envers.html[Spring Data Envers reference documentation]. [[data.sql.jpa-and-spring-data.creating-and-dropping]] -==== Creating and Dropping JPA Databases +=== Creating and Dropping JPA Databases + By default, JPA databases are automatically created *only* if you use an embedded database (H2, HSQL, or Derby). You can explicitly configure JPA settings by using `+spring.jpa.*+` properties. For example, to create and drop tables you can add the following line to your `application.properties`: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - jpa: - hibernate.ddl-auto: "create-drop" +spring: + jpa: + hibernate.ddl-auto: "create-drop" ---- NOTE: Hibernate's own internal property name for this (if you happen to remember it better) is `hibernate.hbm2ddl.auto`. You can set it, along with other Hibernate native properties, by using `+spring.jpa.properties.*+` (the prefix is stripped before adding them to the entity manager). The following line shows an example of setting JPA properties for Hibernate: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - jpa: - properties: - hibernate: - "globally_quoted_identifiers": "true" +spring: + jpa: + properties: + hibernate: + "globally_quoted_identifiers": "true" ---- The line in the preceding example passes a value of `true` for the `hibernate.globally_quoted_identifiers` property to the Hibernate entity manager. @@ -298,14 +312,16 @@ There is also a `spring.jpa.generate-ddl` flag, but it is not used if Hibernate [[data.sql.jpa-and-spring-data.open-entity-manager-in-view]] -==== Open EntityManager in View -If you are running a web application, Spring Boot by default registers {spring-framework-api}/orm/jpa/support/OpenEntityManagerInViewInterceptor.html[`OpenEntityManagerInViewInterceptor`] to apply the "`Open EntityManager in View`" pattern, to allow for lazy loading in web views. +=== Open EntityManager in View + +If you are running a web application, Spring Boot by default registers {url-spring-framework-javadoc}/org/springframework/orm/jpa/support/OpenEntityManagerInViewInterceptor.html[`OpenEntityManagerInViewInterceptor`] to apply the "`Open EntityManager in View`" pattern, to allow for lazy loading in web views. If you do not want this behavior, you should set `spring.jpa.open-in-view` to `false` in your `application.properties`. [[data.sql.jdbc]] -=== Spring Data JDBC +== Spring Data JDBC + Spring Data includes repository support for JDBC and will automatically generate SQL for the methods on `CrudRepository`. For more advanced queries, a `@Query` annotation is provided. @@ -313,18 +329,19 @@ Spring Boot will auto-configure Spring Data's JDBC repositories when the necessa They can be added to your project with a single dependency on `spring-boot-starter-data-jdbc`. If necessary, you can take control of Spring Data JDBC's configuration by adding the `@EnableJdbcRepositories` annotation or an `AbstractJdbcConfiguration` subclass to your application. -TIP: For complete details of Spring Data JDBC, see the {spring-data-jdbc-docs}[reference documentation]. +TIP: For complete details of Spring Data JDBC, see the {url-spring-data-jdbc-docs}[reference documentation]. [[data.sql.h2-web-console]] -=== Using H2's Web Console +== Using H2's Web Console + The https://www.h2database.com[H2 database] provides a https://www.h2database.com/html/quickstart.html#h2_console[browser-based console] that Spring Boot can auto-configure for you. The console is auto-configured when the following conditions are met: * You are developing a servlet-based web application. * `com.h2database:h2` is on the classpath. -* You are using <>. +* You are using xref:using/devtools.adoc[Spring Boot's developer tools]. TIP: If you are not using Spring Boot's developer tools but would still like to make use of H2's console, you can configure the configprop:spring.h2.console.enabled[] property with a value of `true`. @@ -333,25 +350,27 @@ NOTE: The H2 console is only intended for use during development, so you should [[data.sql.h2-web-console.custom-path]] -==== Changing the H2 Console's Path +=== Changing the H2 Console's Path + By default, the console is available at `/h2-console`. You can customize the console's path by using the configprop:spring.h2.console.path[] property. [[data.sql.h2-web-console.spring-security]] -==== Accessing the H2 Console in a Secured Application +=== Accessing the H2 Console in a Secured Application + H2 Console uses frames and, as it is intended for development only, does not implement CSRF protection measures. If your application uses Spring Security, you need to configure it to * disable CSRF protection for requests against the console, * set the header `X-Frame-Options` to `SAMEORIGIN` on responses from the console. -More information on {spring-security-docs}/features/exploits/csrf.html[CSRF] and the header {spring-security-docs}/features/exploits/headers.html#headers-frame-options[X-Frame-Options] can be found in the Spring Security Reference Guide. +More information on {url-spring-security-docs}/features/exploits/csrf.html[CSRF] and the header {url-spring-security-docs}/features/exploits/headers.html#headers-frame-options[X-Frame-Options] can be found in the Spring Security Reference Guide. In simple setups, a `SecurityFilterChain` like the following can be used: -include::code:DevProfileSecurityConfiguration[tag=!customizer] +include-code::DevProfileSecurityConfiguration[tag=!customizer] WARNING: The H2 console is only intended for use during development. In production, disabling CSRF protection or allowing frames for a website may create severe security risks. @@ -361,67 +380,71 @@ TIP: `PathRequest.toH2Console()` returns the correct request matcher also when t [[data.sql.jooq]] -=== Using jOOQ +== Using jOOQ + jOOQ Object Oriented Querying (https://www.jooq.org/[jOOQ]) is a popular product from https://www.datageekery.com/[Data Geekery] which generates Java code from your database and lets you build type-safe SQL queries through its fluent API. Both the commercial and open source editions can be used with Spring Boot. [[data.sql.jooq.codegen]] -==== Code Generation +=== Code Generation + In order to use jOOQ type-safe queries, you need to generate Java classes from your database schema. -You can follow the instructions in the {jooq-docs}/#jooq-in-7-steps-step3[jOOQ user manual]. +You can follow the instructions in the {url-jooq-docs}/#jooq-in-7-steps-step3[jOOQ user manual]. If you use the `jooq-codegen-maven` plugin and you also use the `spring-boot-starter-parent` "`parent POM`", you can safely omit the plugin's `` tag. You can also use Spring Boot-defined version variables (such as `h2.version`) to declare the plugin's database dependency. The following listing shows an example: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - org.jooq - jooq-codegen-maven - + + org.jooq + jooq-codegen-maven + + ... + + + + com.h2database + h2 + ${h2.version} + + + + + org.h2.Driver + jdbc:h2:~/yourdatabase + + ... - - - - com.h2database - h2 - ${h2.version} - - - - - org.h2.Driver - jdbc:h2:~/yourdatabase - - - ... - - - + + + ---- [[data.sql.jooq.dslcontext]] -==== Using DSLContext +=== Using DSLContext + The fluent API offered by jOOQ is initiated through the `org.jooq.DSLContext` interface. Spring Boot auto-configures a `DSLContext` as a Spring Bean and connects it to your application `DataSource`. To use the `DSLContext`, you can inject it, as shown in the following example: -include::code:MyBean[tag=!method] +include-code::MyBean[tag=!method] TIP: The jOOQ manual tends to use a variable named `create` to hold the `DSLContext`. You can then use the `DSLContext` to construct your queries, as shown in the following example: -include::code:MyBean[tag=method] +include-code::MyBean[tag=method] [[data.sql.jooq.sqldialect]] -==== jOOQ SQL Dialect +=== jOOQ SQL Dialect + Unless the configprop:spring.jooq.sql-dialect[] property has been configured, Spring Boot determines the SQL dialect to use for your datasource. If Spring Boot could not detect the dialect, it uses `DEFAULT`. @@ -430,7 +453,8 @@ NOTE: Spring Boot can only auto-configure dialects supported by the open source [[data.sql.jooq.customizing]] -==== Customizing jOOQ +=== Customizing jOOQ + More advanced customizations can be achieved by defining your own `DefaultConfigurationCustomizer` bean that will be invoked prior to creating the `org.jooq.Configuration` `@Bean`. This takes precedence to anything that is applied by the auto-configuration. @@ -439,7 +463,8 @@ You can also create your own `org.jooq.Configuration` `@Bean` if you want to tak [[data.sql.r2dbc]] -=== Using R2DBC +== Using R2DBC + The Reactive Relational Database Connectivity (https://r2dbc.io[R2DBC]) project brings reactive programming APIs to relational databases. R2DBC's `io.r2dbc.spi.Connection` provides a standard method of working with non-blocking database connections. Connections are provided by using a `ConnectionFactory`, similar to a `DataSource` with jdbc. @@ -447,13 +472,13 @@ Connections are provided by using a `ConnectionFactory`, similar to a `DataSourc `ConnectionFactory` configuration is controlled by external configuration properties in `+spring.r2dbc.*+`. For example, you might declare the following section in `application.properties`: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - r2dbc: - url: "r2dbc:postgresql://localhost/test" - username: "dbuser" - password: "dbpass" +spring: + r2dbc: + url: "r2dbc:postgresql://localhost/test" + username: "dbuser" + password: "dbpass" ---- TIP: You do not need to specify a driver class name, since Spring Boot obtains the driver from R2DBC's Connection Factory discovery. @@ -461,16 +486,16 @@ TIP: You do not need to specify a driver class name, since Spring Boot obtains t NOTE: At least the url should be provided. Information specified in the URL takes precedence over individual properties, that is `name`, `username`, `password` and pooling options. -TIP: The "`How-to`" section includes a <>. +TIP: The "`How-to`" section includes a xref:how-to:data-initialization.adoc#howto.data-initialization.using-basic-sql-scripts[section on how to initialize a database]. To customize the connections created by a `ConnectionFactory`, that is, set specific parameters that you do not want (or cannot) configure in your central database configuration, you can use a `ConnectionFactoryOptionsBuilderCustomizer` `@Bean`. The following example shows how to manually override the database port while the rest of the options are taken from the application configuration: -include::code:MyR2dbcConfiguration[] +include-code::MyR2dbcConfiguration[] The following examples show how to set some PostgreSQL connection options: -include::code:MyPostgresR2dbcConfiguration[] +include-code::MyPostgresR2dbcConfiguration[] When a `ConnectionFactory` bean is available, the regular JDBC `DataSource` auto-configuration backs off. If you want to retain the JDBC `DataSource` auto-configuration, and are comfortable with the risk of using the blocking JDBC API in a reactive application, add `@Import(DataSourceAutoConfiguration.class)` on a `@Configuration` class in your application to re-enable it. @@ -478,18 +503,19 @@ If you want to retain the JDBC `DataSource` auto-configuration, and are comforta [[data.sql.r2dbc.embedded]] -==== Embedded Database Support -Similarly to <>, Spring Boot can automatically configure an embedded database for reactive usage. +=== Embedded Database Support + +Similarly to xref:data/sql.adoc#data.sql.datasource.embedded[the JDBC support], Spring Boot can automatically configure an embedded database for reactive usage. You need not provide any connection URLs. You need only include a build dependency to the embedded database that you want to use, as shown in the following example: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - io.r2dbc - r2dbc-h2 - runtime - + + io.r2dbc + r2dbc-h2 + runtime + ---- [NOTE] @@ -501,26 +527,28 @@ If you want to make sure that each context has a separate embedded database, you [[data.sql.r2dbc.using-database-client]] -==== Using DatabaseClient +=== Using DatabaseClient + A `DatabaseClient` bean is auto-configured, and you can `@Autowire` it directly into your own beans, as shown in the following example: -include::code:MyBean[] +include-code::MyBean[] [[data.sql.r2dbc.repositories]] -==== Spring Data R2DBC Repositories +=== Spring Data R2DBC Repositories + https://spring.io/projects/spring-data-r2dbc[Spring Data R2DBC] repositories are interfaces that you can define to access data. Queries are created automatically from your method names. For example, a `CityRepository` interface might declare a `findAllByState(String state)` method to find all the cities in a given state. -For more complex queries, you can annotate your method with Spring Data's {spring-data-r2dbc-api}/repository/Query.html[`Query`] annotation. +For more complex queries, you can annotate your method with Spring Data's {url-spring-data-r2dbc-javadoc}/org/springframework/data/r2dbc/repository/Query.html[`Query`] annotation. -Spring Data repositories usually extend from the {spring-data-commons-api}/repository/Repository.html[`Repository`] or {spring-data-commons-api}/repository/CrudRepository.html[`CrudRepository`] interfaces. -If you use auto-configuration, the <> are searched for repositories. +Spring Data repositories usually extend from the {url-spring-data-commons-javadoc}/org/springframework/data/repository/Repository.html[`Repository`] or {url-spring-data-commons-javadoc}/org/springframework/data/repository/CrudRepository.html[`CrudRepository`] interfaces. +If you use auto-configuration, the xref:using/auto-configuration.adoc#using.auto-configuration.packages[auto-configuration packages] are searched for repositories. The following example shows a typical Spring Data repository interface definition: -include::code:CityRepository[] +include-code::CityRepository[] -TIP: We have barely scratched the surface of Spring Data R2DBC. For complete details, see the {spring-data-r2dbc-docs}[Spring Data R2DBC reference documentation]. +TIP: We have barely scratched the surface of Spring Data R2DBC. For complete details, see the {url-spring-data-r2dbc-docs}[Spring Data R2DBC reference documentation]. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment/cloud.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/deployment/cloud.adoc similarity index 66% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment/cloud.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/deployment/cloud.adoc index 7d175ddf54..430696e549 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment/cloud.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/deployment/cloud.adoc @@ -1,5 +1,6 @@ [[deployment.cloud]] -== Deploying to the Cloud += Deploying to the Cloud + Spring Boot's executable jars are ready-made for most popular cloud PaaS (Platform-as-a-Service) providers. These providers tend to require that you "`bring your own container`". They manage application processes (not Java applications specifically), so they need an intermediary layer that adapts _your_ application to the _cloud's_ notion of a running process. @@ -13,12 +14,13 @@ It minimizes divergence between development and production environments. Ideally, your application, like a Spring Boot executable jar, has everything that it needs to run packaged within it. -In this section, we look at what it takes to get the <> in the "`Getting Started`" section up and running in the Cloud. +In this section, we look at what it takes to get the xref:tutorial:first-application/index.adoc[application that we developed] in the "`Getting Started`" section up and running in the Cloud. [[deployment.cloud.cloud-foundry]] -=== Cloud Foundry +== Cloud Foundry + Cloud Foundry provides default buildpacks that come into play if no other buildpack is specified. The Cloud Foundry https://github.com/cloudfoundry/java-buildpack[Java buildpack] has excellent support for Spring applications, including Spring Boot. You can deploy stand-alone executable jar applications as well as traditional `.war` packaged applications. @@ -27,9 +29,9 @@ Once you have built your application (by using, for example, `mvn clean package` Be sure to have https://docs.cloudfoundry.org/cf-cli/getting-started.html#login[logged in with your `cf` command line client] before pushing an application. The following line shows using the `cf push` command to deploy an application: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ cf push acloudyspringtime -p target/demo-0.0.1-SNAPSHOT.jar +$ cf push acloudyspringtime -p target/demo-0.0.1-SNAPSHOT.jar ---- NOTE: In the preceding example, we substitute `acloudyspringtime` for whatever value you give `cf` as the name of your application. @@ -39,45 +41,45 @@ If there is a Cloud Foundry https://docs.cloudfoundry.org/devguide/deploy-apps/m At this point, `cf` starts uploading your application, producing output similar to the following example: -[indent=0,subs="verbatim,quotes"] +[source,subs="verbatim,quotes"] ---- - Uploading acloudyspringtime... *OK* - Preparing to start acloudyspringtime... *OK* - -----> Downloaded app package (*8.9M*) - -----> Java Buildpack Version: v3.12 (offline) | https://github.com/cloudfoundry/java-buildpack.git#6f25b7e - -----> Downloading Open Jdk JRE - Expanding Open Jdk JRE to .java-buildpack/open_jdk_jre (1.6s) - -----> Downloading Open JDK Like Memory Calculator 2.0.2_RELEASE from https://java-buildpack.cloudfoundry.org/memory-calculator/trusty/x86_64/memory-calculator-2.0.2_RELEASE.tar.gz (found in cache) - Memory Settings: -Xss349K -Xmx681574K -XX:MaxMetaspaceSize=104857K -Xms681574K -XX:MetaspaceSize=104857K - -----> Downloading Container Certificate Trust Store 1.0.0_RELEASE from https://java-buildpack.cloudfoundry.org/container-certificate-trust-store/container-certificate-trust-store-1.0.0_RELEASE.jar (found in cache) - Adding certificates to .java-buildpack/container_certificate_trust_store/truststore.jks (0.6s) - -----> Downloading Spring Auto Reconfiguration 1.10.0_RELEASE from https://java-buildpack.cloudfoundry.org/auto-reconfiguration/auto-reconfiguration-1.10.0_RELEASE.jar (found in cache) - Checking status of app 'acloudyspringtime'... - 0 of 1 instances running (1 starting) - ... - 0 of 1 instances running (1 starting) - ... - 0 of 1 instances running (1 starting) - ... - 1 of 1 instances running (1 running) +Uploading acloudyspringtime... *OK* +Preparing to start acloudyspringtime... *OK* +-----> Downloaded app package (*8.9M*) +-----> Java Buildpack Version: v3.12 (offline) | https://github.com/cloudfoundry/java-buildpack.git#6f25b7e +-----> Downloading Open Jdk JRE + Expanding Open Jdk JRE to .java-buildpack/open_jdk_jre (1.6s) +-----> Downloading Open JDK Like Memory Calculator 2.0.2_RELEASE from https://java-buildpack.cloudfoundry.org/memory-calculator/trusty/x86_64/memory-calculator-2.0.2_RELEASE.tar.gz (found in cache) + Memory Settings: -Xss349K -Xmx681574K -XX:MaxMetaspaceSize=104857K -Xms681574K -XX:MetaspaceSize=104857K +-----> Downloading Container Certificate Trust Store 1.0.0_RELEASE from https://java-buildpack.cloudfoundry.org/container-certificate-trust-store/container-certificate-trust-store-1.0.0_RELEASE.jar (found in cache) + Adding certificates to .java-buildpack/container_certificate_trust_store/truststore.jks (0.6s) +-----> Downloading Spring Auto Reconfiguration 1.10.0_RELEASE from https://java-buildpack.cloudfoundry.org/auto-reconfiguration/auto-reconfiguration-1.10.0_RELEASE.jar (found in cache) +Checking status of app 'acloudyspringtime'... + 0 of 1 instances running (1 starting) + ... + 0 of 1 instances running (1 starting) + ... + 0 of 1 instances running (1 starting) + ... + 1 of 1 instances running (1 running) - App started +App started ---- Congratulations! The application is now live! Once your application is live, you can verify the status of the deployed application by using the `cf apps` command, as shown in the following example: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ cf apps - Getting applications in ... - OK +$ cf apps +Getting applications in ... +OK - name requested state instances memory disk urls - ... - acloudyspringtime started 1/1 512M 1G acloudyspringtime.cfapps.io - ... +name requested state instances memory disk urls +... +acloudyspringtime started 1/1 512M 1G acloudyspringtime.cfapps.io +... ---- Once Cloud Foundry acknowledges that your application has been deployed, you should be able to find the application at the URI given. @@ -86,34 +88,37 @@ In the preceding example, you could find it at `\https://acloudyspringtime.cfapp [[deployment.cloud.cloud-foundry.binding-to-services]] -==== Binding to Services +=== Binding to Services + By default, metadata about the running application as well as service connection information is exposed to the application as environment variables (for example: `$VCAP_SERVICES`). This architecture decision is due to Cloud Foundry's polyglot (any language and platform can be supported as a buildpack) nature. Process-scoped environment variables are language agnostic. Environment variables do not always make for the easiest API, so Spring Boot automatically extracts them and flattens the data into properties that can be accessed through Spring's `Environment` abstraction, as shown in the following example: -include::code:MyBean[] +include-code::MyBean[] All Cloud Foundry properties are prefixed with `vcap`. You can use `vcap` properties to access application information (such as the public URL of the application) and service information (such as database credentials). -See the {spring-boot-module-api}/cloud/CloudFoundryVcapEnvironmentPostProcessor.html[`CloudFoundryVcapEnvironmentPostProcessor`] Javadoc for complete details. +See the xref:api:java/org/springframework/boot/cloud/CloudFoundryVcapEnvironmentPostProcessor.html[`CloudFoundryVcapEnvironmentPostProcessor`] Javadoc for complete details. TIP: The https://github.com/pivotal-cf/java-cfenv/[Java CFEnv] project is a better fit for tasks such as configuring a DataSource. [[deployment.cloud.kubernetes]] -=== Kubernetes +== Kubernetes + Spring Boot auto-detects Kubernetes deployment environments by checking the environment for `"*_SERVICE_HOST"` and `"*_SERVICE_PORT"` variables. You can override this detection with the configprop:spring.main.cloud-platform[] configuration property. -Spring Boot helps you to <> and export it with <>. +Spring Boot helps you to xref:features/spring-application.adoc#features.spring-application.application-availability[manage the state of your application] and export it with xref:actuator/endpoints.adoc#actuator.endpoints.kubernetes-probes[HTTP Kubernetes Probes using Actuator]. [[deployment.cloud.kubernetes.container-lifecycle]] -==== Kubernetes Container Lifecycle +=== Kubernetes Container Lifecycle + When Kubernetes deletes an application instance, the shutdown process involves several subsystems concurrently: shutdown hooks, unregistering the service, removing the instance from the load-balancer... Because this shutdown processing happens in parallel (and due to the nature of distributed systems), there is a window during which traffic can be routed to a pod that has also begun its shutdown processing. @@ -121,19 +126,19 @@ You can configure a sleep execution in a preStop handler to avoid requests being This sleep should be long enough for new requests to stop being routed to the pod and its duration will vary from deployment to deployment. The preStop handler can be configured by using the PodSpec in the pod's configuration file as follows: -[source,yaml,indent=0,subs="verbatim"] +[source,yaml] ---- - spec: - containers: - - name: "example-container" - image: "example-image" - lifecycle: - preStop: - exec: - command: ["sh", "-c", "sleep 10"] +spec: + containers: + - name: "example-container" + image: "example-image" + lifecycle: + preStop: + exec: + command: ["sh", "-c", "sleep 10"] ---- -Once the pre-stop hook has completed, SIGTERM will be sent to the container and <> 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 xref:web/graceful-shutdown.adoc[graceful shutdown] will begin, allowing any remaining in-flight requests to complete. NOTE: When Kubernetes sends a SIGTERM signal to the pod, it waits for a specified time called the termination grace period (the default for which is 30 seconds). If the containers are still running after the grace period, they are sent the SIGKILL signal and forcibly removed. @@ -142,7 +147,8 @@ If the pod takes longer than 30 seconds to shut down, which could be because you [[deployment.cloud.heroku]] -=== Heroku +== Heroku + Heroku is another popular PaaS platform. To customize Heroku builds, you provide a `Procfile`, which provides the incantation required to deploy an application. Heroku assigns a `port` for the Java application to use and then ensures that routing to the external URI works. @@ -150,9 +156,9 @@ Heroku assigns a `port` for the Java application to use and then ensures that ro You must configure your application to listen on the correct port. The following example shows the `Procfile` for our starter REST application: -[indent=0] +[source] ---- - web: java -Dserver.port=$PORT -jar target/demo-0.0.1-SNAPSHOT.jar +web: java -Dserver.port=$PORT -jar target/demo-0.0.1-SNAPSHOT.jar ---- Spring Boot makes `-D` arguments available as properties accessible from a Spring `Environment` instance. @@ -162,52 +168,52 @@ The `$PORT` environment variable is assigned to us by the Heroku PaaS. This should be everything you need. The most common deployment workflow for Heroku deployments is to `git push` the code to production, as shown in the following example: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ git push heroku main +$ git push heroku main ---- Which will result in the following: -[indent=0,subs="verbatim,quotes"] +[source,subs="verbatim,quotes"] ---- - Initializing repository, *done*. - Counting objects: 95, *done*. - Delta compression using up to 8 threads. - Compressing objects: 100% (78/78), *done*. - Writing objects: 100% (95/95), 8.66 MiB | 606.00 KiB/s, *done*. - Total 95 (delta 31), reused 0 (delta 0) +Initializing repository, *done*. +Counting objects: 95, *done*. +Delta compression using up to 8 threads. +Compressing objects: 100% (78/78), *done*. +Writing objects: 100% (95/95), 8.66 MiB | 606.00 KiB/s, *done*. +Total 95 (delta 31), reused 0 (delta 0) - -----> Java app detected - -----> Installing OpenJDK... *done* - -----> Installing Maven... *done* - -----> Installing settings.xml... *done* - -----> Executing: mvn -B -DskipTests=true clean install +-----> Java app detected +-----> Installing OpenJDK... *done* +-----> Installing Maven... *done* +-----> Installing settings.xml... *done* +-----> Executing: mvn -B -DskipTests=true clean install - [INFO] Scanning for projects... - Downloading: https://repo.spring.io/... - Downloaded: https://repo.spring.io/... (818 B at 1.8 KB/sec) - .... - Downloaded: https://s3pository.heroku.com/jvm/... (152 KB at 595.3 KB/sec) - [INFO] Installing /tmp/build_0c35a5d2-a067-4abc-a232-14b1fb7a8229/target/... - [INFO] Installing /tmp/build_0c35a5d2-a067-4abc-a232-14b1fb7a8229/pom.xml ... - [INFO] ------------------------------------------------------------------------ - [INFO] *BUILD SUCCESS* - [INFO] ------------------------------------------------------------------------ - [INFO] Total time: 59.358s - [INFO] Finished at: Fri Mar 07 07:28:25 UTC 2014 - [INFO] Final Memory: 20M/493M - [INFO] ------------------------------------------------------------------------ + [INFO] Scanning for projects... + Downloading: https://repo.spring.io/... + Downloaded: https://repo.spring.io/... (818 B at 1.8 KB/sec) + .... + Downloaded: https://s3pository.heroku.com/jvm/... (152 KB at 595.3 KB/sec) + [INFO] Installing /tmp/build_0c35a5d2-a067-4abc-a232-14b1fb7a8229/target/... + [INFO] Installing /tmp/build_0c35a5d2-a067-4abc-a232-14b1fb7a8229/pom.xml ... + [INFO] ------------------------------------------------------------------------ + [INFO] *BUILD SUCCESS* + [INFO] ------------------------------------------------------------------------ + [INFO] Total time: 59.358s + [INFO] Finished at: Fri Mar 07 07:28:25 UTC 2014 + [INFO] Final Memory: 20M/493M + [INFO] ------------------------------------------------------------------------ - -----> Discovering process types - Procfile declares types -> *web* +-----> Discovering process types + Procfile declares types -> *web* - -----> Compressing... *done*, 70.4MB - -----> Launching... *done*, v6 - https://agile-sierra-1405.herokuapp.com/ *deployed to Heroku* +-----> Compressing... *done*, 70.4MB +-----> Launching... *done*, v6 + https://agile-sierra-1405.herokuapp.com/ *deployed to Heroku* - To git@heroku.com:agile-sierra-1405.git - * [new branch] main -> main +To git@heroku.com:agile-sierra-1405.git + * [new branch] main -> main ---- Your application should now be up and running on Heroku. @@ -216,7 +222,8 @@ For more details, see https://devcenter.heroku.com/articles/deploying-spring-boo [[deployment.cloud.openshift]] -=== OpenShift +== OpenShift + https://www.openshift.com/[OpenShift] has many resources describing how to deploy Spring Boot applications, including: * https://blog.openshift.com/using-openshift-enterprise-grade-spring-boot-deployments/[Using the S2I builder] @@ -227,7 +234,8 @@ https://www.openshift.com/[OpenShift] has many resources describing how to deplo [[deployment.cloud.aws]] -=== Amazon Web Services (AWS) +== Amazon Web Services (AWS) + Amazon Web Services offers multiple ways to install Spring Boot-based applications, either as traditional web applications (war) or as executable jar files with an embedded web server. The options include: @@ -243,14 +251,16 @@ In this document, we describe to approach using AWS Elastic Beanstalk. [[deployment.cloud.aws.beanstalk]] -==== AWS Elastic Beanstalk +=== AWS Elastic Beanstalk + As described in the official https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_Java.html[Elastic Beanstalk Java guide], there are two main options to deploy a Java application. You can either use the "`Tomcat Platform`" or the "`Java SE platform`". [[deployment.cloud.aws.beanstalk.tomcat-platform]] -===== Using the Tomcat Platform +==== Using the Tomcat Platform + This option applies to Spring Boot projects that produce a war file. No special configuration is required. You need only follow the official guide. @@ -258,14 +268,16 @@ You need only follow the official guide. [[deployment.cloud.aws.beanstalk.java-se-platform]] -===== Using the Java SE Platform +==== Using the Java SE Platform + This option applies to Spring Boot projects that produce a jar file and run an embedded web container. Elastic Beanstalk environments run an nginx instance on port 80 to proxy the actual application, running on port 5000. To configure it, add the following line to your `application.properties` file: -[indent=0] +[configprops,yaml] ---- - server.port=5000 +server: + port: 5000 ---- @@ -276,10 +288,10 @@ By default, Elastic Beanstalk uploads sources and compiles them in AWS. However, it is best to upload the binaries instead. To do so, add lines similar to the following to your `.elasticbeanstalk/config.yml` file: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - deploy: - artifact: target/demo-0.0.1-SNAPSHOT.jar +deploy: + artifact: target/demo-0.0.1-SNAPSHOT.jar ---- ==== @@ -291,32 +303,34 @@ The load balancer has a significant cost. To avoid that cost, set the environment type to "`Single instance`", as described in https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environments-create-wizard.html#environments-create-wizard-capacity[the Amazon documentation]. You can also create single instance environments by using the CLI and the following command: -[indent=0] +[source] ---- - eb create -s +eb create -s ---- ==== [[deployment.cloud.aws.summary]] -==== Summary +=== Summary + This is one of the easiest ways to get to AWS, but there are more things to cover, such as how to integrate Elastic Beanstalk into any CI / CD tool, use the Elastic Beanstalk Maven plugin instead of the CLI, and others. There is a https://exampledriven.wordpress.com/2017/01/09/spring-boot-aws-elastic-beanstalk-example/[blog post] covering these topics more in detail. [[deployment.cloud.boxfuse]] -=== CloudCaptain and Amazon Web Services +== CloudCaptain and Amazon Web Services + https://cloudcaptain.sh/[CloudCaptain] works by turning your Spring Boot executable jar or war into a minimal VM image that can be deployed unchanged either on VirtualBox or on AWS. CloudCaptain comes with deep integration for Spring Boot and uses the information from your Spring Boot configuration file to automatically configure ports and health check URLs. CloudCaptain leverages this information both for the images it produces as well as for all the resources it provisions (instances, security groups, elastic load balancers, and so on). Once you have created a https://console.cloudcaptain.sh[CloudCaptain account], connected it to your AWS account, installed the latest version of the CloudCaptain Client, and ensured that the application has been built by Maven or Gradle (by using, for example, `mvn clean package`), you can deploy your Spring Boot application to AWS with a command similar to the following: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ boxfuse run myapp-1.0.jar -env=prod +$ boxfuse run myapp-1.0.jar -env=prod ---- See the https://cloudcaptain.sh/docs/commandline/run.html[`boxfuse run` documentation] for more options. @@ -327,25 +341,25 @@ If your executable jar or war contains an https://cloudcaptain.sh/docs/payloads/ At this point, CloudCaptain creates an image for your application, uploads it, and configures and starts the necessary resources on AWS, resulting in output similar to the following example: -[indent=0,subs="verbatim"] +[source] ---- - Fusing Image for myapp-1.0.jar ... - Image fused in 00:06.838s (53937 K) -> axelfontaine/myapp:1.0 - Creating axelfontaine/myapp ... - Pushing axelfontaine/myapp:1.0 ... - Verifying axelfontaine/myapp:1.0 ... - Creating Elastic IP ... - Mapping myapp-axelfontaine.boxfuse.io to 52.28.233.167 ... - Waiting for AWS to create an AMI for axelfontaine/myapp:1.0 in eu-central-1 (this may take up to 50 seconds) ... - AMI created in 00:23.557s -> ami-d23f38cf - Creating security group boxfuse-sg_axelfontaine/myapp:1.0 ... - Launching t2.micro instance of axelfontaine/myapp:1.0 (ami-d23f38cf) in eu-central-1 ... - Instance launched in 00:30.306s -> i-92ef9f53 - Waiting for AWS to boot Instance i-92ef9f53 and Payload to start at https://52.28.235.61/ ... - Payload started in 00:29.266s -> https://52.28.235.61/ - Remapping Elastic IP 52.28.233.167 to i-92ef9f53 ... - Waiting 15s for AWS to complete Elastic IP Zero Downtime transition ... - Deployment completed successfully. axelfontaine/myapp:1.0 is up and running at https://myapp-axelfontaine.boxfuse.io/ +Fusing Image for myapp-1.0.jar ... +Image fused in 00:06.838s (53937 K) -> axelfontaine/myapp:1.0 +Creating axelfontaine/myapp ... +Pushing axelfontaine/myapp:1.0 ... +Verifying axelfontaine/myapp:1.0 ... +Creating Elastic IP ... +Mapping myapp-axelfontaine.boxfuse.io to 52.28.233.167 ... +Waiting for AWS to create an AMI for axelfontaine/myapp:1.0 in eu-central-1 (this may take up to 50 seconds) ... +AMI created in 00:23.557s -> ami-d23f38cf +Creating security group boxfuse-sg_axelfontaine/myapp:1.0 ... +Launching t2.micro instance of axelfontaine/myapp:1.0 (ami-d23f38cf) in eu-central-1 ... +Instance launched in 00:30.306s -> i-92ef9f53 +Waiting for AWS to boot Instance i-92ef9f53 and Payload to start at https://52.28.235.61/ ... +Payload started in 00:29.266s -> https://52.28.235.61/ +Remapping Elastic IP 52.28.233.167 to i-92ef9f53 ... +Waiting 15s for AWS to complete Elastic IP Zero Downtime transition ... +Deployment completed successfully. axelfontaine/myapp:1.0 is up and running at https://myapp-axelfontaine.boxfuse.io/ ---- Your application should now be up and running on AWS. @@ -355,13 +369,15 @@ See the blog post on https://cloudcaptain.sh/blog/spring-boot-ec2.html[deploying [[deployment.cloud.azure]] -=== Azure +== Azure + This https://spring.io/guides/gs/spring-boot-for-azure/[Getting Started guide] walks you through deploying your Spring Boot application to either https://azure.microsoft.com/en-us/services/spring-cloud/[Azure Spring Cloud] or https://docs.microsoft.com/en-us/azure/app-service/overview[Azure App Service]. [[deployment.cloud.google]] -=== Google Cloud +== Google Cloud + Google Cloud has several options that can be used to launch Spring Boot applications. The easiest to get started with is probably App Engine, but you could also find ways to run Spring Boot in a container with Container Engine or on a virtual machine with Compute Engine. @@ -370,39 +386,39 @@ To deploy your first app to App Engine standard environment, follow https://code Alternatively, App Engine Flex requires you to create an `app.yaml` file to describe the resources your app requires. Normally, you put this file in `src/main/appengine`, and it should resemble the following file: -[source,yaml,indent=0,subs="verbatim"] +[source,yaml] ---- - service: "default" +service: "default" - runtime: "java17" - env: "flex" +runtime: "java17" +env: "flex" - handlers: - - url: "/.*" - script: "this field is required, but ignored" +handlers: +- url: "/.*" + script: "this field is required, but ignored" - manual_scaling: - instances: 1 +manual_scaling: + instances: 1 - health_check: - enable_health_check: false +health_check: + enable_health_check: false - env_variables: - ENCRYPT_KEY: "your_encryption_key_here" +env_variables: + ENCRYPT_KEY: "your_encryption_key_here" ---- You can deploy the app (for example, with a Maven plugin) by adding the project ID to the build configuration, as shown in the following example: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - com.google.cloud.tools - appengine-maven-plugin - 2.4.4 - - myproject - - + + com.google.cloud.tools + appengine-maven-plugin + 2.4.4 + + myproject + + ---- Then deploy with `mvn appengine:deploy` (you need to authenticate first, otherwise the build fails). diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment/efficient.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/deployment/efficient.adoc similarity index 79% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment/efficient.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/deployment/efficient.adoc index 7ab708d613..d5b2c43548 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment/efficient.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/deployment/efficient.adoc @@ -1,19 +1,20 @@ [[deployment.efficient]] -== Efficient deployments += Efficient deployments [[deployment.efficient.unpacking]] -=== Unpacking the Executable JAR +== Unpacking the Executable JAR + If you are running your application from a container, you can use an executable jar, but it is also often an advantage to explode it and run it in a different way. Certain PaaS implementations may also choose to unpack archives before they run. For example, Cloud Foundry operates this way. One way to run an unpacked archive is by starting the appropriate launcher, as follows: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ jar -xf myapp.jar - $ java org.springframework.boot.loader.launch.JarLauncher +$ jar -xf myapp.jar +$ java org.springframework.boot.loader.launch.JarLauncher ---- This is actually slightly faster on startup (depending on the size of the jar) than running from an unexploded archive. @@ -21,10 +22,10 @@ After startup, you should not expect any differences. Once you have unpacked the jar file, you can also get an extra boost to startup time by running the app with its "natural" main method instead of the `JarLauncher`. For example: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ jar -xf myapp.jar - $ java -cp "BOOT-INF/classes:BOOT-INF/lib/*" com.example.MyApplication +$ 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. @@ -33,26 +34,27 @@ The jar contains a `classpath.idx` file which is used by the `JarLauncher` when [[deployment.efficient.aot]] -=== Using Ahead-of-time Processing With the JVM +== Using Ahead-of-time Processing With the JVM + It's beneficial for the startup time to run your application using the AOT generated initialization code. First, you need to ensure that the jar you are building includes AOT generated code. For Maven, this means that you should build with `-Pnative` to activate the `native` profile: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ mvn -Pnative package +$ mvn -Pnative package ---- For Gradle, you need to ensure that your build includes the `org.springframework.boot.aot` plugin. When the JAR has been built, run it with `spring.aot.enabled` system property set to `true`. For example: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ java -Dspring.aot.enabled=true -jar myapplication.jar +$ java -Dspring.aot.enabled=true -jar myapplication.jar - ........ Starting AOT-processed MyApplication ... +........ Starting AOT-processed MyApplication ... ---- Beware that using the ahead-of-time processing has drawbacks. @@ -60,15 +62,16 @@ It implies the following restrictions: * The classpath is fixed and fully defined at build time * The beans defined in your application cannot change at runtime, meaning: -- The Spring `@Profile` annotation and profile-specific configuration <>. +- The Spring `@Profile` annotation and profile-specific configuration xref:how-to:aot.adoc#howto.aot.conditions[have limitations]. - Properties that change if a bean is created are not supported (for example, `@ConditionalOnProperty` and `.enable` properties). -To learn more about ahead-of-time processing, please see the <>. +To learn more about ahead-of-time processing, please see the xref:native-image/introducing-graalvm-native-images.adoc#native-image.introducing-graalvm-native-images.understanding-aot-processing[Understanding Spring Ahead-of-Time Processing section]. [[deployment.efficient.checkpoint-restore]] -=== Checkpoint and Restore With the JVM +== Checkpoint and Restore With the JVM + https://wiki.openjdk.org/display/crac/Main[Coordinated Restore at Checkpoint] (CRaC) is an OpenJDK project that defines a new Java API to allow you to checkpoint and restore an application on the HotSpot JVM. It is based on https://github.com/checkpoint-restore/criu[CRIU], a project that implements checkpoint/restore functionality on Linux. @@ -81,4 +84,4 @@ The restored process retains all the capabilities of the HotSpot JVM, including Based on the foundations provided by Spring Framework, Spring Boot provides support for checkpointing and restoring your application, and manages out-of-the-box the lifecycle of resources such as socket, files and thread pools https://github.com/spring-projects/spring-lifecycle-smoke-tests/blob/main/STATUS.adoc[on a limited scope]. Additional lifecycle management is expected for other dependencies and potentially for the application code dealing with such resources. -You can find more details about the two modes supported ("on demand checkpoint/restore of a running application" and "automatic checkpoint/restore at startup"), how to enable checkpoint and restore support and some guidelines in {spring-framework-docs}/integration/checkpoint-restore.html[the Spring Framework JVM Checkpoint Restore support documentation]. +You can find more details about the two modes supported ("on demand checkpoint/restore of a running application" and "automatic checkpoint/restore at startup"), how to enable checkpoint and restore support and some guidelines in {url-spring-framework-docs}/integration/checkpoint-restore.html[the Spring Framework JVM Checkpoint Restore support documentation]. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/deployment/index.adoc similarity index 68% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/deployment/index.adoc index ecc8190c00..244f6205c1 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/deployment/index.adoc @@ -1,19 +1,8 @@ [[deployment]] = Deploying Spring Boot Applications -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 virtual/real machines, or make them fully executable for Unix systems. This section covers some of the more common deployment scenarios. - -include::deployment/cloud.adoc[] - -include::deployment/installing.adoc[] - -include::deployment/efficient.adoc[] - -include::deployment/whats-next.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment/installing.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/deployment/installing.adoc similarity index 83% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment/installing.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/deployment/installing.adoc index 9461d903a3..d7caf5e9b7 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment/installing.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/deployment/installing.adoc @@ -1,35 +1,37 @@ [[deployment.installing]] -== Installing Spring Boot Applications += Installing Spring Boot Applications + In addition to running Spring Boot applications by using `java -jar` directly, it is also possible to run them as `systemd`, `init.d` or Windows services. [[deployment.installing.system-d]] -=== Installation as a systemd Service +== Installation as a systemd Service + `systemd` is the successor of the System V init system and is now being used by many modern Linux distributions. Spring Boot applications can be launched by using `systemd` '`service`' scripts. Assuming that you have a Spring Boot application packaged as an uber jar in `/var/myapp`, to install it as a `systemd` service, create a script named `myapp.service` and place it in `/etc/systemd/system` directory. The following script offers an example: -[indent=0] +[source] ---- - [Unit] - Description=myapp - After=syslog.target network.target +[Unit] +Description=myapp +After=syslog.target network.target - [Service] - User=myapp - Group=myapp +[Service] +User=myapp +Group=myapp - Environment="JAVA_HOME=/path/to/java/home" +Environment="JAVA_HOME=/path/to/java/home" - ExecStart=${JAVA_HOME}/bin/java -jar /var/myapp/myapp.jar - ExecStop=/bin/kill -15 $MAINPID - SuccessExitStatus=143 +ExecStart=${JAVA_HOME}/bin/java -jar /var/myapp/myapp.jar +ExecStop=/bin/kill -15 $MAINPID +SuccessExitStatus=143 - [Install] - WantedBy=multi-user.target +[Install] +WantedBy=multi-user.target ---- IMPORTANT: Remember to change the `Description`, `User`, `Group`, `Environment` and `ExecStart` fields for your application. @@ -41,9 +43,9 @@ Consult the https://www.freedesktop.org/software/systemd/man/systemd.service.htm To flag the application to start automatically on system boot, use the following command: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ systemctl enable myapp.service +$ systemctl enable myapp.service ---- Run `man systemctl` for more details. @@ -51,8 +53,9 @@ Run `man systemctl` for more details. [[deployment.installing.init-d]] -=== Installation as an init.d Service (System V) -To use your application as `init.d` service, configure its build to produce a <>. +== Installation as an init.d Service (System V) + +To use your application as `init.d` service, configure its build to produce a xref:deployment/installing.adoc[fully executable jar]. CAUTION: Fully executable jars work by embedding an extra script at the front of the file. Currently, some tools do not accept this format, so you may not always be able to use this technique. @@ -65,24 +68,24 @@ A standard-format jar file that contains one or more zip64-format nested jars ca To create a '`fully executable`' jar with Maven, use the following plugin configuration: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - org.springframework.boot - spring-boot-maven-plugin - - true - - + + org.springframework.boot + spring-boot-maven-plugin + + true + + ---- The following example shows the equivalent Gradle configuration: -[source,gradle,indent=0,subs="verbatim"] +[source,gradle] ---- - tasks.named('bootJar') { - launchScript() - } +tasks.named('bootJar') { + launchScript() +} ---- It can then be symlinked to `init.d` to support the standard `start`, `stop`, `restart`, and `status` commands. @@ -97,17 +100,17 @@ The default scripts supports the following features: Assuming that you have a Spring Boot application installed in `/var/myapp`, to install a Spring Boot application as an `init.d` service, create a symlink, as follows: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ sudo ln -s /var/myapp/myapp.jar /etc/init.d/myapp +$ sudo ln -s /var/myapp/myapp.jar /etc/init.d/myapp ---- Once installed, you can start and stop the service in the usual way. For example, on a Debian-based system, you could start it with the following command: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ service myapp start +$ service myapp start ---- TIP: If your application fails to start, check the log file written to `/var/log/.log` for errors. @@ -115,15 +118,16 @@ TIP: If your application fails to start, check the log file written to `/var/log You can also flag the application to start automatically by using your standard operating system tools. For example, on Debian, you could use the following command: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ update-rc.d myapp defaults +$ update-rc.d myapp defaults ---- [[deployment.installing.init-d.securing]] -==== Securing an init.d Service +=== Securing an init.d Service + NOTE: The following is a set of guidelines on how to secure a Spring Boot application that runs as an init.d service. It is not intended to be an exhaustive list of everything that should be done to harden an application and the environment in which it runs. @@ -132,9 +136,9 @@ When the environment variable is not set, the user who owns the jar file is used You should never run a Spring Boot application as `root`, so `RUN_AS_USER` should never be root and your application's jar file should never be owned by root. Instead, create a specific user to run your application and set the `RUN_AS_USER` environment variable or use `chown` to make it the owner of the jar file, as shown in the following example: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ chown bootapp:bootapp your-app.jar +$ chown bootapp:bootapp your-app.jar ---- In this case, the default executable script runs the application as the `bootapp` user. @@ -145,36 +149,37 @@ For example, you can set the account's shell to `/usr/sbin/nologin`. You should also take steps to prevent the modification of your application's jar file. Firstly, configure its permissions so that it cannot be written and can only be read or executed by its owner, as shown in the following example: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ chmod 500 your-app.jar +$ chmod 500 your-app.jar ---- Second, you should also take steps to limit the damage if your application or the account that is running it is compromised. If an attacker does gain access, they could make the jar file writable and change its contents. One way to protect against this is to make it immutable by using `chattr`, as shown in the following example: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ sudo chattr +i your-app.jar +$ sudo chattr +i your-app.jar ---- This will prevent any user, including root, from modifying the jar. -If root is used to control the application's service and you <> to customize its startup, the `.conf` file is read and evaluated by the root user. +If root is used to control the application's service and you xref:deployment/installing.adoc#deployment.installing.init-d.script-customization.when-running.conf-file[use a `.conf` file] to customize its startup, the `.conf` file is read and evaluated by the root user. It should be secured accordingly. Use `chmod` so that the file can only be read by the owner and use `chown` to make root the owner, as shown in the following example: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ chmod 400 your-app.conf - $ sudo chown root:root your-app.conf +$ chmod 400 your-app.conf +$ sudo chown root:root your-app.conf ---- [[deployment.installing.init-d.script-customization]] -==== Customizing the Startup Script +=== Customizing the Startup Script + The default embedded startup script written by the Maven or Gradle plugin can be customized in a number of ways. For most people, using the default script along with a few customizations is usually enough. If you find you cannot customize something that you need to, use the `embeddedLaunchScript` option to write your own file entirely. @@ -182,12 +187,13 @@ If you find you cannot customize something that you need to, use the `embeddedLa [[deployment.installing.init-d.script-customization.when-written]] -===== Customizing the Start Script When It Is Written +==== Customizing the Start Script When It Is Written + It often makes sense to customize elements of the start script as it is written into the jar file. For example, init.d scripts can provide a "`description`". Since you know the description up front (and it need not change), you may as well provide it when the jar is generated. -To customize written elements, use the `embeddedLaunchScriptProperties` option of the Spring Boot Maven plugin or the {spring-boot-gradle-plugin-docs}#packaging-executable-configuring-launch-script[`properties` property of the Spring Boot Gradle plugin's `launchScript`]. +To customize written elements, use the `embeddedLaunchScriptProperties` option of the Spring Boot Maven plugin or the xref:gradle-plugin:packaging.adoc#packaging-executable.configuring.launch-script[`properties` property of the Spring Boot Gradle plugin's `launchScript`]. The following property substitutions are supported with the default script: @@ -290,8 +296,9 @@ The following property substitutions are supported with the default script: [[deployment.installing.init-d.script-customization.when-running]] -===== Customizing a Script When It Runs -For items of the script that need to be customized _after_ the jar has been written, you can use environment variables or a <>. +==== Customizing a Script When It Runs + +For items of the script that need to be customized _after_ the jar has been written, you can use environment variables or a xref:deployment/installing.adoc#deployment.installing.init-d.script-customization.when-running.conf-file[config file]. The following environment properties are supported with the default script: @@ -355,26 +362,28 @@ See the https://www.freedesktop.org/software/systemd/man/systemd.service.html[se [[deployment.installing.init-d.script-customization.when-running.conf-file]] -====== Using a Conf File +===== Using a Conf File + With the exception of `JARFILE` and `APP_NAME`, the settings listed in the preceding section can be configured by using a `.conf` file. The file is expected to be next to the jar file and have the same name but suffixed with `.conf` rather than `.jar`. For example, a jar named `/var/myapp/myapp.jar` uses the configuration file named `/var/myapp/myapp.conf`, as shown in the following example: .myapp.conf -[indent=0,subs="verbatim"] +[source,properties] ---- - JAVA_OPTS=-Xmx1024M - LOG_FOLDER=/custom/log/folder +JAVA_OPTS=-Xmx1024M +LOG_FOLDER=/custom/log/folder ---- TIP: If you do not like having the config file next to the jar file, you can set a `CONF_FOLDER` environment variable to customize the location of the config file. -To learn about securing this file appropriately, see <>. +To learn about securing this file appropriately, see xref:deployment/installing.adoc#deployment.installing.init-d.securing[the guidelines for securing an init.d service]. [[deployment.installing.windows-services]] -=== Microsoft Windows Services +== Microsoft Windows Services + A Spring Boot application can be started as a Windows service by using https://github.com/kohsuke/winsw[`winsw`]. A (https://github.com/snicoll/spring-boot-daemon[separately maintained sample]) describes step-by-step how you can create a Windows service for your Spring Boot application. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/aop.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/aop.adoc similarity index 72% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/aop.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/aop.adoc index ad7dcc6c4f..6d5803789f 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/aop.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/aop.adoc @@ -1,7 +1,8 @@ [[features.aop]] -== Aspect-Oriented Programming += Aspect-Oriented Programming + Spring Boot provides auto-configuration for aspect-oriented programming (AOP). -You can learn more about AOP with Spring in the {spring-framework-docs}/core/aop-api.html[Spring Framework reference documentation]. +You can learn more about AOP with Spring in the {url-spring-framework-docs}/core/aop-api.html[Spring Framework reference documentation]. By default, Spring Boot's auto-configuration configures Spring AOP to use CGLib proxies. To use JDK proxies instead, set `configprop:spring.aop.proxy-target-class` to `false`. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/developing-auto-configuration.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/developing-auto-configuration.adoc similarity index 81% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/developing-auto-configuration.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/developing-auto-configuration.adoc index 4184cef7eb..e01f5630e8 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/developing-auto-configuration.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/developing-auto-configuration.adoc @@ -1,35 +1,37 @@ [[features.developing-auto-configuration]] -== Creating Your Own Auto-configuration += Creating Your Own Auto-configuration + If you work in a company that develops shared libraries, or if you work on an open-source or commercial library, you might want to develop your own auto-configuration. Auto-configuration classes can be bundled in external jars and still be picked up by Spring Boot. Auto-configuration can be associated to a "`starter`" that provides the auto-configuration code as well as the typical libraries that you would use with it. -We first cover what you need to know to build your own auto-configuration and then we move on to the <>. +We first cover what you need to know to build your own auto-configuration and then we move on to the xref:features/developing-auto-configuration.adoc#features.developing-auto-configuration.custom-starter[typical steps required to create a custom starter]. [[features.developing-auto-configuration.understanding-auto-configured-beans]] -=== Understanding Auto-configured Beans +== Understanding Auto-configured Beans + Classes that implement auto-configuration are annotated with `@AutoConfiguration`. This annotation itself is meta-annotated with `@Configuration`, making auto-configurations standard `@Configuration` classes. Additional `@Conditional` annotations are used to constrain when the auto-configuration should apply. Usually, auto-configuration classes use `@ConditionalOnClass` and `@ConditionalOnMissingBean` annotations. This ensures that auto-configuration applies only when relevant classes are found and when you have not declared your own `@Configuration`. -You can browse the source code of {spring-boot-autoconfigure-module-code}[`spring-boot-autoconfigure`] to see the `@AutoConfiguration` classes that Spring provides (see the {spring-boot-code}/spring-boot-project/spring-boot-autoconfigure/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports[`META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`] file). +You can browse the source code of {code-spring-boot-autoconfigure-src}[`spring-boot-autoconfigure`] to see the `@AutoConfiguration` classes that Spring provides (see the {code-spring-boot}/spring-boot-project/spring-boot-autoconfigure/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports[`META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`] file). [[features.developing-auto-configuration.locating-auto-configuration-candidates]] -=== Locating Auto-configuration Candidates +== Locating Auto-configuration Candidates Spring Boot checks for the presence of a `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports` file within your published jar. The file should list your configuration classes, with one class name per line, as shown in the following example: -[indent=0] +[source] ---- - com.mycorp.libx.autoconfigure.LibXAutoConfiguration - com.mycorp.libx.autoconfigure.LibXWebAutoConfiguration +com.mycorp.libx.autoconfigure.LibXAutoConfiguration +com.mycorp.libx.autoconfigure.LibXWebAutoConfiguration ---- TIP: You can add comments to the imports file using the `#` character. @@ -39,7 +41,7 @@ Make sure that they are defined in a specific package space and that they are ne Furthermore, auto-configuration classes should not enable component scanning to find additional components. Specific `@Import` annotations should be used instead. -If your configuration needs to be applied in a specific order, you can use the `before`, `beforeName`, `after` and `afterName` attributes on the {spring-boot-autoconfigure-module-code}/AutoConfiguration.java[`@AutoConfiguration`] annotation or the dedicated {spring-boot-autoconfigure-module-code}/AutoConfigureBefore.java[`@AutoConfigureBefore`] and {spring-boot-autoconfigure-module-code}/AutoConfigureAfter.java[`@AutoConfigureAfter`] annotations. +If your configuration needs to be applied in a specific order, you can use the `before`, `beforeName`, `after` and `afterName` attributes on the {code-spring-boot-autoconfigure-src}/AutoConfiguration.java[`@AutoConfiguration`] annotation or the dedicated {code-spring-boot-autoconfigure-src}/AutoConfigureBefore.java[`@AutoConfigureBefore`] and {code-spring-boot-autoconfigure-src}/AutoConfigureAfter.java[`@AutoConfigureAfter`] annotations. For example, if you provide web-specific configuration, your class may need to be applied after `WebMvcAutoConfiguration`. If you want to order certain auto-configurations that should not have any direct knowledge of each other, you can also use `@AutoConfigureOrder`. @@ -51,24 +53,26 @@ The order in which those beans are subsequently created is unaffected and is det [[features.developing-auto-configuration.condition-annotations]] -=== Condition Annotations +== Condition Annotations + You almost always want to include one or more `@Conditional` annotations on your auto-configuration class. The `@ConditionalOnMissingBean` annotation is one common example that is used to allow developers to override auto-configuration if they are not happy with your defaults. Spring Boot includes a number of `@Conditional` annotations that you can reuse in your own code by annotating `@Configuration` classes or individual `@Bean` methods. These annotations include: -* <> -* <> -* <> -* <> -* <> -* <> +* xref:features/developing-auto-configuration.adoc#features.developing-auto-configuration.condition-annotations.class-conditions[Class Conditions] +* xref:features/developing-auto-configuration.adoc#features.developing-auto-configuration.condition-annotations.bean-conditions[Bean Conditions] +* xref:features/developing-auto-configuration.adoc#features.developing-auto-configuration.condition-annotations.property-conditions[Property Conditions] +* xref:features/developing-auto-configuration.adoc#features.developing-auto-configuration.condition-annotations.resource-conditions[Resource Conditions] +* xref:features/developing-auto-configuration.adoc#features.developing-auto-configuration.condition-annotations.web-application-conditions[Web Application Conditions] +* xref:features/developing-auto-configuration.adoc#features.developing-auto-configuration.condition-annotations.spel-conditions[SpEL Expression Conditions] [[features.developing-auto-configuration.condition-annotations.class-conditions]] -==== Class Conditions +=== Class Conditions + The `@ConditionalOnClass` and `@ConditionalOnMissingClass` annotations let `@Configuration` classes be included based on the presence or absence of specific classes. Due to the fact that annotation metadata is parsed by using https://asm.ow2.io/[ASM], you can use the `value` attribute to refer to the real class, even though that class might not actually appear on the running application classpath. You can also use the `name` attribute if you prefer to specify the class name by using a `String` value. @@ -77,21 +81,22 @@ This mechanism does not apply the same way to `@Bean` methods where typically th To handle this scenario, a separate `@Configuration` class can be used to isolate the condition, as shown in the following example: -include::code:MyAutoConfiguration[] +include-code::MyAutoConfiguration[] TIP: If you use `@ConditionalOnClass` or `@ConditionalOnMissingClass` as a part of a meta-annotation to compose your own composed annotations, you must use `name` as referring to the class in such a case is not handled. [[features.developing-auto-configuration.condition-annotations.bean-conditions]] -==== Bean Conditions +=== Bean Conditions + The `@ConditionalOnBean` and `@ConditionalOnMissingBean` annotations let a bean be included based on the presence or absence of specific beans. You can use the `value` attribute to specify beans by type or `name` to specify beans by name. The `search` attribute lets you limit the `ApplicationContext` hierarchy that should be considered when searching for beans. When placed on a `@Bean` method, the target type defaults to the return type of the method, as shown in the following example: -include::code:MyAutoConfiguration[] +include-code::MyAutoConfiguration[] In the preceding example, the `someService` bean is going to be created if no bean of type `SomeService` is already contained in the `ApplicationContext`. @@ -108,7 +113,8 @@ Providing as much type information as possible in `@Bean` methods is particularl [[features.developing-auto-configuration.condition-annotations.property-conditions]] -==== Property Conditions +=== Property Conditions + The `@ConditionalOnProperty` annotation lets configuration be included based on a Spring Environment property. Use the `prefix` and `name` attributes to specify the property that should be checked. By default, any property that exists and is not equal to `false` is matched. @@ -117,14 +123,16 @@ You can also create more advanced checks by using the `havingValue` and `matchIf [[features.developing-auto-configuration.condition-annotations.resource-conditions]] -==== Resource Conditions +=== Resource Conditions + The `@ConditionalOnResource` annotation lets configuration be included only when a specific resource is present. Resources can be specified by using the usual Spring conventions, as shown in the following example: `file:/home/user/test.dat`. [[features.developing-auto-configuration.condition-annotations.web-application-conditions]] -==== Web Application Conditions +=== Web Application Conditions + The `@ConditionalOnWebApplication` and `@ConditionalOnNotWebApplication` annotations let configuration be included depending on whether the application is a web application. A servlet-based web application is any application that uses a Spring `WebApplicationContext`, defines a `session` scope, or has a `ConfigurableWebEnvironment`. A reactive web application is any application that uses a `ReactiveWebApplicationContext`, or has a `ConfigurableReactiveWebEnvironment`. @@ -135,8 +143,9 @@ This condition will not match for applications that are run with an embedded web [[features.developing-auto-configuration.condition-annotations.spel-conditions]] -==== SpEL Expression Conditions -The `@ConditionalOnExpression` annotation lets configuration be included based on the result of a {spring-framework-docs}/core/expressions.html[SpEL expression]. +=== SpEL Expression Conditions + +The `@ConditionalOnExpression` annotation lets configuration be included based on the result of a {url-spring-framework-docs}/core/expressions.html[SpEL expression]. NOTE: Referencing a bean in the expression will cause that bean to be initialized very early in context refresh processing. As a result, the bean won't be eligible for post-processing (such as configuration properties binding) and its state may be incomplete. @@ -144,7 +153,8 @@ As a result, the bean won't be eligible for post-processing (such as configurati [[features.developing-auto-configuration.testing]] -=== Testing your Auto-configuration +== Testing your Auto-configuration + An auto-configuration can be affected by many factors: user configuration (`@Bean` definition and `Environment` customization), condition evaluation (presence of a particular library), and others. Concretely, each test should create a well defined `ApplicationContext` that represents a combination of those customizations. `ApplicationContextRunner` provides a great way to achieve that. @@ -154,7 +164,7 @@ WARNING: `ApplicationContextRunner` doesn't work when running the tests in a nat `ApplicationContextRunner` is usually defined as a field of the test class to gather the base, common configuration. The following example makes sure that `MyServiceAutoConfiguration` is always invoked: -include::code:MyServiceAutoConfigurationTests[tag=runner] +include-code::MyServiceAutoConfigurationTests[tag=runner] TIP: If multiple auto-configurations have to be defined, there is no need to order their declarations as they are invoked in the exact same order as when running the application. @@ -162,38 +172,41 @@ Each test can use the runner to represent a particular use case. For instance, the sample below invokes a user configuration (`UserConfiguration`) and checks that the auto-configuration backs off properly. Invoking `run` provides a callback context that can be used with `AssertJ`. -include::code:MyServiceAutoConfigurationTests[tag=test-user-config] +include-code::MyServiceAutoConfigurationTests[tag=test-user-config] It is also possible to easily customize the `Environment`, as shown in the following example: -include::code:MyServiceAutoConfigurationTests[tag=test-env] +include-code::MyServiceAutoConfigurationTests[tag=test-env] The runner can also be used to display the `ConditionEvaluationReport`. The report can be printed at `INFO` or `DEBUG` level. The following example shows how to use the `ConditionEvaluationReportLoggingListener` to print the report in auto-configuration tests. -include::code:MyConditionEvaluationReportingTests[] +include-code::MyConditionEvaluationReportingTests[] [[features.developing-auto-configuration.testing.simulating-a-web-context]] -==== Simulating a Web Context +=== Simulating a Web Context + If you need to test an auto-configuration that only operates in a servlet or reactive web application context, use the `WebApplicationContextRunner` or `ReactiveWebApplicationContextRunner` respectively. [[features.developing-auto-configuration.testing.overriding-classpath]] -==== Overriding the Classpath +=== Overriding the Classpath + It is also possible to test what happens when a particular class and/or package is not present at runtime. Spring Boot ships with a `FilteredClassLoader` that can easily be used by the runner. In the following example, we assert that if `MyService` is not present, the auto-configuration is properly disabled: -include::code:../MyServiceAutoConfigurationTests[tag=test-classloader] +include-code::../MyServiceAutoConfigurationTests[tag=test-classloader] [[features.developing-auto-configuration.custom-starter]] -=== Creating Your Own Starter +== Creating Your Own Starter + A typical Spring Boot starter contains code to auto-configure and customize the infrastructure of a given technology, let's call that "acme". To make it easily extensible, a number of configuration keys in a dedicated namespace can be exposed to the environment. Finally, a single "starter" dependency is provided to help users get started as easily as possible. @@ -214,7 +227,8 @@ If the auto-configuration is relatively straightforward and does not have option [[features.developing-auto-configuration.custom-starter.naming]] -==== Naming +=== Naming + You should make sure to provide a proper namespace for your starter. Do not start your module names with `spring-boot`, even if you use a different Maven `groupId`. We may offer official support for the thing you auto-configure in the future. @@ -226,7 +240,8 @@ If you only have one module that combines the two, name it `acme-spring-boot-sta [[features.developing-auto-configuration.custom-starter.configuration-keys]] -==== Configuration keys +=== Configuration keys + If your starter provides configuration keys, use a unique namespace for them. In particular, do not include your keys in the namespaces that Spring Boot uses (such as `server`, `management`, `spring`, and so on). If you use the same namespace, we may modify these namespaces in the future in ways that break your modules. @@ -234,7 +249,7 @@ As a rule of thumb, prefix all your keys with a namespace that you own (for exam Make sure that configuration keys are documented by adding field javadoc for each property, as shown in the following example: -include::code:AcmeProperties[] +include-code::AcmeProperties[] NOTE: You should only use plain text with `@ConfigurationProperties` field Javadoc, since they are not processed before being added to the JSON. @@ -246,14 +261,15 @@ Here are some rules we follow internally to make sure descriptions are consisten * Use `java.time.Duration` rather than `long` and describe the default unit if it differs from milliseconds, such as "If a duration suffix is not specified, seconds will be used". * Do not provide the default value in the description unless it has to be determined at runtime. -Make sure to <> so that IDE assistance is available for your keys as well. +Make sure to xref:specification:configuration-metadata/annotation-processor.adoc[trigger meta-data generation] so that IDE assistance is available for your keys as well. You may want to review the generated metadata (`META-INF/spring-configuration-metadata.json`) to make sure your keys are properly documented. Using your own starter in a compatible IDE is also a good idea to validate that quality of the metadata. [[features.developing-auto-configuration.custom-starter.autoconfigure-module]] -==== The "`autoconfigure`" Module +=== The "`autoconfigure`" Module + The `autoconfigure` module contains everything that is necessary to get started with the library. It may also contain configuration key definitions (such as `@ConfigurationProperties`) and any callback interface that can be used to further customize how the components are initialized. @@ -265,52 +281,53 @@ If that file is present, it is used to eagerly filter auto-configurations that d When building with Maven, it is recommended to add the following dependency in a module that contains auto-configurations: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - org.springframework.boot - spring-boot-autoconfigure-processor - true - + + org.springframework.boot + spring-boot-autoconfigure-processor + true + ---- If you have defined auto-configurations directly in your application, make sure to configure the `spring-boot-maven-plugin` to prevent the `repackage` goal from adding the dependency into the uber jar: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - org.springframework.boot - spring-boot-autoconfigure-processor - - - - - - - + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.springframework.boot + spring-boot-autoconfigure-processor + + + + + + + ---- With Gradle, the dependency should be declared in the `annotationProcessor` configuration, as shown in the following example: -[source,gradle,indent=0,subs="verbatim"] +[source,gradle] ---- - dependencies { - annotationProcessor "org.springframework.boot:spring-boot-autoconfigure-processor" - } +dependencies { + annotationProcessor "org.springframework.boot:spring-boot-autoconfigure-processor" +} ---- [[features.developing-auto-configuration.custom-starter.starter-module]] -==== Starter Module +=== Starter Module + The starter is really an empty jar. Its only purpose is to provide the necessary dependencies to work with the library. You can think of it as an opinionated view of what is required to get started. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/docker-compose.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/docker-compose.adoc similarity index 80% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/docker-compose.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/docker-compose.adoc index bb5f205819..668e4a2d93 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/docker-compose.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/docker-compose.adoc @@ -1,5 +1,6 @@ [[features.docker-compose]] -== Docker Compose Support += Docker Compose Support + Docker Compose is a popular technology that can be used to define and manage multiple containers for services that your application needs. A `compose.yml` file is typically created next to your application which defines and configures service containers. @@ -9,23 +10,23 @@ The `spring-boot-docker-compose` module can be included in a project to provide Add the module dependency to your build, as shown in the following listings for Maven and Gradle: .Maven -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - - org.springframework.boot - spring-boot-docker-compose - true - - + + + org.springframework.boot + spring-boot-docker-compose + true + + ---- .Gradle -[source,gradle,indent=0,subs="verbatim"] +[source,gradle] ---- - dependencies { - developmentOnly("org.springframework.boot:spring-boot-docker-compose") - } +dependencies { + developmentOnly("org.springframework.boot:spring-boot-docker-compose") +} ---- When this module is included as a dependency Spring Boot will do the following: @@ -44,14 +45,16 @@ To enable it, set configprop:spring.docker.compose.skip.in-tests[] to `false`. [[features.docker-compose.prerequisites]] -=== Prerequisites +== Prerequisites + You need to have the `docker` and `docker compose` (or `docker-compose`) CLI applications on your path. The minimum supported Docker Compose version is 2.2.0. [[features.docker-compose.service-connections]] -=== Service Connections +== Service Connections + A service connection is a connection to any remote service. Spring Boot’s auto-configuration can consume the details of a service connection and use them to establish a connection to a remote service. When doing so, the connection details take precedence over any connection-related configuration properties. @@ -118,7 +121,8 @@ The following service connections are currently supported: [[features.docker-compose.custom-images]] -=== Custom Images +== Custom Images + Sometimes you may need to use your own version of an image to provide a service. You can use any custom image as long as it behaves in the same way as the standard image. Specifically, any environment variables that the standard image supports must also be used in your custom image. @@ -128,58 +132,61 @@ Use a label named `org.springframework.boot.service-connection` to provide the s For example: -[source,yaml,indent=0] +[source,yaml,] ---- - services: - redis: - image: 'mycompany/mycustomredis:7.0' - ports: - - '6379' - labels: - org.springframework.boot.service-connection: redis +services: + redis: + image: 'mycompany/mycustomredis:7.0' + ports: + - '6379' + labels: + org.springframework.boot.service-connection: redis ---- [[features.docker-compose.skipping]] -=== Skipping Specific Containers +== Skipping Specific Containers + If you have a container image defined in your `compose.yml` that you don’t want connected to your application you can use a label to ignore it. Any container with labeled with `org.springframework.boot.ignore` will be ignored by Spring Boot. For example: -[source,yaml,indent=0] +[source,yaml] ---- - services: - redis: - image: 'redis:7.0' - ports: - - '6379' - labels: - org.springframework.boot.ignore: true +services: + redis: + image: 'redis:7.0' + ports: + - '6379' + labels: + org.springframework.boot.ignore: true ---- [[features.docker-compose.specific-file]] -=== Using a Specific Compose File +== Using a Specific Compose File + If your compose file is not in the same directory as your application, or if it’s named differently, you can use configprop:spring.docker.compose.file[] in your `application.properties` or `application.yaml` to point to a different file. Properties can be defined as an exact path or a path that’s relative to your application. For example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - docker: - compose: - file: "../my-compose.yml" +spring: + docker: + compose: + file: "../my-compose.yml" ---- [[features.docker-compose.readiness]] -=== Waiting for Container Readiness +== Waiting for Container Readiness + Containers started by Docker Compose may take some time to become fully ready. The recommended way of checking for readiness is to add a `healthcheck` section under the service definition in your `compose.yml` file. @@ -190,28 +197,28 @@ You can disable this on a per-container basis by adding a `org.springframework.b For example: -[source,yaml,indent=0] +[source,yaml] ---- - services: - redis: - image: 'redis:7.0' - ports: - - '6379' - labels: - org.springframework.boot.readiness-check.tcp.disable: true +services: + redis: + image: 'redis:7.0' + ports: + - '6379' + labels: + org.springframework.boot.readiness-check.tcp.disable: true ---- You can also change timeout values in your `application.properties` or `application.yaml` file: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - docker: - compose: - readiness: - tcp: - connect-timeout: 10s - read-timeout: 5s +spring: + docker: + compose: + readiness: + tcp: + connect-timeout: 10s + read-timeout: 5s ---- The overall timeout can be configured using configprop:spring.docker.compose.readiness.timeout[]. @@ -219,7 +226,8 @@ The overall timeout can be configured using configprop:spring.docker.compose.rea [[features.docker-compose.lifecycle]] -=== Controlling the Docker Compose Lifecycle +== Controlling the Docker Compose Lifecycle + By default Spring Boot calls `docker compose up` when your application starts and `docker compose stop` when it's shut down. If you prefer to have different lifecycle management you can use the configprop:spring.docker.compose.lifecycle-management[] property. @@ -234,31 +242,32 @@ The configprop:spring.docker.compose.stop.command[] allows you to configure if ` The following example shows how lifecycle management can be configured: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - docker: - compose: - lifecycle-management: start-and-stop - start: - command: start - stop: - command: down - timeout: 1m +spring: + docker: + compose: + lifecycle-management: start-and-stop + start: + command: start + stop: + command: down + timeout: 1m ---- [[features.docker-compose.profiles]] -=== Activating Docker Compose Profiles +== Activating Docker Compose Profiles + Docker Compose profiles are similar to Spring profiles in that they let you adjust your Docker Compose configuration for specific environments. If you want to activate a specific Docker Compose profile you can use the configprop:spring.docker.compose.profiles.active[] property in your `application.properties` or `application.yaml` file: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - docker: - compose: - profiles: - active: "myprofile" +spring: + docker: + compose: + profiles: + active: "myprofile" ---- diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/external-config.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/external-config.adoc similarity index 80% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/external-config.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/external-config.adoc index a45717e7f4..5dfa966222 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/external-config.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/external-config.adoc @@ -1,16 +1,17 @@ [[features.external-config]] -== Externalized Configuration += Externalized Configuration + Spring Boot lets you externalize your configuration so that you can work with the same application code in different environments. You can use a variety of external configuration sources including Java properties files, YAML files, environment variables, and command-line arguments. -Property values can be injected directly into your beans by using the `@Value` annotation, accessed through Spring's `Environment` abstraction, or be <> through `@ConfigurationProperties`. +Property values can be injected directly into your beans by using the `@Value` annotation, accessed through Spring's `Environment` abstraction, or be xref:features/external-config.adoc#features.external-config.typesafe-configuration-properties[bound to structured objects] through `@ConfigurationProperties`. Spring Boot uses a very particular `PropertySource` order that is designed to allow sensible overriding of values. Later property sources can override the values defined in earlier ones. Sources are considered in the following order: . Default properties (specified by setting `SpringApplication.setDefaultProperties`). -. {spring-framework-api}/context/annotation/PropertySource.html[`@PropertySource`] annotations on your `@Configuration` classes. +. {url-spring-framework-javadoc}/org/springframework/context/annotation/PropertySource.html[`@PropertySource`] annotations on your `@Configuration` classes. Please note that such property sources are not added to the `Environment` until the application context is being refreshed. This is too late to configure certain properties such as `+logging.*+` and `+spring.main.*+` which are read before refresh begins. . Config data (such as `application.properties` files). @@ -23,29 +24,29 @@ Sources are considered in the following order: . Properties from `SPRING_APPLICATION_JSON` (inline JSON embedded in an environment variable or system property). . Command line arguments. . `properties` attribute on your tests. - Available on {spring-boot-test-module-api}/context/SpringBootTest.html[`@SpringBootTest`] and the <>. -. {spring-framework-api}/test/context/DynamicPropertySource.html[`@DynamicPropertySource`] annotations in your tests. -. {spring-framework-api}/test/context/TestPropertySource.html[`@TestPropertySource`] annotations on your tests. -. <> in the `$HOME/.config/spring-boot` directory when devtools is active. + Available on xref:api:java/org/springframework/boot/test/context/SpringBootTest.html[`@SpringBootTest`] and the xref:features/testing.adoc#features.testing.spring-boot-applications.autoconfigured-tests[test annotations for testing a particular slice of your application]. +. {url-spring-framework-javadoc}/org/springframework/test/context/DynamicPropertySource.html[`@DynamicPropertySource`] annotations in your tests. +. {url-spring-framework-javadoc}/org/springframework/test/context/TestPropertySource.html[`@TestPropertySource`] annotations on your tests. +. xref:using/devtools.adoc#using.devtools.globalsettings[Devtools global settings properties] in the `$HOME/.config/spring-boot` directory when devtools is active. Config data files are considered in the following order: -. <> packaged inside your jar (`application.properties` and YAML variants). -. <> packaged inside your jar (`application-\{profile}.properties` and YAML variants). -. <> outside of your packaged jar (`application.properties` and YAML variants). -. <> outside of your packaged jar (`application-\{profile}.properties` and YAML variants). +. xref:features/external-config.adoc#features.external-config.files[Application properties] packaged inside your jar (`application.properties` and YAML variants). +. xref:features/external-config.adoc#features.external-config.files.profile-specific[Profile-specific application properties] packaged inside your jar (`application-\{profile}.properties` and YAML variants). +. xref:features/external-config.adoc#features.external-config.files[Application properties] outside of your packaged jar (`application.properties` and YAML variants). +. xref:features/external-config.adoc#features.external-config.files.profile-specific[Profile-specific application properties] outside of your packaged jar (`application-\{profile}.properties` and YAML variants). NOTE: It is recommended to stick with one format for your entire application. If you have configuration files with both `.properties` and YAML format in the same location, `.properties` takes precedence. NOTE: If you use environment variables rather than system properties, most operating systems disallow period-separated key names, but you can use underscores instead (for example, configprop:spring.config.name[format=envvar] instead of configprop:spring.config.name[]). -See <> for details. +See xref:features/external-config.adoc#features.external-config.typesafe-configuration-properties.relaxed-binding.environment-variables[Binding From Environment Variables] for details. NOTE: If your application runs in a servlet container or application server, then JNDI properties (in `java:comp/env`) or servlet context initialization parameters can be used instead of, or as well as, environment variables or system properties. To provide a concrete example, suppose you develop a `@Component` that uses a `name` property, as shown in the following example: -include::code:MyBean[] +include-code::MyBean[] On your application classpath (for example, inside your jar) you can have an `application.properties` file that provides a sensible default property value for `name`. When running in a new environment, an `application.properties` file can be provided outside of your jar that overrides the `name`. @@ -53,12 +54,13 @@ For one-off testing, you can launch with a specific command line switch (for exa TIP: The `env` and `configprops` endpoints can be useful in determining why a property has a particular value. You can use these two endpoints to diagnose unexpected property values. -See the "<>" section for details. +See the "xref:actuator/endpoints.adoc[Production ready features]" section for details. [[features.external-config.command-line-args]] -=== Accessing Command Line Properties +== Accessing Command Line Properties + By default, `SpringApplication` converts any command line option arguments (that is, arguments starting with `--`, such as `--server.port=9000`) to a `property` and adds them to the Spring `Environment`. As mentioned previously, command line properties always take precedence over file-based property sources. @@ -67,7 +69,8 @@ If you do not want command line properties to be added to the `Environment`, you [[features.external-config.application-json]] -=== JSON Application Properties +== JSON Application Properties + Environment variables and system properties often have restrictions that mean some property names cannot be used. To help with this, Spring Boot allows you to encode a block of properties into a single JSON structure. @@ -75,25 +78,25 @@ When your application starts, any `spring.application.json` or `SPRING_APPLICATI For example, the `SPRING_APPLICATION_JSON` property can be supplied on the command line in a UN{asterisk}X shell as an environment variable: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ SPRING_APPLICATION_JSON='{"my":{"name":"test"}}' java -jar myapp.jar +$ SPRING_APPLICATION_JSON='{"my":{"name":"test"}}' java -jar myapp.jar ---- In the preceding example, you end up with `my.name=test` in the Spring `Environment`. The same JSON can also be provided as a system property: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ java -Dspring.application.json='{"my":{"name":"test"}}' -jar myapp.jar +$ java -Dspring.application.json='{"my":{"name":"test"}}' -jar myapp.jar ---- Or you could supply the JSON by using a command line argument: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ java -jar myapp.jar --spring.application.json='{"my":{"name":"test"}}' +$ java -jar myapp.jar --spring.application.json='{"my":{"name":"test"}}' ---- If you are deploying to a classic Application Server, you could also use a JNDI variable named `java:comp/env/spring.application.json`. @@ -104,7 +107,8 @@ This means that the JSON cannot override properties from lower order property so [[features.external-config.files]] -=== External Application Properties +== External Application Properties + Spring Boot will automatically find and load `application.properties` and `application.yaml` files from the following locations when your application starts: . From the classpath @@ -121,9 +125,9 @@ Documents from the loaded files are added as `PropertySources` to the Spring `En If you do not like `application` as the configuration file name, you can switch to another file name by specifying a configprop:spring.config.name[] environment property. For example, to look for `myproject.properties` and `myproject.yaml` files you can run your application as follows: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ java -jar myproject.jar --spring.config.name=myproject +$ java -jar myproject.jar --spring.config.name=myproject ---- You can also refer to an explicit location by using the configprop:spring.config.location[] environment property. @@ -131,14 +135,14 @@ This property accepts a comma-separated list of one or more locations to check. The following example shows how to specify two distinct files: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ java -jar myproject.jar --spring.config.location=\ - optional:classpath:/default.properties,\ - optional:classpath:/override.properties +$ java -jar myproject.jar --spring.config.location=\ + optional:classpath:/default.properties,\ + optional:classpath:/override.properties ---- -TIP: Use the prefix `optional:` if the <> and you do not mind if they do not exist. +TIP: Use the prefix `optional:` if the xref:features/external-config.adoc#features.external-config.files.optional-prefix[locations are optional] and you do not mind if they do not exist. WARNING: `spring.config.name`, `spring.config.location`, and `spring.config.additional-location` are used very early to determine which files have to be loaded. They must be defined as an environment property (typically an OS environment variable, a system property, or a command-line argument). @@ -147,7 +151,7 @@ If `spring.config.location` contains directories (as opposed to files), they sho At runtime they will be appended with the names generated from `spring.config.name` before being loaded. Files specified in `spring.config.location` are imported directly. -NOTE: Both directory and file location values are also expanded to check for <>. +NOTE: Both directory and file location values are also expanded to check for xref:features/external-config.adoc#features.external-config.files.profile-specific[profile-specific files]. For example, if you have a `spring.config.location` of `classpath:myconfig.properties`, you will also find appropriate `classpath:myconfig-.properties` files are loaded. In most situations, each configprop:spring.config.location[] item you add will reference a single file or directory. @@ -158,7 +162,7 @@ If you have a complex location setup, and you use profile-specific configuration A location group is a collection of locations that are all considered at the same level. For example, you might want to group all classpath locations, then all external locations. Items within a location group should be separated with `;`. -See the example in the "`<>`" section for more details. +See the example in the "`xref:features/external-config.adoc#features.external-config.files.profile-specific[Profile Specific Files]`" section for more details. Locations configured by using `spring.config.location` replace the default locations. For example, if `spring.config.location` is configured with the value `optional:classpath:/custom-config/,optional:file:./custom-config/`, the complete set of locations considered is: @@ -182,11 +186,12 @@ These default values can then be overridden at runtime with a different file loc [[features.external-config.files.optional-prefix]] -==== Optional Locations +=== Optional Locations + By default, when a specified config data location does not exist, Spring Boot will throw a `ConfigDataLocationNotFoundException` and your application will not start. If you want to specify a location, but you do not mind if it does not always exist, you can use the `optional:` prefix. -You can use this prefix with the `spring.config.location` and `spring.config.additional-location` properties, as well as with <> declarations. +You can use this prefix with the `spring.config.location` and `spring.config.additional-location` properties, as well as with xref:features/external-config.adoc#features.external-config.files.importing[`spring.config.import`] declarations. For example, a `spring.config.import` value of `optional:file:./myconfig.properties` allows your application to start, even if the `myconfig.properties` file is missing. @@ -196,7 +201,8 @@ Set the value to `ignore` using `SpringApplication.setDefaultProperties(...)` or [[features.external-config.files.wildcard-locations]] -==== Wildcard Locations +=== Wildcard Locations + If a config file location includes the `{asterisk}` character for the last path segment, it is considered a wildcard location. Wildcards are expanded when the config is loaded so that immediate subdirectories are also checked. Wildcard locations are particularly useful in an environment such as Kubernetes when there are multiple sources of config properties. @@ -219,7 +225,8 @@ You cannot use a wildcard in a `classpath:` location. [[features.external-config.files.profile-specific]] -==== Profile Specific Files +=== Profile Specific Files + As well as `application` property files, Spring Boot will also attempt to load profile-specific files using the naming convention `application-\{profile}`. For example, if your application activates a profile named `prod` and uses YAML files, then both `application.yaml` and `application-prod.yaml` will be considered. @@ -229,7 +236,7 @@ For example, if profiles `prod,live` are specified by the configprop:spring.prof [NOTE] ==== -The last-wins strategy applies at the <> level. +The last-wins strategy applies at the xref:features/external-config.adoc#features.external-config.files.location-groups[location group] level. A configprop:spring.config.location[] of `classpath:/cfg/,classpath:/ext/` will not have the same override rules as `classpath:/cfg/;classpath:/ext/`. For example, continuing our `prod,live` example above, we might have the following files: @@ -260,24 +267,25 @@ The `Environment` has a set of default profiles (by default, `[default]`) that a In other words, if no profiles are explicitly activated, then properties from `application-default` are considered. NOTE: Properties files are only ever loaded once. -If you have already directly <> a profile specific property files then it will not be imported a second time. +If you have already directly xref:features/external-config.adoc#features.external-config.files.importing[imported] a profile specific property files then it will not be imported a second time. [[features.external-config.files.importing]] -==== Importing Additional Data +=== Importing Additional Data + Application properties may import further config data from other locations using the `spring.config.import` property. Imports are processed as they are discovered, and are treated as additional documents inserted immediately below the one that declares the import. For example, you might have the following in your classpath `application.properties` file: -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops,yaml] ---- - spring: - application: - name: "myapp" - config: - import: "optional:file:./dev.properties" +spring: + application: + name: "myapp" + config: + import: "optional:file:./dev.properties" ---- This will trigger the import of a `dev.properties` file in current directory (if such a file exists). @@ -288,22 +296,22 @@ An import will only be imported once no matter how many times it is declared. The order an import is defined inside a single document within the properties/yaml file does not matter. For instance, the two examples below produce the same result: -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops%novalidate,yaml] ---- - spring: - config: - import: "my.properties" - my: - property: "value" +spring: + config: + import: "my.properties" +my: + property: "value" ---- -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops%novalidate,yaml] ---- - my: - property: "value" - spring: - config: - import: "my.properties" +my: + property: "value" +spring: + config: + import: "my.properties" ---- In both of the above examples, the values from the `my.properties` file will take precedence over the file that triggered its import. @@ -311,13 +319,13 @@ In both of the above examples, the values from the `my.properties` file will tak Several locations can be specified under a single `spring.config.import` key. Locations will be processed in the order that they are defined, with later imports taking precedence. -NOTE: When appropriate, <> are also considered for import. +NOTE: When appropriate, xref:features/external-config.adoc#features.external-config.files.profile-specific[Profile-specific variants] are also considered for import. The example above would import both `my.properties` as well as any `my-.properties` variants. [TIP] ==== Spring Boot includes pluggable API that allows various different location addresses to be supported. -By default you can import Java Properties, YAML and "`<>`". +By default you can import Java Properties, YAML and "`xref:features/external-config.adoc#features.external-config.files.configtree[configuration trees]`". Third-party jars can offer support for additional technologies (there is no requirement for files to be local). For example, you can imagine config data being from external stores such as Consul, Apache ZooKeeper or Netflix Archaius. @@ -328,7 +336,8 @@ If you want to support your own locations, see the `ConfigDataLocationResolver` [[features.external-config.files.importing-extensionless]] -==== Importing Extensionless Files +=== Importing Extensionless Files + Some cloud platforms cannot add a file extension to volume mounted files. To import these extensionless files, you need to give Spring Boot a hint so that it knows how to load them. You can do this by putting an extension hint in square brackets. @@ -336,17 +345,18 @@ You can do this by putting an extension hint in square brackets. For example, suppose you have a `/etc/config/myconfig` file that you wish to import as yaml. You can import it from your `application.properties` using the following: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - config: - import: "file:/etc/config/myconfig[.yaml]" +spring: + config: + import: "file:/etc/config/myconfig[.yaml]" ---- [[features.external-config.files.configtree]] -==== Using Configuration Trees +=== Using Configuration Trees + When running applications on a cloud platform (such as Kubernetes) you often need to read config values that the platform supplies. It is not uncommon to use environment variables for such purposes, but this can have drawbacks, especially if the value is supposed to be kept secret. @@ -358,29 +368,29 @@ There are two common volume mount patterns that can be used: . A single file contains a complete set of properties (usually written as YAML). . Multiple files are written to a directory tree, with the filename becoming the '`key`' and the contents becoming the '`value`'. -For the first case, you can import the YAML or Properties file directly using `spring.config.import` as described <>. +For the first case, you can import the YAML or Properties file directly using `spring.config.import` as described xref:features/external-config.adoc#features.external-config.files.importing[above]. For the second case, you need to use the `configtree:` prefix so that Spring Boot knows it needs to expose all the files as properties. As an example, let's imagine that Kubernetes has mounted the following volume: -[indent=0] +[source] ---- - etc/ - config/ - myapp/ - username - password +etc/ + config/ + myapp/ + username + password ---- The contents of the `username` file would be a config value, and the contents of `password` would be a secret. To import these properties, you can add the following to your `application.properties` or `application.yaml` file: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - config: - import: "optional:configtree:/etc/config/" +spring: + config: + import: "optional:configtree:/etc/config/" ---- You can then access or inject `myapp.username` and `myapp.password` properties from the `Environment` in the usual way. @@ -399,27 +409,27 @@ As with a non-wildcard import, the names of the folders and files under each con For example, given the following volume: -[indent=0] +[source] ---- - etc/ - config/ - dbconfig/ - db/ - username - password - mqconfig/ - mq/ - username - password +etc/ + config/ + dbconfig/ + db/ + username + password + mqconfig/ + mq/ + username + password ---- You can use `configtree:/etc/config/*/` as the import location: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - config: - import: "optional:configtree:/etc/config/*/" +spring: + config: + import: "optional:configtree:/etc/config/*/" ---- This will add `db.username`, `db.password`, `mq.username` and `mq.password` properties. @@ -432,28 +442,29 @@ Configuration trees can also be used for Docker secrets. When a Docker swarm service is granted access to a secret, the secret gets mounted into the container. For example, if a secret named `db.password` is mounted at location `/run/secrets/`, you can make `db.password` available to the Spring environment using the following: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - config: - import: "optional:configtree:/run/secrets/" +spring: + config: + import: "optional:configtree:/run/secrets/" ---- [[features.external-config.files.property-placeholders]] -==== Property Placeholders +=== Property Placeholders + The values in `application.properties` and `application.yaml` are filtered through the existing `Environment` when they are used, so you can refer back to previously defined values (for example, from System properties or environment variables). The standard `$\{name}` property-placeholder syntax can be used anywhere within a value. Property placeholders can also specify a default value using a `:` to separate the default value from the property name, for example `${name:default}`. The use of placeholders with and without defaults is shown in the following example: -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops%novalidate,yaml] ---- - app: - name: "MyApp" - description: "${app.name} is a Spring Boot application written by ${username:Unknown}" +app: + name: "MyApp" + description: "${app.name} is a Spring Boot application written by ${username:Unknown}" ---- Assuming that the `username` property has not been set elsewhere, `app.description` will have the value `MyApp is a Spring Boot application written by Unknown`. @@ -461,19 +472,20 @@ Assuming that the `username` property has not been set elsewhere, `app.descripti [NOTE] ==== You should always refer to property names in the placeholder using their canonical form (kebab-case using only lowercase letters). -This will allow Spring Boot to use the same logic as it does when <> `@ConfigurationProperties`. +This will allow Spring Boot to use the same logic as it does when xref:features/external-config.adoc#features.external-config.typesafe-configuration-properties.relaxed-binding[relaxed binding] `@ConfigurationProperties`. For example, `${demo.item-price}` will pick up `demo.item-price` and `demo.itemPrice` forms from the `application.properties` file, as well as `DEMO_ITEMPRICE` from the system environment. If you used `${demo.itemPrice}` instead, `demo.item-price` and `DEMO_ITEMPRICE` would not be considered. ==== TIP: You can also use this technique to create "`short`" variants of existing Spring Boot properties. -See the _<>_ how-to for details. +See the _xref:how-to:properties-and-configuration.adoc#howto.properties-and-configuration.short-command-line-arguments[Use '`Short`' Command Line Arguments]_ how-to for details. [[features.external-config.files.multi-document]] -==== Working With Multi-Document Files +=== Working With Multi-Document Files + Spring Boot allows you to split a single physical file into multiple logical documents which are each added independently. Documents are processed in order, from top to bottom. Later documents can override the properties defined in earlier ones. @@ -483,42 +495,43 @@ Three consecutive hyphens represent the end of one document, and the start of th For example, the following file has two logical documents: -[source,yaml,indent=0,subs="verbatim"] +[source,yaml] ---- - spring: - application: - name: "MyApp" - --- - spring: - application: - name: "MyCloudApp" - config: - activate: - on-cloud-platform: "kubernetes" +spring: + application: + name: "MyApp" +--- +spring: + application: + name: "MyCloudApp" + config: + activate: + on-cloud-platform: "kubernetes" ---- For `application.properties` files a special `#---` or `!---` comment is used to mark the document splits: -[source,properties,indent=0,subs="verbatim"] +[source,properties] ---- - spring.application.name=MyApp - #--- - spring.application.name=MyCloudApp - spring.config.activate.on-cloud-platform=kubernetes +spring.application.name=MyApp +#--- +spring.application.name=MyCloudApp +spring.config.activate.on-cloud-platform=kubernetes ---- NOTE: Property file separators must not have any leading whitespace and must have exactly three hyphen characters. The lines immediately before and after the separator must not be same comment prefix. TIP: Multi-document property files are often used in conjunction with activation properties such as `spring.config.activate.on-profile`. -See the <> for details. +See the xref:features/external-config.adoc#features.external-config.files.activation-properties[next section] for details. WARNING: Multi-document property files cannot be loaded by using the `@PropertySource` or `@TestPropertySource` annotations. [[features.external-config.files.activation-properties]] -==== Activation Properties +=== Activation Properties + It is sometimes useful to only activate a given set of properties when certain conditions are met. For example, you might have properties that are only relevant when a specific profile is active. @@ -540,33 +553,35 @@ The following activation properties are available: For example, the following specifies that the second document is only active when running on Kubernetes, and only when either the "`prod`" or "`staging`" profiles are active: -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops%novalidate,yaml] ---- - myprop: - "always-set" - --- - spring: - config: - activate: - on-cloud-platform: "kubernetes" - on-profile: "prod | staging" - myotherprop: "sometimes-set" +myprop: + "always-set" +--- +spring: + config: + activate: + on-cloud-platform: "kubernetes" + on-profile: "prod | staging" +myotherprop: "sometimes-set" ---- [[features.external-config.encrypting]] -=== Encrypting Properties +== Encrypting Properties + Spring Boot does not provide any built-in support for encrypting property values, however, it does provide the hook points necessary to modify values contained in the Spring `Environment`. The `EnvironmentPostProcessor` interface allows you to manipulate the `Environment` before the application starts. -See <> for details. +See xref:how-to:application.adoc#howto.application.customize-the-environment-or-application-context[Customize the Environment or ApplicationContext Before It Starts] for details. If you need a secure way to store credentials and passwords, the https://cloud.spring.io/spring-cloud-vault/[Spring Cloud Vault] project provides support for storing externalized configuration in https://www.vaultproject.io/[HashiCorp Vault]. [[features.external-config.yaml]] -=== Working With YAML +== Working With YAML + https://yaml.org[YAML] is a superset of JSON and, as such, is a convenient format for specifying hierarchical configuration data. The `SpringApplication` class automatically supports YAML as an alternative to properties whenever you have the https://github.com/snakeyaml/snakeyaml[SnakeYAML] library on your classpath. @@ -575,53 +590,54 @@ NOTE: If you use "`Starters`", SnakeYAML is automatically provided by `spring-bo [[features.external-config.yaml.mapping-to-properties]] -==== Mapping YAML to Properties +=== Mapping YAML to Properties + YAML documents need to be converted from their hierarchical format to a flat structure that can be used with the Spring `Environment`. For example, consider the following YAML document: -[source,yaml,indent=0,subs="verbatim"] +[source,yaml] ---- - environments: - dev: - url: "https://dev.example.com" - name: "Developer Setup" - prod: - url: "https://another.example.com" - name: "My Cool App" +environments: + dev: + url: "https://dev.example.com" + name: "Developer Setup" + prod: + url: "https://another.example.com" + name: "My Cool App" ---- In order to access these properties from the `Environment`, they would be flattened as follows: -[source,properties,indent=0,subs="verbatim"] +[source,properties] ---- - environments.dev.url=https://dev.example.com - environments.dev.name=Developer Setup - environments.prod.url=https://another.example.com - environments.prod.name=My Cool App +environments.dev.url=https://dev.example.com +environments.dev.name=Developer Setup +environments.prod.url=https://another.example.com +environments.prod.name=My Cool App ---- Likewise, YAML lists also need to be flattened. They are represented as property keys with `[index]` dereferencers. For example, consider the following YAML: -[source,yaml,indent=0,subs="verbatim"] +[source,yaml] ---- - my: - servers: - - "dev.example.com" - - "another.example.com" + my: + servers: + - "dev.example.com" + - "another.example.com" ---- The preceding example would be transformed into these properties: -[source,properties,indent=0,subs="verbatim"] +[source,properties] ---- - my.servers[0]=dev.example.com - my.servers[1]=another.example.com +my.servers[0]=dev.example.com +my.servers[1]=another.example.com ---- TIP: Properties that use the `[index]` notation can be bound to Java `List` or `Set` objects using Spring Boot's `Binder` class. -For more details see the "`<>`" section below. +For more details see the "`xref:features/external-config.adoc#features.external-config.typesafe-configuration-properties[Type-safe Configuration Properties]`" section below. WARNING: YAML files cannot be loaded by using the `@PropertySource` or `@TestPropertySource` annotations. So, in the case that you need to load values that way, you need to use a properties file. @@ -629,8 +645,8 @@ So, in the case that you need to load values that way, you need to use a propert [[features.external-config.yaml.directly-loading]] -[[features.external-config.yaml.directly-loading]] -==== Directly Loading YAML +=== Directly Loading YAML + Spring Framework provides two convenient classes that can be used to load YAML documents. The `YamlPropertiesFactoryBean` loads YAML as `Properties` and the `YamlMapFactoryBean` loads YAML as a `Map`. @@ -639,19 +655,20 @@ You can also use the `YamlPropertySourceLoader` class if you want to load YAML a [[features.external-config.random-values]] -=== Configuring Random Values +== Configuring Random Values + The `RandomValuePropertySource` is useful for injecting random values (for example, into secrets or test cases). It can produce integers, longs, uuids, or strings, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops%novalidate,yaml] ---- - my: - secret: "${random.value}" - number: "${random.int}" - bignumber: "${random.long}" - uuid: "${random.uuid}" - number-less-than-ten: "${random.int(10)}" - number-in-range: "${random.int[1024,65536]}" +my: + secret: "${random.value}" + number: "${random.int}" + bignumber: "${random.long}" + uuid: "${random.uuid}" + number-less-than-ten: "${random.int(10)}" + number-in-range: "${random.int[1024,65536]}" ---- The `+random.int*+` syntax is `OPEN value (,max) CLOSE` where the `OPEN,CLOSE` are any character and `value,max` are integers. @@ -660,7 +677,8 @@ If `max` is provided, then `value` is the minimum value and `max` is the maximum [[features.external-config.system-environment]] -=== Configuring System Environment Properties +== Configuring System Environment Properties + Spring Boot supports setting a prefix for environment properties. This is useful if the system environment is shared by multiple Spring Boot applications with different configuration requirements. The prefix for system environment properties can be set directly on `SpringApplication`. @@ -670,19 +688,21 @@ For example, if you set the prefix to `input`, a property such as `remote.timeou [[features.external-config.typesafe-configuration-properties]] -=== Type-safe Configuration Properties +== Type-safe Configuration Properties + Using the `@Value("$\{property}")` annotation to inject configuration properties can sometimes be cumbersome, especially if you are working with multiple properties or your data is hierarchical in nature. Spring Boot provides an alternative method of working with properties that lets strongly typed beans govern and validate the configuration of your application. -TIP: See also the <>. +TIP: See also the xref:features/external-config.adoc#features.external-config.typesafe-configuration-properties.vs-value-annotation[differences between `@Value` and type-safe configuration properties]. [[features.external-config.typesafe-configuration-properties.java-bean-binding]] -==== JavaBean Properties Binding +=== JavaBean Properties Binding + It is possible to bind a bean declaring standard JavaBean properties as shown in the following example: -include::code:MyProperties[] +include-code::MyProperties[] The preceding POJO defines the following properties: @@ -717,10 +737,11 @@ Finally, only standard Java Bean properties are considered and binding on static [[features.external-config.typesafe-configuration-properties.constructor-binding]] -==== Constructor Binding +=== Constructor Binding + The example in the previous section can be rewritten in an immutable fashion as shown in the following example: -include::code:MyProperties[] +include-code::MyProperties[] In this setup, the presence of a single parameterized constructor implies that constructor binding should be used. This means that the binder will find a constructor with the parameters that you wish to have bound. @@ -737,7 +758,7 @@ The conversion service will be applied to coerce the annotation's `String` value Referring to the previous example, if no properties are bound to `Security`, the `MyProperties` instance will contain a `null` value for `security`. To make it contain a non-null instance of `Security` even when no properties are bound to it (when using Kotlin, this will require the `username` and `password` parameters of `Security` to be declared as nullable as they do not have default values), use an empty `@DefaultValue` annotation: -include::code:nonnull/MyProperties[tag=*] +include-code::nonnull/MyProperties[tag=*] NOTE: To use constructor binding the class must be enabled using `@EnableConfigurationProperties` or configuration property scanning. You cannot use constructor binding with beans that are created by the regular Spring mechanisms (for example `@Component` beans, beans created by using `@Bean` methods or beans loaded by using `@Import`) @@ -752,7 +773,8 @@ For consistency with properties of other types, if you do declare an `Optional` [[features.external-config.typesafe-configuration-properties.enabling-annotated-types]] -==== Enabling @ConfigurationProperties-annotated Types +=== Enabling @ConfigurationProperties-annotated Types + Spring Boot provides infrastructure to bind `@ConfigurationProperties` types and register them as beans. You can either enable configuration properties on a class-by-class basis or enable configuration property scanning that works in a similar manner to component scanning. @@ -760,15 +782,15 @@ Sometimes, classes annotated with `@ConfigurationProperties` might not be suitab In these cases, specify the list of types to process using the `@EnableConfigurationProperties` annotation. This can be done on any `@Configuration` class, as shown in the following example: -include::code:MyConfiguration[] -include::code:SomeProperties[] +include-code::MyConfiguration[] +include-code::SomeProperties[] To use configuration property scanning, add the `@ConfigurationPropertiesScan` annotation to your application. Typically, it is added to the main application class that is annotated with `@SpringBootApplication` but it can be added to any `@Configuration` class. By default, scanning will occur from the package of the class that declares the annotation. If you want to define specific packages to scan, you can do so as shown in the following example: -include::code:MyApplication[] +include-code::MyApplication[] [NOTE] ==== @@ -785,51 +807,54 @@ If you still want to inject other beans using the constructor, the configuration [[features.external-config.typesafe-configuration-properties.using-annotated-types]] -==== Using @ConfigurationProperties-annotated Types +=== Using @ConfigurationProperties-annotated Types + This style of configuration works particularly well with the `SpringApplication` external YAML configuration, as shown in the following example: -[source,yaml,indent=0,subs="verbatim"] +[source,yaml] ---- - my: - service: - remote-address: 192.168.1.1 - security: - username: "admin" - roles: - - "USER" - - "ADMIN" +my: + service: + remote-address: 192.168.1.1 + security: + username: "admin" + roles: + - "USER" + - "ADMIN" ---- To work with `@ConfigurationProperties` beans, you can inject them in the same way as any other bean, as shown in the following example: -include::code:MyService[] +include-code::MyService[] TIP: Using `@ConfigurationProperties` also lets you generate metadata files that can be used by IDEs to offer auto-completion for your own keys. -See the <> for details. +See the xref:specification:configuration-metadata/index.adoc[appendix] for details. [[features.external-config.typesafe-configuration-properties.third-party-configuration]] -==== Third-party Configuration +=== Third-party Configuration + As well as using `@ConfigurationProperties` to annotate a class, you can also use it on public `@Bean` methods. Doing so can be particularly useful when you want to bind properties to third-party components that are outside of your control. To configure a bean from the `Environment` properties, add `@ConfigurationProperties` to its bean registration, as shown in the following example: -include::code:ThirdPartyConfiguration[] +include-code::ThirdPartyConfiguration[] Any JavaBean property defined with the `another` prefix is mapped onto that `AnotherComponent` bean in manner similar to the preceding `SomeProperties` example. [[features.external-config.typesafe-configuration-properties.relaxed-binding]] -==== Relaxed Binding +=== Relaxed Binding + Spring Boot uses some relaxed rules for binding `Environment` properties to `@ConfigurationProperties` beans, so there does not need to be an exact match between the `Environment` property name and the bean property name. Common examples where this is useful include dash-separated environment properties (for example, `context-path` binds to `contextPath`), and capitalized environment properties (for example, `PORT` binds to `port`). As an example, consider the following `@ConfigurationProperties` class: -include::code:MyPersonProperties[] +include-code::MyPersonProperties[] With the preceding code, the following properties names can all be used: @@ -867,8 +892,8 @@ NOTE: The `prefix` value for the annotation _must_ be in kebab case (lowercase a | Standard YAML list syntax or comma-separated values | Environment Variables -| Upper case format with underscore as the delimiter (see <>). -| Numeric values surrounded by underscores (see <>) +| Upper case format with underscore as the delimiter (see xref:features/external-config.adoc#features.external-config.typesafe-configuration-properties.relaxed-binding.environment-variables[Binding From Environment Variables]). +| Numeric values surrounded by underscores (see xref:features/external-config.adoc#features.external-config.typesafe-configuration-properties.relaxed-binding.environment-variables[Binding From Environment Variables]) | System properties | Camel case, kebab case, or underscore notation @@ -880,29 +905,20 @@ TIP: We recommend that, when possible, properties are stored in lower-case kebab [[features.external-config.typesafe-configuration-properties.relaxed-binding.maps]] -===== Binding Maps +==== Binding Maps + When binding to `Map` properties you may need to use a special bracket notation so that the original `key` value is preserved. If the key is not surrounded by `[]`, any characters that are not alpha-numeric, `-` or `.` are removed. For example, consider binding the following properties to a `Map`: - -[source,properties,indent=0,subs="verbatim",role="primary"] -.Properties +[configprops%novalidate,yaml] ---- - my.map.[/key1]=value1 - my.map.[/key2]=value2 - my.map./key3=value3 ----- - -[source,yaml,indent=0,subs="verbatim",role="secondary"] -.Yaml ----- - my: - map: - "[/key1]": "value1" - "[/key2]": "value2" - "/key3": "value3" +my: + map: + "[/key1]": "value1" + "[/key2]": "value2" + "/key3": "value3" ---- NOTE: For YAML files, the brackets need to be surrounded by quotes for the keys to be parsed properly. @@ -919,7 +935,8 @@ For example, binding `a.b=c` to `Map` will return a Map with the [[features.external-config.typesafe-configuration-properties.relaxed-binding.environment-variables]] -===== Binding From Environment Variables +==== Binding From Environment Variables + Most operating systems impose strict rules around the names that can be used for environment variables. For example, Linux shell variables can contain only letters (`a` to `z` or `A` to `Z`), numbers (`0` to `9`) or the underscore character (`_`). By convention, Unix shell variables will also have their names in UPPERCASE. @@ -942,37 +959,39 @@ For example, the configuration property `my.service[0].other` would use an envir [[features.external-config.typesafe-configuration-properties.relaxed-binding.caching]] -===== Caching +==== Caching + Relaxed binding uses a cache to improve performance. By default, this caching is only applied to immutable property sources. To customize this behavior, for example to enable caching for mutable property sources, use `ConfigurationPropertyCaching`. [[features.external-config.typesafe-configuration-properties.merging-complex-types]] -==== Merging Complex Types +=== Merging Complex Types + When lists are configured in more than one place, overriding works by replacing the entire list. For example, assume a `MyPojo` object with `name` and `description` attributes that are `null` by default. The following example exposes a list of `MyPojo` objects from `MyProperties`: -include::code:list/MyProperties[] +include-code::list/MyProperties[] Consider the following configuration: -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops%novalidate,yaml] ---- - my: - list: - - name: "my name" - description: "my description" - --- - spring: - config: - activate: - on-profile: "dev" - my: - list: - - name: "my another name" +my: + list: + - name: "my name" + description: "my description" +--- +spring: + config: + activate: + on-profile: "dev" +my: + list: + - name: "my another name" ---- If the `dev` profile is not active, `MyProperties.list` contains one `MyPojo` entry, as previously defined. @@ -982,22 +1001,22 @@ This configuration _does not_ add a second `MyPojo` instance to the list, and it When a `List` is specified in multiple profiles, the one with the highest priority (and only that one) is used. Consider the following example: -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops%novalidate,yaml] ---- - my: - list: - - name: "my name" - description: "my description" - - name: "another name" - description: "another description" - --- - spring: - config: - activate: - on-profile: "dev" - my: - list: - - name: "my another name" +my: + list: + - name: "my name" + description: "my description" + - name: "another name" + description: "another description" +--- +spring: + config: + activate: + on-profile: "dev" +my: + list: + - name: "my another name" ---- In the preceding example, if the `dev` profile is active, `MyProperties.list` contains _one_ `MyPojo` entry (with a name of `my another name` and a description of `null`). @@ -1007,29 +1026,29 @@ For `Map` properties, you can bind with property values drawn from multiple sour However, for the same property in multiple sources, the one with the highest priority is used. The following example exposes a `Map` from `MyProperties`: -include::code:map/MyProperties[] +include-code::map/MyProperties[] Consider the following configuration: -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops%novalidate,yaml] ---- - my: - map: - key1: - name: "my name 1" - description: "my description 1" - --- - spring: - config: - activate: - on-profile: "dev" - my: - map: - key1: - name: "dev name 1" - key2: - name: "dev name 2" - description: "dev description 2" +my: + map: + key1: + name: "my name 1" + description: "my description 1" +--- +spring: + config: + activate: + on-profile: "dev" +my: + map: + key1: + name: "dev name 1" + key2: + name: "dev name 2" + description: "dev description 2" ---- If the `dev` profile is not active, `MyProperties.map` contains one entry with key `key1` (with a name of `my name 1` and a description of `my description 1`). @@ -1040,7 +1059,8 @@ NOTE: The preceding merging rules apply to properties from all property sources, [[features.external-config.typesafe-configuration-properties.conversion]] -==== Properties Conversion +=== Properties Conversion + Spring Boot attempts to coerce the external application properties to the right type when it binds to the `@ConfigurationProperties` beans. If you need custom type conversion, you can provide a `ConversionService` bean (with a bean named `conversionService`) or custom property editors (through a `CustomEditorConfigurer` bean) or custom `Converters` (with bean definitions annotated as `@ConfigurationPropertiesBinding`). @@ -1051,17 +1071,18 @@ You may want to rename your custom `ConversionService` if it is not required for [[features.external-config.typesafe-configuration-properties.conversion.durations]] -===== Converting Durations +==== Converting Durations + Spring Boot has dedicated support for expressing durations. If you expose a `java.time.Duration` property, the following formats in application properties are available: * A regular `long` representation (using milliseconds as the default unit unless a `@DurationUnit` has been specified) -* The standard ISO-8601 format {java-api}/java.base/java/time/Duration.html#parse(java.lang.CharSequence)[used by `java.time.Duration`] +* The standard ISO-8601 format {apiref-openjdk}/java.base/java/time/Duration.html#parse(java.lang.CharSequence)[used by `java.time.Duration`] * A more readable format where the value and the unit are coupled (`10s` means 10 seconds) Consider the following example: -include::code:javabeanbinding/MyProperties[] +include-code::javabeanbinding/MyProperties[] To specify a session timeout of 30 seconds, `30`, `PT30S` and `30s` are all equivalent. A read timeout of 500ms can be specified in any of the following form: `500`, `PT0.5S` and `500ms`. @@ -1081,7 +1102,7 @@ The default unit is milliseconds and can be overridden using `@DurationUnit` as If you prefer to use constructor binding, the same properties can be exposed, as shown in the following example: -include::code:constructorbinding/MyProperties[] +include-code::constructorbinding/MyProperties[] TIP: If you are upgrading a `Long` property, make sure to define the unit (using `@DurationUnit`) if it is not milliseconds. @@ -1090,12 +1111,13 @@ Doing so gives a transparent upgrade path while supporting a much richer format. [[features.external-config.typesafe-configuration-properties.conversion.periods]] -===== Converting Periods +==== Converting Periods + In addition to durations, Spring Boot can also work with `java.time.Period` type. The following formats can be used in application properties: * An regular `int` representation (using days as the default unit unless a `@PeriodUnit` has been specified) -* The standard ISO-8601 format {java-api}/java.base/java/time/Period.html#parse(java.lang.CharSequence)[used by `java.time.Period`] +* The standard ISO-8601 format {apiref-openjdk}/java.base/java/time/Period.html#parse(java.lang.CharSequence)[used by `java.time.Period`] * A simpler format where the value and the unit pairs are coupled (`1y3d` means 1 year and 3 days) The following units are supported with the simple format: @@ -1110,7 +1132,8 @@ NOTE: The `java.time.Period` type never actually stores the number of weeks, it [[features.external-config.typesafe-configuration-properties.conversion.data-sizes]] -===== Converting Data Sizes +==== Converting Data Sizes + Spring Framework has a `DataSize` value type that expresses a size in bytes. If you expose a `DataSize` property, the following formats in application properties are available: @@ -1119,7 +1142,7 @@ If you expose a `DataSize` property, the following formats in application proper Consider the following example: -include::code:javabeanbinding/MyProperties[] +include-code::javabeanbinding/MyProperties[] To specify a buffer size of 10 megabytes, `10` and `10MB` are equivalent. A size threshold of 256 bytes can be specified as `256` or `256B`. @@ -1137,7 +1160,7 @@ The default unit is bytes and can be overridden using `@DataSizeUnit` as illustr If you prefer to use constructor binding, the same properties can be exposed, as shown in the following example: -include::code:constructorbinding/MyProperties[] +include-code::constructorbinding/MyProperties[] TIP: If you are upgrading a `Long` property, make sure to define the unit (using `@DataSizeUnit`) if it is not bytes. Doing so gives a transparent upgrade path while supporting a much richer format. @@ -1145,19 +1168,20 @@ Doing so gives a transparent upgrade path while supporting a much richer format. [[features.external-config.typesafe-configuration-properties.validation]] -==== @ConfigurationProperties Validation +=== @ConfigurationProperties Validation + Spring Boot attempts to validate `@ConfigurationProperties` classes whenever they are annotated with Spring's `@Validated` annotation. You can use JSR-303 `jakarta.validation` constraint annotations directly on your configuration class. To do so, ensure that a compliant JSR-303 implementation is on your classpath and then add constraint annotations to your fields, as shown in the following example: -include::code:MyProperties[] +include-code::MyProperties[] TIP: You can also trigger validation by annotating the `@Bean` method that creates the configuration properties with `@Validated`. To ensure that validation is always triggered for nested properties, even when no properties are found, the associated field must be annotated with `@Valid`. The following example builds on the preceding `MyProperties` example: -include::code:nested/MyProperties[] +include-code::nested/MyProperties[] You can also add a custom Spring `Validator` by creating a bean definition called `configurationPropertiesValidator`. The `@Bean` method should be declared `static`. @@ -1166,12 +1190,13 @@ Doing so avoids any problems that may be caused by early instantiation. TIP: The `spring-boot-actuator` module includes an endpoint that exposes all `@ConfigurationProperties` beans. Point your web browser to `/actuator/configprops` or use the equivalent JMX endpoint. -See the "<>" section for details. +See the "xref:actuator/endpoints.adoc[Production ready features]" section for details. [[features.external-config.typesafe-configuration-properties.vs-value-annotation]] -==== @ConfigurationProperties vs. @Value +=== @ConfigurationProperties vs. @Value + The `@Value` annotation is a core container feature, and it does not provide the same features as type-safe configuration properties. The following table summarizes the features that are supported by `@ConfigurationProperties` and `@Value`: @@ -1179,11 +1204,11 @@ The following table summarizes the features that are supported by `@Configuratio |=== | Feature |`@ConfigurationProperties` |`@Value` -| <> +| xref:features/external-config.adoc#features.external-config.typesafe-configuration-properties.relaxed-binding[Relaxed binding] | Yes -| Limited (see <>) +| Limited (see xref:features/external-config.adoc#features.external-config.typesafe-configuration-properties.vs-value-annotation.note[note below]) -| <> +| xref:specification:configuration-metadata/index.adoc[Meta-data support] | Yes | No @@ -1196,7 +1221,7 @@ The following table summarizes the features that are supported by `@Configuratio [NOTE] ==== If you do want to use `@Value`, we recommend that you refer to property names using their canonical form (kebab-case using only lowercase letters). -This will allow Spring Boot to use the same logic as it does when <> `@ConfigurationProperties`. +This will allow Spring Boot to use the same logic as it does when xref:features/external-config.adoc#features.external-config.typesafe-configuration-properties.relaxed-binding[relaxed binding] `@ConfigurationProperties`. For example, `@Value("${demo.item-price}")` will pick up `demo.item-price` and `demo.itemPrice` forms from the `application.properties` file, as well as `DEMO_ITEMPRICE` from the system environment. If you used `@Value("${demo.itemPrice}")` instead, `demo.item-price` and `DEMO_ITEMPRICE` would not be considered. @@ -1205,6 +1230,6 @@ If you used `@Value("${demo.itemPrice}")` instead, `demo.item-price` and `DEMO_I If you define a set of configuration keys for your own components, we recommend you group them in a POJO annotated with `@ConfigurationProperties`. Doing so will provide you with structured, type-safe object that you can inject into your own beans. -`SpEL` expressions from <> are not processed at time of parsing these files and populating the environment. +`SpEL` expressions from xref:features/external-config.adoc#features.external-config.files[application property files] are not processed at time of parsing these files and populating the environment. However, it is possible to write a `SpEL` expression in `@Value`. If the value of a property from an application property file is a `SpEL` expression, it will be evaluated when consumed through `@Value`. diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/index.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/index.adoc new file mode 100644 index 0000000000..77b77b7f87 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/index.adoc @@ -0,0 +1,7 @@ +[[features]] += Core Features + +This section dives into the details of Spring Boot. +Here you can learn about the key features that you may want to use and customize. +If you have not already done so, you might want to read the "xref:tutorial:index.adoc[Tutoral]" and "xref:using/index.adoc[Developing with Spring Boot]" sections, so that you have a good grounding of the basics. + diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/internationalization.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/internationalization.adoc similarity index 74% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/internationalization.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/internationalization.adoc index bc0b7c43a4..0f27a5222b 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/internationalization.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/internationalization.adoc @@ -1,5 +1,6 @@ [[features.internationalization]] -== Internationalization += Internationalization + Spring Boot supports localized messages so that your application can cater to users of different language preferences. By default, Spring Boot looks for the presence of a `messages` resource bundle at the root of the classpath. @@ -9,14 +10,14 @@ If no properties file is found that matches any of the configured base names, th The basename of the resource bundle as well as several other attributes can be configured using the `spring.messages` namespace, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - messages: - basename: "messages,config.i18n.messages" - fallback-to-system-locale: false +spring: + messages: + basename: "messages,config.i18n.messages" + fallback-to-system-locale: false ---- TIP: `spring.messages.basename` supports comma-separated list of locations, either a package qualifier or a resource resolved from the classpath root. -See {spring-boot-autoconfigure-module-code}/context/MessageSourceProperties.java[`MessageSourceProperties`] for more supported options. +See {code-spring-boot-autoconfigure-src}/context/MessageSourceProperties.java[`MessageSourceProperties`] for more supported options. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/json.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/json.adoc similarity index 73% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/json.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/json.adoc index 0170a669d9..1dfd6d1ce1 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/json.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/json.adoc @@ -1,5 +1,6 @@ [[features.json]] -== JSON += JSON + Spring Boot provides integration with three JSON mapping libraries: - Gson @@ -11,37 +12,40 @@ Jackson is the preferred and default library. [[features.json.jackson]] -=== Jackson +== Jackson + Auto-configuration for Jackson is provided and Jackson is part of `spring-boot-starter-json`. When Jackson is on the classpath an `ObjectMapper` bean is automatically configured. -Several configuration properties are provided for <>. +Several configuration properties are provided for xref:how-to:spring-mvc.adoc#howto.spring-mvc.customize-jackson-objectmapper[customizing the configuration of the `ObjectMapper`]. [[features.json.jackson.custom-serializers-and-deserializers]] -==== Custom Serializers and Deserializers +=== Custom Serializers and Deserializers + If you use Jackson to serialize and deserialize JSON data, you might want to write your own `JsonSerializer` and `JsonDeserializer` classes. Custom serializers are usually https://github.com/FasterXML/jackson-docs/wiki/JacksonHowToCustomSerializers[registered with Jackson through a module], but Spring Boot provides an alternative `@JsonComponent` annotation that makes it easier to directly register Spring Beans. You can use the `@JsonComponent` annotation directly on `JsonSerializer`, `JsonDeserializer` or `KeyDeserializer` implementations. You can also use it on classes that contain serializers/deserializers as inner classes, as shown in the following example: -include::code:MyJsonComponent[] +include-code::MyJsonComponent[] All `@JsonComponent` beans in the `ApplicationContext` are automatically registered with Jackson. Because `@JsonComponent` is meta-annotated with `@Component`, the usual component-scanning rules apply. -Spring Boot also provides {spring-boot-module-code}/jackson/JsonObjectSerializer.java[`JsonObjectSerializer`] and {spring-boot-module-code}/jackson/JsonObjectDeserializer.java[`JsonObjectDeserializer`] base classes that provide useful alternatives to the standard Jackson versions when serializing objects. -See {spring-boot-module-api}/jackson/JsonObjectSerializer.html[`JsonObjectSerializer`] and {spring-boot-module-api}/jackson/JsonObjectDeserializer.html[`JsonObjectDeserializer`] in the Javadoc for details. +Spring Boot also provides {code-spring-boot-src}/jackson/JsonObjectSerializer.java[`JsonObjectSerializer`] and {code-spring-boot-src}/jackson/JsonObjectDeserializer.java[`JsonObjectDeserializer`] base classes that provide useful alternatives to the standard Jackson versions when serializing objects. +See xref:api:java/org/springframework/boot/jackson/JsonObjectSerializer.html[`JsonObjectSerializer`] and xref:api:java/org/springframework/boot/jackson/JsonObjectDeserializer.html[`JsonObjectDeserializer`] in the Javadoc for details. The example above can be rewritten to use `JsonObjectSerializer`/`JsonObjectDeserializer` as follows: -include::code:object/MyJsonComponent[] +include-code::object/MyJsonComponent[] [[features.json.jackson.mixins]] -==== Mixins +=== Mixins + Jackson has support for mixins that can be used to mix additional annotations into those already declared on a target class. Spring Boot's Jackson auto-configuration will scan your application's packages for classes annotated with `@JsonMixin` and register them with the auto-configured `ObjectMapper`. The registration is performed by Spring Boot's `JsonMixinModule`. @@ -49,7 +53,8 @@ The registration is performed by Spring Boot's `JsonMixinModule`. [[features.json.gson]] -=== Gson +== Gson + Auto-configuration for Gson is provided. When Gson is on the classpath a `Gson` bean is automatically configured. Several `+spring.gson.*+` configuration properties are provided for customizing the configuration. @@ -58,7 +63,8 @@ To take more control, one or more `GsonBuilderCustomizer` beans can be used. [[features.json.json-b]] -=== JSON-B +== JSON-B + Auto-configuration for JSON-B is provided. When the JSON-B API and an implementation are on the classpath a `Jsonb` bean will be automatically configured. The preferred JSON-B implementation is Eclipse Yasson for which dependency management is provided. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/kotlin.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/kotlin.adoc similarity index 75% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/kotlin.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/kotlin.adoc index a50eb957cc..38b3d3edf4 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/kotlin.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/kotlin.adoc @@ -1,9 +1,10 @@ [[features.kotlin]] -== Kotlin Support -https://kotlinlang.org[Kotlin] is a statically-typed language targeting the JVM (and other platforms) which allows writing concise and elegant code while providing {kotlin-docs}java-interop.html[interoperability] with existing libraries written in Java. += Kotlin Support + +https://kotlinlang.org[Kotlin] is a statically-typed language targeting the JVM (and other platforms) which allows writing concise and elegant code while providing {url-kotlin-docs}/java-interop.html[interoperability] with existing libraries written in Java. Spring Boot provides Kotlin support by leveraging the support in other Spring projects such as Spring Framework, Spring Data, and Reactor. -See the {spring-framework-docs}/languages/kotlin.html[Spring Framework Kotlin support documentation] for more information. +See the {url-spring-framework-docs}/languages/kotlin.html[Spring Framework Kotlin support documentation] for more information. The easiest way to start with Spring Boot and Kotlin is to follow https://spring.io/guides/tutorials/spring-boot-kotlin/[this comprehensive tutorial]. You can create new Kotlin projects by using https://start.spring.io/#!language=kotlin[start.spring.io]. @@ -12,12 +13,13 @@ Feel free to join the #spring channel of https://slack.kotlinlang.org/[Kotlin Sl [[features.kotlin.requirements]] -=== Requirements +== Requirements + Spring Boot requires at least Kotlin 1.7.x and manages a suitable Kotlin version through dependency management. To use Kotlin, `org.jetbrains.kotlin:kotlin-stdlib` and `org.jetbrains.kotlin:kotlin-reflect` must be present on the classpath. The `kotlin-stdlib` variants `kotlin-stdlib-jdk7` and `kotlin-stdlib-jdk8` can also be used. -Since https://discuss.kotlinlang.org/t/classes-final-by-default/166[Kotlin classes are final by default], you are likely to want to configure {kotlin-docs}compiler-plugins.html#spring-support[kotlin-spring] plugin in order to automatically open Spring-annotated classes so that they can be proxied. +Since https://discuss.kotlinlang.org/t/classes-final-by-default/166[Kotlin classes are final by default], you are likely to want to configure {url-kotlin-docs}/compiler-plugins.html#spring-support[kotlin-spring] plugin in order to automatically open Spring-annotated classes so that they can be proxied. https://github.com/FasterXML/jackson-module-kotlin[Jackson's Kotlin module] is required for serializing / deserializing JSON data in Kotlin. It is automatically registered when found on the classpath. @@ -28,15 +30,16 @@ TIP: These dependencies and plugins are provided by default if one bootstraps a [[features.kotlin.null-safety]] -=== Null-safety -One of Kotlin's key features is {kotlin-docs}null-safety.html[null-safety]. +== Null-safety + +One of Kotlin's key features is {url-kotlin-docs}/null-safety.html[null-safety]. It deals with `null` values at compile time rather than deferring the problem to runtime and encountering a `NullPointerException`. This helps to eliminate a common source of bugs without paying the cost of wrappers like `Optional`. Kotlin also allows using functional constructs with nullable values as described in this https://www.baeldung.com/kotlin-null-safety[comprehensive guide to null-safety in Kotlin]. Although Java does not allow one to express null-safety in its type system, Spring Framework, Spring Data, and Reactor now provide null-safety of their API through tooling-friendly annotations. -By default, types from Java APIs used in Kotlin are recognized as {kotlin-docs}java-interop.html#null-safety-and-platform-types[platform types] for which null-checks are relaxed. -{kotlin-docs}java-interop.html#jsr-305-support[Kotlin's support for JSR 305 annotations] combined with nullability annotations provide null-safety for the related Spring API in Kotlin. +By default, types from Java APIs used in Kotlin are recognized as {url-kotlin-docs}/java-interop.html#null-safety-and-platform-types[platform types] for which null-checks are relaxed. +{url-kotlin-docs}/java-interop.html#jsr-305-support[Kotlin's support for JSR 305 annotations] combined with nullability annotations provide null-safety for the related Spring API in Kotlin. The JSR 305 checks can be configured by adding the `-Xjsr305` compiler flag with the following options: `-Xjsr305={strict|warn|ignore}`. The default behavior is the same as `-Xjsr305=warn`. @@ -44,47 +47,49 @@ The `strict` value is required to have null-safety taken in account in Kotlin ty WARNING: Generic type arguments, varargs and array elements nullability are not yet supported. See https://jira.spring.io/browse/SPR-15942[SPR-15942] for up-to-date information. -Also be aware that Spring Boot's own API is {github-issues}10712[not yet annotated]. +Also be aware that Spring Boot's own API is {url-github-issues}/10712[not yet annotated]. [[features.kotlin.api]] -=== Kotlin API +== Kotlin API [[features.kotlin.api.run-application]] -==== runApplication +=== runApplication + Spring Boot provides an idiomatic way to run an application with `runApplication(*args)` as shown in the following example: -[source,kotlin,indent=0,subs="verbatim"] +[source,kotlin] ---- - import org.springframework.boot.autoconfigure.SpringBootApplication - import org.springframework.boot.runApplication +import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.boot.runApplication - @SpringBootApplication - class MyApplication +@SpringBootApplication +class MyApplication - fun main(args: Array) { - runApplication(*args) - } +fun main(args: Array) { + runApplication(*args) +} ---- This is a drop-in replacement for `SpringApplication.run(MyApplication::class.java, *args)`. It also allows customization of the application as shown in the following example: -[source,kotlin,indent=0,subs="verbatim"] +[source,kotlin] ---- - runApplication(*args) { - setBannerMode(OFF) - } +runApplication(*args) { + setBannerMode(OFF) +} ---- [[features.kotlin.api.extensions]] -==== Extensions -Kotlin {kotlin-docs}extensions.html[extensions] provide the ability to extend existing classes with additional functionality. +=== Extensions + +Kotlin {url-kotlin-docs}/extensions.html[extensions] provide the ability to extend existing classes with additional functionality. The Spring Boot Kotlin API makes use of these extensions to add new Kotlin specific conveniences to existing APIs. `TestRestTemplate` extensions, similar to those provided by Spring Framework for `RestOperations` in Spring Framework, are provided. @@ -93,7 +98,8 @@ Among other things, the extensions make it possible to take advantage of Kotlin [[features.kotlin.dependency-management]] -=== Dependency management +== Dependency management + In order to avoid mixing different versions of Kotlin dependencies on the classpath, Spring Boot imports the Kotlin BOM. With Maven, the Kotlin version can be customized by setting the `kotlin.version` property and plugin management is provided for `kotlin-maven-plugin`. @@ -107,10 +113,11 @@ TIP: `org.jetbrains.kotlinx:kotlinx-coroutines-reactor` dependency is provided b [[features.kotlin.configuration-properties]] -=== @ConfigurationProperties -`@ConfigurationProperties` when used in combination with <> supports classes with immutable `val` properties as shown in the following example: +== @ConfigurationProperties -[source,kotlin,indent=0,subs="verbatim"] +`@ConfigurationProperties` when used in combination with xref:features/external-config.adoc#features.external-config.typesafe-configuration-properties.constructor-binding[constructor binding] supports classes with immutable `val` properties as shown in the following example: + +[source,kotlin] ---- @ConfigurationProperties("example.kotlin") data class KotlinExampleProperties( @@ -125,30 +132,32 @@ data class KotlinExampleProperties( } ---- -TIP: To generate <> using the annotation processor, {kotlin-docs}kapt.html[`kapt` should be configured] with the `spring-boot-configuration-processor` dependency. +TIP: To generate xref:specification:configuration-metadata/annotation-processor.adoc[your own metadata] using the annotation processor, {url-kotlin-docs}/kapt.html[`kapt` should be configured] with the `spring-boot-configuration-processor` dependency. Note that some features (such as detecting the default value or deprecated items) are not working due to limitations in the model kapt provides. [[features.kotlin.testing]] -=== Testing +== Testing + While it is possible to use JUnit 4 to test Kotlin code, JUnit 5 is provided by default and is recommended. JUnit 5 enables a test class to be instantiated once and reused for all of the class's tests. This makes it possible to use `@BeforeAll` and `@AfterAll` annotations on non-static methods, which is a good fit for Kotlin. To mock Kotlin classes, https://mockk.io/[MockK] is recommended. -If you need the `MockK` equivalent of the Mockito specific <>, you can use https://github.com/Ninja-Squad/springmockk[SpringMockK] which provides similar `@MockkBean` and `@SpykBean` annotations. +If you need the `MockK` equivalent of the Mockito specific xref:features/testing.adoc#features.testing.spring-boot-applications.mocking-beans[`@MockBean` and `@SpyBean` annotations], you can use https://github.com/Ninja-Squad/springmockk[SpringMockK] which provides similar `@MockkBean` and `@SpykBean` annotations. [[features.kotlin.resources]] -=== Resources +== Resources [[features.kotlin.resources.further-reading]] -==== Further reading -* {kotlin-docs}[Kotlin language reference] +=== Further reading + +* {url-kotlin-docs}[Kotlin language reference] * https://kotlinlang.slack.com/[Kotlin Slack] (with a dedicated #spring channel) * https://stackoverflow.com/questions/tagged/spring+kotlin[Stack Overflow with `spring` and `kotlin` tags] * https://try.kotlinlang.org/[Try Kotlin in your browser] @@ -163,7 +172,8 @@ If you need the `MockK` equivalent of the Mockito specific <=+` where `level` is one of TRACE, DEBUG, INFO, WARN, ERROR, FATAL, or OFF. The `root` logger can be configured by using `logging.level.root`. The following example shows potential logging settings in `application.properties`: -[source,properties,indent=0,subs="verbatim",configprops,role="primary"] -.Properties +[configprops,yaml] ---- - logging.level.root=warn - logging.level.org.springframework.web=debug - logging.level.org.hibernate=error ----- - -[source,properties,indent=0,subs="verbatim",role="secondary"] -.Yaml ----- - logging: - level: - root: "warn" - org.springframework.web: "debug" - org.hibernate: "error" +logging: + level: + root: "warn" + org.springframework.web: "debug" + org.hibernate: "error" ---- It is also possible to set logging levels using environment variables. @@ -216,32 +215,33 @@ For example, `LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_WEB=DEBUG` will set `org.springf NOTE: The above approach will only work for package level logging. Since relaxed binding always converts environment variables to lowercase, it is not possible to configure logging for an individual class in this way. -If you need to configure logging for a class, you can use <> variable. +If you need to configure logging for a class, you can use xref:features/external-config.adoc#features.external-config.application-json[the `SPRING_APPLICATION_JSON`] variable. [[features.logging.log-groups]] -=== Log Groups +== Log Groups + It is often useful to be able to group related loggers together so that they can all be configured at the same time. For example, you might commonly change the logging levels for _all_ Tomcat related loggers, but you can not easily remember top level packages. To help with this, Spring Boot allows you to define logging groups in your Spring `Environment`. For example, here is how you could define a "`tomcat`" group by adding it to your `application.properties`: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - logging: - group: - tomcat: "org.apache.catalina,org.apache.coyote,org.apache.tomcat" +logging: + group: + tomcat: "org.apache.catalina,org.apache.coyote,org.apache.tomcat" ---- Once defined, you can change the level for all the loggers in the group with a single line: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - logging: - level: - tomcat: "trace" +logging: + level: + tomcat: "trace" ---- Spring Boot includes the following pre-defined logging groups that can be used out-of-the-box: @@ -260,7 +260,8 @@ Spring Boot includes the following pre-defined logging groups that can be used o [[features.logging.shutdown-hook]] -=== Using a Log Shutdown Hook +== Using a Log Shutdown Hook + In order to release logging resources when your application terminates, a shutdown hook that will trigger log system cleanup when the JVM exits is provided. This shutdown hook is registered automatically unless your application is deployed as a war file. If your application has complex context hierarchies the shutdown hook may not meet your needs. @@ -270,16 +271,17 @@ You can use the configprop:logging.register-shutdown-hook[] property to disable Setting it to `false` will disable the registration. You can set the property in your `application.properties` or `application.yaml` file: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - logging: - register-shutdown-hook: false +logging: + register-shutdown-hook: false ---- [[features.logging.custom-log-configuration]] -=== Custom Log Configuration +== Custom Log Configuration + The various logging systems can be activated by including the appropriate libraries on the classpath and can be further customized by providing a suitable configuration file in the root of the classpath or in a location specified by the following Spring `Environment` property: configprop:logging.config[]. You can force Spring Boot to use a particular logging system by using the `org.springframework.boot.logging.LoggingSystem` system property. @@ -396,13 +398,13 @@ If you use Logback, the following properties are also transferred: All the supported logging systems can consult System properties when parsing their configuration files. See the default configurations in `spring-boot.jar` for examples: -* {spring-boot-code}/spring-boot-project/spring-boot/src/main/resources/org/springframework/boot/logging/logback/defaults.xml[Logback] -* {spring-boot-code}/spring-boot-project/spring-boot/src/main/resources/org/springframework/boot/logging/log4j2/log4j2.xml[Log4j 2] -* {spring-boot-code}/spring-boot-project/spring-boot/src/main/resources/org/springframework/boot/logging/java/logging-file.properties[Java Util logging] +* {code-spring-boot}/spring-boot-project/spring-boot/src/main/resources/org/springframework/boot/logging/logback/defaults.xml[Logback] +* {code-spring-boot}/spring-boot-project/spring-boot/src/main/resources/org/springframework/boot/logging/log4j2/log4j2.xml[Log4j 2] +* {code-spring-boot}/spring-boot-project/spring-boot/src/main/resources/org/springframework/boot/logging/java/logging-file.properties[Java Util logging] [TIP] ==== -If you want to use a placeholder in a logging property, you should use <> and not the syntax of the underlying framework. +If you want to use a placeholder in a logging property, you should use xref:features/external-config.adoc#features.external-config.files.property-placeholders[Spring Boot's syntax] and not the syntax of the underlying framework. Notably, if you use Logback, you should use `:` as the delimiter between a property name and its default value and not use `:-`. ==== @@ -411,17 +413,18 @@ Notably, if you use Logback, you should use `:` as the delimiter between a prope You can add MDC and other ad-hoc content to log lines by overriding only the `LOG_LEVEL_PATTERN` (or `logging.pattern.level` with Logback). For example, if you use `logging.pattern.level=user:%X\{user} %5p`, then the default log format contains an MDC entry for "user", if it exists, as shown in the following example. -[indent=0] +[source] ---- - 2019-08-30 12:30:04.031 user:someone INFO 22174 --- [ nio-8080-exec-0] demo.Controller - Handling authenticated request +2019-08-30 12:30:04.031 user:someone INFO 22174 --- [ nio-8080-exec-0] demo.Controller +Handling authenticated request ---- ==== [[features.logging.logback-extensions]] -=== Logback Extensions +== Logback Extensions + Spring Boot includes a number of extensions to Logback that can help with advanced configuration. You can use these extensions in your `logback-spring.xml` configuration file. @@ -431,43 +434,45 @@ You need to either use `logback-spring.xml` or define a configprop:logging.confi WARNING: The extensions cannot be used with Logback's https://logback.qos.ch/manual/configuration.html#autoScan[configuration scanning]. If you attempt to do so, making changes to the configuration file results in an error similar to one of the following being logged: -[indent=0] +[source] ---- - ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProperty], current ElementPath is [[configuration][springProperty]] - ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProfile], current ElementPath is [[configuration][springProfile]] +ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProperty], current ElementPath is [[configuration][springProperty]] +ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProfile], current ElementPath is [[configuration][springProfile]] ---- [[features.logging.logback-extensions.profile-specific]] -==== Profile-specific Configuration +=== Profile-specific Configuration + The `` tag lets you optionally include or exclude sections of configuration based on the active Spring profiles. Profile sections are supported anywhere within the `` element. Use the `name` attribute to specify which profile accepts the configuration. The `` tag can contain a profile name (for example `staging`) or a profile expression. A profile expression allows for more complicated profile logic to be expressed, for example `production & (eu-central | eu-west)`. -Check the {spring-framework-docs}/core/beans/environment.html#beans-definition-profiles-java[Spring Framework reference guide] for more details. +Check the {url-spring-framework-docs}/core/beans/environment.html#beans-definition-profiles-java[Spring Framework reference guide] for more details. The following listing shows three sample profiles: -[source,xml,subs="verbatim",indent=0] +[source,xml] ---- - - - + + + - - - + + + - - - + + + ---- [[features.logging.logback-extensions.environment-properties]] -==== Environment Properties +=== Environment Properties + The `` tag lets you expose properties from the Spring `Environment` for use within Logback. Doing so can be useful if you want to access values from your `application.properties` file in your Logback configuration. The tag works in a similar way to Logback's standard `` tag. @@ -476,14 +481,14 @@ If you need to store the property somewhere other than in `local` scope, you can If you need a fallback value (in case the property is not set in the `Environment`), you can use the `defaultValue` attribute. The following example shows how to expose properties for use within Logback: -[source,xml,subs="verbatim",indent=0] +[source,xml] ---- - - - ${fluentHost} - ... - + + + ${fluentHost} + ... + ---- NOTE: The `source` must be specified in kebab case (such as `my.property-name`). @@ -492,7 +497,8 @@ However, properties can be added to the `Environment` by using the relaxed rules [[features.logging.log4j2-extensions]] -=== Log4j2 Extensions +== Log4j2 Extensions + Spring Boot includes a number of extensions to Log4j2 that can help with advanced configuration. You can use these extensions in any `log4j2-spring.xml` configuration file. @@ -505,44 +511,46 @@ You should make sure not to include the `org.apache.logging.log4j:log4j-spring-b [[features.logging.log4j2-extensions.profile-specific]] -==== Profile-specific Configuration +=== Profile-specific Configuration + The `` tag lets you optionally include or exclude sections of configuration based on the active Spring profiles. Profile sections are supported anywhere within the `` element. Use the `name` attribute to specify which profile accepts the configuration. The `` tag can contain a profile name (for example `staging`) or a profile expression. A profile expression allows for more complicated profile logic to be expressed, for example `production & (eu-central | eu-west)`. -Check the {spring-framework-docs}/core/beans/environment.html#beans-definition-profiles-java[Spring Framework reference guide] for more details. +Check the {url-spring-framework-docs}/core/beans/environment.html#beans-definition-profiles-java[Spring Framework reference guide] for more details. The following listing shows three sample profiles: -[source,xml,subs="verbatim",indent=0] +[source,xml] ---- - - - + + + - - - + + + - - - + + + ---- [[features.logging.log4j2-extensions.environment-properties-lookup]] -==== Environment Properties Lookup +=== Environment Properties Lookup + If you want to refer to properties from your Spring `Environment` within your Log4j2 configuration you can use `spring:` prefixed https://logging.apache.org/log4j/2.x/manual/lookups.html[lookups]. Doing so can be useful if you want to access values from your `application.properties` file in your Log4j2 configuration. The following example shows how to set a Log4j2 property named `applicationName` that reads `spring.application.name` from the Spring `Environment`: -[source,xml,subs="verbatim",indent=0] +[source,xml] ---- - - ${spring:spring.application.name} - + + ${spring:spring.application.name} + ---- NOTE: The lookup key should be specified in kebab case (such as `my.property-name`). @@ -550,7 +558,8 @@ NOTE: The lookup key should be specified in kebab case (such as `my.property-nam [[features.logging.log4j2-extensions.environment-property-source]] -==== Log4j2 System Properties +=== Log4j2 System Properties + Log4j2 supports a number of https://logging.apache.org/log4j/2.x/manual/configuration.html#SystemProperties[System Properties] that can be used to configure various items. For example, the `log4j2.skipJansi` system property can be used to configure if the `ConsoleAppender` will try to use a https://github.com/fusesource/jansi[Jansi] output stream on Windows. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/profiles.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/profiles.adoc similarity index 67% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/profiles.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/profiles.adoc index b76554a076..b1e76d0e1e 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/profiles.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/profiles.adoc @@ -1,9 +1,10 @@ [[features.profiles]] -== Profiles += Profiles + Spring Profiles provide a way to segregate parts of your application configuration and make it be available only in certain environments. Any `@Component`, `@Configuration` or `@ConfigurationProperties` can be marked with `@Profile` to limit when it is loaded, as shown in the following example: -include::code:ProductionConfiguration[] +include-code::ProductionConfiguration[] NOTE: If `@ConfigurationProperties` beans are registered through `@EnableConfigurationProperties` instead of automatic scanning, the `@Profile` annotation needs to be specified on the `@Configuration` class that has the `@EnableConfigurationProperties` annotation. In the case where `@ConfigurationProperties` are scanned, `@Profile` can be specified on the `@ConfigurationProperties` class itself. @@ -12,11 +13,11 @@ You can use a configprop:spring.profiles.active[] `Environment` property to spec You can specify the property in any of the ways described earlier in this chapter. For example, you could include it in your `application.properties`, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - profiles: - active: "dev,hsqldb" +spring: + profiles: + active: "dev,hsqldb" ---- You could also specify it on the command line by using the following switch: `--spring.profiles.active=dev,hsqldb`. @@ -24,66 +25,68 @@ You could also specify it on the command line by using the following switch: `-- If no profile is active, a default profile is enabled. The name of the default profile is `default` and it can be tuned using the configprop:spring.profiles.default[] `Environment` property, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - profiles: - default: "none" +spring: + profiles: + default: "none" ---- `spring.profiles.active` and `spring.profiles.default` can only be used in non-profile specific documents. -This means they cannot be included in <> or <> by `spring.config.activate.on-profile`. +This means they cannot be included in xref:features/external-config.adoc#features.external-config.files.profile-specific[profile specific files] or xref:features/external-config.adoc#features.external-config.files.activation-properties[documents activated] by `spring.config.activate.on-profile`. For example, the second document configuration is invalid: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - # this document is valid - spring: - profiles: - active: "prod" - --- - # this document is invalid - spring: - config: - activate: - on-profile: "prod" - profiles: - active: "metrics" +# this document is valid +spring: + profiles: + active: "prod" +--- +# this document is invalid +spring: + config: + activate: + on-profile: "prod" + profiles: + active: "metrics" ---- [[features.profiles.adding-active-profiles]] -=== Adding Active Profiles +== Adding Active Profiles + The configprop:spring.profiles.active[] property follows the same ordering rules as other properties: The highest `PropertySource` wins. This means that you can specify active profiles in `application.properties` and then *replace* them by using the command line switch. Sometimes, it is useful to have properties that *add* to the active profiles rather than replace them. The `spring.profiles.include` property can be used to add active profiles on top of those activated by the configprop:spring.profiles.active[] property. The `SpringApplication` entry point also has a Java API for setting additional profiles. -See the `setAdditionalProfiles()` method in {spring-boot-module-api}/SpringApplication.html[SpringApplication]. +See the `setAdditionalProfiles()` method in xref:api:java/org/springframework/boot/SpringApplication.html[SpringApplication]. For example, when an application with the following properties is run, the common and local profiles will be activated even when it runs using the `--spring.profiles.active` switch: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - profiles: - include: - - "common" - - "local" +spring: + profiles: + include: + - "common" + - "local" ---- WARNING: Similar to `spring.profiles.active`, `spring.profiles.include` can only be used in non-profile specific documents. -This means it cannot be included in <> or <> by `spring.config.activate.on-profile`. +This means it cannot be included in xref:features/external-config.adoc#features.external-config.files.profile-specific[profile specific files] or xref:features/external-config.adoc#features.external-config.files.activation-properties[documents activated] by `spring.config.activate.on-profile`. -Profile groups, which are described in the <> can also be used to add active profiles if a given profile is active. +Profile groups, which are described in the xref:features/profiles.adoc#features.profiles.groups[next section] can also be used to add active profiles if a given profile is active. [[features.profiles.groups]] -=== Profile Groups +== Profile Groups + Occasionally the profiles that you define and use in your application are too fine-grained and become cumbersome to use. For example, you might have `proddb` and `prodmq` profiles that you use to enable database and messaging features independently. @@ -92,14 +95,14 @@ A profile group allows you to define a logical name for a related group of profi For example, we can create a `production` group that consists of our `proddb` and `prodmq` profiles. -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops,yaml] ---- - spring: - profiles: - group: - production: - - "proddb" - - "prodmq" +spring: + profiles: + group: + production: + - "proddb" + - "prodmq" ---- Our application can now be started using `--spring.profiles.active=production` to activate the `production`, `proddb` and `prodmq` profiles in one hit. @@ -107,13 +110,15 @@ Our application can now be started using `--spring.profiles.active=production` t [[features.profiles.programmatically-setting-profiles]] -=== Programmatically Setting Profiles +== Programmatically Setting Profiles + You can programmatically set active profiles by calling `SpringApplication.setAdditionalProfiles(...)` before your application runs. It is also possible to activate profiles by using Spring's `ConfigurableEnvironment` interface. [[features.profiles.profile-specific-configuration-files]] -=== Profile-specific Configuration Files +== Profile-specific Configuration Files + Profile-specific variants of both `application.properties` (or `application.yaml`) and files referenced through `@ConfigurationProperties` are considered as files and loaded. -See "<>" for details. +See "xref:features/external-config.adoc#features.external-config.files.profile-specific[Profile Specific Files]" for details. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/spring-application.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/spring-application.adoc similarity index 81% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/spring-application.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/spring-application.adoc index feef506659..fb6fe4df08 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/spring-application.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/spring-application.adoc @@ -1,21 +1,22 @@ [[features.spring-application]] -== SpringApplication += SpringApplication + The `SpringApplication` class provides a convenient way to bootstrap a Spring application that is started from a `main()` method. In many situations, you can delegate to the static `SpringApplication.run` method, as shown in the following example: -include::code:MyApplication[] +include-code::MyApplication[] When your application starts, you should see something similar to the following output: -[indent=0,subs="verbatim,attributes"] +[source,subs="verbatim,attributes"] ---- -include::{spring-application-output}[] +include::ROOT:partial$application/spring-application.txt[] ---- By default, `INFO` logging messages are shown, including some relevant startup details, such as the user that launched the application. -If you need a log level other than `INFO`, you can set it, as described in <>. +If you need a log level other than `INFO`, you can set it, as described in xref:features/logging.adoc#features.logging.log-levels[Log Levels]. The application version is determined using the implementation version from the main application class's package. Startup information logging can be turned off by setting `spring.main.log-startup-info` to `false`. This will also turn off logging of the application's active profiles. @@ -25,41 +26,43 @@ TIP: To add additional logging during startup, you can override `logStartupInfo( [[features.spring-application.startup-failure]] -=== Startup Failure +== Startup Failure + If your application fails to start, registered `FailureAnalyzers` get a chance to provide a dedicated error message and a concrete action to fix the problem. For instance, if you start a web application on port `8080` and that port is already in use, you should see something similar to the following message: -[indent=0] +[source] ---- - *************************** - APPLICATION FAILED TO START - *************************** +*************************** +APPLICATION FAILED TO START +*************************** - Description: +Description: - Embedded servlet container failed to start. Port 8080 was already in use. +Embedded servlet container failed to start. Port 8080 was already in use. - Action: +Action: - Identify and stop the process that is listening on port 8080 or configure this application to listen on another port. +Identify and stop the process that is listening on port 8080 or configure this application to listen on another port. ---- -NOTE: Spring Boot provides numerous `FailureAnalyzer` implementations, and you can <>. +NOTE: Spring Boot provides numerous `FailureAnalyzer` implementations, and you can xref:how-to:application.adoc#howto.application.failure-analyzer[add your own]. If no failure analyzers are able to handle the exception, you can still display the full conditions report to better understand what went wrong. -To do so, you need to <> or <> for `org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener`. +To do so, you need to xref:features/external-config.adoc[enable the `debug` property] or xref:features/logging.adoc#features.logging.log-levels[enable `DEBUG` logging] for `org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener`. For instance, if you are running your application by using `java -jar`, you can enable the `debug` property as follows: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ java -jar myproject-0.0.1-SNAPSHOT.jar --debug +$ java -jar myproject-0.0.1-SNAPSHOT.jar --debug ---- [[features.spring-application.lazy-initialization]] -=== Lazy Initialization +== Lazy Initialization + `SpringApplication` allows an application to be initialized lazily. When lazy initialization is enabled, beans are created as they are needed rather than during application startup. As a result, enabling lazy initialization can reduce the time that it takes your application to start. @@ -73,11 +76,11 @@ For these reasons, lazy initialization is not enabled by default and it is recom Lazy initialization can be enabled programmatically using the `lazyInitialization` method on `SpringApplicationBuilder` or the `setLazyInitialization` method on `SpringApplication`. Alternatively, it can be enabled using the configprop:spring.main.lazy-initialization[] property as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - main: - lazy-initialization: true +spring: + main: + lazy-initialization: true ---- TIP: If you want to disable lazy initialization for certain beans while using lazy initialization for the rest of the application, you can explicitly set their lazy attribute to false using the `@Lazy(false)` annotation. @@ -85,7 +88,8 @@ TIP: If you want to disable lazy initialization for certain beans while using la [[features.spring-application.banner]] -=== Customizing the Banner +== Customizing the Banner + The banner that is printed on start up can be changed by adding a `banner.txt` file to your classpath or by setting the configprop:spring.banner.location[] property to the location of such a file. If the file has an encoding other than UTF-8, you can set `spring.banner.charset`. @@ -105,15 +109,15 @@ Inside your `banner.txt` file, you can use any key available in the `Environment | `${spring-boot.version}` | The Spring Boot version that you are using. - For example `{spring-boot-version}`. + For example `{version-spring-boot}`. | `${spring-boot.formatted-version}` | The Spring Boot version that you are using, formatted for display (surrounded with brackets and prefixed with `v`). - For example `(v{spring-boot-version})`. + For example `(v{version-spring-boot})`. | `${Ansi.NAME}` (or `${AnsiColor.NAME}`, `${AnsiBackground.NAME}`, `${AnsiStyle.NAME}`) | Where `NAME` is the name of an ANSI escape code. - See {spring-boot-module-code}/ansi/AnsiPropertySource.java[`AnsiPropertySource`] for details. + See {code-spring-boot-src}/ansi/AnsiPropertySource.java[`AnsiPropertySource`] for details. | `${application.title}` | The title of your application, as declared in `MANIFEST.MF`. @@ -140,38 +144,41 @@ This will initialize the `application.*` banner properties before building the c [[features.spring-application.customizing-spring-application]] -=== Customizing SpringApplication +== Customizing SpringApplication + If the `SpringApplication` defaults are not to your taste, you can instead create a local instance and customize it. For example, to turn off the banner, you could write: -include::code:MyApplication[] +include-code::MyApplication[] NOTE: The constructor arguments passed to `SpringApplication` are configuration sources for Spring beans. In most cases, these are references to `@Configuration` classes, but they could also be direct references `@Component` classes. It is also possible to configure the `SpringApplication` by using an `application.properties` file. -See _<>_ for details. +See _xref:features/external-config.adoc[Externalized Configuration]_ for details. -For a complete list of the configuration options, see the {spring-boot-module-api}/SpringApplication.html[`SpringApplication` Javadoc]. +For a complete list of the configuration options, see the xref:api:java/org/springframework/boot/SpringApplication.html[`SpringApplication` Javadoc]. [[features.spring-application.fluent-builder-api]] -=== Fluent Builder API +== Fluent Builder API + If you need to build an `ApplicationContext` hierarchy (multiple contexts with a parent/child relationship) or if you prefer using a "`fluent`" builder API, you can use the `SpringApplicationBuilder`. The `SpringApplicationBuilder` lets you chain together multiple method calls and includes `parent` and `child` methods that let you create a hierarchy, as shown in the following example: -include::code:MyApplication[tag=*] +include-code::MyApplication[tag=*] NOTE: There are some restrictions when creating an `ApplicationContext` hierarchy. For example, Web components *must* be contained within the child context, and the same `Environment` is used for both parent and child contexts. -See the {spring-boot-module-api}/builder/SpringApplicationBuilder.html[`SpringApplicationBuilder` Javadoc] for full details. +See the xref:api:java/org/springframework/boot/builder/SpringApplicationBuilder.html[`SpringApplicationBuilder` Javadoc] for full details. [[features.spring-application.application-availability]] -=== Application Availability +== Application Availability + When deployed on platforms, applications can provide information about their availability to the platform using infrastructure such as https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/[Kubernetes Probes]. Spring Boot includes out-of-the box support for the commonly used "`liveness`" and "`readiness`" availability states. If you are using Spring Boot's "`actuator`" support then these states are exposed as health endpoint groups. @@ -181,52 +188,56 @@ In addition, you can also obtain availability states by injecting the `Applicati [[features.spring-application.application-availability.liveness]] -==== Liveness State +=== Liveness State + The "`Liveness`" state of an application tells whether its internal state allows it to work correctly, or recover by itself if it is currently failing. A broken "`Liveness`" state means that the application is in a state that it cannot recover from, and the infrastructure should restart the application. -NOTE: In general, the "Liveness" state should not be based on external checks, such as <>. +NOTE: In general, the "Liveness" state should not be based on external checks, such as xref:actuator/endpoints.adoc#actuator.endpoints.health[Health checks]. If it did, a failing external system (a database, a Web API, an external cache) would trigger massive restarts and cascading failures across the platform. The internal state of Spring Boot applications is mostly represented by the Spring `ApplicationContext`. If the application context has started successfully, Spring Boot assumes that the application is in a valid state. -An application is considered live as soon as the context has been refreshed, see <>. +An application is considered live as soon as the context has been refreshed, see xref:features/spring-application.adoc#features.spring-application.application-events-and-listeners[Spring Boot application lifecycle and related Application Events]. [[features.spring-application.application-availability.readiness]] -==== Readiness State +=== Readiness State + The "`Readiness`" state of an application tells whether the application is ready to handle traffic. A failing "`Readiness`" state tells the platform that it should not route traffic to the application for now. This typically happens during startup, while `CommandLineRunner` and `ApplicationRunner` components are being processed, or at any time if the application decides that it is too busy for additional traffic. -An application is considered ready as soon as application and command-line runners have been called, see <>. +An application is considered ready as soon as application and command-line runners have been called, see xref:features/spring-application.adoc#features.spring-application.application-events-and-listeners[Spring Boot application lifecycle and related Application Events]. TIP: Tasks expected to run during startup should be executed by `CommandLineRunner` and `ApplicationRunner` components instead of using Spring component lifecycle callbacks such as `@PostConstruct`. [[features.spring-application.application-availability.managing]] -==== Managing the Application Availability State +=== Managing the Application Availability State + Application components can retrieve the current availability state at any time, by injecting the `ApplicationAvailability` interface and calling methods on it. More often, applications will want to listen to state updates or update the state of the application. For example, we can export the "Readiness" state of the application to a file so that a Kubernetes "exec Probe" can look at this file: -include::code:MyReadinessStateExporter[] +include-code::MyReadinessStateExporter[] We can also update the state of the application, when the application breaks and cannot recover: -include::code:MyLocalCacheVerifier[] +include-code::MyLocalCacheVerifier[] -Spring Boot provides <>. -You can get more guidance about <>. +Spring Boot provides xref:actuator/endpoints.adoc#actuator.endpoints.kubernetes-probes[Kubernetes HTTP probes for "Liveness" and "Readiness" with Actuator Health Endpoints]. +You can get more guidance about xref:deployment/cloud.adoc#deployment.cloud.kubernetes[deploying Spring Boot applications on Kubernetes in the dedicated section]. [[features.spring-application.application-events-and-listeners]] -=== Application Events and Listeners -In addition to the usual Spring Framework events, such as {spring-framework-api}/context/event/ContextRefreshedEvent.html[`ContextRefreshedEvent`], a `SpringApplication` sends some additional application events. +== Application Events and Listeners + +In addition to the usual Spring Framework events, such as {url-spring-framework-javadoc}/org/springframework/context/event/ContextRefreshedEvent.html[`ContextRefreshedEvent`], a `SpringApplication` sends some additional application events. [NOTE] ==== @@ -235,9 +246,9 @@ You can register them with the `SpringApplication.addListeners(...)` method or t If you want those listeners to be registered automatically, regardless of the way the application is created, you can add a `META-INF/spring.factories` file to your project and reference your listener(s) by using the `org.springframework.context.ApplicationListener` key, as shown in the following example: -[indent=0] +[source] ---- - org.springframework.context.ApplicationListener=com.example.project.MyListener +org.springframework.context.ApplicationListener=com.example.project.MyListener ---- ==== @@ -250,7 +261,7 @@ Application events are sent in the following order, as your application runs: . An `ApplicationPreparedEvent` is sent just before the refresh is started but after bean definitions have been loaded. . An `ApplicationStartedEvent` is sent after the context has been refreshed but before any application and command-line runners have been called. . An `AvailabilityChangeEvent` is sent right after with `LivenessState.CORRECT` to indicate that the application is considered as live. -. An `ApplicationReadyEvent` is sent after any <> have been called. +. An `ApplicationReadyEvent` is sent after any xref:features/spring-application.adoc#features.spring-application.command-line-runner[application and command-line runners] have been called. . An `AvailabilityChangeEvent` is sent right after with `ReadinessState.ACCEPTING_TRAFFIC` to indicate that the application is ready to service requests. . An `ApplicationFailedEvent` is sent if there is an exception on startup. @@ -265,7 +276,7 @@ TIP: You often need not use application events, but it can be handy to know that Internally, Spring Boot uses events to handle a variety of tasks. NOTE: Event listeners should not run potentially lengthy tasks as they execute in the same thread by default. -Consider using <> instead. +Consider using xref:features/spring-application.adoc#features.spring-application.command-line-runner[application and command-line runners] instead. Application events are sent by using Spring Framework's event publishing mechanism. Part of this mechanism ensures that an event published to the listeners in a child context is also published to the listeners in any ancestor contexts. @@ -277,7 +288,8 @@ The context can be injected by implementing `ApplicationContextAware` or, if the [[features.spring-application.web-environment]] -=== Web Environment +== Web Environment + A `SpringApplication` attempts to create the right type of `ApplicationContext` on your behalf. The algorithm used to determine a `WebApplicationType` is the following: @@ -295,11 +307,12 @@ TIP: It is often desirable to call `setWebApplicationType(WebApplicationType.NON [[features.spring-application.application-arguments]] -=== Accessing Application Arguments +== Accessing Application Arguments + If you need to access the application arguments that were passed to `SpringApplication.run(...)`, you can inject a `org.springframework.boot.ApplicationArguments` bean. The `ApplicationArguments` interface provides access to both the raw `String[]` arguments as well as parsed `option` and `non-option` arguments, as shown in the following example: -include::code:MyBean[] +include-code::MyBean[] TIP: Spring Boot also registers a `CommandLinePropertySource` with the Spring `Environment`. This lets you also inject single application arguments by using the `@Value` annotation. @@ -307,7 +320,8 @@ This lets you also inject single application arguments by using the `@Value` ann [[features.spring-application.command-line-runner]] -=== Using the ApplicationRunner or CommandLineRunner +== Using the ApplicationRunner or CommandLineRunner + If you need to run some specific code once the `SpringApplication` has started, you can implement the `ApplicationRunner` or `CommandLineRunner` interfaces. Both interfaces work in the same way and offer a single `run` method, which is called just before `SpringApplication.run(...)` completes. @@ -317,21 +331,22 @@ NOTE: This contract is well suited for tasks that should run after application s The `CommandLineRunner` interfaces provides access to application arguments as a string array, whereas the `ApplicationRunner` uses the `ApplicationArguments` interface discussed earlier. The following example shows a `CommandLineRunner` with a `run` method: -include::code:MyCommandLineRunner[] +include-code::MyCommandLineRunner[] If several `CommandLineRunner` or `ApplicationRunner` beans are defined that must be called in a specific order, you can additionally implement the `org.springframework.core.Ordered` interface or use the `org.springframework.core.annotation.Order` annotation. [[features.spring-application.application-exit]] -=== Application Exit +== Application Exit + Each `SpringApplication` registers a shutdown hook with the JVM to ensure that the `ApplicationContext` closes gracefully on exit. All the standard Spring lifecycle callbacks (such as the `DisposableBean` interface or the `@PreDestroy` annotation) can be used. In addition, beans may implement the `org.springframework.boot.ExitCodeGenerator` interface if they wish to return a specific exit code when `SpringApplication.exit()` is called. This exit code can then be passed to `System.exit()` to return it as a status code, as shown in the following example: -include::code:MyApplication[] +include-code::MyApplication[] Also, the `ExitCodeGenerator` interface may be implemented by exceptions. When such an exception is encountered, Spring Boot returns the exit code provided by the implemented `getExitCode()` method. @@ -342,9 +357,10 @@ To control the order in which the generators are called, additionally implement [[features.spring-application.admin]] -=== Admin Features +== Admin Features + It is possible to enable admin-related features for the application by specifying the configprop:spring.application.admin.enabled[] property. -This exposes the {spring-boot-module-code}/admin/SpringApplicationAdminMXBean.java[`SpringApplicationAdminMXBean`] on the platform `MBeanServer`. +This exposes the {code-spring-boot-src}/admin/SpringApplicationAdminMXBean.java[`SpringApplicationAdminMXBean`] on the platform `MBeanServer`. You could use this feature to administer your Spring Boot application remotely. This feature could also be useful for any service wrapper implementation. @@ -353,35 +369,37 @@ TIP: If you want to know on which HTTP port the application is running, get the [[features.spring-application.startup-tracking]] -=== Application Startup tracking +== Application Startup tracking + During the application startup, the `SpringApplication` and the `ApplicationContext` perform many tasks related to the application lifecycle, the beans lifecycle or even processing application events. -With {spring-framework-api}/core/metrics/ApplicationStartup.html[`ApplicationStartup`], Spring Framework {spring-framework-docs}/core/beans/context-introduction.html#context-functionality-startup[allows you to track the application startup sequence with `StartupStep` objects]. +With {url-spring-framework-javadoc}/org/springframework/core/metrics/ApplicationStartup.html[`ApplicationStartup`], Spring Framework {url-spring-framework-docs}/core/beans/context-introduction.html#context-functionality-startup[allows you to track the application startup sequence with `StartupStep` objects]. This data can be collected for profiling purposes, or just to have a better understanding of an application startup process. You can choose an `ApplicationStartup` implementation when setting up the `SpringApplication` instance. For example, to use the `BufferingApplicationStartup`, you could write: -include::code:MyApplication[] +include-code::MyApplication[] The first available implementation, `FlightRecorderApplicationStartup` is provided by Spring Framework. It adds Spring-specific startup events to a Java Flight Recorder session and is meant for profiling applications and correlating their Spring context lifecycle with JVM events (such as allocations, GCs, class loading...). Once configured, you can record data by running the application with the Flight Recorder enabled: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ java -XX:StartFlightRecording:filename=recording.jfr,duration=10s -jar demo.jar +$ java -XX:StartFlightRecording:filename=recording.jfr,duration=10s -jar demo.jar ---- Spring Boot ships with the `BufferingApplicationStartup` variant; this implementation is meant for buffering the startup steps and draining them into an external metrics system. Applications can ask for the bean of type `BufferingApplicationStartup` in any component. -Spring Boot can also be configured to expose a {spring-boot-actuator-restapi-docs}/#startup[`startup` endpoint] that provides this information as a JSON document. +Spring Boot can also be configured to expose a xref:api:rest/actuator/startup.adoc[`startup` endpoint] that provides this information as a JSON document. [[features.spring-application.virtual-threads]] -=== Virtual threads +== Virtual threads + If you're running on Java 21 or up, you can enable virtual threads by setting the property configprop:spring.threads.virtual.enabled[] to `true`. Before turning on this option for your application, you should consider https://docs.oracle.com/en/java/javase/21/core/virtual-threads.html[reading the official Java virtual threads documentation]. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/ssl.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/ssl.adoc similarity index 85% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/ssl.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/ssl.adoc index 79db46ccd5..b3bc924c69 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/ssl.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/ssl.adoc @@ -1,18 +1,20 @@ [[features.ssl]] -== SSL += SSL + Spring Boot provides the ability to configure SSL trust material that can be applied to several types of connections in order to support secure communications. Configuration properties with the prefix `spring.ssl.bundle` can be used to specify named sets of trust material and associated information. [[features.ssl.jks]] -=== Configuring SSL With Java KeyStore Files +== Configuring SSL With Java KeyStore Files + Configuration properties with the prefix `spring.ssl.bundle.jks` can be used to configure bundles of trust material created with the Java `keytool` utility and stored in Java KeyStore files in the JKS or PKCS12 format. Each bundle has a user-provided name that can be used to reference the bundle. When used to secure an embedded web server, a `keystore` is typically configured with a Java KeyStore containing a certificate and private key as shown in this example: -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops,yaml] ---- spring: ssl: @@ -29,7 +31,7 @@ When used to secure an embedded web server, a `keystore` is typically configured When used to secure a client-side connection, a `truststore` is typically configured with a Java KeyStore containing the server certificate as shown in this example: -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops,yaml] ---- spring: ssl: @@ -41,18 +43,19 @@ When used to secure a client-side connection, a `truststore` is typically config password: "secret" ---- -See {spring-boot-autoconfigure-module-code}/ssl/JksSslBundleProperties.java[JksSslBundleProperties] for the full set of supported properties. +See {code-spring-boot-autoconfigure-src}/ssl/JksSslBundleProperties.java[JksSslBundleProperties] for the full set of supported properties. [[features.ssl.pem]] -=== Configuring SSL With PEM-encoded Certificates +== Configuring SSL With PEM-encoded Certificates + Configuration properties with the prefix `spring.ssl.bundle.pem` can be used to configure bundles of trust material in the form of PEM-encoded text. Each bundle has a user-provided name that can be used to reference the bundle. When used to secure an embedded web server, a `keystore` is typically configured with a certificate and private key as shown in this example: -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops,yaml] ---- spring: ssl: @@ -66,7 +69,7 @@ When used to secure an embedded web server, a `keystore` is typically configured When used to secure a client-side connection, a `truststore` is typically configured with the server certificate as shown in this example: -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops,yaml] ---- spring: ssl: @@ -84,7 +87,7 @@ If the property values contain `BEGIN` and `END` markers then they will be treat The following example shows how a truststore certificate can be defined: -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops,yaml] ---- spring: ssl: @@ -104,19 +107,21 @@ The following example shows how a truststore certificate can be defined: ---- ==== -See {spring-boot-autoconfigure-module-code}/ssl/PemSslBundleProperties.java[PemSslBundleProperties] for the full set of supported properties. +See {code-spring-boot-autoconfigure-src}/ssl/PemSslBundleProperties.java[PemSslBundleProperties] for the full set of supported properties. [[features.ssl.applying]] -=== Applying SSL Bundles +== Applying SSL Bundles + Once configured using properties, SSL bundles can be referred to by name in configuration properties for various types of connections that are auto-configured by Spring Boot. -See the sections on <>, <>, and <> for further information. +See the sections on xref:how-to:webserver.adoc#howto.webserver.configure-ssl[embedded web servers], xref:data/index.adoc[data technologies], and xref:io/rest-client.adoc[REST clients] for further information. [[features.ssl.bundles]] -=== Using SSL Bundles +== Using SSL Bundles + Spring Boot auto-configures a bean of type `SslBundles` that provides access to each of the named bundles configured using the `spring.ssl.bundle` properties. An `SslBundle` can be retrieved from the auto-configured `SslBundles` bean and used to create objects that are used to configure SSL connectivity in client libraries. @@ -130,12 +135,13 @@ In addition, the `SslBundle` provides details about the key being used, the prot The following example shows retrieving an `SslBundle` and using it to create an `SSLContext`: -include::code:MyComponent[] +include-code::MyComponent[] [[features.ssl.reloading]] -=== Reloading SSL bundles +== Reloading SSL bundles + SSL bundles can be reloaded when the key material changes. The component consuming the bundle has to be compatible with reloadable SSL bundles. Currently the following components are compatible: @@ -145,7 +151,7 @@ Currently the following components are compatible: To enable reloading, you need to opt-in via a configuration property as shown in this example: -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops,yaml] ---- spring: ssl: diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/task-execution-and-scheduling.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/task-execution-and-scheduling.adoc similarity index 88% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/task-execution-and-scheduling.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/task-execution-and-scheduling.adoc index f238c9b969..1acc798476 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/task-execution-and-scheduling.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/task-execution-and-scheduling.adoc @@ -1,5 +1,6 @@ [[features.task-execution-and-scheduling]] -== Task Execution and Scheduling += Task Execution and Scheduling + In the absence of an `Executor` bean in the context, Spring Boot auto-configures an `AsyncTaskExecutor`. When virtual threads are enabled (using Java 21+ and configprop:spring.threads.virtual.enabled[] set to `true`) this will be a `SimpleAsyncTaskExecutor` that uses virtual threads. Otherwise, it will be a `ThreadPoolTaskExecutor` with sensible defaults. @@ -22,15 +23,15 @@ The auto-configured `ThreadPoolTaskExecutorBuilder` allows you to easily create When a `ThreadPoolTaskExecutor` is auto-configured, the thread pool uses 8 core threads that can grow and shrink according to the load. Those default settings can be fine-tuned using the `spring.task.execution` namespace, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - task: - execution: - pool: - max-size: 16 - queue-capacity: 100 - keep-alive: "10s" +spring: + task: + execution: + pool: + max-size: 16 + queue-capacity: 100 + keep-alive: "10s" ---- This changes the thread pool to use a bounded queue so that when the queue is full (100 tasks), the thread pool increases to maximum 16 threads. @@ -44,14 +45,14 @@ This `SimpleAsyncTaskScheduler` will ignore any pooling related properties. If virtual threads are not enabled, it will be a `ThreadPoolTaskScheduler` with sensible defaults. The `ThreadPoolTaskScheduler` uses one thread by default and its settings can be fine-tuned using the `spring.task.scheduling` namespace, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - task: - scheduling: - thread-name-prefix: "scheduling-" - pool: - size: 2 +spring: + task: + scheduling: + thread-name-prefix: "scheduling-" + pool: + size: 2 ---- A `ThreadPoolTaskExecutorBuilder` bean, a `SimpleAsyncTaskExecutorBuilder` bean, a `ThreadPoolTaskSchedulerBuilder` bean and a `SimpleAsyncTaskSchedulerBuilder` are made available in the context if a custom executor or scheduler needs to be created. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/testcontainers.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/testcontainers.adoc similarity index 76% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/testcontainers.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/testcontainers.adoc index 826db3cb7e..2252f05615 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/testcontainers.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/testcontainers.adoc @@ -1,12 +1,14 @@ [[features.testcontainers]] -== Testcontainers Support -As well as <>, it's also possible to use them at development time. += Testcontainers Support + +As well as xref:features/testing.adoc#features.testing.testcontainers[using Testcontainers for integration testing], it's also possible to use them at development time. The next sections will provide more details about that. [[features.testcontainers.at-development-time]] -=== Using Testcontainers at Development Time +== Using Testcontainers at Development Time + This approach allows developers to quickly start containers for the services that the application depends on, removing the need to manually provision things like database servers. Using Testcontainers in this way provides functionality similar to Docker Compose, except that your container configuration is in Java rather than YAML. @@ -18,18 +20,18 @@ For example, if your main application is in `src/main/java/com/example/MyApplica The `TestMyApplication` class can use the `SpringApplication.from(...)` method to launch the real application: -include::code:launch/TestMyApplication[] +include-code::launch/TestMyApplication[] You'll also need to define the `Container` instances that you want to start along with your application. To do this, you need to make sure that the `spring-boot-testcontainers` module has been added as a `test` dependency. Once that has been done, you can create a `@TestConfiguration` class that declares `@Bean` methods for the containers you want to start. You can also annotate your `@Bean` methods with `@ServiceConnection` in order to create `ConnectionDetails` beans. -See <> section for details of the supported technologies. +See xref:features/testing.adoc#features.testing.testcontainers.service-connections[the service connections] section for details of the supported technologies. A typical Testcontainers configuration would look like this: -include::code:test/MyContainersConfiguration[] +include-code::test/MyContainersConfiguration[] NOTE: The lifecycle of `Container` beans is automatically managed by Spring Boot. Containers will be started and stopped automatically. @@ -39,7 +41,7 @@ By default `sequential` startup is used, but you may also choose `parallel` if y Once you have defined your test configuration, you can use the `with(...)` method to attach it to your test launcher: -include::code:test/TestMyApplication[] +include-code::test/TestMyApplication[] You can now launch `TestMyApplication` as you would any regular Java `main` method application to start your application and the containers that it needs to run. @@ -48,46 +50,49 @@ TIP: You can use the Maven goal `spring-boot:test-run` or the Gradle task `bootT [[features.testcontainers.at-development-time.dynamic-properties]] -==== Contributing Dynamic Properties at Development Time +=== Contributing Dynamic Properties at Development Time + If you want to contribute dynamic properties at development time from your `Container` `@Bean` methods, you can do so by injecting a `DynamicPropertyRegistry`. -This works in a similar way to the <> that you can use in your tests. +This works in a similar way to the xref:features/testing.adoc#features.testing.testcontainers.dynamic-properties[`@DynamicPropertySource` annotation] that you can use in your tests. It allows you to add properties that will become available once your container has started. A typical configuration would look like this: -include::code:MyContainersConfiguration[] +include-code::MyContainersConfiguration[] NOTE: Using a `@ServiceConnection` is recommended whenever possible, however, dynamic properties can be a useful fallback for technologies that don't yet have `@ServiceConnection` support. [[features.testcontainers.at-development-time.importing-container-declarations]] -==== Importing Testcontainer Declaration Classes +=== Importing Testcontainer Declaration Classes + A common pattern when using Testcontainers is to declare `Container` instances as static fields. Often these fields are defined directly on the test class. They can also be declared on a parent class or on an interface that the test implements. For example, the following `MyContainers` interface declares `mongo` and `neo4j` containers: -include::code:MyContainers[] +include-code::MyContainers[] If you already have containers defined in this way, or you just prefer this style, you can import these declaration classes rather than defining you containers as `@Bean` methods. To do so, add the `@ImportTestcontainers` annotation to your test configuration class: -include::code:MyContainersConfiguration[] +include-code::MyContainersConfiguration[] -TIP: If you don't intend to use the <> but want to use <> instead, remove the `@ServiceConnection` annotation from the `Container` fields. +TIP: If you don't intend to use the xref:features/testing.adoc#features.testing.testcontainers.service-connections[service connections feature] but want to use xref:features/testing.adoc#features.testing.testcontainers.dynamic-properties[`@DynamicPropertySource`] instead, remove the `@ServiceConnection` annotation from the `Container` fields. You can also add `@DynamicPropertySource` annotated methods to your declaration class. [[features.testcontainers.at-development-time.devtools]] -==== Using DevTools with Testcontainers at Development Time +=== Using DevTools with Testcontainers at Development Time + When using devtools, you can annotate beans and bean methods with `@RestartScope`. Such beans won't be recreated when the devtools restart the application. This is especially useful for Testcontainer `Container` beans, as they keep their state despite the application restart. -include::code:MyContainersConfiguration[] +include-code::MyContainersConfiguration[] WARNING: If you're using Gradle and want to use this feature, you need to change the configuration of the `spring-boot-devtools` dependency from `developmentOnly` to `testAndDevelopmentOnly`. With the default scope of `developmentOnly`, the `bootTestRun` task will not pick up changes in your code, as the devtools are not active. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/testing.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/testing.adoc similarity index 77% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/testing.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/testing.adoc index 669de91351..e50037cbfb 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/testing.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/features/testing.adoc @@ -1,5 +1,6 @@ [[features.testing]] -== Testing += Testing + Spring Boot provides a number of utilities and annotations to help when testing your application. Test support is provided by two modules: `spring-boot-test` contains core items, and `spring-boot-test-autoconfigure` supports auto-configuration for tests. @@ -10,19 +11,19 @@ Most developers use the `spring-boot-starter-test` "`Starter`", which imports bo If you have tests that use JUnit 4, JUnit 5's vintage engine can be used to run them. To use the vintage engine, add a dependency on `junit-vintage-engine`, as shown in the following example: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - org.junit.vintage - junit-vintage-engine - test - - - org.hamcrest - hamcrest-core - - - + + org.junit.vintage + junit-vintage-engine + test + + + org.hamcrest + hamcrest-core + + + ---- ==== @@ -31,11 +32,12 @@ To use the vintage engine, add a dependency on `junit-vintage-engine`, as shown [[features.testing.test-scope-dependencies]] -=== Test Scope Dependencies +== Test Scope Dependencies + The `spring-boot-starter-test` "`Starter`" (in the `test` `scope`) contains the following provided libraries: * https://junit.org/junit5/[JUnit 5]: The de-facto standard for unit testing Java applications. -* {spring-framework-docs}/testing/integration.html[Spring Test] & Spring Boot Test: Utilities and integration test support for Spring Boot applications. +* {url-spring-framework-docs}/testing/integration.html[Spring Test] & Spring Boot Test: Utilities and integration test support for Spring Boot applications. * https://assertj.github.io/doc/[AssertJ]: A fluent assertion library. * https://github.com/hamcrest/JavaHamcrest[Hamcrest]: A library of matcher objects (also known as constraints or predicates). * https://site.mockito.org/[Mockito]: A Java mocking framework. @@ -49,7 +51,8 @@ If these libraries do not suit your needs, you can add additional test dependenc [[features.testing.spring-applications]] -=== Testing Spring Applications +== Testing Spring Applications + One of the major advantages of dependency injection is that it should make your code easier to unit test. You can instantiate objects by using the `new` operator without even involving Spring. You can also use _mock objects_ instead of real dependencies. @@ -60,19 +63,20 @@ It is useful to be able to perform integration testing without requiring deploym The Spring Framework includes a dedicated test module for such integration testing. You can declare a dependency directly to `org.springframework:spring-test` or use the `spring-boot-starter-test` "`Starter`" to pull it in transitively. -If you have not used the `spring-test` module before, you should start by reading the {spring-framework-docs}/testing.html[relevant section] of the Spring Framework reference documentation. +If you have not used the `spring-test` module before, you should start by reading the {url-spring-framework-docs}/testing.html[relevant section] of the Spring Framework reference documentation. [[features.testing.spring-boot-applications]] -=== Testing Spring Boot Applications +== Testing Spring Boot Applications + A Spring Boot application is a Spring `ApplicationContext`, so nothing very special has to be done to test it beyond what you would normally do with a vanilla Spring context. NOTE: External properties, logging, and other features of Spring Boot are installed in the context by default only if you use `SpringApplication` to create it. Spring Boot provides a `@SpringBootTest` annotation, which can be used as an alternative to the standard `spring-test` `@ContextConfiguration` annotation when you need Spring Boot features. -The annotation works by <>. -In addition to `@SpringBootTest` a number of other annotations are also provided for <> of an application. +The annotation works by xref:features/testing.adoc#features.testing.spring-boot-applications.detecting-configuration[creating the `ApplicationContext` used in your tests through `SpringApplication`]. +In addition to `@SpringBootTest` a number of other annotations are also provided for xref:features/testing.adoc#features.testing.spring-boot-applications.autoconfigured-tests[testing more specific slices] of an application. TIP: If you are using JUnit 4, do not forget to also add `@RunWith(SpringRunner.class)` to your test, otherwise the annotations will be ignored. If you are using JUnit 5, there is no need to add the equivalent `@ExtendWith(SpringExtension.class)` as `@SpringBootTest` and the other `@...Test` annotations are already annotated with it. @@ -83,7 +87,7 @@ You can use the `webEnvironment` attribute of `@SpringBootTest` to further refin * `MOCK`(Default) : Loads a web `ApplicationContext` and provides a mock web environment. Embedded servers are not started when using this annotation. If a web environment is not available on your classpath, this mode transparently falls back to creating a regular non-web `ApplicationContext`. - It can be used in conjunction with <> for mock-based testing of your web application. + It can be used in conjunction with xref:features/testing.adoc#features.testing.spring-boot-applications.with-mock-environment[`@AutoConfigureMockMvc` or `@AutoConfigureWebTestClient`] for mock-based testing of your web application. * `RANDOM_PORT`: Loads a `WebServerApplicationContext` and provides a real web environment. Embedded servers are started and listen on a random port. * `DEFINED_PORT`: Loads a `WebServerApplicationContext` and provides a real web environment. @@ -99,19 +103,21 @@ NOTE: `@SpringBootTest` with `webEnvironment = WebEnvironment.RANDOM_PORT` will [[features.testing.spring-boot-applications.detecting-web-app-type]] -==== Detecting Web Application Type +=== Detecting Web Application Type + If Spring MVC is available, a regular MVC-based application context is configured. If you have only Spring WebFlux, we will detect that and configure a WebFlux-based application context instead. If both are present, Spring MVC takes precedence. If you want to test a reactive web application in this scenario, you must set the configprop:spring.main.web-application-type[] property: -include::code:MyWebFluxTests[] +include-code::MyWebFluxTests[] [[features.testing.spring-boot-applications.detecting-configuration]] -==== Detecting Test Configuration +=== Detecting Test Configuration + If you are familiar with the Spring Test Framework, you may be used to using `@ContextConfiguration(classes=...)` in order to specify which Spring `@Configuration` to load. Alternatively, you might have often used nested `@Configuration` classes within your test. @@ -119,11 +125,11 @@ When testing Spring Boot applications, this is often not required. Spring Boot's `@*Test` annotations search for your primary configuration automatically whenever you do not explicitly define one. The search algorithm works up from the package that contains the test until it finds a class annotated with `@SpringBootApplication` or `@SpringBootConfiguration`. -As long as you <> in a sensible way, your main configuration is usually found. +As long as you xref:using/structuring-your-code.adoc[structured your code] in a sensible way, your main configuration is usually found. [NOTE] ==== -If you use a <>, you should avoid adding configuration settings that are specific to a particular area on the <>. +If you use a xref:features/testing.adoc#features.testing.spring-boot-applications.autoconfigured-tests[test annotation to test a more specific slice of your application], you should avoid adding configuration settings that are specific to a particular area on the xref:features/testing.adoc#features.testing.spring-boot-applications.user-configuration-and-slicing[main method's application class]. The underlying component scan configuration of `@SpringBootApplication` defines exclude filters that are used to make sure slicing works as expected. If you are using an explicit `@ComponentScan` directive on your `@SpringBootApplication`-annotated class, be aware that those filters will be disabled. @@ -139,20 +145,21 @@ Therefore, as long as your tests share the same configuration (no matter how it [[features.testing.spring-boot-applications.using-main]] -==== Using the Test Configuration Main Method +=== Using the Test Configuration Main Method + Typically the test configuration discovered by `@SpringBootTest` will be your main `@SpringBootApplication`. In most well structured applications, this configuration class will also include the `main` method used to launch the application. For example, the following is a very common code pattern for a typical Spring Boot application: -include::code:typical/MyApplication[] +include-code::typical/MyApplication[] In the example above, the `main` method doesn't do anything other than delegate to `SpringApplication.run`. It is, however, possible to have a more complex `main` method that applies customizations before calling `SpringApplication.run`. For example, here is an application that changes the banner mode and sets additional profiles: -include::code:custom/MyApplication[] +include-code::custom/MyApplication[] Since customizations in the `main` method can affect the resulting `ApplicationContext`, it's possible that you might also want to use the `main` method to create the `ApplicationContext` used in your tests. By default, `@SpringBootTest` will not call your `main` method, and instead the class itself is used directly to create the `ApplicationContext` @@ -164,22 +171,23 @@ When set to `WHEN_AVAILABLE` the `main` method will be used if it is available, For example, the following test will invoke the `main` method of `MyApplication` in order to create the `ApplicationContext`. If the main method sets additional profiles then those will be active when the `ApplicationContext` starts. -include::code:always/MyApplicationTests[] +include-code::always/MyApplicationTests[] [[features.testing.spring-boot-applications.excluding-configuration]] -==== Excluding Test Configuration +=== Excluding Test Configuration + If your application uses component scanning (for example, if you use `@SpringBootApplication` or `@ComponentScan`), you may find top-level configuration classes that you created only for specific tests accidentally get picked up everywhere. -As we <>, `@TestConfiguration` can be used on an inner class of a test to customize the primary configuration. +As we xref:features/testing.adoc#features.testing.spring-boot-applications.detecting-configuration[have seen earlier], `@TestConfiguration` can be used on an inner class of a test to customize the primary configuration. `@TestConfiguration` can also be used on a top-level class. Doing so indicates that the class should not be picked up by scanning. You can then import the class explicitly where it is required, as shown in the following example: -include::code:MyTests[] +include-code::MyTests[] NOTE: If you directly use `@ComponentScan` (that is, not through `@SpringBootApplication`) you need to register the `TypeExcludeFilter` with it. -See {spring-boot-module-api}/context/TypeExcludeFilter.html[the Javadoc] for details. +See xref:api:java/org/springframework/boot/context/TypeExcludeFilter.html[the Javadoc] for details. NOTE: An imported `@TestConfiguration` is processed earlier than an inner-class `@TestConfiguration` and an imported `@TestConfiguration` will be processed before any configuration found through component scanning. Generally speaking, this difference in ordering has no noticeable effect but it is something to be aware of if you're relying on bean overriding. @@ -187,27 +195,29 @@ Generally speaking, this difference in ordering has no noticeable effect but it [[features.testing.spring-boot-applications.using-application-arguments]] -==== Using Application Arguments -If your application expects <>, you can +=== Using Application Arguments + +If your application expects xref:features/spring-application.adoc#features.spring-application.application-arguments[arguments], you can have `@SpringBootTest` inject them using the `args` attribute. -include::code:MyApplicationArgumentTests[] +include-code::MyApplicationArgumentTests[] [[features.testing.spring-boot-applications.with-mock-environment]] -==== Testing With a Mock Environment +=== Testing With a Mock Environment + By default, `@SpringBootTest` does not start the server but instead sets up a mock environment for testing web endpoints. -With Spring MVC, we can query our web endpoints using {spring-framework-docs}/testing/spring-mvc-test-framework.html[`MockMvc`] or `WebTestClient`, as shown in the following example: +With Spring MVC, we can query our web endpoints using {url-spring-framework-docs}/testing/spring-mvc-test-framework.html[`MockMvc`] or `WebTestClient`, as shown in the following example: -include::code:MyMockMvcTests[] +include-code::MyMockMvcTests[] -TIP: If you want to focus only on the web layer and not start a complete `ApplicationContext`, consider <>. +TIP: If you want to focus only on the web layer and not start a complete `ApplicationContext`, consider xref:features/testing.adoc#features.testing.spring-boot-applications.spring-mvc-tests[using `@WebMvcTest` instead]. -With Spring WebFlux endpoints, you can use {spring-framework-docs}/testing/webtestclient.html[`WebTestClient`] as shown in the following example: +With Spring WebFlux endpoints, you can use {url-spring-framework-docs}/testing/webtestclient.html[`WebTestClient`] as shown in the following example: -include::code:MyMockWebTestClientTests[] +include-code::MyMockWebTestClientTests[] [TIP] ==== @@ -215,78 +225,86 @@ 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 xref:web/servlet.adoc#web.servlet.spring-mvc.error-handling.error-pages[custom error page] is rendered. If you need to test these lower-level concerns, you can start a fully running server as described in the next section. ==== [[features.testing.spring-boot-applications.with-running-server]] -==== Testing With a Running Server +=== Testing With a Running Server + If you need to start a full running server, we recommend that you use random ports. If you use `@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)`, an available port is picked at random each time your test runs. -The `@LocalServerPort` annotation can be used to <> into your test. -For convenience, tests that need to make REST calls to the started server can additionally `@Autowire` a {spring-framework-docs}/testing/webtestclient.html[`WebTestClient`], which resolves relative links to the running server and comes with a dedicated API for verifying responses, as shown in the following example: +The `@LocalServerPort` annotation can be used to xref:how-to:webserver.adoc#howto.webserver.discover-port[inject the actual port used] into your test. +For convenience, tests that need to make REST calls to the started server can additionally `@Autowire` a {url-spring-framework-docs}/testing/webtestclient.html[`WebTestClient`], which resolves relative links to the running server and comes with a dedicated API for verifying responses, as shown in the following example: -include::code:MyRandomPortWebTestClientTests[] +include-code::MyRandomPortWebTestClientTests[] -TIP: `WebTestClient` can also used with a <>, removing the need for a running server, by annotating your test class with `@AutoConfigureWebTestClient`. +TIP: `WebTestClient` can also used with a xref:features/testing.adoc#features.testing.spring-boot-applications.with-mock-environment[mock environment], removing the need for a running server, by annotating your test class with `@AutoConfigureWebTestClient`. This setup requires `spring-webflux` on the classpath. If you can not or will not add webflux, Spring Boot also provides a `TestRestTemplate` facility: -include::code:MyRandomPortTestRestTemplateTests[] +include-code::MyRandomPortTestRestTemplateTests[] [[features.testing.spring-boot-applications.customizing-web-test-client]] -==== Customizing WebTestClient +=== Customizing WebTestClient + To customize the `WebTestClient` bean, configure a `WebTestClientBuilderCustomizer` bean. Any such beans are called with the `WebTestClient.Builder` that is used to create the `WebTestClient`. [[features.testing.spring-boot-applications.jmx]] -==== Using JMX +=== Using JMX + As the test context framework caches context, JMX is disabled by default to prevent identical components to register on the same domain. If such test needs access to an `MBeanServer`, consider marking it dirty as well: -include::code:MyJmxTests[] +include-code::MyJmxTests[] + [[features.testing.spring-boot-applications.observations]] -==== Using Observations -If you annotate <> with `@AutoConfigureObservability`, it auto-configures an `ObservationRegistry`. +=== Using Observations + +If you annotate xref:features/testing.adoc#features.testing.spring-boot-applications.autoconfigured-tests[a sliced test] with `@AutoConfigureObservability`, it auto-configures an `ObservationRegistry`. [[features.testing.spring-boot-applications.metrics]] -==== Using Metrics +=== Using Metrics + Regardless of your classpath, meter registries, except the in-memory backed, are not auto-configured when using `@SpringBootTest`. If you need to export metrics to a different backend as part of an integration test, annotate it with `@AutoConfigureObservability`. -If you annotate <> with `@AutoConfigureObservability`, it auto-configures an in-memory `MeterRegistry`. +If you annotate xref:features/testing.adoc#features.testing.spring-boot-applications.autoconfigured-tests[a sliced test] with `@AutoConfigureObservability`, it auto-configures an in-memory `MeterRegistry`. Data exporting in sliced tests is not supported with the `@AutoConfigureObservability` annotation. [[features.testing.spring-boot-applications.tracing]] -==== Using Tracing +=== Using Tracing + Regardless of your classpath, tracing components which are reporting data are not auto-configured when using `@SpringBootTest`. If you need those components as part of an integration test, annotate the test with `@AutoConfigureObservability`. If you have created your own reporting components (e.g. a custom `SpanExporter` or `SpanHandler`) and you don't want them to be active in tests, you can use the `@ConditionalOnEnabledTracing` annotation to disable them. -If you annotate <> with `@AutoConfigureObservability`, it auto-configures a no-op `Tracer`. +If you annotate xref:features/testing.adoc#features.testing.spring-boot-applications.autoconfigured-tests[a sliced test] with `@AutoConfigureObservability`, it auto-configures a no-op `Tracer`. Data exporting in sliced tests is not supported with the `@AutoConfigureObservability` annotation. [[features.testing.spring-boot-applications.mocking-beans]] -==== Mocking and Spying Beans +=== Mocking and Spying Beans + When running tests, it is sometimes necessary to mock certain components within your application context. For example, you may have a facade over some remote service that is unavailable during development. Mocking can also be useful when you want to simulate failures that might be hard to trigger in a real environment. @@ -302,19 +320,19 @@ Mock beans are automatically reset after each test method. If your test uses one of Spring Boot's test annotations (such as `@SpringBootTest`), this feature is automatically enabled. To use this feature with a different arrangement, listeners must be explicitly added, as shown in the following example: -include::code:listener/MyTests[] +include-code::listener/MyTests[] ==== The following example replaces an existing `RemoteService` bean with a mock implementation: -include::code:bean/MyTests[] +include-code::bean/MyTests[] NOTE: `@MockBean` cannot be used to mock the behavior of a bean that is exercised during application context refresh. By the time the test is executed, the application context refresh has completed and it is too late to configure the mocked behavior. We recommend using a `@Bean` method to create and configure the mock in this situation. Additionally, you can use `@SpyBean` to wrap any existing bean with a Mockito `spy`. -See the {spring-boot-test-module-api}/mock/mockito/SpyBean.html[Javadoc] for full details. +See the xref:api:java/org/springframework/boot/test/mock/mockito/SpyBean.html[Javadoc] for full details. NOTE: While Spring's test framework caches application contexts between tests and reuses a context for tests sharing the same configuration, the use of `@MockBean` or `@SpyBean` influences the cache key, which will most likely increase the number of contexts. @@ -327,7 +345,8 @@ Use `AopTestUtils.getTargetObject(yourProxiedSpy)` to do so. [[features.testing.spring-boot-applications.autoconfigured-tests]] -==== Auto-configured Tests +=== Auto-configured Tests + Spring Boot's auto-configuration system works well for applications but can sometimes be a little too much for tests. It often helps to load only the parts of the configuration that are required to test a "`slice`" of your application. For example, you might want to test that Spring MVC controllers are mapping URLs correctly, and you do not want to involve database calls in those tests, or you might want to test JPA entities, and you are not interested in the web layer when those tests run. @@ -348,7 +367,8 @@ You can use this combination if you are not interested in "`slicing`" your appli [[features.testing.spring-boot-applications.json-tests]] -==== Auto-configured JSON Tests +=== Auto-configured JSON Tests + To test that object JSON serialization and deserialization is working as expected, you can use the `@JsonTest` annotation. `@JsonTest` auto-configures the available supported JSON mapper, which can be one of the following libraries: @@ -356,7 +376,7 @@ To test that object JSON serialization and deserialization is working as expecte * `Gson` * `Jsonb` -TIP: A list of the auto-configurations that are enabled by `@JsonTest` can be <>. +TIP: A list of the auto-configurations that are enabled by `@JsonTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix]. If you need to configure elements of the auto-configuration, you can use the `@AutoConfigureJsonTesters` annotation. @@ -365,7 +385,7 @@ The `JacksonTester`, `GsonTester`, `JsonbTester`, and `BasicJsonTester` classes Any helper fields on the test class can be `@Autowired` when using `@JsonTest`. The following example shows a test class for Jackson: -include::code:MyJsonTests[] +include-code::MyJsonTests[] NOTE: JSON helper classes can also be used directly in standard unit tests. To do so, call the `initFields` method of the helper in your `@Before` method if you do not use `@JsonTest`. @@ -374,18 +394,19 @@ If you use Spring Boot's AssertJ-based helpers to assert on a number value at a Instead, you can use AssertJ's `satisfies` to assert that the value matches the given condition. For instance, the following example asserts that the actual number is a float value close to `0.15` within an offset of `0.01`. -include::code:MyJsonAssertJTests[tag=*] +include-code::MyJsonAssertJTests[tag=*] [[features.testing.spring-boot-applications.spring-mvc-tests]] -==== Auto-configured Spring MVC Tests +=== Auto-configured Spring MVC Tests + To test whether Spring MVC controllers are working as expected, use the `@WebMvcTest` annotation. `@WebMvcTest` auto-configures the Spring MVC infrastructure and limits scanned beans to `@Controller`, `@ControllerAdvice`, `@JsonComponent`, `Converter`, `GenericConverter`, `Filter`, `HandlerInterceptor`, `WebMvcConfigurer`, `WebMvcRegistrations`, and `HandlerMethodArgumentResolver`. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@WebMvcTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. -TIP: A list of the auto-configuration settings that are enabled by `@WebMvcTest` can be <>. +TIP: A list of the auto-configuration settings that are enabled by `@WebMvcTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix]. TIP: If you need to register extra components, such as the Jackson `Module`, you can import additional configuration classes by using `@Import` on your test. @@ -397,14 +418,14 @@ Mock MVC offers a powerful way to quickly test MVC controllers without needing t TIP: You can also auto-configure `MockMvc` in a non-`@WebMvcTest` (such as `@SpringBootTest`) by annotating it with `@AutoConfigureMockMvc`. The following example uses `MockMvc`: -include::code:MyControllerTests[] +include-code::MyControllerTests[] TIP: If you need to configure elements of the auto-configuration (for example, when servlet filters should be applied) you can use attributes in the `@AutoConfigureMockMvc` annotation. If you use HtmlUnit and Selenium, auto-configuration also provides an HtmlUnit `WebClient` bean and/or a Selenium `WebDriver` bean. The following example uses HtmlUnit: -include::code:MyHtmlUnitTests[] +include-code::MyHtmlUnitTests[] NOTE: By default, Spring Boot puts `WebDriver` beans in a special "`scope`" to ensure that the driver exits after each test and that a new instance is injected. If you do not want this behavior, you can add `@Scope("singleton")` to your `WebDriver` `@Bean` definition. @@ -414,31 +435,32 @@ If you define your own `webDriver` scope you may find it stops working when you If you have Spring Security on the classpath, `@WebMvcTest` will also scan `WebSecurityConfigurer` beans. Instead of disabling security completely for such tests, you can use Spring Security's test support. -More details on how to use Spring Security's `MockMvc` support can be found in this _<>_ how-to section. +More details on how to use Spring Security's `MockMvc` support can be found in this _xref:how-to:testing.adoc#howto.testing.with-spring-security[Testing With Spring Security]_ how-to section. -TIP: Sometimes writing Spring MVC tests is not enough; Spring Boot can help you run <>. +TIP: Sometimes writing Spring MVC tests is not enough; Spring Boot can help you run xref:features/testing.adoc#features.testing.spring-boot-applications.with-running-server[full end-to-end tests with an actual server]. [[features.testing.spring-boot-applications.spring-webflux-tests]] -==== Auto-configured Spring WebFlux Tests -To test that {spring-framework-docs}/web-reactive.html[Spring WebFlux] controllers are working as expected, you can use the `@WebFluxTest` annotation. +=== Auto-configured Spring WebFlux Tests + +To test that {url-spring-framework-docs}/web-reactive.html[Spring WebFlux] controllers are working as expected, you can use the `@WebFluxTest` annotation. `@WebFluxTest` auto-configures the Spring WebFlux infrastructure and limits scanned beans to `@Controller`, `@ControllerAdvice`, `@JsonComponent`, `Converter`, `GenericConverter`, `WebFilter`, and `WebFluxConfigurer`. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@WebFluxTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. -TIP: A list of the auto-configurations that are enabled by `@WebFluxTest` can be <>. +TIP: A list of the auto-configurations that are enabled by `@WebFluxTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix]. TIP: If you need to register extra components, such as Jackson `Module`, you can import additional configuration classes using `@Import` on your test. Often, `@WebFluxTest` is limited to a single controller and used in combination with the `@MockBean` annotation to provide mock implementations for required collaborators. -`@WebFluxTest` also auto-configures {spring-framework-docs}/testing/webtestclient.html[`WebTestClient`], which offers a powerful way to quickly test WebFlux controllers without needing to start a full HTTP server. +`@WebFluxTest` also auto-configures {url-spring-framework-docs}/testing/webtestclient.html[`WebTestClient`], which offers a powerful way to quickly test WebFlux controllers without needing to start a full HTTP server. TIP: You can also auto-configure `WebTestClient` in a non-`@WebFluxTest` (such as `@SpringBootTest`) by annotating it with `@AutoConfigureWebTestClient`. The following example shows a class that uses both `@WebFluxTest` and a `WebTestClient`: -include::code:MyControllerTests[] +include-code::MyControllerTests[] TIP: This setup is only supported by WebFlux applications as using `WebTestClient` in a mocked web application only works with WebFlux at the moment. @@ -448,119 +470,124 @@ For testing `RouterFunction` beans in the context, consider importing your `Rout NOTE: `@WebFluxTest` cannot detect custom security configuration registered as a `@Bean` of type `SecurityWebFilterChain`. To include that in your test, you will need to import the configuration that registers the bean by using `@Import` or by using `@SpringBootTest`. -TIP: Sometimes writing Spring WebFlux tests is not enough; Spring Boot can help you run <>. +TIP: Sometimes writing Spring WebFlux tests is not enough; Spring Boot can help you run xref:features/testing.adoc#features.testing.spring-boot-applications.with-running-server[full end-to-end tests with an actual server]. [[features.testing.spring-boot-applications.spring-graphql-tests]] -==== Auto-configured Spring GraphQL Tests +=== Auto-configured Spring GraphQL Tests + Spring GraphQL offers a dedicated testing support module; you'll need to add it to your project: .Maven -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - - org.springframework.graphql - spring-graphql-test - test - - - - org.springframework.boot - spring-boot-starter-webflux - test - - + + + org.springframework.graphql + spring-graphql-test + test + + + + org.springframework.boot + spring-boot-starter-webflux + test + + ---- .Gradle -[source,gradle,indent=0,subs="verbatim"] +[source,gradle] ---- - dependencies { - testImplementation("org.springframework.graphql:spring-graphql-test") - // Unless already present in the implementation configuration - testImplementation("org.springframework.boot:spring-boot-starter-webflux") - } +dependencies { + testImplementation("org.springframework.graphql:spring-graphql-test") + // Unless already present in the implementation configuration + testImplementation("org.springframework.boot:spring-boot-starter-webflux") +} ---- -This testing module ships the {spring-graphql-docs}/#testing-graphqltester[GraphQlTester]. +This testing module ships the {url-spring-graphql-docs}/#testing-graphqltester[GraphQlTester]. The tester is heavily used in test, so be sure to become familiar with using it. There are `GraphQlTester` variants and Spring Boot will auto-configure them depending on the type of tests: * the `ExecutionGraphQlServiceTester` performs tests on the server side, without a client nor a transport * the `HttpGraphQlTester` performs tests with a client that connects to a server, with or without a live server -Spring Boot helps you to test your {spring-graphql-docs}/#controllers[Spring GraphQL Controllers] with the `@GraphQlTest` annotation. +Spring Boot helps you to test your {url-spring-graphql-docs}/#controllers[Spring GraphQL Controllers] with the `@GraphQlTest` annotation. `@GraphQlTest` auto-configures the Spring GraphQL infrastructure, without any transport nor server being involved. This limits scanned beans to `@Controller`, `RuntimeWiringConfigurer`, `JsonComponent`, `Converter`, `GenericConverter`, `DataFetcherExceptionResolver`, `Instrumentation` and `GraphQlSourceBuilderCustomizer`. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@GraphQlTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. -TIP: A list of the auto-configurations that are enabled by `@GraphQlTest` can be <>. +TIP: A list of the auto-configurations that are enabled by `@GraphQlTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix]. Often, `@GraphQlTest` is limited to a set of controllers and used in combination with the `@MockBean` annotation to provide mock implementations for required collaborators. -include::code:GreetingControllerTests[] +include-code::GreetingControllerTests[] `@SpringBootTest` tests are full integration tests and involve the entire application. When using a random or defined port, a live server is configured and an `HttpGraphQlTester` bean is contributed automatically so you can use it to test your server. When a MOCK environment is configured, you can also request an `HttpGraphQlTester` bean by annotating your test class with `@AutoConfigureHttpGraphQlTester`: -include::code:GraphQlIntegrationTests[] +include-code::GraphQlIntegrationTests[] [[features.testing.spring-boot-applications.autoconfigured-spring-data-cassandra]] -==== Auto-configured Data Cassandra Tests +=== Auto-configured Data Cassandra Tests + You can use `@DataCassandraTest` to test Cassandra applications. By default, it configures a `CassandraTemplate`, scans for `@Table` classes, and configures Spring Data Cassandra repositories. 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 "<>".) +(For more about using Cassandra with Spring Boot, see "xref:data/nosql.adoc#data.nosql.cassandra[Cassandra]".) -TIP: A list of the auto-configuration settings that are enabled by `@DataCassandraTest` can be <>. +TIP: A list of the auto-configuration settings that are enabled by `@DataCassandraTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix]. The following example shows a typical setup for using Cassandra tests in Spring Boot: -include::code:MyDataCassandraTests[] +include-code::MyDataCassandraTests[] [[features.testing.spring-boot-applications.autoconfigured-spring-data-couchbase]] -==== Auto-configured Data Couchbase Tests +=== Auto-configured Data Couchbase Tests + You can use `@DataCouchbaseTest` to test Couchbase applications. By default, it configures a `CouchbaseTemplate` or `ReactiveCouchbaseTemplate`, scans for `@Document` classes, and configures Spring Data Couchbase repositories. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataCouchbaseTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. -(For more about using Couchbase with Spring Boot, see "<>", earlier in this chapter.) +(For more about using Couchbase with Spring Boot, see "xref:data/nosql.adoc#data.nosql.couchbase[Couchbase]", earlier in this chapter.) -TIP: A list of the auto-configuration settings that are enabled by `@DataCouchbaseTest` can be <>. +TIP: A list of the auto-configuration settings that are enabled by `@DataCouchbaseTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix]. The following example shows a typical setup for using Couchbase tests in Spring Boot: -include::code:MyDataCouchbaseTests[] +include-code::MyDataCouchbaseTests[] [[features.testing.spring-boot-applications.autoconfigured-spring-data-elasticsearch]] -==== Auto-configured Data Elasticsearch Tests +=== Auto-configured Data Elasticsearch Tests + You can use `@DataElasticsearchTest` to test Elasticsearch applications. By default, it configures an `ElasticsearchRestTemplate`, scans for `@Document` classes, and configures Spring Data Elasticsearch repositories. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataElasticsearchTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. -(For more about using Elasticsearch with Spring Boot, see "<>", earlier in this chapter.) +(For more about using Elasticsearch with Spring Boot, see "xref:data/nosql.adoc#data.nosql.elasticsearch[Elasticsearch]", earlier in this chapter.) -TIP: A list of the auto-configuration settings that are enabled by `@DataElasticsearchTest` can be <>. +TIP: A list of the auto-configuration settings that are enabled by `@DataElasticsearchTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix]. The following example shows a typical setup for using Elasticsearch tests in Spring Boot: -include::code:MyDataElasticsearchTests[] +include-code::MyDataElasticsearchTests[] [[features.testing.spring-boot-applications.autoconfigured-spring-data-jpa]] -==== Auto-configured Data JPA Tests +=== Auto-configured Data JPA Tests + You can use the `@DataJpaTest` annotation to test JPA applications. By default, it scans for `@Entity` classes and configures Spring Data JPA repositories. If an embedded database is available on the classpath, it configures one as well. @@ -570,15 +597,15 @@ This can be disabled using the `showSql` attribute of the annotation. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataJpaTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. -TIP: A list of the auto-configuration settings that are enabled by `@DataJpaTest` can be <>. +TIP: A list of the auto-configuration settings that are enabled by `@DataJpaTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix]. By default, data JPA tests are transactional and roll back at the end of each test. -See the {spring-framework-docs}/testing/testcontext-framework/tx.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. +See the {url-spring-framework-docs}/testing/testcontext-framework/tx.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. If that is not what you want, you can disable transaction management for a test or for the whole class as follows: -include::code:MyNonTransactionalTests[] +include-code::MyNonTransactionalTests[] -Data JPA tests may also inject a {spring-boot-test-autoconfigure-module-code}/orm/jpa/TestEntityManager.java[`TestEntityManager`] bean, which provides an alternative to the standard JPA `EntityManager` that is specifically designed for tests. +Data JPA tests may also inject a {code-spring-boot-test-autoconfigure-src}/orm/jpa/TestEntityManager.java[`TestEntityManager`] bean, which provides an alternative to the standard JPA `EntityManager` that is specifically designed for tests. TIP: `TestEntityManager` can also be auto-configured to any of your Spring-based test class by adding `@AutoConfigureTestEntityManager`. When doing so, make sure that your test is running in a transaction, for instance by adding `@Transactional` on your test class or method. @@ -586,125 +613,131 @@ When doing so, make sure that your test is running in a transaction, for instanc A `JdbcTemplate` is also available if you need that. The following example shows the `@DataJpaTest` annotation in use: -include::code:withoutdb/MyRepositoryTests[] +include-code::withoutdb/MyRepositoryTests[] In-memory embedded databases generally work well for tests, since they are fast and do not require any installation. If, however, you prefer to run tests against a real database you can use the `@AutoConfigureTestDatabase` annotation, as shown in the following example: -include::code:withdb/MyRepositoryTests[] +include-code::withdb/MyRepositoryTests[] [[features.testing.spring-boot-applications.autoconfigured-jdbc]] -==== Auto-configured JDBC Tests +=== Auto-configured JDBC Tests + `@JdbcTest` is similar to `@DataJpaTest` but is for tests that only require a `DataSource` and do not use Spring Data JDBC. By default, it configures an in-memory embedded database and a `JdbcTemplate`. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@JdbcTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. -TIP: A list of the auto-configurations that are enabled by `@JdbcTest` can be <>. +TIP: A list of the auto-configurations that are enabled by `@JdbcTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix]. By default, JDBC tests are transactional and roll back at the end of each test. -See the {spring-framework-docs}/testing/testcontext-framework/tx.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. +See the {url-spring-framework-docs}/testing/testcontext-framework/tx.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. If that is not what you want, you can disable transaction management for a test or for the whole class, as follows: -include::code:MyTransactionalTests[] +include-code::MyTransactionalTests[] If you prefer your test to run against a real database, you can use the `@AutoConfigureTestDatabase` annotation in the same way as for `@DataJpaTest`. -(See "<>".) +(See "xref:features/testing.adoc#features.testing.spring-boot-applications.autoconfigured-spring-data-jpa[Auto-configured Data JPA Tests]".) [[features.testing.spring-boot-applications.autoconfigured-spring-data-jdbc]] -==== Auto-configured Data JDBC Tests +=== Auto-configured Data JDBC Tests + `@DataJdbcTest` is similar to `@JdbcTest` but is for tests that use Spring Data JDBC repositories. By default, it configures an in-memory embedded database, a `JdbcTemplate`, and Spring Data JDBC repositories. Only `AbstractJdbcConfiguration` subclasses are scanned when the `@DataJdbcTest` annotation is used, regular `@Component` and `@ConfigurationProperties` beans are not scanned. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. -TIP: A list of the auto-configurations that are enabled by `@DataJdbcTest` can be <>. +TIP: A list of the auto-configurations that are enabled by `@DataJdbcTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix]. By default, Data JDBC tests are transactional and roll back at the end of each test. -See the {spring-framework-docs}/testing/testcontext-framework/tx.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. -If that is not what you want, you can disable transaction management for a test or for the whole test class as <>. +See the {url-spring-framework-docs}/testing/testcontext-framework/tx.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. +If that is not what you want, you can disable transaction management for a test or for the whole test class as xref:features/testing.adoc#features.testing.spring-boot-applications.autoconfigured-jdbc[shown in the JDBC example]. If you prefer your test to run against a real database, you can use the `@AutoConfigureTestDatabase` annotation in the same way as for `@DataJpaTest`. -(See "<>".) +(See "xref:features/testing.adoc#features.testing.spring-boot-applications.autoconfigured-spring-data-jpa[Auto-configured Data JPA Tests]".) [[features.testing.spring-boot-applications.autoconfigured-spring-data-r2dbc]] -==== Auto-configured Data R2DBC Tests +=== Auto-configured Data R2DBC Tests + `@DataR2dbcTest` is similar to `@DataJdbcTest` but is for tests that use Spring Data R2DBC repositories. By default, it configures an in-memory embedded database, an `R2dbcEntityTemplate`, and Spring Data R2DBC repositories. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataR2dbcTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. -TIP: A list of the auto-configurations that are enabled by `@DataR2dbcTest` can be <>. +TIP: A list of the auto-configurations that are enabled by `@DataR2dbcTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix]. By default, Data R2DBC tests are not transactional. If you prefer your test to run against a real database, you can use the `@AutoConfigureTestDatabase` annotation in the same way as for `@DataJpaTest`. -(See "<>".) +(See "xref:features/testing.adoc#features.testing.spring-boot-applications.autoconfigured-spring-data-jpa[Auto-configured Data JPA Tests]".) [[features.testing.spring-boot-applications.autoconfigured-jooq]] -==== Auto-configured jOOQ Tests +=== Auto-configured jOOQ Tests + You can use `@JooqTest` in a similar fashion as `@JdbcTest` but for jOOQ-related tests. As jOOQ relies heavily on a Java-based schema that corresponds with the database schema, the existing `DataSource` is used. If you want to replace it with an in-memory database, you can use `@AutoConfigureTestDatabase` to override those settings. -(For more about using jOOQ with Spring Boot, see "<>".) +(For more about using jOOQ with Spring Boot, see "xref:data/sql.adoc#data.sql.jooq[Using jOOQ]".) Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@JooqTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. -TIP: A list of the auto-configurations that are enabled by `@JooqTest` can be <>. +TIP: A list of the auto-configurations that are enabled by `@JooqTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix]. `@JooqTest` configures a `DSLContext`. The following example shows the `@JooqTest` annotation in use: -include::code:MyJooqTests[] +include-code::MyJooqTests[] JOOQ tests are transactional and roll back at the end of each test by default. -If that is not what you want, you can disable transaction management for a test or for the whole test class as <>. +If that is not what you want, you can disable transaction management for a test or for the whole test class as xref:features/testing.adoc#features.testing.spring-boot-applications.autoconfigured-jdbc[shown in the JDBC example]. [[features.testing.spring-boot-applications.autoconfigured-spring-data-mongodb]] -==== Auto-configured Data MongoDB Tests +=== Auto-configured Data MongoDB Tests + You can use `@DataMongoTest` to test MongoDB applications. By default, it 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 "<>".) +(For more about using MongoDB with Spring Boot, see "xref:data/nosql.adoc#data.nosql.mongodb[MongoDB]".) -TIP: A list of the auto-configuration settings that are enabled by `@DataMongoTest` can be <>. +TIP: A list of the auto-configuration settings that are enabled by `@DataMongoTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix]. The following class shows the `@DataMongoTest` annotation in use: -include::code:MyDataMongoDbTests[] +include-code::MyDataMongoDbTests[] [[features.testing.spring-boot-applications.autoconfigured-spring-data-neo4j]] -==== Auto-configured Data Neo4j Tests +=== Auto-configured Data Neo4j Tests + You can use `@DataNeo4jTest` to test Neo4j applications. By default, it scans for `@Node` classes, and configures Spring Data Neo4j repositories. 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 "<>".) +(For more about using Neo4J with Spring Boot, see "xref:data/nosql.adoc#data.nosql.neo4j[Neo4j]".) -TIP: A list of the auto-configuration settings that are enabled by `@DataNeo4jTest` can be <>. +TIP: A list of the auto-configuration settings that are enabled by `@DataNeo4jTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix]. The following example shows a typical setup for using Neo4J tests in Spring Boot: -include::code:propagation/MyDataNeo4jTests[] +include-code::propagation/MyDataNeo4jTests[] By default, Data Neo4j tests are transactional and roll back at the end of each test. -See the {spring-framework-docs}/testing/testcontext-framework/tx.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. +See the {url-spring-framework-docs}/testing/testcontext-framework/tx.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. If that is not what you want, you can disable transaction management for a test or for the whole class, as follows: -include::code:nopropagation/MyDataNeo4jTests[] +include-code::nopropagation/MyDataNeo4jTests[] NOTE: Transactional tests are not supported with reactive access. If you are using this style, you must configure `@DataNeo4jTest` tests as described above. @@ -712,66 +745,70 @@ If you are using this style, you must configure `@DataNeo4jTest` tests as descri [[features.testing.spring-boot-applications.autoconfigured-spring-data-redis]] -==== Auto-configured Data Redis Tests +=== Auto-configured Data Redis Tests + You can use `@DataRedisTest` to test Redis applications. By default, it scans for `@RedisHash` classes and configures Spring Data Redis repositories. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataRedisTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. -(For more about using Redis with Spring Boot, see "<>".) +(For more about using Redis with Spring Boot, see "xref:data/nosql.adoc#data.nosql.redis[Redis]".) -TIP: A list of the auto-configuration settings that are enabled by `@DataRedisTest` can be <>. +TIP: A list of the auto-configuration settings that are enabled by `@DataRedisTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix]. The following example shows the `@DataRedisTest` annotation in use: -include::code:MyDataRedisTests[] +include-code::MyDataRedisTests[] [[features.testing.spring-boot-applications.autoconfigured-spring-data-ldap]] -==== Auto-configured Data LDAP Tests +=== Auto-configured Data LDAP Tests + You can use `@DataLdapTest` to test LDAP applications. By default, it configures an in-memory embedded LDAP (if available), configures an `LdapTemplate`, scans for `@Entry` classes, and configures Spring Data LDAP repositories. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataLdapTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. -(For more about using LDAP with Spring Boot, see "<>".) +(For more about using LDAP with Spring Boot, see "xref:data/nosql.adoc#data.nosql.ldap[LDAP]".) -TIP: A list of the auto-configuration settings that are enabled by `@DataLdapTest` can be <>. +TIP: A list of the auto-configuration settings that are enabled by `@DataLdapTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix]. The following example shows the `@DataLdapTest` annotation in use: -include::code:inmemory/MyDataLdapTests[] +include-code::inmemory/MyDataLdapTests[] In-memory embedded LDAP generally works well for tests, since it is fast and does not require any developer installation. If, however, you prefer to run tests against a real LDAP server, you should exclude the embedded LDAP auto-configuration, as shown in the following example: -include::code:server/MyDataLdapTests[] +include-code::server/MyDataLdapTests[] [[features.testing.spring-boot-applications.autoconfigured-rest-client]] -==== Auto-configured REST Clients +=== Auto-configured REST Clients + You can use the `@RestClientTest` annotation to test REST clients. By default, it auto-configures Jackson, GSON, and Jsonb support, configures a `RestTemplateBuilder` and a `RestClient.Builder`, and adds support for `MockRestServiceServer`. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@RestClientTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. -TIP: A list of the auto-configuration settings that are enabled by `@RestClientTest` can be <>. +TIP: A list of the auto-configuration settings that are enabled by `@RestClientTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix]. The specific beans that you want to test should be specified by using the `value` or `components` attribute of `@RestClientTest`. When using a `RestTemplateBuilder` in the beans under test and `RestTemplateBuilder.rootUri(String rootUri)` has been called when building the `RestTemplate`, then the root URI should be omitted from the `MockRestServiceServer` expectations as shown in the following example: -include::code:MyRestTemplateServiceTests[] +include-code::MyRestTemplateServiceTests[] When using a `RestClient.Builder` in the beans under test, or when using a `RestTemplateBuilder` without calling `rootUri(String rootURI)`, the full URI must be used in the `MockRestServiceServer` expectations as shown in the following example: -include::code:MyRestClientServiceTests[] +include-code::MyRestClientServiceTests[] [[features.testing.spring-boot-applications.autoconfigured-spring-restdocs]] -==== Auto-configured Spring REST Docs Tests -You can use the `@AutoConfigureRestDocs` annotation to use {spring-restdocs}[Spring REST Docs] in your tests with Mock MVC, REST Assured, or WebTestClient. +=== Auto-configured Spring REST Docs Tests + +You can use the `@AutoConfigureRestDocs` annotation to use {url-spring-restdocs-site}[Spring REST Docs] in your tests with Mock MVC, REST Assured, or WebTestClient. It removes the need for the JUnit extension in Spring REST Docs. `@AutoConfigureRestDocs` can be used to override the default output directory (`target/generated-snippets` if you are using Maven or `build/generated-snippets` if you are using Gradle). @@ -780,105 +817,111 @@ It can also be used to configure the host, scheme, and port that appears in any [[features.testing.spring-boot-applications.autoconfigured-spring-restdocs.with-mock-mvc]] -===== Auto-configured Spring REST Docs Tests With Mock MVC +==== Auto-configured Spring REST Docs Tests With Mock MVC + `@AutoConfigureRestDocs` customizes the `MockMvc` bean to use Spring REST Docs when testing servlet-based web applications. You can inject it by using `@Autowired` and use it in your tests as you normally would when using Mock MVC and Spring REST Docs, as shown in the following example: -include::code:MyUserDocumentationTests[] +include-code::MyUserDocumentationTests[] If you require more control over Spring REST Docs configuration than offered by the attributes of `@AutoConfigureRestDocs`, you can use a `RestDocsMockMvcConfigurationCustomizer` bean, as shown in the following example: -include::code:MyRestDocsConfiguration[] +include-code::MyRestDocsConfiguration[] If you want to make use of Spring REST Docs support for a parameterized output directory, you can create a `RestDocumentationResultHandler` bean. The auto-configuration calls `alwaysDo` with this result handler, thereby causing each `MockMvc` call to automatically generate the default snippets. The following example shows a `RestDocumentationResultHandler` being defined: -include::code:MyResultHandlerConfiguration[] +include-code::MyResultHandlerConfiguration[] [[features.testing.spring-boot-applications.autoconfigured-spring-restdocs.with-web-test-client]] -===== Auto-configured Spring REST Docs Tests With WebTestClient +==== Auto-configured Spring REST Docs Tests With WebTestClient + `@AutoConfigureRestDocs` can also be used with `WebTestClient` when testing reactive web applications. You can inject it by using `@Autowired` and use it in your tests as you normally would when using `@WebFluxTest` and Spring REST Docs, as shown in the following example: -include::code:MyUsersDocumentationTests[] +include-code::MyUsersDocumentationTests[] If you require more control over Spring REST Docs configuration than offered by the attributes of `@AutoConfigureRestDocs`, you can use a `RestDocsWebTestClientConfigurationCustomizer` bean, as shown in the following example: -include::code:MyRestDocsConfiguration[] +include-code::MyRestDocsConfiguration[] If you want to make use of Spring REST Docs support for a parameterized output directory, you can use a `WebTestClientBuilderCustomizer` to configure a consumer for every entity exchange result. The following example shows such a `WebTestClientBuilderCustomizer` being defined: -include::code:MyWebTestClientBuilderCustomizerConfiguration[] +include-code::MyWebTestClientBuilderCustomizerConfiguration[] [[features.testing.spring-boot-applications.autoconfigured-spring-restdocs.with-rest-assured]] -===== Auto-configured Spring REST Docs Tests With REST Assured +==== Auto-configured Spring REST Docs Tests With REST Assured + `@AutoConfigureRestDocs` makes a `RequestSpecification` bean, preconfigured to use Spring REST Docs, available to your tests. You can inject it by using `@Autowired` and use it in your tests as you normally would when using REST Assured and Spring REST Docs, as shown in the following example: -include::code:MyUserDocumentationTests[] +include-code::MyUserDocumentationTests[] If you require more control over Spring REST Docs configuration than offered by the attributes of `@AutoConfigureRestDocs`, a `RestDocsRestAssuredConfigurationCustomizer` bean can be used, as shown in the following example: -include::code:MyRestDocsConfiguration[] +include-code::MyRestDocsConfiguration[] [[features.testing.spring-boot-applications.autoconfigured-webservices]] -==== Auto-configured Spring Web Services Tests +=== Auto-configured Spring Web Services Tests [[features.testing.spring-boot-applications.autoconfigured-webservices.client]] -===== Auto-configured Spring Web Services Client Tests +==== Auto-configured Spring Web Services Client Tests + You can use `@WebServiceClientTest` to test applications that call web services using the Spring Web Services project. By default, it configures a mock `WebServiceServer` bean and automatically customizes your `WebServiceTemplateBuilder`. -(For more about using Web Services with Spring Boot, see "<>".) +(For more about using Web Services with Spring Boot, see "xref:io/webservices.adoc[Web Services]".) -TIP: A list of the auto-configuration settings that are enabled by `@WebServiceClientTest` can be <>. +TIP: A list of the auto-configuration settings that are enabled by `@WebServiceClientTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix]. The following example shows the `@WebServiceClientTest` annotation in use: -include::code:MyWebServiceClientTests[] +include-code::MyWebServiceClientTests[] [[features.testing.spring-boot-applications.autoconfigured-webservices.server]] -===== Auto-configured Spring Web Services Server Tests +==== Auto-configured Spring Web Services Server Tests + You can use `@WebServiceServerTest` to test applications that implement web services using the Spring Web Services project. By default, it configures a `MockWebServiceClient` bean that can be used to call your web service endpoints. -(For more about using Web Services with Spring Boot, see "<>".) +(For more about using Web Services with Spring Boot, see "xref:io/webservices.adoc[Web Services]".) -TIP: A list of the auto-configuration settings that are enabled by `@WebServiceServerTest` can be <>. +TIP: A list of the auto-configuration settings that are enabled by `@WebServiceServerTest` can be xref:appendix:test-auto-configuration/index.adoc[found in the appendix]. The following example shows the `@WebServiceServerTest` annotation in use: -include::code:MyWebServiceServerTests[] +include-code::MyWebServiceServerTests[] [[features.testing.spring-boot-applications.additional-autoconfiguration-and-slicing]] -==== Additional Auto-configuration and Slicing +=== Additional Auto-configuration and Slicing + Each slice provides one or more `@AutoConfigure...` annotations that namely defines the auto-configurations that should be included as part of a slice. Additional auto-configurations can be added on a test-by-test basis by creating a custom `@AutoConfigure...` annotation or by adding `@ImportAutoConfiguration` to the test as shown in the following example: -include::code:MyJdbcTests[] +include-code::MyJdbcTests[] NOTE: Make sure to not use the regular `@Import` annotation to import auto-configurations as they are handled in a specific way by Spring Boot. Alternatively, additional auto-configurations can be added for any use of a slice annotation by registering them in a file stored in `META-INF/spring` as shown in the following example: .META-INF/spring/org.springframework.boot.test.autoconfigure.jdbc.JdbcTest.imports -[indent=0] +[source] ---- - com.example.IntegrationAutoConfiguration +com.example.IntegrationAutoConfiguration ---- In this example, the `com.example.IntegrationAutoConfiguration` is enabled on every test annotated with `@JdbcTest`. @@ -890,39 +933,40 @@ TIP: A slice or `@AutoConfigure...` annotation can be customized this way as lon [[features.testing.spring-boot-applications.user-configuration-and-slicing]] -==== User Configuration and Slicing -If you <> in a sensible way, your `@SpringBootApplication` class is <> as the configuration of your tests. +=== User Configuration and Slicing + +If you xref:using/structuring-your-code.adoc[structure your code] in a sensible way, your `@SpringBootApplication` class is xref:features/testing.adoc#features.testing.spring-boot-applications.detecting-configuration[used by default] as the configuration of your tests. It then becomes important not to litter the application's main class with configuration settings that are specific to a particular area of its functionality. Assume that you are using Spring Data MongoDB, you rely on the auto-configuration for it, and you have enabled auditing. You could define your `@SpringBootApplication` as follows: -include::code:MyApplication[] +include-code::MyApplication[] Because this class is the source configuration for the test, any slice test actually tries to enable Mongo auditing, which is definitely not what you want to do. A recommended approach is to move that area-specific configuration to a separate `@Configuration` class at the same level as your application, as shown in the following example: -include::code:MyMongoConfiguration[] +include-code::MyMongoConfiguration[] NOTE: Depending on the complexity of your application, you may either have a single `@Configuration` class for your customizations or one class per domain area. The latter approach lets you enable it in one of your tests, if necessary, with the `@Import` annotation. -See <> for more details on when you might want to enable specific `@Configuration` classes for slice tests. +See xref:how-to:testing.adoc#howto.testing.slice-tests[this how-to section] for more details on when you might want to enable specific `@Configuration` classes for slice tests. Test slices exclude `@Configuration` classes from scanning. For example, for a `@WebMvcTest`, the following configuration will not include the given `WebMvcConfigurer` bean in the application context loaded by the test slice: -include::code:MyWebConfiguration[] +include-code::MyWebConfiguration[] The configuration below will, however, cause the custom `WebMvcConfigurer` to be loaded by the test slice. -include::code:MyWebMvcConfigurer[] +include-code::MyWebMvcConfigurer[] Another source of confusion is classpath scanning. Assume that, while you structured your code in a sensible way, you need to scan an additional package. Your application may resemble the following code: -include::code:scan/MyApplication[] +include-code::scan/MyApplication[] Doing so effectively overrides the default component scan directive with the side effect of scanning those two packages regardless of the slice that you chose. For instance, a `@DataJpaTest` seems to suddenly scan components and user configurations of your application. @@ -934,7 +978,8 @@ Alternatively, you can specify a source for your test, which disables the behavi [[features.testing.spring-boot-applications.spock]] -==== Using Spock to Test Spring Boot Applications +=== Using Spock to Test Spring Boot Applications + Spock 2.2 or later can be used to test a Spring Boot application. To do so, add a dependency on a `-groovy-4.0` version of Spock's `spock-spring` module to your application's build. `spock-spring` integrates Spring's test framework into Spock. @@ -943,14 +988,15 @@ See https://spockframework.org/spock/docs/2.2-M1/modules.html#_spring_module[the [[features.testing.testcontainers]] -=== Testcontainers +== Testcontainers + The https://www.testcontainers.org/[Testcontainers] library provides a way to manage services running inside Docker containers. It integrates with JUnit, allowing you to write a test class that can start up a container before any of the tests run. Testcontainers is especially useful for writing integration tests that talk to a real backend service such as MySQL, MongoDB, Cassandra and others. Testcontainers can be used in a Spring Boot test as follows: -include::code:vanilla/MyIntegrationTests[] +include-code::vanilla/MyIntegrationTests[] This will start up a docker container running Neo4j (if Docker is running locally) before any of the tests are run. In most cases, you will need to configure the application to connect to the service running in the container. @@ -958,14 +1004,15 @@ In most cases, you will need to configure the application to connect to the serv [[features.testing.testcontainers.service-connections]] -==== Service Connections +=== Service Connections + A service connection is a connection to any remote service. Spring Boot's auto-configuration can consume the details of a service connection and use them to establish a connection to a remote service. When doing so, the connection details take precedence over any connection-related configuration properties. When using Testcontainers, connection details can be automatically created for a service running in a container by annotating the container field in the test class. -include::code:MyIntegrationTests[] +include-code::MyIntegrationTests[] Thanks to `@ServiceConnection`, the above configuration allows Neo4j-related beans in the application to communicate with Neo4j running inside the Testcontainers-managed Docker container. This is done by automatically defining a `Neo4jConnectionDetails` bean which is then used by the Neo4j auto-configuration, overriding any connection-related configuration properties. @@ -1051,7 +1098,7 @@ Instead, the return type of the bean method is used to find out which connection This works as long as you're using typed containers, e.g. `Neo4jContainer` or `RabbitMQContainer`. This stops working if you're using `GenericContainer`, e.g. with Redis, as shown in the following example: -include::code:MyRedisConfiguration[] +include-code::MyRedisConfiguration[] Spring Boot can't tell from `GenericContainer` which container image is used, so the `name` attribute from `@ServiceConnection` must be used to provide that hint. @@ -1061,28 +1108,31 @@ If you are using the Docker image `registry.mycompany.com/mirror/myredis`, you'd [[features.testing.testcontainers.dynamic-properties]] -==== Dynamic Properties +=== Dynamic Properties + A slightly more verbose but also more flexible alternative to service connections is `@DynamicPropertySource`. A static `@DynamicPropertySource` method allows adding dynamic property values to the Spring Environment. -include::code:MyIntegrationTests[] +include-code::MyIntegrationTests[] The above configuration allows Neo4j-related beans in the application to communicate with Neo4j running inside the Testcontainers-managed Docker container. [[features.testing.utilities]] -=== Test Utilities +== Test Utilities + A few test utility classes that are generally useful when testing your application are packaged as part of `spring-boot`. [[features.testing.utilities.config-data-application-context-initializer]] -==== ConfigDataApplicationContextInitializer +=== ConfigDataApplicationContextInitializer + `ConfigDataApplicationContextInitializer` is an `ApplicationContextInitializer` that you can apply to your tests to load Spring Boot `application.properties` files. You can use it when you do not need the full set of features provided by `@SpringBootTest`, as shown in the following example: -include::code:MyConfigFileTests[] +include-code::MyConfigFileTests[] NOTE: Using `ConfigDataApplicationContextInitializer` alone does not provide support for `@Value("${...}")` injection. Its only job is to ensure that `application.properties` files are loaded into Spring's `Environment`. @@ -1091,32 +1141,35 @@ For `@Value` support, you need to either additionally configure a `PropertySourc [[features.testing.utilities.test-property-values]] -==== TestPropertyValues +=== TestPropertyValues + `TestPropertyValues` lets you quickly add properties to a `ConfigurableEnvironment` or `ConfigurableApplicationContext`. You can call it with `key=value` strings, as follows: -include::code:MyEnvironmentTests[] +include-code::MyEnvironmentTests[] [[features.testing.utilities.output-capture]] -==== OutputCapture +=== OutputCapture + `OutputCapture` is a JUnit `Extension` that you can use to capture `System.out` and `System.err` output. To use it, add `@ExtendWith(OutputCaptureExtension.class)` and inject `CapturedOutput` as an argument to your test class constructor or test method as follows: -include::code:MyOutputCaptureTests[] +include-code::MyOutputCaptureTests[] [[features.testing.utilities.test-rest-template]] -==== TestRestTemplate +=== TestRestTemplate + `TestRestTemplate` is a convenience alternative to Spring's `RestTemplate` that is useful in integration tests. You can get a vanilla template or one that sends Basic HTTP authentication (with a username and password). In either case, the template is fault tolerant. This means that it behaves in a test-friendly way by not throwing exceptions on 4xx and 5xx errors. Instead, such errors can be detected through the returned `ResponseEntity` and its status code. -TIP: Spring Framework 5.0 provides a new `WebTestClient` that works for <> and both <>. +TIP: Spring Framework 5.0 provides a new `WebTestClient` that works for xref:features/testing.adoc#features.testing.spring-boot-applications.spring-webflux-tests[WebFlux integration tests] and both xref:features/testing.adoc#features.testing.spring-boot-applications.with-running-server[WebFlux and MVC end-to-end testing]. It provides a fluent API for assertions, unlike `TestRestTemplate`. It is recommended, but not mandatory, to use the Apache HTTP Client (version 5.1 or better). @@ -1128,10 +1181,10 @@ If you do use Apache's HTTP client, some additional test-friendly features are e `TestRestTemplate` can be instantiated directly in your integration tests, as shown in the following example: -include::code:MyTests[] +include-code::MyTests[] Alternatively, if you use the `@SpringBootTest` annotation with `WebEnvironment.RANDOM_PORT` or `WebEnvironment.DEFINED_PORT`, you can inject a fully configured `TestRestTemplate` and start using it. If necessary, additional customizations can be applied through the `RestTemplateBuilder` bean. Any URLs that do not specify a host and port automatically connect to the embedded server, as shown in the following example: -include::code:MySpringBootTests[] +include-code::MySpringBootTests[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/caching.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/caching.adoc similarity index 78% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/caching.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/caching.adoc index fcbf3fc7bc..e19cd057e1 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/caching.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/caching.adoc @@ -1,15 +1,16 @@ [[io.caching]] -== Caching += Caching + The Spring Framework provides support for transparently adding caching to an application. At its core, the abstraction applies caching to methods, thus reducing the number of executions based on the information available in the cache. The caching logic is applied transparently, without any interference to the invoker. Spring Boot auto-configures the cache infrastructure as long as caching support is enabled by using the `@EnableCaching` annotation. -NOTE: Check the {spring-framework-docs}/integration/cache.html[relevant section] of the Spring Framework reference for more details. +NOTE: Check the {url-spring-framework-docs}/integration/cache.html[relevant section] of the Spring Framework reference for more details. In a nutshell, to add caching to an operation of your service add the relevant annotation to its method, as shown in the following example: -include::code:MyMathService[] +include-code::MyMathService[] This example demonstrates the use of caching on a potentially costly operation. Before invoking `computePiDecimal`, the abstraction looks for an entry in the `piDecimals` cache that matches the `i` argument. @@ -19,37 +20,38 @@ 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 xref:io/caching.adoc#io.caching.provider.simple[simple provider] that uses concurrent maps in memory. When a cache is required (such as `piDecimals` in the preceding example), this provider creates it for you. The simple provider is not really recommended for production usage, but it is great for getting started and making sure that you understand the features. When you have made up your mind about the cache provider to use, please make sure to read its documentation to figure out how to configure the caches that your application uses. Nearly all providers require you to explicitly configure every cache that you use in the application. Some offer a way to customize the default caches defined by the configprop:spring.cache.cache-names[] property. -TIP: It is also possible to transparently {spring-framework-docs}/integration/cache/annotations.html#cache-annotations-put[update] or {spring-framework-docs}/integration/cache/annotations.html#cache-annotations-evict[evict] data from the cache. +TIP: It is also possible to transparently {url-spring-framework-docs}/integration/cache/annotations.html#cache-annotations-put[update] or {url-spring-framework-docs}/integration/cache/annotations.html#cache-annotations-evict[evict] data from the cache. [[io.caching.provider]] -=== Supported Cache Providers +== 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): +If you have not defined a bean of type `CacheManager` or a `CacheResolver` named `cacheResolver` (see {url-spring-framework-javadoc}/org/springframework/cache/annotation/CachingConfigurer.html[`CachingConfigurer`]), Spring Boot tries to detect the following providers (in the indicated order): -. <> -. <> (EhCache 3, Hazelcast, Infinispan, and others) -. <> -. <> -. <> -. <> -. <> -. <> -. <> +. xref:io/caching.adoc#io.caching.provider.generic[Generic] +. xref:io/caching.adoc#io.caching.provider.jcache[JCache (JSR-107)] (EhCache 3, Hazelcast, Infinispan, and others) +. xref:io/caching.adoc#io.caching.provider.hazelcast[Hazelcast] +. xref:io/caching.adoc#io.caching.provider.infinispan[Infinispan] +. xref:io/caching.adoc#io.caching.provider.couchbase[Couchbase] +. xref:io/caching.adoc#io.caching.provider.redis[Redis] +. xref:io/caching.adoc#io.caching.provider.caffeine[Caffeine] +. xref:io/caching.adoc#io.caching.provider.cache2k[Cache2k] +. xref:io/caching.adoc#io.caching.provider.simple[Simple] -Additionally, {spring-boot-for-apache-geode}[Spring Boot for Apache Geode] provides {spring-boot-for-apache-geode-docs}#geode-caching-provider[auto-configuration for using Apache Geode as a cache provider]. +Additionally, {url-spring-boot-for-apache-geode-site}[Spring Boot for Apache Geode] provides {url-spring-boot-for-apache-geode-docs}#geode-caching-provider[auto-configuration for using Apache Geode as a cache provider]. TIP: If the `CacheManager` is auto-configured by Spring Boot, it is possible to _force_ a particular cache provider by setting the configprop:spring.cache.type[] property. -Use this property if you need to <> in certain environments (such as tests). +Use this property if you need to xref:io/caching.adoc#io.caching.provider.none[use no-op caches] in certain environments (such as tests). TIP: Use the `spring-boot-starter-cache` "`Starter`" to quickly add basic caching dependencies. The starter brings in `spring-context-support`. @@ -58,7 +60,7 @@ If you add dependencies manually, you must include `spring-context-support` in o If the `CacheManager` is auto-configured by Spring Boot, you can further tune its configuration before it is fully initialized by exposing a bean that implements the `CacheManagerCustomizer` interface. The following example sets a flag to say that `null` values should not be passed down to the underlying map: -include::code:MyCacheManagerConfiguration[] +include-code::MyCacheManagerConfiguration[] NOTE: In the preceding example, an auto-configured `ConcurrentMapCacheManager` is expected. If that is not the case (either you provided your own config or a different cache provider was auto-configured), the customizer is not invoked at all. @@ -67,14 +69,16 @@ You can have as many customizers as you want, and you can also order them by usi [[io.caching.provider.generic]] -==== Generic +=== Generic + Generic caching is used if the context defines _at least_ one `org.springframework.cache.Cache` bean. A `CacheManager` wrapping all beans of that type is created. [[io.caching.provider.jcache]] -==== JCache (JSR-107) +=== JCache (JSR-107) + https://jcp.org/en/jsr/detail?id=107[JCache] is bootstrapped through the presence of a `javax.cache.spi.CachingProvider` on the classpath (that is, a JSR-107 compliant caching library exists on the classpath), and the `JCacheCacheManager` is provided by the `spring-boot-starter-cache` "`Starter`". Various compliant libraries are available, and Spring Boot provides dependency management for Ehcache 3, Hazelcast, and Infinispan. Any other compliant library can be added as well. @@ -82,7 +86,7 @@ Any other compliant library can be added as well. It might happen that more than one provider is present, in which case the provider must be explicitly specified. Even if the JSR-107 standard does not enforce a standardized way to define the location of the configuration file, Spring Boot does its best to accommodate setting a cache with implementation details, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- # Only necessary if more than one provider is present spring: @@ -94,7 +98,7 @@ Even if the JSR-107 standard does not enforce a standardized way to define the l NOTE: When a cache library offers both a native implementation and JSR-107 support, Spring Boot prefers the JSR-107 support, so that the same features are available if you switch to a different JSR-107 implementation. -TIP: Spring Boot has <>. +TIP: Spring Boot has xref:io/hazelcast.adoc[general support for Hazelcast]. If a single `HazelcastInstance` is available, it is automatically reused for the `CacheManager` as well, unless the configprop:spring.cache.jcache.config[] property is specified. There are two ways to customize the underlying `javax.cache.cacheManager`: @@ -109,28 +113,30 @@ No further customization is applied to it. [[io.caching.provider.hazelcast]] -==== Hazelcast +=== Hazelcast -Spring Boot has <>. +Spring Boot has xref:io/hazelcast.adoc[general support for Hazelcast]. If a `HazelcastInstance` has been auto-configured and `com.hazelcast:hazelcast-spring` is on the classpath, it is automatically wrapped in a `CacheManager`. NOTE: Hazelcast can be used as a JCache compliant cache or as a Spring `CacheManager` compliant cache. When setting configprop:spring.cache.type[] to `hazelcast`, Spring Boot will use the `CacheManager` based implementation. If you want to use Hazelcast as a JCache compliant cache, set configprop:spring.cache.type[] to `jcache`. -If you have multiple JCache compliant cache providers and want to force the use of Hazelcast, you have to <>. +If you have multiple JCache compliant cache providers and want to force the use of Hazelcast, you have to xref:io/caching.adoc#io.caching.provider.jcache[explicitly set the JCache provider]. + + [[io.caching.provider.infinispan]] -==== Infinispan +=== Infinispan https://infinispan.org/[Infinispan] has no default configuration file location, so it must be specified explicitly. Otherwise, the default bootstrap is used. -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - cache: - infinispan: - config: "infinispan.xml" +spring: + cache: + infinispan: + config: "infinispan.xml" ---- Caches can be created on startup by setting the configprop:spring.cache.cache-names[] property. @@ -143,40 +149,42 @@ For example, `infinispan-core-jakarta` and `infinispan-commons-jakarta` must be [[io.caching.provider.couchbase]] -==== Couchbase -If Spring Data Couchbase is available and Couchbase is <>, a `CouchbaseCacheManager` is auto-configured. +=== Couchbase + +If Spring Data Couchbase is available and Couchbase is xref:data/nosql.adoc#data.nosql.couchbase[configured], a `CouchbaseCacheManager` is auto-configured. It is possible to create additional caches on startup by setting the configprop:spring.cache.cache-names[] property and cache defaults can be configured by using `spring.cache.couchbase.*` properties. For instance, the following configuration creates `cache1` and `cache2` caches with an entry _expiration_ of 10 minutes: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - cache: - cache-names: "cache1,cache2" - couchbase: - expiration: "10m" +spring: + cache: + cache-names: "cache1,cache2" + couchbase: + expiration: "10m" ---- If you need more control over the configuration, consider registering a `CouchbaseCacheManagerBuilderCustomizer` bean. The following example shows a customizer that configures a specific entry expiration for `cache1` and `cache2`: -include::code:MyCouchbaseCacheManagerConfiguration[] +include-code::MyCouchbaseCacheManagerConfiguration[] [[io.caching.provider.redis]] -==== Redis +=== Redis + If https://redis.io/[Redis] is available and configured, a `RedisCacheManager` is auto-configured. It is possible to create additional caches on startup by setting the configprop:spring.cache.cache-names[] property and cache defaults can be configured by using `spring.cache.redis.*` properties. For instance, the following configuration creates `cache1` and `cache2` caches with a _time to live_ of 10 minutes: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - cache: - cache-names: "cache1,cache2" - redis: - time-to-live: "10m" +spring: + cache: + cache-names: "cache1,cache2" + redis: + time-to-live: "10m" ---- NOTE: By default, a key prefix is added so that, if two separate caches use the same key, Redis does not have overlapping keys and cannot return invalid values. @@ -188,12 +196,13 @@ This can be useful if you need to customize the default serialization strategy. If you need more control over the configuration, consider registering a `RedisCacheManagerBuilderCustomizer` bean. The following example shows a customizer that configures a specific time to live for `cache1` and `cache2`: -include::code:MyRedisCacheManagerConfiguration[] +include-code::MyRedisCacheManagerConfiguration[] [[io.caching.provider.caffeine]] -==== Caffeine +=== Caffeine + https://github.com/ben-manes/caffeine[Caffeine] is a Java 8 rewrite of Guava's cache that supersedes support for Guava. If Caffeine is present, a `CaffeineCacheManager` (provided by the `spring-boot-starter-cache` "`Starter`") is auto-configured. Caches can be created on startup by setting the configprop:spring.cache.cache-names[] property and can be customized by one of the following (in the indicated order): @@ -204,13 +213,13 @@ Caches can be created on startup by setting the configprop:spring.cache.cache-na For instance, the following configuration creates `cache1` and `cache2` caches with a maximum size of 500 and a _time to live_ of 10 minutes -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - cache: - cache-names: "cache1,cache2" - caffeine: - spec: "maximumSize=500,expireAfterAccess=600s" +spring: + cache: + cache-names: "cache1,cache2" + caffeine: + spec: "maximumSize=500,expireAfterAccess=600s" ---- If a `com.github.benmanes.caffeine.cache.CacheLoader` bean is defined, it is automatically associated to the `CaffeineCacheManager`. @@ -220,7 +229,8 @@ The auto-configuration ignores any other generic type. [[io.caching.provider.cache2k]] -==== Cache2k +=== Cache2k + https://cache2k.org/[Cache2k] is an in-memory cache. If the Cache2k spring integration is present, a `SpringCache2kCacheManager` is auto-configured. @@ -228,22 +238,23 @@ Caches can be created on startup by setting the configprop:spring.cache.cache-na Cache defaults can be customized using a `Cache2kBuilderCustomizer` bean. The following example shows a customizer that configures the capacity of the cache to 200 entries, with an expiration of 5 minutes: -include::code:MyCache2kDefaultsConfiguration[] +include-code::MyCache2kDefaultsConfiguration[] [[io.caching.provider.simple]] -==== Simple +=== Simple + If none of the other providers can be found, a simple implementation using a `ConcurrentHashMap` as the cache store is configured. This is the default if no caching library is present in your application. By default, caches are created as needed, but you can restrict the list of available caches by setting the `cache-names` property. For instance, if you want only `cache1` and `cache2` caches, set the `cache-names` property as follows: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - cache: - cache-names: "cache1,cache2" +spring: + cache: + cache-names: "cache1,cache2" ---- If you do so and your application uses a cache not listed, then it fails at runtime when the cache is needed, but not on startup. @@ -252,16 +263,17 @@ This is similar to the way the "real" cache providers behave if you use an undec [[io.caching.provider.none]] -==== None +=== None + When `@EnableCaching` is present in your configuration, a suitable cache configuration is expected as well. If you have a custom `CacheManager`, consider defining it in a separate `@Configuration` class so that you can override it if necessary. None uses a no-op implementation that is useful in tests, and slice tests use that by default via `@AutoConfigureCache`. If you need to use a no-op cache rather than the auto-configured cache manager in a certain environment, set the cache type to `none`, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - cache: - type: "none" +spring: + cache: + type: "none" ---- diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/email.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/email.adoc similarity index 58% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/email.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/email.adoc index 0646df468f..2645b4e91c 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/email.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/email.adoc @@ -1,32 +1,33 @@ [[io.email]] -== Sending Email += Sending Email + The Spring Framework provides an abstraction for sending email by using the `JavaMailSender` interface, and Spring Boot provides auto-configuration for it as well as a starter module. -TIP: See the {spring-framework-docs}/integration/email.html[reference documentation] for a detailed explanation of how you can use `JavaMailSender`. +TIP: See the {url-spring-framework-docs}/integration/email.html[reference documentation] for a detailed explanation of how you can use `JavaMailSender`. If `spring.mail.host` and the relevant libraries (as defined by `spring-boot-starter-mail`) are available, a default `JavaMailSender` is created if none exists. The sender can be further customized by configuration items from the `spring.mail` namespace. -See {spring-boot-autoconfigure-module-code}/mail/MailProperties.java[`MailProperties`] for more details. +See {code-spring-boot-autoconfigure-src}/mail/MailProperties.java[`MailProperties`] for more details. In particular, certain default timeout values are infinite, and you may want to change that to avoid having a thread blocked by an unresponsive mail server, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - mail: - properties: - "[mail.smtp.connectiontimeout]": 5000 - "[mail.smtp.timeout]": 3000 - "[mail.smtp.writetimeout]": 5000 +spring: + mail: + properties: + "[mail.smtp.connectiontimeout]": 5000 + "[mail.smtp.timeout]": 3000 + "[mail.smtp.writetimeout]": 5000 ---- It is also possible to configure a `JavaMailSender` with an existing `Session` from JNDI: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - mail: - jndi-name: "mail/Session" +spring: + mail: + jndi-name: "mail/Session" ---- When a `jndi-name` is set, it takes precedence over all other Session-related settings. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/hazelcast.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/hazelcast.adoc similarity index 87% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/hazelcast.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/hazelcast.adoc index a0998eecd1..761f8c6c29 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/hazelcast.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/hazelcast.adoc @@ -1,5 +1,6 @@ [[io.hazelcast]] -== Hazelcast += Hazelcast + If https://hazelcast.com/[Hazelcast] is on the classpath and a suitable configuration is found, Spring Boot auto-configures a `HazelcastInstance` that you can inject in your application. Spring Boot first attempts to create a client by checking the following configuration options: @@ -16,11 +17,11 @@ If your configuration defines an instance name, Spring Boot tries to locate an e You could also specify the Hazelcast configuration file to use through configuration, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - hazelcast: - config: "classpath:config/my-hazelcast.xml" +spring: + hazelcast: + config: "classpath:config/my-hazelcast.xml" ---- Otherwise, Spring Boot tries to find the Hazelcast configuration from the default locations: `hazelcast.xml` in the working directory or at the root of the classpath, or a YAML counterpart in the same locations. @@ -30,5 +31,5 @@ See the https://docs.hazelcast.org/docs/latest/manual/html-single/[Hazelcast doc TIP: By default, `@SpringAware` on Hazelcast components is supported. The `ManagementContext` can be overridden by declaring a `HazelcastConfigCustomizer` bean with an `@Order` higher than zero. -NOTE: Spring Boot also has <>. +NOTE: Spring Boot also has xref:io/caching.adoc#io.caching.provider.hazelcast[explicit caching support for Hazelcast]. If caching is enabled, the `HazelcastInstance` is automatically wrapped in a `CacheManager` implementation. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/index.adoc similarity index 60% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/io.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/index.adoc index f21f11ffc2..12be6754f7 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/index.adoc @@ -1,26 +1,8 @@ [[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 will also cover calling remote REST or SOAP services and sending email. -include::io/caching.adoc[] - -include::io/hazelcast.adoc[] - -include::io/quartz.adoc[] - -include::io/email.adoc[] - -include::io/validation.adoc[] - -include::io/rest-client.adoc[] - -include::io/webservices.adoc[] - -include::io/jta.adoc[] - -include::io/whats-next.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/jta.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/jta.adoc similarity index 78% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/jta.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/jta.adoc index 5f9d1f3a20..2c082cb583 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/jta.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/jta.adoc @@ -1,5 +1,6 @@ [[io.jta]] -== Distributed Transactions With JTA += Distributed Transactions With JTA + Spring Boot supports distributed JTA transactions across multiple XA resources by using a transaction manager retrieved from JNDI. When a JTA environment is detected, Spring's `JtaTransactionManager` is used to manage transactions. @@ -10,36 +11,39 @@ If you are within a JTA environment and still want to use local transactions, yo [[io.jta.jakartaee]] -=== Using a Jakarta EE Managed Transaction Manager +== Using a Jakarta EE Managed Transaction Manager + If you package your Spring Boot application as a `war` or `ear` file and deploy it to a Jakarta EE application server, you can use your application server's built-in transaction manager. Spring Boot tries to auto-configure a transaction manager by looking at common JNDI locations (`java:comp/UserTransaction`, `java:comp/TransactionManager`, and so on). When using a transaction service provided by your application server, you generally also want to ensure that all resources are managed by the server and exposed over JNDI. -Spring Boot tries to auto-configure JMS by looking for a `ConnectionFactory` at the JNDI path (`java:/JmsXA` or `java:/XAConnectionFactory`), and you can use the <> 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 xref:data/sql.adoc#data.sql.datasource.jndi[configprop:spring.datasource.jndi-name[] property] to configure your `DataSource`. [[io.jta.mixing-xa-and-non-xa-connections]] -=== Mixing XA and Non-XA JMS Connections +== Mixing XA and Non-XA JMS Connections + When using JTA, the primary JMS `ConnectionFactory` bean is XA-aware and participates in distributed transactions. You can inject into your bean without needing to use any `@Qualifier`: -include::code:primary/MyBean[tag=*] +include-code::primary/MyBean[tag=*] In some situations, you might want to process certain JMS messages by using a non-XA `ConnectionFactory`. For example, your JMS processing logic might take longer than the XA timeout. If you want to use a non-XA `ConnectionFactory`, you can the `nonXaJmsConnectionFactory` bean: -include::code:nonxa/MyBean[tag=*] +include-code::nonxa/MyBean[tag=*] For consistency, the `jmsConnectionFactory` bean is also provided by using the bean alias `xaJmsConnectionFactory`: -include::code:xa/MyBean[tag=*] +include-code::xa/MyBean[tag=*] [[io.jta.supporting-embedded-transaction-manager]] -=== Supporting an 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 embedded transaction managers. +== Supporting an Embedded Transaction Manager + +The {code-spring-boot-src}/jms/XAConnectionFactoryWrapper.java[`XAConnectionFactoryWrapper`] and {code-spring-boot-src}/jdbc/XADataSourceWrapper.java[`XADataSourceWrapper`] interfaces can be used to support embedded transaction managers. The interfaces are responsible for wrapping `XAConnectionFactory` and `XADataSource` beans and exposing them as regular `ConnectionFactory` and `DataSource` beans, which transparently enroll in the distributed transaction. DataSource and JMS auto-configuration use JTA variants, provided you have a `JtaTransactionManager` bean and appropriate XA wrapper beans registered within your `ApplicationContext`. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/quartz.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/quartz.adoc similarity index 90% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/quartz.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/quartz.adoc index 285d826d63..75c440f8fd 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/quartz.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/quartz.adoc @@ -1,5 +1,6 @@ [[io.quartz]] -== Quartz Scheduler += 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). @@ -13,21 +14,21 @@ Beans of the following types are automatically picked up and associated with the By default, an in-memory `JobStore` is used. However, it is possible to configure a JDBC-based store if a `DataSource` bean is available in your application and if the configprop:spring.quartz.job-store-type[] property is configured accordingly, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - quartz: - job-store-type: "jdbc" +spring: + quartz: + job-store-type: "jdbc" ---- When the JDBC store is used, the schema can be initialized on startup, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - quartz: - jdbc: - initialize-schema: "always" +spring: + quartz: + jdbc: + initialize-schema: "always" ---- WARNING: By default, the database is detected and initialized by using the standard scripts provided with the Quartz library. @@ -50,4 +51,4 @@ If you need to customize the task executor, consider implementing `SchedulerFact Jobs can define setters to inject data map properties. Regular beans can also be injected in a similar manner, as shown in the following example: -include::code:MySampleJob[] +include-code::MySampleJob[] 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/antora/modules/reference/pages/io/rest-client.adoc similarity index 81% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/rest-client.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/rest-client.adoc index 6ec0da3ca5..7a9eaac213 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/rest-client.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/rest-client.adoc @@ -1,5 +1,6 @@ [[io.rest-client]] -== Calling REST Services += Calling REST Services + Spring Boot provides various convenient ways to call remote REST services. If you are developing a non-blocking reactive application and you're using Spring WebFlux, then you can use `WebClient`. If you prefer blocking APIs then you can use `RestClient` or `RestTemplate`. @@ -7,26 +8,28 @@ If you prefer blocking APIs then you can use `RestClient` or `RestTemplate`. [[io.rest-client.webclient]] -=== WebClient +== WebClient + If you have Spring WebFlux on your classpath we recommend that you use `WebClient` to call remote REST services. The `WebClient` interface provides a functional style API and is fully reactive. -You can learn more about the `WebClient` in the dedicated {spring-framework-docs}/web/webflux-webclient.html[section in the Spring Framework docs]. +You can learn more about the `WebClient` in the dedicated {url-spring-framework-docs}/web/webflux-webclient.html[section in the Spring Framework docs]. -TIP: If you are not writing a reactive Spring WebFlux application you can use the <> instead of a `WebClient`. +TIP: If you are not writing a reactive Spring WebFlux application you can use the xref:io/rest-client.adoc#io.rest-client.restclient[`RestClient`] instead of a `WebClient`. This provides a similar functional API, but is blocking rather than reactive. Spring Boot creates and pre-configures a prototype `WebClient.Builder` bean for you. It is strongly advised to inject it in your components and use it to create `WebClient` instances. -Spring Boot is configuring that builder to share HTTP resources and reflect codecs setup in the same fashion as the server ones (see <>), and more. +Spring Boot is configuring that builder to share HTTP resources and reflect codecs setup in the same fashion as the server ones (see xref:web/reactive.adoc#web.reactive.webflux.httpcodecs[WebFlux HTTP codecs auto-configuration]), and more. The following code shows a typical example: -include::code:MyService[] +include-code::MyService[] [[io.rest-client.webclient.runtime]] -==== WebClient Runtime +=== WebClient Runtime + Spring Boot will auto-detect which `ClientHttpConnector` to use to drive `WebClient` depending on the libraries available on the application classpath. In order of preference, the following clients are supported: @@ -45,12 +48,13 @@ Developers can override the resource configuration for Jetty and Reactor Netty b 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/webflux-webclient/client-builder.html[`WebClient` configuration options in the Spring Framework reference documentation]. +You can learn more about the {url-spring-framework-docs}/web/webflux-webclient/client-builder.html[`WebClient` configuration options in the Spring Framework reference documentation]. [[io.rest-client.webclient.customization]] -==== WebClient Customization +=== 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. @@ -65,19 +69,21 @@ In that case, no auto-configuration or `WebClientCustomizer` is applied. [[io.rest-client.webclient.ssl]] -==== WebClient SSL Support +=== WebClient SSL Support + If you need custom SSL configuration on the `ClientHttpConnector` used by the `WebClient`, you can inject a `WebClientSsl` instance that can be used with the builder's `apply` method. -The `WebClientSsl` interface provides access to any <> that you have defined in your `application.properties` or `application.yaml` file. +The `WebClientSsl` interface provides access to any xref:features/ssl.adoc#features.ssl.bundles[SSL bundles] that you have defined in your `application.properties` or `application.yaml` file. The following code shows a typical example: -include::code:MyService[] +include-code::MyService[] [[io.rest-client.restclient]] -=== RestClient +== RestClient + If you are not using Spring WebFlux or Project Reactor in your application we recommend that you use `RestClient` to call remote REST services. The `RestClient` interface provides a functional style blocking API. @@ -88,12 +94,13 @@ Spring Boot is configuring that builder with `HttpMessageConverters` and an appr The following code shows a typical example: -include::code:MyService[] +include-code::MyService[] [[io.rest-client.restclient.customization]] -==== RestClient Customization +=== RestClient Customization + There are three main approaches to `RestClient` customization, depending on how broadly you want the customizations to apply. To make the scope of any customizations as narrow as possible, inject the auto-configured `RestClient.Builder` and then call its methods as required. @@ -108,24 +115,26 @@ In that case, no auto-configuration or `RestClientCustomizer` is applied. [[io.rest-client.restclient.ssl]] -==== RestClient SSL Support +=== RestClient SSL Support + If you need custom SSL configuration on the `ClientHttpRequestFactory` used by the `RestClient`, you can inject a `RestClientSsl` instance that can be used with the builder's `apply` method. -The `RestClientSsl` interface provides access to any <> that you have defined in your `application.properties` or `application.yaml` file. +The `RestClientSsl` interface provides access to any xref:features/ssl.adoc#features.ssl.bundles[SSL bundles] that you have defined in your `application.properties` or `application.yaml` file. The following code shows a typical example: -include::code:MyService[] +include-code::MyService[] If you need to apply other customization in addition to an SSL bundle, you can use the `ClientHttpRequestFactorySettings` class with `ClientHttpRequestFactories`: -include::code:settings/MyService[] +include-code::settings/MyService[] [[io.rest-client.resttemplate]] -=== RestTemplate -Spring Framework's {spring-framework-api}/web/client/RestTemplate.html[`RestTemplate`] class predates `RestClient` and is the classic way that many applications use to call remote REST services. +== RestTemplate + +Spring Framework's {url-spring-framework-javadoc}/org/springframework/web/client/RestTemplate.html[`RestTemplate`] class predates `RestClient` and is the classic way that many applications use to call remote REST services. You might choose to use `RestTemplate` when you have existing code that you don't want to migrate to `RestClient`, or because you're already familiar with the `RestTemplate` API. Since `RestTemplate` instances often need to be customized before being used, Spring Boot does not provide any single auto-configured `RestTemplate` bean. @@ -134,7 +143,7 @@ The auto-configured `RestTemplateBuilder` ensures that sensible `HttpMessageConv The following code shows a typical example: -include::code:MyService[] +include-code::MyService[] `RestTemplateBuilder` includes a number of useful methods that can be used to quickly configure a `RestTemplate`. For example, to add BASIC authentication support, you can use `builder.basicAuthentication("user", "password").build()`. @@ -142,7 +151,8 @@ For example, to add BASIC authentication support, you can use `builder.basicAuth [[io.rest-client.resttemplate.customization]] -==== 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. @@ -153,14 +163,14 @@ All such beans are automatically registered with the auto-configured `RestTempla The following example shows a customizer that configures the use of a proxy for all hosts except `192.168.0.5`: -include::code:MyRestTemplateCustomizer[] +include-code::MyRestTemplateCustomizer[] Finally, you can define your own `RestTemplateBuilder` bean. Doing so will replace the auto-configured builder. If you want any `RestTemplateCustomizer` beans to be applied to your custom builder, as the auto-configuration would have done, configure it using a `RestTemplateBuilderConfigurer`. The following example exposes a `RestTemplateBuilder` that matches what Spring Boot's auto-configuration would have done, except that custom connect and read timeouts are also specified: -include::code:MyRestTemplateBuilderConfiguration[] +include-code::MyRestTemplateBuilderConfiguration[] The most extreme (and rarely used) option is to create your own `RestTemplateBuilder` bean without using a configurer. In addition to replacing the auto-configured builder, this also prevents any `RestTemplateCustomizer` beans from being used. @@ -168,15 +178,17 @@ In addition to replacing the auto-configured builder, this also prevents any `Re [[io.rest-client.resttemplate.ssl]] -==== RestTemplate SSL Support -If you need custom SSL configuration on the `RestTemplate`, you can apply an <> to the `RestTemplateBuilder` as shown in this example: +=== RestTemplate SSL Support -include::code:MyService[] +If you need custom SSL configuration on the `RestTemplate`, you can apply an xref:features/ssl.adoc#features.ssl.bundles[SSL bundle] to the `RestTemplateBuilder` as shown in this example: + +include-code::MyService[] [[io.rest-client.clienthttprequestfactory]] -=== HTTP Client Detection for RestClient and RestTemplate +== HTTP Client Detection for RestClient and RestTemplate + Spring Boot will auto-detect which HTTP client to use with `RestClient` and `RestTemplate` depending on the libraries available on the application classpath. In order of preference, the following clients are supported: diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/validation.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/validation.adoc similarity index 85% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/validation.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/validation.adoc index 092d48870f..59ad63a805 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/validation.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/validation.adoc @@ -1,15 +1,16 @@ [[io.validation]] -== Validation += Validation + The method validation feature supported by Bean Validation 1.1 is automatically enabled as long as a JSR-303 implementation (such as Hibernate validator) is on the classpath. This lets bean methods be annotated with `jakarta.validation` constraints on their parameters and/or on their return value. Target classes with such annotated methods need to be annotated with the `@Validated` annotation at the type level for their methods to be searched for inline constraint annotations. For instance, the following service triggers the validation of the first argument, making sure its size is between 8 and 10: -include::code:MyBean[] +include-code::MyBean[] The application's `MessageSource` is used when resolving `+{parameters}+` in constraint messages. -This allows you to use <> for Bean Validation messages. +This allows you to use xref:features/internationalization.adoc[your application's `messages.properties` files] for Bean Validation messages. Once the parameters have been resolved, message interpolation is completed using Bean Validation's default interpolator. To customize the `Configuration` used to build the `ValidatorFactory`, define a `ValidationConfigurationCustomizer` bean. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/webservices.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/webservices.adoc similarity index 66% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/webservices.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/webservices.adoc index 04b9e5fce2..7793966a4b 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/webservices.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/io/webservices.adoc @@ -1,33 +1,35 @@ [[io.webservices]] -== Web Services += Web Services + Spring Boot provides Web Services auto-configuration so that all you must do is define your `Endpoints`. -The {spring-webservices-docs}[Spring Web Services features] can be easily accessed with the `spring-boot-starter-webservices` module. +The {url-spring-webservices-docs}[Spring Web Services features] can be easily accessed with the `spring-boot-starter-webservices` module. `SimpleWsdl11Definition` and `SimpleXsdSchema` beans can be automatically created for your WSDLs and XSDs respectively. To do so, configure their location, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - webservices: - wsdl-locations: "classpath:/wsdl" +spring: + webservices: + wsdl-locations: "classpath:/wsdl" ---- [[io.webservices.template]] -=== Calling Web Services with WebServiceTemplate -If you need to call remote Web services from your application, you can use the {spring-webservices-docs}#client-web-service-template[`WebServiceTemplate`] class. +== Calling Web Services with WebServiceTemplate + +If you need to call remote Web services from your application, you can use the {url-spring-webservices-docs}#client-web-service-template[`WebServiceTemplate`] class. Since `WebServiceTemplate` instances often need to be customized before being used, Spring Boot does not provide any single auto-configured `WebServiceTemplate` bean. It does, however, auto-configure a `WebServiceTemplateBuilder`, which can be used to create `WebServiceTemplate` instances when needed. The following code shows a typical example: -include::code:MyService[] +include-code::MyService[] By default, `WebServiceTemplateBuilder` detects a suitable HTTP-based `WebServiceMessageSender` using the available HTTP client libraries on the classpath. You can also customize read and connection timeouts as follows: -include::code:MyWebServiceTemplateConfiguration[] +include-code::MyWebServiceTemplateConfiguration[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/amqp.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/messaging/amqp.adoc similarity index 82% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/amqp.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/messaging/amqp.adoc index 42d230aaac..89e863bc83 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/amqp.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/messaging/amqp.adoc @@ -1,5 +1,6 @@ [[messaging.amqp]] -== 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`". @@ -7,36 +8,37 @@ Spring Boot offers several conveniences for working with AMQP through RabbitMQ, [[messaging.amqp.rabbitmq]] -=== RabbitMQ Support +== 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] +[configprops,yaml] ---- - spring: - rabbitmq: - host: "localhost" - port: 5672 - username: "admin" - password: "secret" +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] +[configprops,yaml] ---- - spring: - rabbitmq: - addresses: "amqp://admin:secret@localhost" +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. +See {code-spring-boot-autoconfigure-src}/amqp/RabbitProperties.java[`RabbitProperties`] for more of the supported property-based configuration options. To configure lower-level details of the RabbitMQ `ConnectionFactory` that is used by Spring AMQP, define a `ConnectionFactoryCustomizer` bean. If a `ConnectionNameStrategy` bean exists in the context, it will be automatically used to name connections created by the auto-configured `CachingConnectionFactory`. @@ -48,26 +50,27 @@ TIP: See https://spring.io/blog/2010/06/14/understanding-amqp-the-protocol-used- [[messaging.amqp.sending]] -=== Sending a Message +== Sending a Message + Spring's `AmqpTemplate` and `AmqpAdmin` are auto-configured, and you can autowire them directly into your own beans, as shown in the following example: -include::code:MyBean[] +include-code::MyBean[] -NOTE: {spring-amqp-api}/rabbit/core/RabbitMessagingTemplate.html[`RabbitMessagingTemplate`] can be injected in a similar manner. +NOTE: {url-spring-amqp-javadoc}/rabbit/core/RabbitMessagingTemplate.html[`RabbitMessagingTemplate`] can be injected in a similar manner. If a `MessageConverter` bean is defined, it is associated automatically to the auto-configured `AmqpTemplate`. If necessary, any `org.springframework.amqp.core.Queue` that is defined as a bean is automatically used to declare a corresponding queue on the RabbitMQ instance. To retry operations, you can enable retries on the `AmqpTemplate` (for example, in the event that the broker connection is lost): -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - rabbitmq: - template: - retry: - enabled: true - initial-interval: "2s" +spring: + rabbitmq: + template: + retry: + enabled: true + initial-interval: "2s" ---- Retries are disabled by default. @@ -78,15 +81,16 @@ If you need to create more `RabbitTemplate` instances or if you want to override [[messaging.amqp.sending-stream]] -=== Sending a Message To A Stream +== Sending a Message To A Stream + To send a message to a particular stream, specify the name of the stream, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - rabbitmq: - stream: - name: "my-stream" +spring: + rabbitmq: + stream: + name: "my-stream" ---- If a `MessageConverter`, `StreamMessageConverter`, or `ProducerCustomizer` bean is defined, it is associated automatically to the auto-configured `RabbitStreamTemplate`. @@ -96,16 +100,17 @@ If you need to create more `RabbitStreamTemplate` instances or if you want to ov [[messaging.amqp.receiving]] -=== Receiving a Message +== Receiving a Message + When the Rabbit infrastructure is present, any bean can be annotated with `@RabbitListener` to create a listener endpoint. If no `RabbitListenerContainerFactory` has been defined, a default `SimpleRabbitListenerContainerFactory` is automatically configured and you can switch to a direct container using the configprop:spring.rabbitmq.listener.type[] property. If a `MessageConverter` or a `MessageRecoverer` bean is defined, it is automatically associated with the default factory. The following sample component creates a listener endpoint on the `someQueue` queue: -include::code:MyBean[] +include-code::MyBean[] -TIP: See {spring-amqp-api}/rabbit/annotation/EnableRabbit.html[the Javadoc of `@EnableRabbit`] for more details. +TIP: See {url-spring-amqp-javadoc}/rabbit/annotation/EnableRabbit.html[the Javadoc of `@EnableRabbit`] for more details. If you need to create more `RabbitListenerContainerFactory` instances or if you want to override the default, Spring Boot provides a `SimpleRabbitListenerContainerFactoryConfigurer` and a `DirectRabbitListenerContainerFactoryConfigurer` that you can use to initialize a `SimpleRabbitListenerContainerFactory` and a `DirectRabbitListenerContainerFactory` with the same settings as the factories used by the auto-configuration. @@ -114,11 +119,11 @@ Those two beans are exposed by the auto-configuration. For instance, the following configuration class exposes another factory that uses a specific `MessageConverter`: -include::code:custom/MyRabbitConfiguration[] +include-code::custom/MyRabbitConfiguration[] Then you can use the factory in any `@RabbitListener`-annotated method, as follows: -include::code:custom/MyBean[] +include-code::custom/MyBean[] You can enable retries to handle situations where your listener throws an exception. By default, `RejectAndDontRequeueRecoverer` is used, but you can define a `MessageRecoverer` of your own. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/messaging/index.adoc similarity index 66% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/messaging/index.adoc index 12aca393d1..88957a1d7c 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/messaging/index.adoc @@ -1,31 +1,8 @@ [[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 and Apache Pulsar. - - -include::messaging/jms.adoc[] - -include::messaging/amqp.adoc[] - -include::messaging/kafka.adoc[] - -include::messaging/pulsar.adoc[] - -include::messaging/rsocket.adoc[] - -include::messaging/spring-integration.adoc[] - -include::messaging/websockets.adoc[] - -include::messaging/whats-next.adoc[] - - - - - diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/jms.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/messaging/jms.adoc similarity index 77% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/jms.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/messaging/jms.adoc index d0a22ebe44..af7bdfe4bf 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/jms.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/messaging/jms.adoc @@ -1,14 +1,16 @@ [[messaging.jms]] -== JMS += JMS + The `jakarta.jms.ConnectionFactory` interface provides a standard method of creating a `jakarta.jms.Connection` for interacting with a JMS broker. Although Spring needs a `ConnectionFactory` to work with JMS, you generally need not use it directly yourself and can instead rely on higher level messaging abstractions. -(See the {spring-framework-docs}/integration/jms.html[relevant section] of the Spring Framework reference documentation for details.) +(See the {url-spring-framework-docs}/integration/jms.html[relevant section] of the Spring Framework reference documentation for details.) Spring Boot also auto-configures the necessary infrastructure to send and receive messages. [[messaging.jms.activemq]] -=== ActiveMQ "Classic" Support +== ActiveMQ "Classic" Support + When https://activemq.apache.org/components/classic[ActiveMQ "Classic"] is available on the classpath, Spring Boot can configure a `ConnectionFactory`. NOTE: If you use `spring-boot-starter-activemq`, the necessary dependencies to connect to an ActiveMQ "Classic" instance are provided, as is the Spring infrastructure to integrate with JMS. @@ -16,37 +18,37 @@ NOTE: If you use `spring-boot-starter-activemq`, the necessary dependencies to c ActiveMQ "Classic" configuration is controlled by external configuration properties in `+spring.activemq.*+`. By default, ActiveMQ "Classic" is auto-configured to use the https://activemq.apache.org/tcp-transport-reference[TCP transport], connecting by default to `tcp://localhost:61616`. The following example shows how to change the default broker URL: -[source,yaml,indent=0,configprops,configblocks] +[configprops,yaml] ---- - spring: - activemq: - broker-url: "tcp://192.168.1.210:9876" - user: "admin" - password: "secret" +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] +[configprops,yaml] ---- - spring: - jms: - cache: - session-cache-size: 5 +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] +[configprops,yaml] ---- - spring: - activemq: - pool: - enabled: true - max-connections: 50 +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. +TIP: See {code-spring-boot-autoconfigure-src}/jms/activemq/ActiveMQProperties.java[`ActiveMQProperties`] for more of the supported options. You can also register an arbitrary number of beans that implement `ActiveMQConnectionFactoryCustomizer` for more advanced customizations. By default, ActiveMQ "Classic" creates a destination if it does not yet exist so that destinations are resolved against their provided names. @@ -54,7 +56,8 @@ By default, ActiveMQ "Classic" creates a destination if it does not yet exist so [[messaging.jms.artemis]] -=== ActiveMQ Artemis Support +== 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). @@ -66,14 +69,14 @@ Adding `org.apache.activemq:artemis-jakarta-server` to your application lets you 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] +[configprops,yaml] ---- - spring: - artemis: - mode: native - broker-url: "tcp://192.168.1.210:9876" - user: "admin" - password: "secret" +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. @@ -81,59 +84,61 @@ These can be specified as a comma-separated list to create them with the default 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] +[configprops,yaml] ---- - spring: - jms: - cache: - session-cache-size: 5 +spring: + jms: + cache: + session-cache-size: 5 ---- If you'd rather use native pooling, you can do so by adding a dependency on `org.messaginghub:pooled-jms` and configuring the `JmsPoolConnectionFactory` accordingly, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - artemis: - pool: - enabled: true - max-connections: 50 +spring: + artemis: + pool: + enabled: true + max-connections: 50 ---- -See {spring-boot-autoconfigure-module-code}/jms/artemis/ArtemisProperties.java[`ArtemisProperties`] for more supported options. +See {code-spring-boot-autoconfigure-src}/jms/artemis/ArtemisProperties.java[`ArtemisProperties`] for more supported options. No JNDI lookup is involved, and destinations are resolved against their names, using either the `name` attribute in the ActiveMQ Artemis configuration or the names provided through configuration. [[messaging.jms.jndi]] -=== Using a JNDI ConnectionFactory +== 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] +[configprops,yaml] ---- - spring: - jms: - jndi-name: "java:/MyConnectionFactory" +spring: + jms: + jndi-name: "java:/MyConnectionFactory" ---- [[messaging.jms.sending]] -=== Sending a Message +== Sending a Message + Spring's `JmsTemplate` is auto-configured, and you can autowire it directly into your own beans, as shown in the following example: -include::code:MyBean[] +include-code::MyBean[] -NOTE: {spring-framework-api}/jms/core/JmsMessagingTemplate.html[`JmsMessagingTemplate`] can be injected in a similar manner. +NOTE: {url-spring-framework-javadoc}/org/springframework/jms/core/JmsMessagingTemplate.html[`JmsMessagingTemplate`] can be injected in a similar manner. If a `DestinationResolver` or a `MessageConverter` bean is defined, it is associated automatically to the auto-configured `JmsTemplate`. [[messaging.jms.receiving]] -=== Receiving a Message +== 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. @@ -148,16 +153,16 @@ This also includes sending response messages that have been performed on the sam The following component creates a listener endpoint on the `someQueue` destination: -include::code:MyBean[] +include-code::MyBean[] -TIP: See {spring-framework-api}/jms/annotation/EnableJms.html[the Javadoc of `@EnableJms`] for more details. +TIP: See {url-spring-framework-javadoc}/org/springframework/jms/annotation/EnableJms.html[the Javadoc of `@EnableJms`] for more details. If you need to create more `JmsListenerContainerFactory` instances or if you want to override the default, Spring Boot provides a `DefaultJmsListenerContainerFactoryConfigurer` that you can use to initialize a `DefaultJmsListenerContainerFactory` with the same settings as the one that is auto-configured. For instance, the following example exposes another factory that uses a specific `MessageConverter`: -include::code:custom/MyJmsConfiguration[] +include-code::custom/MyJmsConfiguration[] Then you can use the factory in any `@JmsListener`-annotated method as follows: -include::code:custom/MyBean[] +include-code::custom/MyBean[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/kafka.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/messaging/kafka.adoc similarity index 72% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/kafka.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/messaging/kafka.adoc index 314b0e3a0a..0dea787ba2 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/kafka.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/messaging/kafka.adoc @@ -1,31 +1,33 @@ [[messaging.kafka]] -== Apache Kafka Support += 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] +[configprops,yaml] ---- - spring: - kafka: - bootstrap-servers: "localhost:9092" - consumer: - group-id: "myGroup" +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. +See {code-spring-boot-autoconfigure-src}/kafka/KafkaProperties.java[`KafkaProperties`] for more supported options. [[messaging.kafka.sending]] -=== Sending a Message +== Sending a Message + Spring's `KafkaTemplate` is auto-configured, and you can autowire it directly in your own beans, as shown in the following example: -include::code:MyBean[] +include-code::MyBean[] NOTE: If the property configprop:spring.kafka.producer.transaction-id-prefix[] is defined, a `KafkaTransactionManager` is automatically configured. Also, if a `RecordMessageConverter` bean is defined, it is automatically associated to the auto-configured `KafkaTemplate`. @@ -33,13 +35,14 @@ Also, if a `RecordMessageConverter` bean is defined, it is automatically associa [[messaging.kafka.receiving]] -=== Receiving a Message +== Receiving a Message + When the Apache Kafka infrastructure is present, any bean can be annotated with `@KafkaListener` to create a listener endpoint. If no `KafkaListenerContainerFactory` has been defined, a default one is automatically configured with keys defined in `spring.kafka.listener.*`. The following component creates a listener endpoint on the `someTopic` topic: -include::code:MyBean[] +include-code::MyBean[] If a `KafkaTransactionManager` bean is defined, it is automatically associated to the container factory. Similarly, if a `RecordFilterStrategy`, `CommonErrorHandler`, `AfterRollbackProcessor` or `ConsumerAwareRebalanceListener` bean is defined, it is automatically associated to the default factory. @@ -52,7 +55,8 @@ TIP: A custom `ChainedKafkaTransactionManager` must be marked `@Primary` as it u [[messaging.kafka.streams]] -=== Kafka Streams +== Kafka Streams + Spring for Apache Kafka provides a factory bean to create a `StreamsBuilder` object and manage the lifecycle of its streams. Spring Boot auto-configures the required `KafkaStreamsConfiguration` bean as long as `kafka-streams` is on the classpath and Kafka Streams is enabled by the `@EnableKafkaStreams` annotation. @@ -61,11 +65,11 @@ The former can be configured using `spring.kafka.streams.application-id`, defaul 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. +See also xref:messaging/kafka.adoc#messaging.kafka.additional-properties[Additional Kafka Properties] for more information. To use the factory bean, wire `StreamsBuilder` into your `@Bean` as shown in the following example: -include::code:MyKafkaStreamsConfiguration[] +include-code::MyKafkaStreamsConfiguration[] By default, the streams managed by the `StreamBuilder` object are started automatically. You can customize this behavior using the configprop:spring.kafka.streams.auto-startup[] property. @@ -73,8 +77,9 @@ You can customize this behavior using the configprop:spring.kafka.streams.auto-s [[messaging.kafka.additional-properties]] -=== Additional Kafka Properties -The properties supported by auto configuration are shown in the <> section of the Appendix. +== Additional Kafka Properties + +The properties supported by auto configuration are shown in the xref:appendix:application-properties/index.adoc#appendix.application-properties.integration["`Integration Properties`"] section of the Appendix. Note that, for the most part, these properties (hyphenated or camelCase) map directly to the Apache Kafka dotted properties. See the Apache Kafka documentation for details. @@ -87,51 +92,51 @@ Spring Boot auto-configuration supports all HIGH importance properties, some sel Only a subset of the properties supported by Kafka are available directly through the `KafkaProperties` class. If you wish to configure the individual client types with additional properties that are not directly supported, use the following properties: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - kafka: - properties: - "[prop.one]": "first" - admin: - properties: - "[prop.two]": "second" - consumer: - properties: - "[prop.three]": "third" - producer: - properties: - "[prop.four]": "fourth" - streams: - properties: - "[prop.five]": "fifth" +spring: + kafka: + properties: + "[prop.one]": "first" + admin: + properties: + "[prop.two]": "second" + consumer: + properties: + "[prop.three]": "third" + producer: + properties: + "[prop.four]": "fourth" + streams: + properties: + "[prop.five]": "fifth" ---- This sets the common `prop.one` Kafka property to `first` (applies to producers, consumers, admins, and streams), the `prop.two` admin property to `second`, the `prop.three` consumer property to `third`, the `prop.four` producer property to `fourth` and the `prop.five` streams property to `fifth`. You can also configure the Spring Kafka `JsonDeserializer` as follows: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - kafka: - consumer: - value-deserializer: "org.springframework.kafka.support.serializer.JsonDeserializer" - properties: - "[spring.json.value.default.type]": "com.example.Invoice" - "[spring.json.trusted.packages]": "com.example.main,com.example.another" +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] +[configprops,yaml] ---- - spring: - kafka: - producer: - value-serializer: "org.springframework.kafka.support.serializer.JsonSerializer" - properties: - "[spring.json.add.type.headers]": false +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. @@ -139,27 +144,28 @@ IMPORTANT: Properties set in this way override any configuration item that Sprin [[messaging.kafka.embedded]] -=== Testing with Embedded Kafka +== 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}testing.html#ekb[reference manual]. +For more information, please see the Spring for Apache Kafka {url-spring-kafka-docs}/testing.html#ekb[reference manual]. To make Spring Boot auto-configuration work with the aforementioned embedded Apache Kafka broker, you need to remap a system property for embedded broker addresses (populated by the `EmbeddedKafkaBroker`) into the Spring Boot configuration property for Apache Kafka. There are several ways to do that: * Provide a system property to map embedded broker addresses into configprop:spring.kafka.bootstrap-servers[] in the test class: -include::code:property/MyTest[tag=*] +include-code::property/MyTest[tag=*] * Configure a property name on the `@EmbeddedKafka` annotation: -include::code:annotation/MyTest[] +include-code::annotation/MyTest[] * Use a placeholder in configuration properties: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - kafka: - bootstrap-servers: "${spring.embedded.kafka.brokers}" +spring: + kafka: + bootstrap-servers: "${spring.embedded.kafka.brokers}" ---- diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/pulsar.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/messaging/pulsar.adoc similarity index 88% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/pulsar.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/messaging/pulsar.adoc index 4e0da8a877..d5d05a32c8 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/pulsar.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/messaging/pulsar.adoc @@ -1,6 +1,7 @@ [[messaging.pulsar]] -== Apache Pulsar Support -https://pulsar.apache.org/[Apache Pulsar] is supported by providing auto-configuration of the {spring-pulsar-docs}[Spring for Apache Pulsar] project. += Apache Pulsar Support + +https://pulsar.apache.org/[Apache Pulsar] is supported by providing auto-configuration of the {url-spring-pulsar-site}[Spring for Apache Pulsar] project. Spring Boot will auto-configure and register the classic (imperative) Spring for Apache Pulsar components when `org.springframework.pulsar:spring-pulsar` is on the classpath. It will do the same for the reactive components when `org.springframework.pulsar:spring-pulsar-reactive` is on the classpath. @@ -10,7 +11,8 @@ There are `spring-boot-starter-pulsar` and `spring-boot-starter-pulsar-reactive` [[messaging.pulsar.connecting]] -=== Connecting to Pulsar +== Connecting to Pulsar + When you use the Pulsar starter, Spring Boot will auto-configure and register a `PulsarClient` bean. By default, the application tries to connect to a local Pulsar instance at `pulsar://localhost:6650`. @@ -25,12 +27,13 @@ If you need more control over the configuration, consider registering one or mor [[messaging.pulsar.connecting.auth]] -==== Authentication +=== Authentication + To connect to a Pulsar cluster that requires authentication, you need to specify which authentication plugin to use by setting the `pluginClassName` and any parameters required by the plugin. You can set the parameters as a map of parameter names to parameter values. The following example shows how to configure the `AuthenticationOAuth2` plugin. -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- spring: pulsar: @@ -52,22 +55,24 @@ For example, if you want to configure the issuer url for the `AuthenticationOAut If you use other forms, such as `issuerurl` or `issuer-url`, the setting will not be applied to the plugin. This lack of relaxed binding also makes using environment variables for authentication parameters problematic because the case sensitivity is lost during translation. -If you use environment variables for the parameters then you will need to follow {spring-pulsar-docs}reference/pulsar.html#client-authentication-env-vars[these steps] in the Spring for Apache Pulsar reference documentation for it to work properly. +If you use environment variables for the parameters then you will need to follow {url-spring-pulsar-docs}/reference/pulsar.html#client-authentication-env-vars[these steps] in the Spring for Apache Pulsar reference documentation for it to work properly. ==== [[messaging.pulsar.connecting.ssl]] -==== SSL -By default, Pulsar clients communicate with Pulsar services in plain text. -You can follow {spring-pulsar-docs}reference/pulsar.html#tls-encryption[these steps] in the Spring for Apache Pulsar reference documentation to enable TLS encryption. +=== SSL -For complete details on the client and authentication see the Spring for Apache Pulsar {spring-pulsar-docs}reference/pulsar.html#pulsar-client[reference documentation]. +By default, Pulsar clients communicate with Pulsar services in plain text. +You can follow {url-spring-pulsar-docs}reference/pulsar.html#tls-encryption[these steps] in the Spring for Apache Pulsar reference documentation to enable TLS encryption. + +For complete details on the client and authentication see the Spring for Apache Pulsar {url-spring-pulsar-docs}reference/pulsar.html#pulsar-client[reference documentation]. [[messaging.pulsar.connecting-reactive]] -=== Connecting to Pulsar Reactively +== Connecting to Pulsar Reactively + When the Reactive auto-configuration is activated, Spring Boot will auto-configure and register a `ReactivePulsarClient` bean. The `ReactivePulsarClient` adapts an instance of the previously described `PulsarClient`. @@ -76,7 +81,8 @@ Therefore, follow the previous section to configure the `PulsarClient` used by t [[messaging.pulsar.admin]] -=== Connecting to Pulsar Administration +== Connecting to Pulsar Administration + Spring for Apache Pulsar's `PulsarAdministration` client is also auto-configured. By default, the application tries to connect to a local Pulsar instance at `\http://localhost:8080`. @@ -85,10 +91,12 @@ This can be adjusted by setting the configprop:spring.pulsar.admin.service-url[] If you need more control over the configuration, consider registering one or more `PulsarAdminBuilderCustomizer` beans. + [[messaging.pulsar.admin.auth]] -==== Authentication +=== Authentication + When accessing a Pulsar cluster that requires authentication, the admin client requires the same security configuration as the regular Pulsar client. -You can use the aforementioned <> by replacing `spring.pulsar.client.authentication` with `spring.pulsar.admin.authentication`. +You can use the aforementioned xref:messaging/pulsar.adoc#messaging.pulsar.connecting.auth[authentication configuration] by replacing `spring.pulsar.client.authentication` with `spring.pulsar.admin.authentication`. TIP: To create a topic on startup, add a bean of type `PulsarTopic`. If the topic already exists, the bean is ignored. @@ -96,10 +104,11 @@ If the topic already exists, the bean is ignored. [[messaging.pulsar.sending]] -=== Sending a Message +== Sending a Message + Spring's `PulsarTemplate` is auto-configured, and you can use it to send messages, as shown in the following example: -include::code:MyBean[] +include-code::MyBean[] The `PulsarTemplate` relies on a `PulsarProducerFactory` to create the underlying Pulsar producer. Spring Boot auto-configuration also provides this producer factory, which by default, caches the producers that it creates. @@ -114,10 +123,11 @@ If you need more control over the message being sent, you can pass in a `TypedMe [[messaging.pulsar.sending-reactive]] -=== Sending a Message Reactively +== Sending a Message Reactively + When the Reactive auto-configuration is activated, Spring's `ReactivePulsarTemplate` is auto-configured, and you can use it to send messages, as shown in the following example: -include::code:MyBean[] +include-code::MyBean[] The `ReactivePulsarTemplate` relies on a `ReactivePulsarSenderFactory` to actually create the underlying sender. Spring Boot auto-configuration also provides this sender factory, which by default, caches the producers that it creates. @@ -132,11 +142,12 @@ If you need more control over the message being sent, you can pass in a `Message [[messaging.pulsar.receiving]] -=== Receiving a Message +== Receiving a Message + When the Apache Pulsar infrastructure is present, any bean can be annotated with `@PulsarListener` to create a listener endpoint. The following component creates a listener endpoint on the `someTopic` topic: -include::code:MyBean[] +include-code::MyBean[] Spring Boot auto-configuration provides all the components necessary for `PulsarListener`, such as the `PulsarListenerContainerFactory` and the consumer factory it uses to construct the underlying Pulsar consumers. You can configure these components by specifying any of the `spring.pulsar.listener.\*` and `spring.pulsar.consumer.*` prefixed application properties. @@ -148,11 +159,12 @@ You can also customize a single listener by setting the `consumerCustomizer` att [[messaging.pulsar.receiving-reactive]] -=== Receiving a Message Reactively +== Receiving a Message Reactively + When the Apache Pulsar infrastructure is present and the Reactive auto-configuration is activated, any bean can be annotated with `@ReactivePulsarListener` to create a reactive listener endpoint. The following component creates a reactive listener endpoint on the `someTopic` topic: -include::code:MyBean[] +include-code::MyBean[] Spring Boot auto-configuration provides all the components necessary for `ReactivePulsarListener`, such as the `ReactivePulsarListenerContainerFactory` and the consumer factory it uses to construct the underlying reactive Pulsar consumers. You can configure these components by specifying any of the `spring.pulsar.listener.*` and `spring.pulsar.consumer.*` prefixed application properties. @@ -164,14 +176,15 @@ You can also customize a single listener by setting the `consumerCustomizer` att [[messaging.pulsar.reading]] -=== Reading a Message +== Reading a Message + The Pulsar reader interface enables applications to manually manage cursors. When you use a reader to connect to a topic you need to specify which message the reader begins reading from when it connects to a topic. When the Apache Pulsar infrastructure is present, any bean can be annotated with `@PulsarReader` to consume messages using a reader. The following component creates a reader endpoint that starts reading messages from the beginning of the `someTopic` topic: -include::code:MyBean[] +include-code::MyBean[] The `@PulsarReader` relies on a `PulsarReaderFactory` to create the underlying Pulsar reader. Spring Boot auto-configuration provides this reader factory which can be customized by setting any of the `spring.pulsar.reader.*` prefixed application properties. @@ -183,11 +196,12 @@ You can also customize a single listener by setting the `readerCustomizer` attri [[messaging.pulsar.reading-reactive]] -=== Reading a Message Reactively +== Reading a Message Reactively + When the Apache Pulsar infrastructure is present and the Reactive auto-configuration is activated, Spring's `ReactivePulsarReaderFactory` is provided, and you can use it to create a reader in order to read messages in a reactive fashion. The following component creates a reader using the provided factory and reads a single message from 5 minutes ago from the `someTopic` topic: -include::code:MyBean[] +include-code::MyBean[] Spring Boot auto-configuration provides this reader factory which can be customized by setting any of the `spring.pulsar.reader.*` prefixed application properties. @@ -197,13 +211,14 @@ If you need more control over the reader factory configuration, consider registe These customizers are applied to all created readers. You can also pass one or more `ReactiveMessageReaderBuilderCustomizer` when creating a reader to only apply the customizations to the created reader. -TIP: For more details on any of the above components and to discover other available features, see the Spring for Apache Pulsar {spring-pulsar-docs}[reference documentation]. +TIP: For more details on any of the above components and to discover other available features, see the Spring for Apache Pulsar {url-spring-pulsar-docs}[reference documentation]. [[messaging.pulsar.additional-properties]] -=== Additional Pulsar Properties -The properties supported by auto-configuration are shown in the <> section of the Appendix. +== Additional Pulsar Properties + +The properties supported by auto-configuration are shown in the xref:appendix:application-properties/index.adoc#appendix.application-properties.integration["`Integration Properties`"] section of the Appendix. Note that, for the most part, these properties (hyphenated or camelCase) map directly to the Apache Pulsar configuration properties. See the Apache Pulsar documentation for details. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/rsocket.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/messaging/rsocket.adoc similarity index 79% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/rsocket.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/messaging/rsocket.adoc index a3a9c76c60..ff5829a252 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/rsocket.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/messaging/rsocket.adoc @@ -1,16 +1,18 @@ [[messaging.rsocket]] -== RSocket += RSocket + https://rsocket.io[RSocket] is a binary protocol for use on byte stream transports. It enables symmetric interaction models through async message passing over a single connection. The `spring-messaging` module of the Spring Framework provides support for RSocket requesters and responders, both on the client and on the server side. -See the {spring-framework-docs}/rsocket.html#rsocket-spring[RSocket section] of the Spring Framework reference for more details, including an overview of the RSocket protocol. +See the {url-spring-framework-docs}/rsocket.html#rsocket-spring[RSocket section] of the Spring Framework reference for more details, including an overview of the RSocket protocol. [[messaging.rsocket.strategies-auto-configuration]] -=== RSocket Strategies Auto-configuration +== 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): @@ -18,7 +20,7 @@ By default, the auto-configuration will try to configure the following (in order . JSON codecs with Jackson The `spring-boot-starter-rsocket` starter provides both dependencies. -See the <> to know more about customization possibilities. +See the xref:features/json.adoc#features.json.jackson[Jackson support section] to know more about customization possibilities. Developers can customize the `RSocketStrategies` component by creating beans that implement the `RSocketStrategiesCustomizer` interface. Note that their `@Order` is important, as it determines the order of codecs. @@ -26,7 +28,8 @@ Note that their `@Order` is important, as it determines the order of codecs. [[messaging.rsocket.server-auto-configuration]] -=== 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`. @@ -35,13 +38,13 @@ This depends on the type of application and its configuration. For WebFlux application (that is of type `WebApplicationType.REACTIVE`), the RSocket server will be plugged into the Web Server only if the following properties match: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - rsocket: - server: - mapping-path: "/rsocket" - transport: "websocket" +spring: + rsocket: + server: + mapping-path: "/rsocket" + transport: "websocket" ---- WARNING: Plugging RSocket into a web server is only supported with Reactor Netty, as RSocket itself is built with that library. @@ -49,18 +52,19 @@ WARNING: Plugging RSocket into a web server is only supported with Reactor Netty Alternatively, an RSocket TCP or websocket server is started as an independent, embedded server. Besides the dependency requirements, the only required configuration is to define a port for that server: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - rsocket: - server: - port: 9898 +spring: + rsocket: + server: + port: 9898 ---- [[messaging.rsocket.messaging]] -=== Spring Messaging RSocket support +== Spring Messaging RSocket support + Spring Boot will auto-configure the Spring Messaging infrastructure for RSocket. This means that Spring Boot will create a `RSocketMessageHandler` bean that will handle RSocket requests to your application. @@ -68,7 +72,8 @@ This means that Spring Boot will create a `RSocketMessageHandler` bean that will [[messaging.rsocket.requester]] -=== Calling RSocket Services with RSocketRequester +== Calling RSocket Services with RSocketRequester + Once the `RSocket` channel is established between server and client, any party can send or receive requests to the other. As a server, you can get injected with an `RSocketRequester` instance on any handler method of an RSocket `@Controller`. @@ -80,4 +85,4 @@ This is done on purpose since this builder is stateful and you should not create The following code shows a typical example: -include::code:MyService[] +include-code::MyService[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/spring-integration.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/messaging/spring-integration.adoc similarity index 54% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/spring-integration.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/messaging/spring-integration.adoc index 67b55870b5..6f751940d2 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/spring-integration.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/messaging/spring-integration.adoc @@ -1,22 +1,23 @@ [[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 + +Spring Boot offers several conveniences for working with {url-spring-integration-site}[Spring Integration], including the `spring-boot-starter-integration` "`Starter`". Spring Integration provides abstractions over messaging and also other transports such as HTTP, TCP, and others. If Spring Integration is available on your classpath, it is initialized through the `@EnableIntegration` annotation. -Spring Integration polling logic relies <>. +Spring Integration polling logic relies xref:features/task-execution-and-scheduling.adoc[on the auto-configured `TaskScheduler`]. The default `PollerMetadata` (poll unbounded number of messages every second) can be customized with `spring.integration.poller.*` configuration properties. Spring Boot also configures some features that are triggered by the presence of additional Spring Integration modules. If `spring-integration-jmx` is also on the classpath, message processing statistics are published over JMX. If `spring-integration-jdbc` is available, the default database schema can be created on startup, as shown in the following line: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - integration: - jdbc: - initialize-schema: "always" +spring: + integration: + jdbc: + initialize-schema: "always" ---- If `spring-integration-rsocket` is available, developers can configure an RSocket server using `"spring.rsocket.server.*"` properties and let it use `IntegrationRSocketEndpoint` or `RSocketOutboundGateway` components to handle incoming RSocket messages. @@ -24,25 +25,25 @@ This infrastructure can handle Spring Integration RSocket channel adapters and ` Spring Boot can also auto-configure an `ClientRSocketConnector` using configuration properties: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - # Connecting to a RSocket server over TCP - spring: - integration: - rsocket: - client: - host: "example.org" - port: 9898 +# Connecting to a RSocket server over TCP +spring: + integration: + rsocket: + client: + host: "example.org" + port: 9898 ---- -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - # Connecting to a RSocket Server over WebSocket - spring: - integration: - rsocket: - client: - uri: "ws://example.org" +# Connecting to a RSocket Server over WebSocket +spring: + integration: + rsocket: + client: + uri: "ws://example.org" ---- -See the {spring-boot-autoconfigure-module-code}/integration/IntegrationAutoConfiguration.java[`IntegrationAutoConfiguration`] and {spring-boot-autoconfigure-module-code}/integration/IntegrationProperties.java[`IntegrationProperties`] classes for more details. +See the {code-spring-boot-autoconfigure-src}/integration/IntegrationAutoConfiguration.java[`IntegrationAutoConfiguration`] and {code-spring-boot-autoconfigure-src}/integration/IntegrationProperties.java[`IntegrationProperties`] classes for more details. diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/messaging/websockets.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/messaging/websockets.adoc new file mode 100644 index 0000000000..a6e7dd9af6 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/messaging/websockets.adoc @@ -0,0 +1,17 @@ +[[messaging.websockets]] += WebSockets + +Spring Boot provides WebSockets auto-configuration for embedded Tomcat, Jetty, and Undertow. +If you deploy a war file to a standalone container, Spring Boot assumes that the container is responsible for the configuration of its WebSocket support. + +Spring Framework provides {url-spring-framework-docs}/web/websocket.html[rich WebSocket support] for MVC web applications that can be easily accessed through the `spring-boot-starter-websocket` module. + +WebSocket support is also available for {url-spring-framework-docs}/web/webflux-websocket.html[reactive web applications] and requires to include the WebSocket API alongside `spring-boot-starter-webflux`: + +[source,xml] +---- + + jakarta.websocket + jakarta.websocket-api + +---- diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/native-image/advanced-topics.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/native-image/advanced-topics.adoc similarity index 76% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/native-image/advanced-topics.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/native-image/advanced-topics.adoc index e1735662d9..f83e7c5554 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/native-image/advanced-topics.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/native-image/advanced-topics.adoc @@ -1,41 +1,43 @@ [[native-image.advanced]] -== Advanced Native Images Topics += Advanced Native Images Topics [[native-image.advanced.nested-configuration-properties]] -=== Nested Configuration Properties +== Nested Configuration Properties Reflection hints are automatically created for configuration properties by the Spring ahead-of-time engine. Nested configuration properties which are not inner classes, however, *must* be annotated with `@NestedConfigurationProperty`, otherwise they won't be detected and will not be bindable. -include::code:MyProperties[] +include-code::MyProperties[] where `Nested` is: -include::code:Nested[] +include-code::Nested[] The example above produces configuration properties for `my.properties.name` and `my.properties.nested.number`. Without the `@NestedConfigurationProperty` annotation on the `nested` field, the `my.properties.nested.number` property would not be bindable in a native image. When using constructor binding, you have to annotate the field with `@NestedConfigurationProperty`: -include::code:MyPropertiesCtor[] +include-code::MyPropertiesCtor[] When using records, you have to annotate the parameter with `@NestedConfigurationProperty`: -include::code:MyPropertiesRecord[] +include-code::MyPropertiesRecord[] When using Kotlin, you need to annotate the parameter of a data class with `@NestedConfigurationProperty`: -include::code:MyPropertiesKotlin[] +include-code::MyPropertiesKotlin[] NOTE: Please use public getters and setters in all cases, otherwise the properties will not be bindable. -[[native-image.advanced.converting-executable-jars]] -=== Converting a Spring Boot Executable Jar -It is possible to convert a Spring Boot <> into a native image as long as the jar contains the AOT generated assets. + +[[native-image.advanced.converting-executable-jars]] +== Converting a Spring Boot Executable Jar + +It is possible to convert a Spring Boot xref:specification:executable-jar/index.adoc[executable jar] into a native image as long as the jar contains the AOT generated assets. This can be useful for a number of reasons, including: * You can keep your regular JVM pipeline and turn the JVM application into a native image on your CI/CD platform. @@ -48,7 +50,8 @@ NOTE: Your executable jar must include AOT generated assets such as generated cl [[native-image.advanced.converting-executable-jars.buildpacks]] -==== Using Buildpacks +=== Using Buildpacks + Spring Boot applications usually use Cloud Native Buildpacks through the Maven (`mvn spring-boot:build-image`) or Gradle (`gradle bootBuildImage`) integrations. You can, however, also use https://buildpacks.io//docs/tools/pack/[`pack`] to turn an AOT processed Spring Boot executable jar into a native container image. @@ -60,41 +63,42 @@ You also need to install `pack` by following https://buildpacks.io//docs/tools/p Assuming an AOT processed Spring Boot executable jar built as `myproject-0.0.1-SNAPSHOT.jar` is in the `target` directory, run: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ pack build --builder paketobuildpacks/builder-jammy-tiny \ - --path target/myproject-0.0.1-SNAPSHOT.jar \ - --env 'BP_NATIVE_IMAGE=true' \ - my-application:0.0.1-SNAPSHOT +$ pack build --builder paketobuildpacks/builder-jammy-tiny \ + --path target/myproject-0.0.1-SNAPSHOT.jar \ + --env 'BP_NATIVE_IMAGE=true' \ + my-application:0.0.1-SNAPSHOT ---- NOTE: You do not need to have a local GraalVM installation to generate an image in this way. Once `pack` has finished, you can launch the application using `docker run`: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ docker run --rm -p 8080:8080 docker.io/library/myproject:0.0.1-SNAPSHOT +$ docker run --rm -p 8080:8080 docker.io/library/myproject:0.0.1-SNAPSHOT ---- [[native-image.advanced.converting-executable-jars.native-image]] -==== Using GraalVM native-image +=== Using GraalVM native-image + Another option to turn an AOT processed Spring Boot executable jar into a native executable is to use the GraalVM `native-image` tool. For this to work, you'll need a GraalVM distribution on your machine. -You can either download it manually on the {liberica-nik-download}[Liberica Native Image Kit page] or you can use a download manager like SDKMAN!. +You can either download it manually on the {url-download-liberica-nik}[Liberica Native Image Kit page] or you can use a download manager like SDKMAN!. Assuming an AOT processed Spring Boot executable jar built as `myproject-0.0.1-SNAPSHOT.jar` is in the `target` directory, run: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ rm -rf target/native - $ mkdir -p target/native - $ cd target/native - $ jar -xvf ../myproject-0.0.1-SNAPSHOT.jar - $ native-image -H:Name=myproject @META-INF/native-image/argfile -cp .:BOOT-INF/classes:`find BOOT-INF/lib | tr '\n' ':'` - $ mv myproject ../ +$ rm -rf target/native +$ mkdir -p target/native +$ cd target/native +$ jar -xvf ../myproject-0.0.1-SNAPSHOT.jar +$ native-image -H:Name=myproject @META-INF/native-image/argfile -cp .:BOOT-INF/classes:`find BOOT-INF/lib | tr '\n' ':'` +$ mv myproject ../ ---- NOTE: These commands work on Linux or macOS machines, but you will need to adapt them for Windows. @@ -108,8 +112,9 @@ You need to ensure that all jars are listed (the command above uses `find` and ` [[native-image.advanced.using-the-tracing-agent]] -=== Using the Tracing Agent -The GraalVM native image {graal-native-image-docs}/metadata/AutomaticMetadataCollection[tracing agent] allows you to intercept reflection, resources or proxy usage on the JVM in order to generate the related hints. +== Using the Tracing Agent + +The GraalVM native image {url-graal-docs-native-image}/metadata/AutomaticMetadataCollection[tracing agent] allows you to intercept reflection, resources or proxy usage on the JVM in order to generate the related hints. Spring should generate most of these hints automatically, but the tracing agent can be used to quickly identify the missing entries. When using the agent to generate hints for a native image, there are a couple of approaches: @@ -126,14 +131,15 @@ To address this problem the agent supports an access-filter file that will cause [[native-image.advanced.using-the-tracing-agent.launch]] -==== Launch the Application Directly +=== Launch the Application Directly + Use the following command to launch the application with the native image tracing agent attached: -[source,shell,indent=0,subs="verbatim,attributes"] +[source,shell,subs="verbatim,attributes"] ---- - $ java -Dspring.aot.enabled=true \ - -agentlib:native-image-agent=config-output-dir=/path/to/config-dir/ \ - -jar target/myproject-0.0.1-SNAPSHOT.jar +$ java -Dspring.aot.enabled=true \ + -agentlib:native-image-agent=config-output-dir=/path/to/config-dir/ \ + -jar target/myproject-0.0.1-SNAPSHOT.jar ---- Now you can exercise the code paths you want to have hints for and then stop the application with `ctrl-c`. @@ -144,41 +150,46 @@ To use them as input, copy them into the `src/main/resources/META-INF/native-ima The next time you build the native image, GraalVM will take these files into consideration. There are more advanced options which can be set on the native image tracing agent, for example filtering the recorded hints by caller classes, etc. -For further reading, please see {graal-native-image-docs}/metadata/AutomaticMetadataCollection[the official documentation]. +For further reading, please see {url-graal-docs-native-image}/metadata/AutomaticMetadataCollection[the official documentation]. [[native-image.advanced.custom-hints]] -=== Custom Hints +== Custom Hints + If you need to provide your own hints for reflection, resources, serialization, proxy usage etc. you can use the `RuntimeHintsRegistrar` API. Create a class that implements the `RuntimeHintsRegistrar` interface, and then make appropriate calls to the provided `RuntimeHints` instance: -include::code:MyRuntimeHints[] +include-code::MyRuntimeHints[] You can then use `@ImportRuntimeHints` on any `@Configuration` class (for example your `@SpringBootApplication` annotated application class) to activate those hints. -If you have classes which need binding (mostly needed when serializing or deserializing JSON), you can use {spring-framework-docs}/core/aot.html#aot.hints.register-reflection-for-binding[`@RegisterReflectionForBinding`] on any bean. +If you have classes which need binding (mostly needed when serializing or deserializing JSON), you can use {url-spring-framework-docs}/core/aot.html#aot.hints.register-reflection-for-binding[`@RegisterReflectionForBinding`] on any bean. Most of the hints are automatically inferred, for example when accepting or returning data from a `@RestController` method. But when you work with `WebClient`, `RestClient` or `RestTemplate` directly, you might need to use `@RegisterReflectionForBinding`. + + [[native-image.advanced.custom-hints.testing]] -==== Testing custom hints +=== Testing custom hints + The `RuntimeHintsPredicates` API can be used to test your hints. The API provides methods that build a `Predicate` that can be used to test a `RuntimeHints` instance. If you're using AssertJ, your test would look like this: -include::code:MyRuntimeHintsTests[] +include-code::MyRuntimeHintsTests[] [[native-image.advanced.known-limitations]] -=== Known Limitations +== Known Limitations + GraalVM native images are an evolving technology and not all libraries provide support. The GraalVM community is helping by providing https://github.com/oracle/graalvm-reachability-metadata[reachability metadata] for projects that don't yet ship their own. Spring itself doesn't contain hints for 3rd party libraries and instead relies on the reachability metadata project. -If you encounter problems when generating native images for Spring Boot applications, please check the {github-wiki}/Spring-Boot-with-GraalVM[Spring Boot with GraalVM] page of the Spring Boot wiki. +If you encounter problems when generating native images for Spring Boot applications, please check the {url-github-wiki}/Spring-Boot-with-GraalVM[Spring Boot with GraalVM] page of the Spring Boot wiki. You can also contribute issues to the https://github.com/spring-projects/spring-aot-smoke-tests[spring-aot-smoke-tests] project on GitHub which is used to confirm that common application types are working as expected. If you find a library which doesn't work with GraalVM, please raise an issue on the https://github.com/oracle/graalvm-reachability-metadata[reachability metadata project]. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/native-image/developing-your-first-application.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/native-image/developing-your-first-application.adoc similarity index 66% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/native-image/developing-your-first-application.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/native-image/developing-your-first-application.adoc index fe5a0d5683..e8d2fa01cc 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/native-image/developing-your-first-application.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/native-image/developing-your-first-application.adoc @@ -1,5 +1,6 @@ [[native-image.developing-your-first-application]] -== Developing Your First GraalVM Native Application += Developing Your First GraalVM Native Application + Now that we have a good overview of GraalVM Native Images and how the Spring ahead-of-time engine works, we can look at how to create an application. There are two main ways to build a Spring Boot native image application: @@ -13,20 +14,22 @@ The included `HELP.md` file will provide getting started hints. [[native-image.developing-your-first-application.sample-application]] -=== Sample Application +== Sample Application + We need an example application that we can use to create our native image. -For our purposes, the simple "`Hello World!`" web application that's covered in the "`<>`" section will suffice. +For our purposes, the simple "`Hello World!`" web application that's covered in the "`xref:tutorial:first-application/index.adoc[Developing Your First Spring Boot Application]`" section will suffice. To recap, our main application code looks like this: -include::code:MyApplication[] +include-code::MyApplication[] This application uses Spring MVC and embedded Tomcat, both of which have been tested and verified to work with GraalVM native images. [[native-image.developing-your-first-application.buildpacks]] -=== Building a Native Image Using Buildpacks +== Building a Native Image Using Buildpacks + Spring Boot includes buildpack support for native images directly for both Maven and Gradle. This means you can just type a single command and quickly get a sensible image into your locally running Docker daemon. The resulting image doesn't contain a JVM, instead the native image is compiled statically. @@ -38,12 +41,13 @@ It has small footprint and reduced attack surface, but you can also use `paketob [[native-image.developing-your-first-application.buildpacks.system-requirements]] -==== System Requirements +=== System Requirements + Docker should be installed. See https://docs.docker.com/installation/#installation[Get Docker] for more details. https://docs.docker.com/engine/install/linux-postinstall/#manage-docker-as-a-non-root-user[Configure it to allow non-root user] if you are on Linux. NOTE: You can run `docker run hello-world` (without `sudo`) to check the Docker daemon is reachable as expected. -Check the {spring-boot-maven-plugin-docs}/#build-image-docker-daemon[Maven] or {spring-boot-gradle-plugin-docs}/#build-image-docker-daemon[Gradle] Spring Boot plugin documentation for more details. +Check the xref:maven-plugin:build-image.adoc#build-image.docker-daemon[Maven] or xref:gradle-plugin:packaging-oci-image.adoc#build-image.docker-daemon[Gradle] Spring Boot plugin documentation for more details. TIP: On macOS, it is recommended to increase the memory allocated to Docker to at least `8GB`, and potentially add more CPUs as well. See this https://stackoverflow.com/questions/44533319/how-to-assign-more-memory-to-docker-container/44533437#44533437[Stack Overflow answer] for more details. @@ -52,27 +56,28 @@ On Microsoft Windows, make sure to enable the https://docs.docker.com/docker-for [[native-image.developing-your-first-application.buildpacks.maven]] -==== Using Maven +=== Using Maven + To build a native image container using Maven you should ensure that your `pom.xml` file uses the `spring-boot-starter-parent` and the `org.graalvm.buildtools:native-maven-plugin`. You should have a `` section that looks like this: -[source,xml,indent=0,subs="verbatim,attributes"] +[source,xml,subs="verbatim,attributes"] ---- - - org.springframework.boot - spring-boot-starter-parent - {spring-boot-version} - + + org.springframework.boot + spring-boot-starter-parent + {version-spring-boot} + ---- You additionally should have this in the ` ` section: -[source,xml,indent=0,subs="verbatim,attributes"] +[source,xml,subs="verbatim,attributes"] ---- - - org.graalvm.buildtools - native-maven-plugin - + + org.graalvm.buildtools + native-maven-plugin + ---- The `spring-boot-starter-parent` declares a `native` profile that configures the executions that need to run in order to create a native image. @@ -82,62 +87,64 @@ TIP: If you don't want to use `spring-boot-starter-parent` you'll need to config To build the image, you can run the `spring-boot:build-image` goal with the `native` profile active: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ mvn -Pnative spring-boot:build-image +$ mvn -Pnative spring-boot:build-image ---- [[native-image.developing-your-first-application.buildpacks.gradle]] -==== Using Gradle +=== Using Gradle + The Spring Boot Gradle plugin automatically configures AOT tasks when the GraalVM Native Image plugin is applied. You should check that your Gradle build contains a `plugins` block that includes `org.graalvm.buildtools.native`. As long as the `org.graalvm.buildtools.native` plugin is applied, the `bootBuildImage` task will generate a native image rather than a JVM one. You can run the task using: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ gradle bootBuildImage +$ gradle bootBuildImage ---- [[native-image.developing-your-first-application.buildpacks.running]] -==== Running the example +=== Running the example + Once you have run the appropriate build command, a Docker image should be available. You can start your application using `docker run`: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ docker run --rm -p 8080:8080 docker.io/library/myproject:0.0.1-SNAPSHOT +$ docker run --rm -p 8080:8080 docker.io/library/myproject:0.0.1-SNAPSHOT ---- You should see output similar to the following: -[source,shell,indent=0,subs="verbatim,attributes"] +[source,shell] ---- - . ____ _ __ _ _ - /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ - ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ - \\/ ___)| |_)| | | | | || (_| | ) ) ) ) - ' |____| .__|_| |_|_| |_\__, | / / / / - =========|_|==============|___/=/_/_/_/ - :: Spring Boot :: (v{spring-boot-version}) - ....... . . . - ....... . . . (log output here) - ....... . . . - ........ Started MyApplication in 0.08 seconds (process running for 0.095) + . ____ _ __ _ _ + /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ +( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ + \\/ ___)| |_)| | | | | || (_| | ) ) ) ) + ' |____| .__|_| |_|_| |_\__, | / / / / + =========|_|==============|___/=/_/_/_/ + :: Spring Boot :: (v{version-spring-boot}) +....... . . . +....... . . . (log output here) +....... . . . +........ Started MyApplication in 0.08 seconds (process running for 0.095) ---- NOTE: The startup time differs from machine to machine, but it should be much faster than a Spring Boot application running on a JVM. If you open a web browser to `http://localhost:8080`, you should see the following output: -[indent=0] +[source] ---- - Hello World! +Hello World! ---- To gracefully exit the application, press `ctrl-c`. @@ -145,7 +152,8 @@ To gracefully exit the application, press `ctrl-c`. [[native-image.developing-your-first-application.native-build-tools]] -=== Building a Native Image using Native Build Tools +== Building a Native Image using Native Build Tools + If you want to generate a native executable directly without using Docker, you can use GraalVM Native Build Tools. Native Build Tools are plugins shipped by GraalVM for both Maven and Gradle. You can use them to perform a variety of GraalVM tasks, including generating a native image. @@ -153,52 +161,55 @@ You can use them to perform a variety of GraalVM tasks, including generating a n [[native-image.developing-your-first-application.native-build-tools.prerequisites]] -==== Prerequisites +=== Prerequisites + To build a native image using the Native Build Tools, you'll need a GraalVM distribution on your machine. -You can either download it manually on the {liberica-nik-download}[Liberica Native Image Kit page], or you can use a download manager like SDKMAN!. +You can either download it manually on the {url-download-liberica-nik}[Liberica Native Image Kit page], or you can use a download manager like SDKMAN!. + + [[native-image.developing-your-first-application.native-build-tools.prerequisites.linux-macos]] -===== Linux and macOS +==== Linux and macOS To install the native image compiler on macOS or Linux, we recommend using SDKMAN!. Get SDKMAN! from https://sdkman.io and install the Liberica GraalVM distribution by using the following commands: -[source,shell,indent=0,subs="verbatim,attributes"] +[source,shell,subs="verbatim,attributes"] ---- - $ sdk install java {graal-version}.r17-nik - $ sdk use java {graal-version}.r17-nik +$ sdk install java {version-graal}.r17-nik +$ sdk use java {version-graal}.r17-nik ---- Verify that the correct version has been configured by checking the output of `java -version`: -[source,shell,indent=0,subs="verbatim,attributes"] +[source,shell,subs="verbatim,attributes"] ---- - $ java -version - openjdk version "17.0.5" 2022-10-18 LTS - OpenJDK Runtime Environment GraalVM 22.3.0 (build 17.0.5+8-LTS) - OpenJDK 64-Bit Server VM GraalVM 22.3.0 (build 17.0.5+8-LTS, mixed mode) +$ java -version +openjdk version "17.0.5" 2022-10-18 LTS +OpenJDK Runtime Environment GraalVM 22.3.0 (build 17.0.5+8-LTS) +OpenJDK 64-Bit Server VM GraalVM 22.3.0 (build 17.0.5+8-LTS, mixed mode) ---- [[native-image.developing-your-first-application.native-build-tools.prerequisites.windows]] -===== Windows +==== Windows -On Windows, follow https://medium.com/graalvm/using-graalvm-and-native-image-on-windows-10-9954dc071311[these instructions] to install either https://www.graalvm.org/downloads/[GraalVM] or {liberica-nik-download}[Liberica Native Image Kit] in version {graal-version}, the Visual Studio Build Tools and the Windows SDK. +On Windows, follow https://medium.com/graalvm/using-graalvm-and-native-image-on-windows-10-9954dc071311[these instructions] to install either https://www.graalvm.org/downloads/[GraalVM] or {url-download-liberica-nik}[Liberica Native Image Kit] in version {version-graal}, the Visual Studio Build Tools and the Windows SDK. Due to the https://docs.microsoft.com/en-US/troubleshoot/windows-client/shell-experience/command-line-string-limitation[Windows related command-line maximum length], make sure to use x64 Native Tools Command Prompt instead of the regular Windows command line to run Maven or Gradle plugins. [[native-image.developing-your-first-application.native-build-tools.maven]] -==== Using Maven +=== Using Maven -As with the <>, you need to make sure that you're using `spring-boot-starter-parent` in order to inherit the `native` profile and that the `org.graalvm.buildtools:native-maven-plugin` plugin is used. +As with the xref:native-image/developing-your-first-application.adoc#native-image.developing-your-first-application.buildpacks.maven[buildpack support], you need to make sure that you're using `spring-boot-starter-parent` in order to inherit the `native` profile and that the `org.graalvm.buildtools:native-maven-plugin` plugin is used. With the `native` profile active, you can invoke the `native:compile` goal to trigger `native-image` compilation: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ mvn -Pnative native:compile +$ mvn -Pnative native:compile ---- The native image executable can be found in the `target` directory. @@ -206,13 +217,14 @@ The native image executable can be found in the `target` directory. [[native-image.developing-your-first-application.native-build-tools.gradle]] -==== Using Gradle +=== Using Gradle + When the Native Build Tools Gradle plugin is applied to your project, the Spring Boot Gradle plugin will automatically trigger the Spring AOT engine. Task dependencies are automatically configured, so you can just run the standard `nativeCompile` task to generate a native image: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ gradle nativeCompile +$ gradle nativeCompile ---- The native image executable can be found in the `build/native/nativeCompile` directory. @@ -220,45 +232,50 @@ The native image executable can be found in the `build/native/nativeCompile` dir [[native-image.developing-your-first-application.native-build-tools.running]] -==== Running the Example +=== Running the Example + At this point, your application should work. You can now start the application by running it directly: -[source,shell,indent=0,subs="verbatim",role="primary"] -.Maven +[tabs] +====== +Maven:: ++ +[source,shell] ---- - $ target/myproject +$ target/myproject ---- - -[source,shell,indent=0,subs="verbatim",role="secondary"] -.Gradle +Gradle:: ++ +[source,shell] ---- - $ build/native/nativeCompile/myproject +$ build/native/nativeCompile/myproject ---- +====== You should see output similar to the following: -[source,shell,indent=0,subs="verbatim,attributes"] +[source,shell,subs="verbatim,attributes"] ---- - . ____ _ __ _ _ - /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ - ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ - \\/ ___)| |_)| | | | | || (_| | ) ) ) ) - ' |____| .__|_| |_|_| |_\__, | / / / / - =========|_|==============|___/=/_/_/_/ - :: Spring Boot :: (v{spring-boot-version}) - ....... . . . - ....... . . . (log output here) - ....... . . . - ........ Started MyApplication in 0.08 seconds (process running for 0.095) + . ____ _ __ _ _ + /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ +( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ + \\/ ___)| |_)| | | | | || (_| | ) ) ) ) + ' |____| .__|_| |_|_| |_\__, | / / / / + =========|_|==============|___/=/_/_/_/ + :: Spring Boot :: (v{version-spring-boot}) +....... . . . +....... . . . (log output here) +....... . . . +........ Started MyApplication in 0.08 seconds (process running for 0.095) ---- NOTE: The startup time differs from machine to machine, but it should be much faster than a Spring Boot application running on a JVM. If you open a web browser to `http://localhost:8080`, you should see the following output: -[indent=0] +[source] ---- - Hello World! +Hello World! ---- To gracefully exit the application, press `ctrl-c`. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/native-image.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/native-image/index.adoc similarity index 51% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/native-image.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/native-image/index.adoc index 80a6b732ea..a7d9026476 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/native-image.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/native-image/index.adoc @@ -1,16 +1,6 @@ [[native-image]] = GraalVM Native Image Support -include::attributes.adoc[] https://www.graalvm.org/native-image/[GraalVM Native Images] are standalone executables that can be generated by processing compiled Java applications ahead-of-time. Native Images generally have a smaller memory footprint and start faster than their JVM counterparts. -include::native-image/introducing-graalvm-native-images.adoc[] - -include::native-image/developing-your-first-application.adoc[] - -include::native-image/testing-native-applications.adoc[] - -include::native-image/advanced-topics.adoc[] - -include::native-image/whats-next.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/native-image/introducing-graalvm-native-images.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/native-image/introducing-graalvm-native-images.adoc similarity index 86% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/native-image/introducing-graalvm-native-images.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/native-image/introducing-graalvm-native-images.adoc index bacc73c713..19ece74cbc 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/native-image/introducing-graalvm-native-images.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/native-image/introducing-graalvm-native-images.adoc @@ -1,5 +1,6 @@ [[native-image.introducing-graalvm-native-images]] -== Introducing GraalVM Native Images += Introducing GraalVM Native Images + GraalVM Native Images provide a new way to deploy and run Java applications. Compared to the Java Virtual Machine, native images can run with a smaller memory footprint and with much faster startup times. @@ -11,12 +12,13 @@ This ahead-of-time processing involves statically analyzing your application cod A GraalVM Native Image is a complete, platform-specific executable. You do not need to ship a Java Virtual Machine in order to run a native image. -TIP: If you just want to get started and experiment with GraalVM you can skip ahead to the "`<>`" section and return to this section later. +TIP: If you just want to get started and experiment with GraalVM you can skip ahead to the "`xref:native-image/developing-your-first-application.adoc[Developing Your First GraalVM Native Application]`" section and return to this section later. [[native-image.introducing-graalvm-native-images.key-differences-with-jvm-deployments]] -=== Key Differences with JVM Deployments +== Key Differences with JVM Deployments + The fact that GraalVM Native Images are produced ahead-of-time means that there are some key differences between native and JVM based applications. The main differences are: @@ -27,25 +29,26 @@ The main differences are: * There is no lazy class loading, everything shipped in the executables will be loaded in memory on startup. * There are some limitations around some aspects of Java applications that are not fully supported. -On top of those differences, Spring uses a process called <>, which imposes further limitations. +On top of those differences, Spring uses a process called xref:native-image/introducing-graalvm-native-images.adoc#native-image.introducing-graalvm-native-images.understanding-aot-processing[Spring Ahead-of-Time processing], which imposes further limitations. Please make sure to read at least the beginning of the next section to learn about those. -TIP: The {graal-native-image-docs}/metadata/Compatibility/[Native Image Compatibility Guide] section of the GraalVM reference documentation provides more details about GraalVM limitations. +TIP: The {url-graal-docs-native-image}/metadata/Compatibility/[Native Image Compatibility Guide] section of the GraalVM reference documentation provides more details about GraalVM limitations. [[native-image.introducing-graalvm-native-images.understanding-aot-processing]] -=== Understanding Spring Ahead-of-Time Processing +== Understanding Spring Ahead-of-Time Processing + Typical Spring Boot applications are quite dynamic and configuration is performed at runtime. In fact, the concept of Spring Boot auto-configuration depends heavily on reacting to the state of the runtime in order to configure things correctly. Although it would be possible to tell GraalVM about these dynamic aspects of the application, doing so would undo most of the benefit of static analysis. So instead, when using Spring Boot to create native images, a closed-world is assumed and the dynamic aspects of the application are restricted. -A closed-world assumption implies, besides <>, the following restrictions: +A closed-world assumption implies, besides xref:native-image/introducing-graalvm-native-images.adoc#native-image.introducing-graalvm-native-images.key-differences-with-jvm-deployments[the limitations created by GraalVM itself], the following restrictions: * The beans defined in your application cannot change at runtime, meaning: -- The Spring `@Profile` annotation and profile-specific configuration <>. +- The Spring `@Profile` annotation and profile-specific configuration xref:how-to:aot.adoc#howto.aot.conditions[have limitations]. - Properties that change if a bean is created are not supported (for example, `@ConditionalOnProperty` and `.enable` properties). When these restrictions are in place, it becomes possible for Spring to perform ahead-of-time processing during build-time and generate additional assets that GraalVM can use. @@ -63,7 +66,8 @@ A Spring AOT processed application will typically generate: [[native-image.introducing-graalvm-native-images.understanding-aot-processing.source-code-generation]] -==== Source Code Generation +=== Source Code Generation + Spring applications are composed of Spring Beans. Internally, Spring Framework uses two distinct concepts to manage beans. There are bean instances, which are the actual instances that have been created and can be injected into other beans. @@ -71,7 +75,7 @@ There are also bean definitions which are used to define attributes of a bean an If we take a typical `@Configuration` class: -include::code:MyConfiguration[] +include-code::MyConfiguration[] The bean definition is created by parsing the `@Configuration` class and finding the `@Bean` methods. In the above example, we're defining a `BeanDefinition` for a singleton bean named `myBean`. @@ -86,7 +90,7 @@ Once the bean definitions have been discovered, they are processed and converted The Spring AOT process would convert the configuration class above to code like this: -include::code:MyConfiguration__BeanDefinitions[] +include-code::MyConfiguration__BeanDefinitions[] NOTE: The exact code generated may differ depending on the nature of your bean definitions. @@ -109,7 +113,8 @@ Generated source files can be found in `target/spring-aot/main/sources` when usi [[native-image.introducing-graalvm-native-images.understanding-aot-processing.hint-file-generation]] -==== Hint File Generation +=== Hint File Generation + In addition to generating source files, the Spring AOT engine will also generate hint files that are used by GraalVM. Hint files contain JSON data that describes how GraalVM should deal with things that it can't understand by directly inspecting the code. @@ -124,7 +129,8 @@ TIP: Generated hint files can be found in `target/spring-aot/main/resources` whe [[native-image.introducing-graalvm-native-images.understanding-aot-processing.proxy-class-generation]] -==== Proxy Class Generation +=== Proxy Class Generation + Spring sometimes needs to generate proxy classes to enhance the code you've written with additional features. To do this, it uses the cglib library which directly generates bytecode. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/native-image/testing-native-applications.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/native-image/testing-native-applications.adoc similarity index 87% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/native-image/testing-native-applications.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/native-image/testing-native-applications.adoc index c2f39893b7..b9571d2897 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/native-image/testing-native-applications.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/native-image/testing-native-applications.adoc @@ -1,5 +1,6 @@ [[native-image.testing]] -== Testing GraalVM Native Images += Testing GraalVM Native Images + When writing native image applications, we recommend that you continue to use the JVM whenever possible to develop the majority of your unit and integration tests. This will help keep developer build times down and allow you to use existing IDE integrations. With broad test coverage on the JVM, you can then focus native image testing on the areas that are likely to be different. @@ -13,7 +14,8 @@ For native image testing, you're generally looking to ensure that the following [[native-image.testing.with-the-jvm]] -=== Testing Ahead-of-time Processing With the JVM +== Testing Ahead-of-time Processing With the JVM + When a Spring Boot application runs, it attempts to detect if it is running as a native image. If it is running as a native image, it will initialize the application using the code that was generated during at build-time by the Spring AOT engine. @@ -26,7 +28,7 @@ To run a Spring Boot application on the JVM and have it use AOT generated code y For example: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- $ java -Dspring.aot.enabled=true -jar myapplication.jar ---- @@ -44,7 +46,8 @@ Or you might consider using a project like Selenium to check your application's [[native-image.testing.with-native-build-tools]] -=== Testing With Native Build Tools +== Testing With Native Build Tools + GraalVM Native Build Tools includes the ability to run tests inside a native image. This can be helpful when you want to deeply test that the internals of your application work in a GraalVM native image. @@ -55,7 +58,7 @@ For example, you might choose to run native tests once a day. Spring Framework includes ahead-of-time support for running tests. All the usual Spring testing features work with native image tests. For example, you can continue to use the `@SpringBootTest` annotation. -You can also use Spring Boot <> to test only specific parts of your application. +You can also use Spring Boot xref:features/testing.adoc#features.testing.spring-boot-applications.autoconfigured-tests[test slices] to test only specific parts of your application. Spring Framework's native testing support works in the following way: @@ -68,17 +71,18 @@ Spring Framework's native testing support works in the following way: [[native-image.testing.with-native-build-tools.maven]] -==== Using Maven +=== Using Maven + To run native tests using Maven, ensure that your `pom.xml` file uses the `spring-boot-starter-parent`. You should have a `` section that looks like this: -[source,xml,indent=0,subs="verbatim,attributes"] +[source,xml,subs="verbatim,attributes"] ---- - - org.springframework.boot - spring-boot-starter-parent - {spring-boot-version} - + + org.springframework.boot + spring-boot-starter-parent + {version-spring-boot} + ---- The `spring-boot-starter-parent` declares a `nativeTest` profile that configures the executions that are needed to run the native tests. @@ -88,22 +92,23 @@ TIP: If you don't want to use `spring-boot-starter-parent` you'll need to config To build the image and run the tests, use the `test` goal with the `nativeTest` profile active: -[indent=0,subs="verbatim"] +[source,shell] ---- - $ mvn -PnativeTest test +$ mvn -PnativeTest test ---- [[native-image.testing.with-native-build-tools.gradle]] -==== Using Gradle +=== Using Gradle + The Spring Boot Gradle plugin automatically configures AOT test tasks when the GraalVM Native Image plugin is applied. You should check that your Gradle build contains a `plugins` block that includes `org.graalvm.buildtools.native`. To run native tests using Gradle you can use the `nativeTest` task: -[indent=0,subs="verbatim"] +[source,shell] ---- - $ gradle nativeTest +$ gradle nativeTest ---- diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/auto-configuration.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/auto-configuration.adoc similarity index 94% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/auto-configuration.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/auto-configuration.adoc index b3c7375f23..98e9ad6e23 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/auto-configuration.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/auto-configuration.adoc @@ -1,5 +1,6 @@ [[using.auto-configuration]] -== Auto-configuration += Auto-configuration + Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added. For example, if `HSQLDB` is on your classpath, and you have not manually configured any database connection beans, then Spring Boot auto-configures an in-memory database. @@ -11,7 +12,8 @@ We generally recommend that you add one or the other to your primary `@Configura [[using.auto-configuration.replacing]] -=== Gradually Replacing Auto-configuration +== Gradually Replacing Auto-configuration + Auto-configuration is non-invasive. At any point, you can start to define your own configuration to replace specific parts of the auto-configuration. For example, if you add your own `DataSource` bean, the default embedded database support backs away. @@ -22,10 +24,11 @@ Doing so enables debug logs for a selection of core loggers and logs a condition [[using.auto-configuration.disabling-specific]] -=== Disabling Specific Auto-configuration Classes +== Disabling Specific Auto-configuration Classes + If you find that specific auto-configuration classes that you do not want are being applied, you can use the exclude attribute of `@SpringBootApplication` to disable them, as shown in the following example: -include::code:MyApplication[] +include-code::MyApplication[] If the class is not on the classpath, you can use the `excludeName` attribute of the annotation and specify the fully qualified name instead. If you prefer to use `@EnableAutoConfiguration` rather than `@SpringBootApplication`, `exclude` and `excludeName` are also available. @@ -37,8 +40,10 @@ NOTE: Even though auto-configuration classes are `public`, the only aspect of th The actual contents of those classes, such as nested configuration classes or bean methods are for internal use only and we do not recommend using those directly. + [[using.auto-configuration.packages]] -=== Auto-configuration Packages +== Auto-configuration Packages + Auto-configuration packages are the packages that various auto-configured features look in by default when scanning for things such as entities and Spring Data repositories. The `@EnableAutoConfiguration` annotation (either directly or through its presence on `@SpringBootApplication`) determines the default auto-configuration package. Additional packages can be configured using the `@AutoConfigurationPackage` annotation. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/build-systems.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/build-systems.adoc similarity index 54% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/build-systems.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/build-systems.adoc index 34a5734244..a8a84e7300 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/build-systems.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/build-systems.adoc @@ -1,13 +1,15 @@ [[using.build-systems]] -== Build Systems -It is strongly recommended that you choose a build system that supports <> and that can consume artifacts published to the "`Maven Central`" repository. += Build Systems + +It is strongly recommended that you choose a build system that supports xref:using/build-systems.adoc#using.build-systems.dependency-management[_dependency management_] and that can consume artifacts published to the "`Maven Central`" repository. We would recommend that you choose Maven or Gradle. It is possible to get Spring Boot to work with other build systems (Ant, for example), but they are not particularly well supported. [[using.build-systems.dependency-management]] -=== Dependency Management +== Dependency Management + Each release of Spring Boot provides a curated list of dependencies that it supports. In practice, you do not need to provide a version for any of these dependencies in your build configuration, as Spring Boot manages that for you. When you upgrade Spring Boot itself, these dependencies are upgraded as well in a consistent way. @@ -15,7 +17,7 @@ When you upgrade Spring Boot itself, these dependencies are upgraded as well in NOTE: You can still specify a version and override Spring Boot's recommendations if you need to do so. The curated list contains all the Spring modules that you can use with Spring Boot as well as a refined list of third party libraries. -The list is available as a standard Bills of Materials (`spring-boot-dependencies`) that can be used with both <> and <>. +The list is available as a standard Bills of Materials (`spring-boot-dependencies`) that can be used with both xref:using/build-systems.adoc#using.build-systems.maven[Maven] and xref:using/build-systems.adoc#using.build-systems.gradle[Gradle]. WARNING: Each release of Spring Boot is associated with a base version of the Spring Framework. We **highly** recommend that you do not specify its version. @@ -23,90 +25,94 @@ We **highly** recommend that you do not specify its version. [[using.build-systems.maven]] -=== Maven +== Maven + To learn about using Spring Boot with Maven, see the documentation for Spring Boot's Maven plugin: -* Reference ({spring-boot-maven-plugin-docs}[HTML] and {spring-boot-maven-plugin-pdfdocs}[PDF]) -* {spring-boot-maven-plugin-api}[API] +* xref:maven-plugin:index.adoc[Reference] +* xref:maven-plugin:api/java/index.html[API] [[using.build-systems.gradle]] -=== Gradle +== Gradle + To learn about using Spring Boot with Gradle, see the documentation for Spring Boot's Gradle plugin: -* Reference ({spring-boot-gradle-plugin-docs}[HTML] and {spring-boot-gradle-plugin-pdfdocs}[PDF]) -* {spring-boot-gradle-plugin-api}[API] +* xref:gradle-plugin:index.adoc[Reference] +* xref:gradle-plugin:api/java/index.html[API] [[using.build-systems.ant]] -=== Ant +== Ant + It is possible to build a Spring Boot project using Apache Ant+Ivy. The `spring-boot-antlib` "`AntLib`" module is also available to help Ant create executable jars. To declare dependencies, a typical `ivy.xml` file looks something like the following example: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - - - - - - - - - + + + + + + + + + + ---- A typical `build.xml` looks like the following example: -[source,xml,indent=0,subs="verbatim,attributes"] +[source,xml,subs="verbatim,attributes"] ---- - + - + - - - + + + - - - - - + + + + + - - - + + + - - - + + + - - - - - - - - + + + + + + + + ---- -TIP: If you do not want to use the `spring-boot-antlib` module, see the _<>_ "`How-to`" . +TIP: If you do not want to use the `spring-boot-antlib` module, see the _xref:how-to:build.adoc#howto.build.build-an-executable-archive-with-ant-without-using-spring-boot-antlib[Build an Executable Archive From Ant without Using spring-boot-antlib]_ "`How-to`" . [[using.build-systems.starters]] -=== Starters +== Starters + Starters are a set of convenient dependency descriptors that you can include in your application. You get a one-stop shop for all the Spring and related technologies that you need without having to hunt through sample code and copy-paste loads of dependency descriptors. For example, if you want to get started using Spring and JPA for database access, include the `spring-boot-starter-data-jpa` dependency in your project. @@ -120,7 +126,7 @@ This naming structure is intended to help when you need to find a starter. The Maven integration in many IDEs lets you search dependencies by name. For example, with the appropriate Eclipse or Spring Tools plugin installed, you can press `ctrl-space` in the POM editor and type "`spring-boot-starter`" for a complete list. -As explained in the "`<>`" section, third party starters should not start with `spring-boot`, as it is reserved for official Spring Boot artifacts. +As explained in the "`xref:features/developing-auto-configuration.adoc#features.developing-auto-configuration.custom-starter[Creating Your Own Starter]`" section, third party starters should not start with `spring-boot`, as it is reserved for official Spring Boot artifacts. Rather, a third-party starter typically starts with the name of the project. For example, a third-party starter project called `thirdpartyproject` would typically be named `thirdpartyproject-spring-boot-starter`. **** @@ -128,18 +134,18 @@ For example, a third-party starter project called `thirdpartyproject` would typi The following application starters are provided by Spring Boot under the `org.springframework.boot` group: .Spring Boot application starters -include::starters/application-starters.adoc[] +include::ROOT:partial$starters/application-starters.adoc[] -In addition to the application starters, the following starters can be used to add _<>_ features: +In addition to the application starters, the following starters can be used to add _xref:how-to:actuator.adoc[production ready]_ features: .Spring Boot production starters -include::starters/production-starters.adoc[] +include::ROOT:partial$starters/production-starters.adoc[] Finally, Spring Boot also includes the following starters that can be used if you want to exclude or swap specific technical facets: .Spring Boot technical starters -include::starters/technical-starters.adoc[] +include::ROOT:partial$starters/technical-starters.adoc[] -To learn how to swap technical facets, please see the how-to documentation for <> and <>. +To learn how to swap technical facets, please see the how-to documentation for xref:how-to:webserver.adoc#howto.webserver.use-another[swapping web server] and xref:how-to:logging.adoc#howto.logging.log4j[logging system]. -TIP: For a list of additional community contributed starters, see the {spring-boot-latest-code}/spring-boot-project/spring-boot-starters/README.adoc[README file] in the `spring-boot-starters` module on GitHub. +TIP: For a list of additional community contributed starters, see the {code-spring-boot-latest}/spring-boot-project/spring-boot-starters/README.adoc[README file] in the `spring-boot-starters` module on GitHub. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/configuration-classes.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/configuration-classes.adoc similarity index 91% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/configuration-classes.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/configuration-classes.adoc index b73af3b0fb..f99fcfae10 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/configuration-classes.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/configuration-classes.adoc @@ -1,5 +1,6 @@ [[using.configuration-classes]] -== Configuration Classes += Configuration Classes + Spring Boot favors Java-based configuration. Although it is possible to use `SpringApplication` with XML sources, we generally recommend that your primary source be a single `@Configuration` class. Usually the class that defines the `main` method is a good candidate as the primary `@Configuration`. @@ -11,7 +12,8 @@ Searching for `+Enable*+` annotations can be a good starting point. [[using.configuration-classes.importing-additional-configuration]] -=== Importing Additional Configuration Classes +== Importing Additional Configuration Classes + You need not put all your `@Configuration` into a single class. The `@Import` annotation can be used to import additional configuration classes. Alternatively, you can use `@ComponentScan` to automatically pick up all Spring components, including `@Configuration` classes. @@ -19,6 +21,7 @@ Alternatively, you can use `@ComponentScan` to automatically pick up all Spring [[using.configuration-classes.importing-xml-configuration]] -=== Importing XML Configuration +== Importing XML Configuration + If you absolutely must use XML based configuration, we recommend that you still start with a `@Configuration` class. You can then use an `@ImportResource` annotation to load XML configuration files. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/devtools.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/devtools.adoc similarity index 79% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/devtools.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/devtools.adoc index 4f480d402a..59838508d9 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/devtools.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/devtools.adoc @@ -1,31 +1,32 @@ [[using.devtools]] -== Developer Tools += Developer Tools + Spring Boot includes an additional set of tools that can make the application development experience a little more pleasant. The `spring-boot-devtools` module can be included in any project to provide additional development-time features. To include devtools support, add the module dependency to your build, as shown in the following listings for Maven and Gradle: .Maven -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - - org.springframework.boot - spring-boot-devtools - true - - + + + org.springframework.boot + spring-boot-devtools + true + + ---- .Gradle -[source,gradle,indent=0,subs="verbatim"] +[source,gradle] ---- - dependencies { - developmentOnly("org.springframework.boot:spring-boot-devtools") - } +dependencies { + developmentOnly("org.springframework.boot:spring-boot-devtools") +} ---- CAUTION: Devtools might cause classloading issues, in particular in multi-module projects. -<> explains how to diagnose and solve them. +xref:using/devtools.adoc#using.devtools.diagnosing-classloading-issues[Diagnosing Classloading Issues] explains how to diagnose and solve them. NOTE: Developer tools are automatically disabled when running a fully packaged application. If your application is launched from `java -jar` or if it is started from a special classloader, then it is considered a "`production application`". @@ -37,27 +38,29 @@ To disable devtools, exclude the dependency or set the `-Dspring.devtools.restar TIP: Flagging the dependency as optional in Maven or using the `developmentOnly` configuration in Gradle (as shown above) prevents devtools from being transitively applied to other modules that use your project. TIP: Repackaged archives do not contain devtools by default. -If you want to use a <>, you need to include it. +If you want to use a xref:using/devtools.adoc#using.devtools.remote-applications[certain remote devtools feature], you need to include it. When using the Maven plugin, set the `excludeDevtools` property to `false`. -When using the Gradle plugin, {spring-boot-gradle-plugin-docs}#packaging-executable-configuring-including-development-only-dependencies[configure the task's classpath to include the `developmentOnly` configuration]. +When using the Gradle plugin, xref:gradle-plugin:packaging.adoc#packaging-executable.configuring.including-development-only-dependencies[configure the task's classpath to include the `developmentOnly` configuration]. [[using.devtools.diagnosing-classloading-issues]] -=== Diagnosing Classloading Issues -As described in the <> section, restart functionality is implemented by using two classloaders. +== Diagnosing Classloading Issues + +As described in the xref:#using.devtools.restart.restart-vs-reload[] section, restart functionality is implemented by using two classloaders. For most applications, this approach works well. However, it can sometimes cause classloading issues, in particular in multi-module projects. -To diagnose whether the classloading issues are indeed caused by devtools and its two classloaders, <>. -If this solves your problems, <> to include your entire project. +To diagnose whether the classloading issues are indeed caused by devtools and its two classloaders, xref:using/devtools.adoc#using.devtools.restart.disable[try disabling restart]. +If this solves your problems, xref:using/devtools.adoc#using.devtools.restart.customizing-the-classload[customize the restart classloader] to include your entire project. [[using.devtools.property-defaults]] -=== Property Defaults +== 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, xref:web/servlet.adoc#web.servlet.spring-mvc.template-engines[template engines] cache compiled templates to avoid repeatedly parsing template files. Also, Spring MVC can add HTTP caching headers to responses when serving static resources. While caching is very beneficial in production, it can be counter-productive during development, preventing you from seeing the changes you just made in your application. @@ -69,7 +72,7 @@ Rather than needing to set these properties manually, the `spring-boot-devtools` The following table lists all the properties that are applied: -include::devtools-property-defaults.adoc[] +include::ROOT:partial$propertydefaults/devtools-property-defaults.adoc[] NOTE: If you do not want property defaults to be applied you can set configprop:spring.devtools.add-properties[] to `false` in your `application.properties`. @@ -80,11 +83,12 @@ If you wish to log all request details (including potentially sensitive informat [[using.devtools.restart]] -=== Automatic Restart +== Automatic Restart + Applications that use `spring-boot-devtools` automatically restart whenever files on the classpath change. This can be a useful feature when working in an IDE, as it gives a very fast feedback loop for code changes. By default, any entry on the classpath that points to a directory is monitored for changes. -Note that certain resources, such as static assets and view templates, <>. +Note that certain resources, such as static assets and view templates, xref:using/devtools.adoc#using.devtools.restart.excluding-resources[do not need to restart the application]. .Triggering a restart **** @@ -101,7 +105,7 @@ NOTE: If you are restarting with Maven or Gradle using the build plugin you must If you disable forking, the isolated application classloader used by devtools will not be created and restarts will not operate properly. TIP: Automatic restart works very well when used with LiveReload. -<> for details. +xref:using/devtools.adoc#using.devtools.livereload[See the LiveReload section] for details. If you use JRebel, automatic restarts are disabled in favor of dynamic class reloading. Other devtools features (such as LiveReload and property overrides) can still be used. @@ -130,36 +134,38 @@ These work by rewriting classes as they are loaded to make them more amenable to [[using.devtools.restart.logging-condition-delta]] -==== Logging Changes in Condition Evaluation +=== Logging Changes in Condition Evaluation + By default, each time your application restarts, a report showing the condition evaluation delta is logged. The report shows the changes to your application's auto-configuration as you make changes such as adding or removing beans and setting configuration properties. To disable the logging of the report, set the following property: -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops,yaml] ---- - spring: - devtools: - restart: - log-condition-evaluation-delta: false +spring: + devtools: + restart: + log-condition-evaluation-delta: false ---- [[using.devtools.restart.excluding-resources]] -==== Excluding Resources +=== Excluding Resources + Certain resources do not necessarily need to trigger a restart when they are changed. For example, Thymeleaf templates can be edited in-place. -By default, changing resources in `/META-INF/maven`, `/META-INF/resources`, `/resources`, `/static`, `/public`, or `/templates` does not trigger a restart but does trigger a <>. +By default, changing resources in `/META-INF/maven`, `/META-INF/resources`, `/resources`, `/static`, `/public`, or `/templates` does not trigger a restart but does trigger a xref:using/devtools.adoc#using.devtools.livereload[live reload]. If you want to customize these exclusions, you can use the configprop:spring.devtools.restart.exclude[] property. For example, to exclude only `/static` and `/public` you would set the following property: -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops,yaml] ---- - spring: - devtools: - restart: - exclude: "static/**,public/**" +spring: + devtools: + restart: + exclude: "static/**,public/**" ---- TIP: If you want to keep those defaults and _add_ additional exclusions, use the configprop:spring.devtools.restart.additional-exclude[] property instead. @@ -167,26 +173,29 @@ TIP: If you want to keep those defaults and _add_ additional exclusions, use the [[using.devtools.restart.watching-additional-paths]] -==== Watching Additional Paths +=== Watching Additional Paths + You may want your application to be restarted or reloaded when you make changes to files that are not on the classpath. To do so, use the configprop:spring.devtools.restart.additional-paths[] property to configure additional paths to watch for changes. -You can use the configprop:spring.devtools.restart.exclude[] property <> to control whether changes beneath the additional paths trigger a full restart or a <>. +You can use the configprop:spring.devtools.restart.exclude[] property xref:using/devtools.adoc#using.devtools.restart.excluding-resources[described earlier] to control whether changes beneath the additional paths trigger a full restart or a xref:using/devtools.adoc#using.devtools.livereload[live reload]. [[using.devtools.restart.disable]] -==== Disabling Restart +=== Disabling Restart + If you do not want to use the restart feature, you can disable it by using the configprop:spring.devtools.restart.enabled[] property. In most cases, you can set this property in your `application.properties` (doing so still initializes the restart classloader, but it does not watch for file changes). If you need to _completely_ disable restart support (for example, because it does not work with a specific library), you need to set the configprop:spring.devtools.restart.enabled[] `System` property to `false` before calling `SpringApplication.run(...)`, as shown in the following example: -include::code:MyApplication[] +include-code::MyApplication[] [[using.devtools.restart.triggerfile]] -==== Using a Trigger File +=== Using a Trigger File + If you work with an IDE that continuously compiles changed files, you might prefer to trigger restarts only at specific times. To do so, you can use a "`trigger file`", which is a special file that must be modified when you want to actually trigger a restart check. @@ -197,27 +206,27 @@ The trigger file must appear somewhere on your classpath. For example, if you have a project with the following structure: -[indent=0] +[source] ---- - src - +- main - +- resources - +- .reloadtrigger +src ++- main + +- resources + +- .reloadtrigger ---- Then your `trigger-file` property would be: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - devtools: - restart: - trigger-file: ".reloadtrigger" +spring: + devtools: + restart: + trigger-file: ".reloadtrigger" ---- Restarts will now only happen when the `src/main/resources/.reloadtrigger` is updated. -TIP: You might want to set `spring.devtools.restart.trigger-file` as a <>, so that all your projects behave in the same way. +TIP: You might want to set `spring.devtools.restart.trigger-file` as a xref:using/devtools.adoc#using.devtools.globalsettings[global setting], so that all your projects behave in the same way. Some IDEs have features that save you from needing to update your trigger file manually. https://spring.io/tools[Spring Tools for Eclipse] and https://www.jetbrains.com/idea/[IntelliJ IDEA (Ultimate Edition)] both have such support. @@ -227,8 +236,9 @@ For IntelliJ IDEA, you can follow the https://www.jetbrains.com/help/idea/spring [[using.devtools.restart.customizing-the-classload]] -==== Customizing the Restart Classloader -As described earlier in the <> section, restart functionality is implemented by using two classloaders. +=== Customizing the Restart Classloader + +As described earlier in the xref:#using.devtools.restart.restart-vs-reload[] section, restart functionality is implemented by using two classloaders. If this causes issues, you might need to customize what gets loaded by which classloader. By default, any open project in your IDE is loaded with the "`restart`" classloader, and any regular `.jar` file is loaded with the "`base`" classloader. @@ -239,13 +249,13 @@ The `spring-devtools.properties` file can contain properties prefixed with `rest The `include` elements are items that should be pulled up into the "`restart`" classloader, and the `exclude` elements are items that should be pushed down into the "`base`" classloader. The value of the property is a regex pattern that is applied to the classpath, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configblocks] +[source,properties] ---- - restart: - exclude: - companycommonlibs: "/mycorp-common-[\\w\\d-\\.]+\\.jar" - include: - projectcommon: "/mycorp-myproj-[\\w\\d-\\.]+\\.jar" +restart: + exclude: + companycommonlibs: "/mycorp-common-[\\w\\d-\\.]+\\.jar" + include: + projectcommon: "/mycorp-myproj-[\\w\\d-\\.]+\\.jar" ---- NOTE: All property keys must be unique. @@ -257,7 +267,8 @@ You can package files inside your project, or in the libraries that the project [[using.devtools.restart.limitations]] -==== Known Limitations +=== Known Limitations + Restart functionality does not work well with objects that are deserialized by using a standard `ObjectInputStream`. If you need to deserialize data, you may need to use Spring's `ConfigurableObjectInputStream` in combination with `Thread.currentThread().getContextClassLoader()`. @@ -267,7 +278,8 @@ If you find such a problem, you need to request a fix with the original authors. [[using.devtools.livereload]] -=== LiveReload +== LiveReload + The `spring-boot-devtools` module includes an embedded LiveReload server that can be used to trigger a browser refresh when a resource is changed. LiveReload browser extensions are freely available for Chrome, Firefox and Safari. You can find these extensions by searching 'LiveReload' in the marketplace or store of your chosen browser. @@ -278,12 +290,13 @@ NOTE: You can only run one LiveReload server at a time. Before starting your application, ensure that no other LiveReload servers are running. If you start multiple applications from your IDE, only the first has LiveReload support. -WARNING: To trigger LiveReload when a file changes, <> must be enabled. +WARNING: To trigger LiveReload when a file changes, xref:using/devtools.adoc#using.devtools.restart[Automatic Restart] must be enabled. [[using.devtools.globalsettings]] -=== Global Settings +== Global Settings + You can configure global devtools settings by adding any of the following files to the `$HOME/.config/spring-boot` directory: . `spring-boot-devtools.properties` @@ -291,14 +304,14 @@ You can configure global devtools settings by adding any of the following files . `spring-boot-devtools.yml` Any properties added to these files apply to _all_ Spring Boot applications on your machine that use devtools. -For example, to configure restart to always use a <>, you would add the following property to your `spring-boot-devtools` file: +For example, to configure restart to always use a xref:using/devtools.adoc#using.devtools.restart.triggerfile[trigger file], you would add the following property to your `spring-boot-devtools` file: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - devtools: - restart: - trigger-file: ".reloadtrigger" +spring: + devtools: + restart: + trigger-file: ".reloadtrigger" ---- By default, `$HOME` is the user's home directory. @@ -311,25 +324,26 @@ This allows you to share the devtools global configuration with applications tha ==== Profiles are not supported in devtools properties/yaml files. -Any profiles activated in `.spring-boot-devtools.properties` will not affect the loading of <>. +Any profiles activated in `.spring-boot-devtools.properties` will not affect the loading of xref:features/external-config.adoc#features.external-config.files.profile-specific[profile-specific configuration files]. Profile specific filenames (of the form `spring-boot-devtools-.properties`) and `spring.config.activate.on-profile` documents in both YAML and Properties files are not supported. ==== [[using.devtools.globalsettings.configuring-file-system-watcher]] -==== Configuring File System Watcher -{spring-boot-devtools-module-code}/filewatch/FileSystemWatcher.java[FileSystemWatcher] works by polling the class changes with a certain time interval, and then waiting for a predefined quiet period to make sure there are no more changes. +=== Configuring File System Watcher + +{code-spring-boot-devtools-src}/filewatch/FileSystemWatcher.java[FileSystemWatcher] works by polling the class changes with a certain time interval, and then waiting for a predefined quiet period to make sure there are no more changes. Since Spring Boot relies entirely on the IDE to compile and copy files into the location from where Spring Boot can read them, you might find that there are times when certain changes are not reflected when devtools restarts the application. If you observe such problems constantly, try increasing the `spring.devtools.restart.poll-interval` and `spring.devtools.restart.quiet-period` parameters to the values that fit your development environment: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - devtools: - restart: - poll-interval: "2s" - quiet-period: "1s" +spring: + devtools: + restart: + poll-interval: "2s" + quiet-period: "1s" ---- The monitored classpath directories are now polled every 2 seconds for changes, and a 1 second quiet period is maintained to make sure there are no additional class changes. @@ -337,7 +351,8 @@ The monitored classpath directories are now polled every 2 seconds for changes, [[using.devtools.remote-applications]] -=== Remote Applications +== Remote Applications + The Spring Boot developer tools are not limited to local development. You can also use several features when running applications remotely. Remote support is opt-in as enabling it can be a security risk. @@ -347,19 +362,19 @@ You should never enable support on a production deployment. To enable it, you need to make sure that `devtools` is included in the repackaged archive, as shown in the following listing: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - - - org.springframework.boot - spring-boot-maven-plugin - - false - - - - + + + + org.springframework.boot + spring-boot-maven-plugin + + false + + + + ---- Then you need to set the configprop:spring.devtools.remote.secret[] property. @@ -374,7 +389,8 @@ NOTE: Remote devtools is not supported for Spring WebFlux applications. [[using.devtools.remote-applications.client]] -==== Running the Remote Client Application +=== Running the Remote Client Application + The remote client application is designed to be run from within your IDE. You need to run `org.springframework.boot.devtools.RemoteSpringApplication` with the same classpath as the remote project that you connect to. The application's single required argument is the remote URL to which it connects. @@ -389,9 +405,9 @@ For example, if you are using Eclipse or Spring Tools and you have a project nam A running remote client might resemble the following listing: -[indent=0,subs="verbatim,attributes"] +[source,subs="verbatim,attributes"] ---- -include::{remote-spring-application-output}[] +include::ROOT:example$remote-spring-application.txt[] ---- NOTE: Because the remote client is using the same classpath as the real application it can directly read application properties. @@ -404,8 +420,9 @@ TIP: If you need to use a proxy to access the remote application, configure the [[using.devtools.remote-applications.update]] -==== Remote Update -The remote client monitors your application classpath for changes in the same way as the <>. +=== Remote Update + +The remote client monitors your application classpath for changes in the same way as the xref:using/devtools.adoc#using.devtools.restart[local restart]. Any updated resource is pushed to the remote application and (_if required_) triggers a restart. This can be helpful if you iterate on a feature that uses a cloud service that you do not have locally. Generally, remote updates and restarts are much quicker than a full rebuild and deploy cycle. @@ -417,7 +434,7 @@ The next batch can’t be sent to the application, since the server is restartin This is typically manifested by a warning in the `RemoteSpringApplication` logs about failing to upload some of the classes, and a consequent retry. But it may also lead to application code inconsistency and failure to restart after the first batch of changes is uploaded. If you observe such problems constantly, try increasing the `spring.devtools.restart.poll-interval` and `spring.devtools.restart.quiet-period` parameters to the values that fit your development environment. -See the <> section for configuring these properties. +See the xref:using/devtools.adoc#using.devtools.globalsettings.configuring-file-system-watcher[Configuring File System Watcher] section for configuring these properties. NOTE: Files are only monitored when the remote client is running. If you change a file before starting the remote client, it is not pushed to the remote server. diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/index.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/index.adoc new file mode 100644 index 0000000000..536025376e --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/index.adoc @@ -0,0 +1,10 @@ +[[using]] += Developing with Spring Boot + +This section goes into more detail about how you should use Spring Boot. +It covers topics such as build systems, auto-configuration, and how to run your applications. +We also cover some Spring Boot best practices. +Although there is nothing particularly special about Spring Boot (it is just another library that you can consume), there are a few recommendations that, when followed, make your development process a little easier. + +If you are starting out with Spring Boot, you should probably read the xref:tutorial:first-application/index.adoc[_Developing your first Spring Boot application_] tutorial before diving into this section. + diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/packaging-for-production.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/packaging-for-production.adoc similarity index 76% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/packaging-for-production.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/packaging-for-production.adoc index 2adc987456..0e100c35f3 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/packaging-for-production.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/packaging-for-production.adoc @@ -1,7 +1,8 @@ [[using.packaging-for-production]] -== Packaging Your Application for Production += Packaging Your Application for Production + Executable jars can be used for production deployment. As they are self-contained, they are also ideally suited for cloud-based deployment. For additional "`production ready`" features, such as health, auditing, and metric REST or JMX end-points, consider adding `spring-boot-actuator`. -See _<>_ for details. +See _xref:how-to:actuator.adoc[Actuator]_ for details. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/running-your-application.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/running-your-application.adoc similarity index 79% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/running-your-application.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/running-your-application.adoc index 51dc6ef81c..04ec59cb72 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/running-your-application.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/running-your-application.adoc @@ -1,5 +1,6 @@ [[using.running-your-application]] -== Running Your Application += Running Your Application + One of the biggest advantages of packaging your application as a jar and using an embedded HTTP server is that you can run your application as you would any other. The sample applies to debugging Spring Boot applications. You do not need any special IDE plugins or extensions. @@ -10,7 +11,8 @@ If you choose to package your application as a war file, see your server and IDE [[using.running-your-application.from-an-ide]] -=== Running From an IDE +== Running From an IDE + You can run a Spring Boot application from your IDE as a Java application. However, you first need to import your project. Import steps vary depending on your IDE and build system. @@ -19,7 +21,7 @@ For example, Eclipse users can select `Import...` -> `Existing Maven Projects` f If you cannot directly import your project into your IDE, you may be able to generate IDE metadata by using a build plugin. Maven includes plugins for https://maven.apache.org/plugins/maven-eclipse-plugin/[Eclipse] and https://maven.apache.org/plugins/maven-idea-plugin/[IDEA]. -Gradle offers plugins for {gradle-docs}/userguide.html[various IDEs]. +Gradle offers plugins for {url-gradle-docs}/userguide.html[various IDEs]. TIP: If you accidentally run a web application twice, you see a "`Port already in use`" error. Spring Tools users can use the `Relaunch` button rather than the `Run` button to ensure that any existing instance is closed. @@ -27,69 +29,73 @@ Spring Tools users can use the `Relaunch` button rather than the `Run` button to [[using.running-your-application.as-a-packaged-application]] -=== Running as a Packaged Application +== Running as a Packaged Application + If you use the Spring Boot Maven or Gradle plugins to create an executable jar, you can run your application using `java -jar`, as shown in the following example: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ java -jar target/myapplication-0.0.1-SNAPSHOT.jar +$ java -jar target/myapplication-0.0.1-SNAPSHOT.jar ---- It is also possible to run a packaged application with remote debugging support enabled. Doing so lets you attach a debugger to your packaged application, as shown in the following example: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ java -agentlib:jdwp=server=y,transport=dt_socket,address=8000,suspend=n \ - -jar target/myapplication-0.0.1-SNAPSHOT.jar +$ java -agentlib:jdwp=server=y,transport=dt_socket,address=8000,suspend=n \ + -jar target/myapplication-0.0.1-SNAPSHOT.jar ---- [[using.running-your-application.with-the-maven-plugin]] -=== Using the Maven Plugin +== Using the Maven Plugin + The Spring Boot Maven plugin includes a `run` goal that can be used to quickly compile and run your application. Applications run in an exploded form, as they do in your IDE. The following example shows a typical Maven command to run a Spring Boot application: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ mvn spring-boot:run +$ mvn spring-boot:run ---- You might also want to use the `MAVEN_OPTS` operating system environment variable, as shown in the following example: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ export MAVEN_OPTS=-Xmx1024m +$ export MAVEN_OPTS=-Xmx1024m ---- [[using.running-your-application.with-the-gradle-plugin]] -=== Using the Gradle Plugin +== Using the Gradle Plugin + The Spring Boot Gradle plugin also includes a `bootRun` task that can be used to run your application in an exploded form. The `bootRun` task is added whenever you apply the `org.springframework.boot` and `java` plugins and is shown in the following example: -[indent=0,subs="verbatim"] +[source,shell] ---- - $ gradle bootRun +$ gradle bootRun ---- You might also want to use the `JAVA_OPTS` operating system environment variable, as shown in the following example: -[indent=0,subs="verbatim"] +[source,shell] ---- - $ export JAVA_OPTS=-Xmx1024m +$ export JAVA_OPTS=-Xmx1024m ---- [[using.running-your-application.hot-swapping]] -=== Hot Swapping +== Hot Swapping + Since Spring Boot applications are plain Java applications, JVM hot-swapping should work out of the box. JVM hot swapping is somewhat limited with the bytecode that it can replace. For a more complete solution, https://www.jrebel.com/products/jrebel[JRebel] can be used. The `spring-boot-devtools` module also includes support for quick application restarts. -See the <> for details. +See the xref:how-to:hotswapping.adoc[Hot swapping "`How-to`"] for details. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/spring-beans-and-dependency-injection.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/spring-beans-and-dependency-injection.adoc similarity index 87% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/spring-beans-and-dependency-injection.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/spring-beans-and-dependency-injection.adoc index d96903bee3..cea04af8dd 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/spring-beans-and-dependency-injection.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/spring-beans-and-dependency-injection.adoc @@ -1,5 +1,6 @@ [[using.spring-beans-and-dependency-injection]] -== Spring Beans and Dependency Injection += Spring Beans and Dependency Injection + You are free to use any of the standard Spring Framework techniques to define your beans and their injected dependencies. We generally recommend using constructor injection to wire up dependencies and `@ComponentScan` to find beans. @@ -8,10 +9,10 @@ All of your application components (`@Component`, `@Service`, `@Repository`, `@C The following example shows a `@Service` Bean that uses constructor injection to obtain a required `RiskAssessor` bean: -include::code:singleconstructor/MyAccountService[] +include-code::singleconstructor/MyAccountService[] If a bean has more than one constructor, you will need to mark the one you want Spring to use with `@Autowired`: -include::code:multipleconstructors/MyAccountService[] +include-code::multipleconstructors/MyAccountService[] TIP: Notice how using constructor injection lets the `riskAssessor` field be marked as `final`, indicating that it cannot be subsequently changed. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/structuring-your-code.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/structuring-your-code.adoc similarity index 71% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/structuring-your-code.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/structuring-your-code.adoc index 406f222608..6f00571b30 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/structuring-your-code.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/structuring-your-code.adoc @@ -1,5 +1,6 @@ [[using.structuring-your-code]] -== Structuring Your Code += Structuring Your Code + Spring Boot does not require any specific code layout to work. However, there are some best practices that help. @@ -8,7 +9,8 @@ TIP: If you wish to enforce a structure based on domains, take a look at https:/ [[using.structuring-your-code.using-the-default-package]] -=== Using the "`default`" Package +== Using the "`default`" Package + When a class does not include a `package` declaration, it is considered to be in the "`default package`". The use of the "`default package`" is generally discouraged and should be avoided. It can cause particular problems for Spring Boot applications that use the `@ComponentScan`, `@ConfigurationPropertiesScan`, `@EntityScan`, or `@SpringBootApplication` annotations, since every class from every jar is read. @@ -18,9 +20,10 @@ TIP: We recommend that you follow Java's recommended package naming conventions [[using.structuring-your-code.locating-the-main-class]] -=== Locating the Main Application Class +== Locating the Main Application Class + We generally recommend that you locate your main application class in a root package above other classes. -The <> is often placed on your main class, and it implicitly defines a base "`search package`" for certain items. +The xref:using/using-the-springbootapplication-annotation.adoc[`@SpringBootApplication` annotation] is often placed on your main class, and it implicitly defines a base "`search package`" for certain items. For example, if you are writing a JPA application, the package of the `@SpringBootApplication` annotated class is used to search for `@Entity` items. Using a root package also allows component scan to apply only on your project. @@ -28,26 +31,26 @@ TIP: If you do not want to use `@SpringBootApplication`, the `@EnableAutoConfigu The following listing shows a typical layout: -[indent=0] +[source] ---- - com - +- example - +- myapplication - +- MyApplication.java - | - +- customer - | +- Customer.java - | +- CustomerController.java - | +- CustomerService.java - | +- CustomerRepository.java - | - +- order - +- Order.java - +- OrderController.java - +- OrderService.java - +- OrderRepository.java +com + +- example + +- myapplication + +- MyApplication.java + | + +- customer + | +- Customer.java + | +- CustomerController.java + | +- CustomerService.java + | +- CustomerRepository.java + | + +- order + +- Order.java + +- OrderController.java + +- OrderService.java + +- OrderRepository.java ---- The `MyApplication.java` file would declare the `main` method, along with the basic `@SpringBootApplication`, as follows: -include::code:MyApplication[] +include-code::MyApplication[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/using-the-springbootapplication-annotation.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/using-the-springbootapplication-annotation.adoc similarity index 67% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/using-the-springbootapplication-annotation.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/using-the-springbootapplication-annotation.adoc index 04695f1b6c..a7587e885d 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/using-the-springbootapplication-annotation.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/using/using-the-springbootapplication-annotation.adoc @@ -1,14 +1,15 @@ [[using.using-the-springbootapplication-annotation]] -== Using the @SpringBootApplication Annotation += Using the @SpringBootApplication Annotation + Many Spring Boot developers like their apps to use auto-configuration, component scan and be able to define extra configuration on their "application class". A single `@SpringBootApplication` annotation can be used to enable those three features, that is: -* `@EnableAutoConfiguration`: enable <> -* `@ComponentScan`: enable `@Component` scan on the package where the application is located (see <>) +* `@EnableAutoConfiguration`: enable xref:using/auto-configuration.adoc[Spring Boot's auto-configuration mechanism] +* `@ComponentScan`: enable `@Component` scan on the package where the application is located (see xref:using/structuring-your-code.adoc[the best practices]) * `@SpringBootConfiguration`: enable registration of extra beans in the context or the import of additional configuration classes. -An alternative to Spring's standard `@Configuration` that aids <> in your integration tests. +An alternative to Spring's standard `@Configuration` that aids xref:features/testing.adoc#features.testing.spring-boot-applications.detecting-configuration[configuration detection] in your integration tests. -include::code:springapplication/MyApplication[] +include-code::springapplication/MyApplication[] NOTE: `@SpringBootApplication` also provides aliases to customize the attributes of `@EnableAutoConfiguration` and `@ComponentScan`. @@ -17,7 +18,7 @@ NOTE: `@SpringBootApplication` also provides aliases to customize the attributes None of these features are mandatory and you may choose to replace this single annotation by any of the features that it enables. For instance, you may not want to use component scan or configuration properties scan in your application: -include::code:individualannotations/MyApplication[] +include-code::individualannotations/MyApplication[] In this example, `MyApplication` is just like any other Spring Boot application except that `@Component`-annotated classes and `@ConfigurationProperties`-annotated classes are not detected automatically and the user-defined beans are imported explicitly (see `@Import`). ==== diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/graceful-shutdown.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/web/graceful-shutdown.adoc similarity index 90% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/graceful-shutdown.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/web/graceful-shutdown.adoc index a7a544d526..76e8ddcc3f 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/graceful-shutdown.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/web/graceful-shutdown.adoc @@ -1,5 +1,6 @@ [[web.graceful-shutdown]] -== 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. @@ -11,7 +12,7 @@ NOTE: Graceful shutdown with Tomcat requires Tomcat 9.0.33 or later. To enable graceful shutdown, configure the configprop:server.shutdown[] property, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- server: shutdown: "graceful" @@ -19,7 +20,7 @@ server: To configure the timeout period, configure the configprop:spring.lifecycle.timeout-per-shutdown-phase[] property, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- spring: lifecycle: diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/web/index.adoc similarity index 50% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/web.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/web/index.adoc index 0bf2c5be45..1f60389781 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/web/index.adoc @@ -1,26 +1,9 @@ [[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-graphql.adoc[] - -include::web/spring-hateoas.adoc[] - -include::web/whats-next.adoc[] +If you have not yet developed a Spring Boot web application, you can follow the "Hello World!" example in the _xref:tutorial:first-application/index.adoc[Getting started]_ section. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/reactive.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/web/reactive.adoc similarity index 79% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/reactive.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/web/reactive.adoc index 3c33bd6e62..c2486ea7da 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/reactive.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/web/reactive.adoc @@ -1,26 +1,30 @@ [[web.reactive]] -== Reactive Web Applications += 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`" +== The "`Spring WebFlux Framework`" + Spring WebFlux is the new reactive web framework introduced in Spring Framework 5.0. Unlike Spring MVC, it does not require the servlet API, is fully asynchronous and non-blocking, and implements the https://www.reactive-streams.org/[Reactive Streams] specification through https://projectreactor.io/[the Reactor project]. Spring WebFlux comes in two flavors: functional and annotation-based. The annotation-based one is quite close to the Spring MVC model, as shown in the following example: -include::code:MyRestController[] +include-code::MyRestController[] -WebFlux is part of the Spring Framework and detailed information is available in its {spring-framework-docs}/web/webflux.html[reference documentation]. +WebFlux is part of the Spring Framework and detailed information is available in its {url-spring-framework-docs}/web/webflux.html[reference documentation]. "`WebFlux.fn`", the functional variant, separates the routing configuration from the actual handling of the requests, as shown in the following example: -include::code:MyRoutingConfiguration[] +include-code::MyRoutingConfiguration[] -include::code:MyUserHandler[] +include-code::MyUserHandler[] -"`WebFlux.fn`" is part of the Spring Framework and detailed information is available in its {spring-framework-docs}/web/webflux-functional.html[reference documentation]. +"`WebFlux.fn`" is part of the Spring Framework and detailed information is available in its {url-spring-framework-docs}/web/webflux-functional.html[reference documentation]. TIP: You can define as many `RouterFunction` beans as you like to modularize the definition of the router. Beans can be ordered if you need to apply a precedence. @@ -34,15 +38,16 @@ You can still enforce your choice by setting the chosen application type to `Spr [[web.reactive.webflux.auto-configuration]] -==== 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 <>). +* Configuring codecs for `HttpMessageReader` and `HttpMessageWriter` instances (described xref:web/reactive.adoc#web.reactive.webflux.httpcodecs[later in this document]). +* Support for serving static resources, including support for WebJars (described xref:web/servlet.adoc#web.servlet.spring-mvc.static-content[later in this document]). -If you want to keep Spring Boot WebFlux features and you want to add additional {spring-framework-docs}/web/webflux/config.html[WebFlux configuration], you can add your own `@Configuration` class of type `WebFluxConfigurer` but *without* `@EnableWebFlux`. +If you want to keep Spring Boot WebFlux features and you want to add additional {url-spring-framework-docs}/web/webflux/config.html[WebFlux configuration], you can add your own `@Configuration` class of type `WebFluxConfigurer` but *without* `@EnableWebFlux`. If you want to add additional customization to the auto-configured `HttpHandler`, you can define beans of type `WebHttpHandlerBuilderCustomizer` and use them to modify the `WebHttpHandlerBuilder`. @@ -51,7 +56,8 @@ If you want to take complete control of Spring WebFlux, you can add your own `@C [[web.reactive.webflux.conversion-service]] -==== Spring WebFlux Conversion Service +=== Spring WebFlux Conversion Service + If you want to customize the `ConversionService` used by Spring WebFlux, you can provide a `WebFluxConfigurer` bean with an `addFormatters` method. Conversion can also be customized using the `spring.webflux.format.*` configuration properties. @@ -73,7 +79,8 @@ When not configured, the following defaults are used: [[web.reactive.webflux.httpcodecs]] -==== HTTP Codecs with HttpMessageReaders and HttpMessageWriters +=== 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. @@ -83,25 +90,26 @@ For example, `+spring.jackson.*+` configuration keys are applied to the Jackson If you need to add or customize codecs, you can create a custom `CodecCustomizer` component, as shown in the following example: -include::code:MyCodecsConfiguration[] +include-code::MyCodecsConfiguration[] -You can also leverage <>. +You can also leverage xref:features/json.adoc#features.json.jackson.custom-serializers-and-deserializers[Boot's custom JSON serializers and deserializers]. [[web.reactive.webflux.static-content]] -==== Static Content +=== 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] +[configprops,yaml] ---- - spring: - webflux: - static-path-pattern: "/resources/**" +spring: + webflux: + static-path-pattern: "/resources/**" ---- You can also customize the static resource locations by using `spring.web.resources.static-locations`. @@ -118,7 +126,8 @@ TIP: Spring WebFlux applications do not strictly depend on the servlet API, so t [[web.reactive.webflux.welcome-page]] -==== 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. @@ -142,7 +151,8 @@ The ordering is defined by the order of `HandlerMapping` beans which is by defau [[web.reactive.webflux.template-engines]] -==== 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. @@ -157,24 +167,25 @@ When you use one of these templating engines with the default configuration, you [[web.reactive.webflux.error-handling]] -==== 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 <>). +You can also provide your own HTML templates to display errors (see the xref:web/reactive.adoc#web.reactive.webflux.error-handling.error-pages[next section]). -Before customizing error handling in Spring Boot directly, you can leverage the {spring-framework-docs}/web/webflux/ann-rest-exceptions.html[RFC 7807 Problem Details] support in Spring WebFlux. +Before customizing error handling in Spring Boot directly, you can leverage the {url-spring-framework-docs}/web/webflux/ann-rest-exceptions.html[RFC 7807 Problem Details] support in Spring WebFlux. Spring WebFlux can produce custom error messages with the `application/problem+json` media type, like: -[source,json,indent=0,subs="verbatim"] +[source,json] ---- { - "type": "https://example.org/problems/unknown-project", - "title": "Unknown project", - "status": 404, - "detail": "No project found for id 'spring-unknown'", - "instance": "/projects/spring-unknown" + "type": "https://example.org/problems/unknown-project", + "title": "Unknown project", + "status": 404, + "detail": "No project found for id 'spring-unknown'", + "instance": "/projects/spring-unknown" } ---- @@ -187,17 +198,18 @@ For that, you can add a bean of type `ErrorAttributes`. To change the error handling behavior, you can implement `ErrorWebExceptionHandler` and register a bean definition of that type. Because an `ErrorWebExceptionHandler` is quite low-level, Spring Boot also provides a convenient `AbstractErrorWebExceptionHandler` to let you handle errors in a WebFlux functional way, as shown in the following example: -include::code:MyErrorWebExceptionHandler[] +include-code::MyErrorWebExceptionHandler[] For a more complete picture, you can also subclass `DefaultErrorWebExceptionHandler` directly and override specific methods. -In some cases, errors handled at the controller level are not recorded by web observations or the <>. -Applications can ensure that such exceptions are recorded with the observations by {spring-framework-docs}/integration/observability.html#observability.http-server.reactive[setting the handled exception on the observation context]. +In some cases, errors handled at the controller level are not recorded by web observations or the xref:actuator/metrics.adoc#actuator.metrics.supported.spring-webflux[metrics infrastructure]. +Applications can ensure that such exceptions are recorded with the observations by {url-spring-framework-docs}/integration/observability.html#observability.http-server.reactive[setting the handled exception on the observation context]. [[web.reactive.webflux.error-handling.error-pages]] -===== Custom Error Pages +==== Custom Error Pages + If you want to display a custom HTML error page for a given status code, you can add views that resolve from `error/*`, for example by adding files to a `/error` directory. Error pages can either be static HTML (that is, added under any of the static resource directories) or built with templates. The name of the file should be the exact status code, a status code series mask, or `error` for a default if nothing else matches. @@ -205,38 +217,39 @@ Note that the path to the default error view is `error/error`, whereas with Spri For example, to map `404` to a static HTML file, your directory structure would be as follows: -[source,indent=0,subs="verbatim"] +[source] ---- - src/ - +- main/ - +- java/ - | + - +- resources/ - +- public/ - +- error/ - | +- 404.html - +- +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"] +[source] ---- - src/ - +- main/ - +- java/ - | + - +- resources/ - +- templates/ - +- error/ - | +- 5xx.mustache - +- +src/ + +- main/ + +- java/ + | + + +- resources/ + +- templates/ + +- error/ + | +- 5xx.mustache + +- ---- [[web.reactive.webflux.web-filters]] -==== 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. @@ -257,7 +270,8 @@ When it does so, the orders shown in the following table will be used: [[web.reactive.reactive-server]] -=== Embedded Reactive Server Support +== 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. @@ -265,7 +279,8 @@ By default, the embedded server listens for HTTP requests on port 8080. [[web.reactive.reactive-server.customizing]] -==== Customizing Reactive Servers +=== Customizing Reactive Servers + Common reactive web server settings can be configured by using Spring `Environment` properties. Usually, you would define the properties in your `application.properties` or `application.yaml` file. @@ -273,45 +288,48 @@ Common server settings include: * Network settings: Listen port for incoming HTTP requests (`server.port`), interface address to bind to (`server.address`), and so on. * Error management: Location of the error page (`server.error.path`) and so on. -* <> -* <> +* xref:how-to:webserver.adoc#howto.webserver.configure-ssl[SSL] +* xref:how-to:webserver.adoc#howto.webserver.enable-response-compression[HTTP compression] Spring Boot tries as much as possible to expose common settings, but this is not always possible. For those cases, dedicated namespaces such as `server.netty.*` offer server-specific customizations. -TIP: See the {spring-boot-autoconfigure-module-code}/web/ServerProperties.java[`ServerProperties`] class for a complete list. +TIP: See the {code-spring-boot-autoconfigure-src}/web/ServerProperties.java[`ServerProperties`] class for a complete list. [[web.reactive.reactive-server.customizing.programmatic]] -===== Programmatic Customization +==== Programmatic Customization + If you need to programmatically configure your reactive web server, you can register a Spring bean that implements the `WebServerFactoryCustomizer` interface. `WebServerFactoryCustomizer` provides access to the `ConfigurableReactiveWebServerFactory`, which includes numerous customization setter methods. The following example shows programmatically setting the port: -include::code:MyWebServerFactoryCustomizer[] +include-code::MyWebServerFactoryCustomizer[] `JettyReactiveWebServerFactory`, `NettyReactiveWebServerFactory`, `TomcatReactiveWebServerFactory`, and `UndertowReactiveWebServerFactory` are dedicated variants of `ConfigurableReactiveWebServerFactory` that have additional customization setter methods for Jetty, Reactor Netty, Tomcat, and Undertow respectively. The following example shows how to customize `NettyReactiveWebServerFactory` that provides access to Reactor Netty-specific configuration options: -include::code:MyNettyWebServerFactoryCustomizer[] +include-code::MyNettyWebServerFactoryCustomizer[] [[web.reactive.reactive-server.customizing.direct]] -===== Customizing ConfigurableReactiveWebServerFactory Directly +==== Customizing ConfigurableReactiveWebServerFactory Directly + For more advanced use cases that require you to extend from `ReactiveWebServerFactory`, you can expose a bean of such type yourself. Setters are provided for many configuration options. Several protected method "`hooks`" are also provided should you need to do something more exotic. -See the {spring-boot-module-api}/web/reactive/server/ConfigurableReactiveWebServerFactory.html[source code documentation] for details. +See the xref:api:java/org/springframework/boot/web/reactive/server/ConfigurableReactiveWebServerFactory.html[source code documentation] for details. NOTE: Auto-configured customizers are still applied on your custom factory, so use that option carefully. [[web.reactive.reactive-server-resources-configuration]] -=== Reactive Server Resources Configuration +== 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: @@ -321,6 +339,6 @@ By default, those resources will be also shared with the Reactor Netty and Jetty 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 <>. +You can learn more about the resource configuration on the client side in the xref:io/rest-client.adoc#io.rest-client.webclient.runtime[WebClient Runtime section]. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/servlet.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/web/servlet.adoc similarity index 78% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/servlet.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/web/servlet.adoc index fbc330fd0c..00a1efe52b 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/servlet.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/web/servlet.adoc @@ -1,26 +1,28 @@ [[web.servlet]] -== Servlet Web Applications += Servlet Web Applications + If you want to build servlet-based web applications, you can take advantage of Spring Boot's auto-configuration for Spring MVC or Jersey. [[web.servlet.spring-mvc]] -=== The "`Spring Web MVC Framework`" -The {spring-framework-docs}/web/webmvc.html[Spring Web MVC framework] (often referred to as "`Spring MVC`") is a rich "`model view controller`" web framework. +== The "`Spring Web MVC Framework`" + +The {url-spring-framework-docs}/web/webmvc.html[Spring Web MVC framework] (often referred to as "`Spring MVC`") is a rich "`model view controller`" web framework. Spring MVC lets you create special `@Controller` or `@RestController` beans to handle incoming HTTP requests. Methods in your controller are mapped to HTTP by using `@RequestMapping` annotations. The following code shows a typical `@RestController` that serves JSON data: -include::code:MyRestController[] +include-code::MyRestController[] "`WebMvc.fn`", the functional variant, separates the routing configuration from the actual handling of the requests, as shown in the following example: -include::code:MyRoutingConfiguration[] +include-code::MyRoutingConfiguration[] -include::code:MyUserHandler[] +include-code::MyUserHandler[] -Spring MVC is part of the core Spring Framework, and detailed information is available in the {spring-framework-docs}/web/webmvc.html[reference documentation]. +Spring MVC is part of the core Spring Framework, and detailed information is available in the {url-spring-framework-docs}/web/webmvc.html[reference documentation]. There are also several guides that cover Spring MVC available at https://spring.io/guides. TIP: You can define as many `RouterFunction` beans as you like to modularize the definition of the router. @@ -29,20 +31,21 @@ Beans can be ordered if you need to apply a precedence. [[web.servlet.spring-mvc.auto-configuration]] -==== Spring MVC Auto-configuration +=== Spring MVC Auto-configuration + Spring Boot provides auto-configuration for Spring MVC that works well with most applications. It replaces the need for `@EnableWebMvc` and the two cannot be used together. In addition to Spring MVC's defaults, the auto-configuration provides the following features: * Inclusion of `ContentNegotiatingViewResolver` and `BeanNameViewResolver` beans. -* Support for serving static resources, including support for WebJars (covered <>). +* Support for serving static resources, including support for WebJars (covered xref:web/servlet.adoc#web.servlet.spring-mvc.static-content[later in this document]). * Automatic registration of `Converter`, `GenericConverter`, and `Formatter` beans. -* Support for `HttpMessageConverters` (covered <>). -* Automatic registration of `MessageCodesResolver` (covered <>). +* Support for `HttpMessageConverters` (covered xref:web/servlet.adoc#web.servlet.spring-mvc.message-converters[later in this document]). +* Automatic registration of `MessageCodesResolver` (covered xref:web/servlet.adoc#web.servlet.spring-mvc.message-codes[later in this document]). * Static `index.html` support. -* Automatic use of a `ConfigurableWebBindingInitializer` bean (covered <>). +* Automatic use of a `ConfigurableWebBindingInitializer` bean (covered xref:web/servlet.adoc#web.servlet.spring-mvc.binding-initializer[later in this document]). -If you want to keep those Spring Boot MVC customizations and make more {spring-framework-docs}/web/webmvc.html[MVC customizations] (interceptors, formatters, view controllers, and other features), you can add your own `@Configuration` class of type `WebMvcConfigurer` but *without* `@EnableWebMvc`. +If you want to keep those Spring Boot MVC customizations and make more {url-spring-framework-docs}/web/webmvc.html[MVC customizations] (interceptors, formatters, view controllers, and other features), you can add your own `@Configuration` class of type `WebMvcConfigurer` but *without* `@EnableWebMvc`. If you want to provide custom instances of `RequestMappingHandlerMapping`, `RequestMappingHandlerAdapter`, or `ExceptionHandlerExceptionResolver`, and still keep the Spring Boot MVC customizations, you can declare a bean of type `WebMvcRegistrations` and use it to provide custom instances of those components. The custom instances will be subject to further initialization and configuration by Spring MVC. @@ -54,7 +57,8 @@ Alternatively, add your own `@Configuration`-annotated `DelegatingWebMvcConfigur [[web.servlet.spring-mvc.conversion-service]] -==== Spring MVC Conversion Service +=== Spring MVC Conversion Service + Spring MVC uses a different `ConversionService` to the one used to convert values from your `application.properties` or `application.yaml` file. It means that `Period`, `Duration` and `DataSize` converters are not available and that `@DurationUnit` and `@DataSizeUnit` annotations will be ignored. @@ -80,7 +84,8 @@ When not configured, the following defaults are used: [[web.servlet.spring-mvc.message-converters]] -==== HttpMessageConverters +=== HttpMessageConverters + Spring MVC uses the `HttpMessageConverter` interface to convert HTTP requests and responses. Sensible defaults are included out of the box. For example, objects can be automatically converted to JSON (by using the Jackson library) or XML (by using the Jackson XML extension, if available, or by using JAXB if the Jackson XML extension is not available). @@ -88,7 +93,7 @@ By default, strings are encoded in `UTF-8`. If you need to add or customize converters, you can use Spring Boot's `HttpMessageConverters` class, as shown in the following listing: -include::code:MyHttpMessageConvertersConfiguration[] +include-code::MyHttpMessageConvertersConfiguration[] Any `HttpMessageConverter` bean that is present in the context is added to the list of converters. You can also override default converters in the same way. @@ -96,14 +101,16 @@ You can also override default converters in the same way. [[web.servlet.spring-mvc.message-codes]] -==== MessageCodesResolver +=== 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`]). +If you set the configprop:spring.mvc.message-codes-resolver-format[] property `PREFIX_ERROR_CODE` or `POSTFIX_ERROR_CODE`, Spring Boot creates one for you (see the enumeration in {url-spring-framework-javadoc}/org/springframework/validation/DefaultMessageCodesResolver.Format.html[`DefaultMessageCodesResolver.Format`]). [[web.servlet.spring-mvc.static-content]] -==== Static Content +=== 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. @@ -116,11 +123,11 @@ Most of the time, this does not happen (unless you modify the default MVC config By default, resources are mapped on `+/**+`, but you can tune that with the configprop:spring.mvc.static-path-pattern[] property. For instance, relocating all resources to `/resources/**` can be achieved as follows: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - mvc: - static-path-pattern: "/resources/**" +spring: + mvc: + static-path-pattern: "/resources/**" ---- You can also customize the static resource locations by using the configprop:spring.web.resources.static-locations[] property (replacing the default values with a list of directory locations). @@ -144,55 +151,56 @@ Otherwise, all Webjars resolve as a `404`. To use cache busting, the following configuration configures a cache busting solution for all static resources, effectively adding a content hash, such as ``, in URLs: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - web: - resources: - chain: - strategy: - content: - enabled: true - paths: "/**" +spring: + web: + resources: + chain: + strategy: + content: + enabled: true + paths: "/**" ---- NOTE: Links to resources are rewritten in templates at runtime, thanks to a `ResourceUrlEncodingFilter` that is auto-configured for Thymeleaf and FreeMarker. You should manually declare this filter when using JSPs. -Other template engines are currently not automatically supported but can be with custom template macros/helpers and the use of the {spring-framework-api}/web/servlet/resource/ResourceUrlProvider.html[`ResourceUrlProvider`]. +Other template engines are currently not automatically supported but can be with custom template macros/helpers and the use of the {url-spring-framework-javadoc}/org/springframework/web/servlet/resource/ResourceUrlProvider.html[`ResourceUrlProvider`]. When loading resources dynamically with, for example, a JavaScript module loader, renaming files is not an option. That is why other strategies are also supported and can be combined. A "fixed" strategy adds a static version string in the URL without changing the file name, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - web: - resources: - chain: - strategy: - content: - enabled: true - paths: "/**" - fixed: - enabled: true - paths: "/js/lib/" - version: "v12" +spring: + web: + resources: + chain: + strategy: + content: + enabled: true + paths: "/**" + fixed: + enabled: true + paths: "/js/lib/" + version: "v12" ---- With this configuration, JavaScript modules located under `"/js/lib/"` use a fixed versioning strategy (`"/v12/js/lib/mymodule.js"`), while other resources still use the content one (``). -See {spring-boot-autoconfigure-module-code}/web/WebProperties.java[`WebProperties.Resources`] for more supported options. +See {code-spring-boot-autoconfigure-src}/web/WebProperties.java[`WebProperties.Resources`] for more supported options. [TIP] ==== -This feature has been thoroughly described in a dedicated https://spring.io/blog/2014/07/24/spring-framework-4-1-handling-static-web-resources[blog post] and in Spring Framework's {spring-framework-docs}/web/webmvc/mvc-config/static-resources.html[reference documentation]. +This feature has been thoroughly described in a dedicated https://spring.io/blog/2014/07/24/spring-framework-4-1-handling-static-web-resources[blog post] and in Spring Framework's {url-spring-framework-docs}/web/webmvc/mvc-config/static-resources.html[reference documentation]. ==== [[web.servlet.spring-mvc.welcome-page]] -==== Welcome Page +=== 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. @@ -214,87 +222,92 @@ The ordering is defined by the order of `HandlerMapping` beans which is by defau |=== + [[web.servlet.spring-mvc.favicon]] -==== Custom Favicon +=== Custom Favicon + As with other static resources, Spring Boot checks for a `favicon.ico` in the configured static content locations. If such a file is present, it is automatically used as the favicon of the application. [[web.servlet.spring-mvc.content-negotiation]] -==== Path Matching and Content Negotiation +=== Path Matching and Content Negotiation + Spring MVC can map incoming HTTP requests to handlers by looking at the request path and matching it to the mappings defined in your application (for example, `@GetMapping` annotations on Controller methods). Spring Boot chooses to disable suffix pattern matching by default, which means that requests like `"GET /projects/spring-boot.json"` will not be matched to `@GetMapping("/projects/spring-boot")` mappings. -This is considered as a {spring-framework-docs}/web/webmvc/mvc-controller/ann-requestmapping.html#mvc-ann-requestmapping-suffix-pattern-match[best practice for Spring MVC applications]. +This is considered as a {url-spring-framework-docs}/web/webmvc/mvc-controller/ann-requestmapping.html#mvc-ann-requestmapping-suffix-pattern-match[best practice for Spring MVC applications]. This feature was mainly useful in the past for HTTP clients which did not send proper "Accept" request headers; we needed to make sure to send the correct Content Type to the client. Nowadays, Content Negotiation is much more reliable. There are other ways to deal with HTTP clients that do not consistently send proper "Accept" request headers. Instead of using suffix matching, we can use a query parameter to ensure that requests like `"GET /projects/spring-boot?format=json"` will be mapped to `@GetMapping("/projects/spring-boot")`: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - mvc: - contentnegotiation: - favor-parameter: true +spring: + mvc: + contentnegotiation: + favor-parameter: true ---- Or if you prefer to use a different parameter name: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - mvc: - contentnegotiation: - favor-parameter: true - parameter-name: "myparam" +spring: + mvc: + contentnegotiation: + favor-parameter: true + parameter-name: "myparam" ---- Most standard media types are supported out-of-the-box, but you can also define new ones: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - mvc: - contentnegotiation: - media-types: - markdown: "text/markdown" +spring: + mvc: + contentnegotiation: + media-types: + markdown: "text/markdown" ---- As of Spring Framework 5.3, Spring MVC supports two strategies for matching request paths to controllers. By default, Spring Boot uses the `PathPatternParser` strategy. `PathPatternParser` is an https://spring.io/blog/2020/06/30/url-matching-with-pathpattern-in-spring-mvc[optimized implementation] but comes with some restrictions compared to the `AntPathMatcher` strategy. -`PathPatternParser` restricts usage of {spring-framework-docs}/web/webmvc/mvc-controller/ann-requestmapping.html#mvc-ann-requestmapping-uri-templates[some path pattern variants]. +`PathPatternParser` restricts usage of {url-spring-framework-docs}/web/webmvc/mvc-controller/ann-requestmapping.html#mvc-ann-requestmapping-uri-templates[some path pattern variants]. It is also incompatible with configuring the `DispatcherServlet` with a path prefix (configprop:spring.mvc.servlet.path[]). The strategy can be configured using the configprop:spring.mvc.pathmatch.matching-strategy[] configuration property, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - mvc: - pathmatch: - matching-strategy: "ant-path-matcher" +spring: + mvc: + pathmatch: + matching-strategy: "ant-path-matcher" ---- By default, Spring MVC will send a 404 Not Found error response if a handler is not found for a request. To have a `NoHandlerFoundException` thrown instead, set configprop:spring.mvc.throw-exception-if-no-handler-found to `true`. -Note that, by default, the <> is mapped to `+/**+` and will, therefore, provide a handler for all requests. +Note that, by default, the xref:web/servlet.adoc#web.servlet.spring-mvc.static-content[serving of static content] is mapped to `+/**+` and will, therefore, provide a handler for all requests. For a `NoHandlerFoundException` to be thrown, you must also set configprop:spring.mvc.static-path-pattern[] to a more specific value such as `/resources/**` or set configprop:spring.web.resources.add-mappings[] to `false` to disable serving of static content entirely. [[web.servlet.spring-mvc.binding-initializer]] -==== ConfigurableWebBindingInitializer +=== ConfigurableWebBindingInitializer + Spring MVC uses a `WebBindingInitializer` to initialize a `WebDataBinder` for a particular request. If you create your own `ConfigurableWebBindingInitializer` `@Bean`, Spring Boot automatically configures Spring MVC to use it. [[web.servlet.spring-mvc.template-engines]] -==== Template Engines +=== Template Engines + As well as REST web services, you can also use Spring MVC to serve dynamic HTML content. Spring MVC supports a variety of templating technologies, including Thymeleaf, FreeMarker, and JSPs. Also, many other templating engines include their own Spring MVC integrations. @@ -307,7 +320,7 @@ Spring Boot includes auto-configuration support for the following templating eng * 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 xref:web/servlet.adoc#web.servlet.embedded-container.jsp-limitations[known limitations] when using them with embedded servlet containers. When you use one of these templating engines with the default configuration, your templates are picked up automatically from `src/main/resources/templates`. @@ -319,13 +332,14 @@ If you have this problem, you can reorder the classpath in the IDE to place the [[web.servlet.spring-mvc.error-handling]] -==== Error Handling +=== Error Handling + By default, Spring Boot provides an `/error` mapping that handles all errors in a sensible way, and it is registered as a "`global`" error page in the servlet container. For machine clients, it produces a JSON response with details of the error, the HTTP status, and the exception message. For browser clients, there is a "`whitelabel`" error view that renders the same data in HTML format (to customize it, add a `View` that resolves to `error`). There are a number of `server.error` properties that can be set if you want to customize the default error handling behavior. -See the <> section of the Appendix. +See the xref:appendix:application-properties/index.adoc#appendix.application-properties.server["`Server Properties`"] section of the Appendix. To replace the default behavior completely, you can implement `ErrorController` and register a bean definition of that type or add a bean of type `ErrorAttributes` to use the existing mechanism but replace the contents. @@ -333,17 +347,17 @@ TIP: The `BasicErrorController` can be used as a base class for a custom `ErrorC This is particularly useful if you want to add a handler for a new content type (the default is to handle `text/html` specifically and provide a fallback for everything else). To do so, extend `BasicErrorController`, add a public method with a `@RequestMapping` that has a `produces` attribute, and create a bean of your new type. -As of Spring Framework 6.0, {spring-framework-docs}/web/webmvc/mvc-ann-rest-exceptions.html[RFC 7807 Problem Details] is supported. +As of Spring Framework 6.0, {url-spring-framework-docs}/web/webmvc/mvc-ann-rest-exceptions.html[RFC 7807 Problem Details] is supported. Spring MVC can produce custom error messages with the `application/problem+json` media type, like: -[source,json,indent=0,subs="verbatim"] +[source,json] ---- { - "type": "https://example.org/problems/unknown-project", - "title": "Unknown project", - "status": 404, - "detail": "No project found for id 'spring-unknown'", - "instance": "/projects/spring-unknown" + "type": "https://example.org/problems/unknown-project", + "title": "Unknown project", + "status": 404, + "detail": "No project found for id 'spring-unknown'", + "instance": "/projects/spring-unknown" } ---- @@ -351,77 +365,80 @@ This support can be enabled by setting configprop:spring.mvc.problemdetails.enab You can also define a class annotated with `@ControllerAdvice` to customize the JSON document to return for a particular controller and/or exception type, as shown in the following example: -include::code:MyControllerAdvice[] +include-code::MyControllerAdvice[] In the preceding example, if `MyException` is thrown by a controller defined in the same package as `SomeController`, a JSON representation of the `MyErrorBody` POJO is used instead of the `ErrorAttributes` representation. -In some cases, errors handled at the controller level are not recorded by web observations or the <>. -Applications can ensure that such exceptions are recorded with the observations by {spring-framework-docs}/integration/observability.html#observability.http-server.servlet[setting the handled exception on the observation context]. +In some cases, errors handled at the controller level are not recorded by web observations or the xref:actuator/metrics.adoc#actuator.metrics.supported.spring-mvc[metrics infrastructure]. +Applications can ensure that such exceptions are recorded with the observations by {url-spring-framework-docs}/integration/observability.html#observability.http-server.servlet[setting the handled exception on the observation context]. [[web.servlet.spring-mvc.error-handling.error-pages]] -===== Custom Error Pages +==== Custom Error Pages + If you want to display a custom HTML error page for a given status code, you can add a file to an `/error` directory. Error pages can either be static HTML (that is, added under any of the static resource directories) or be built by using templates. The name of the file should be the exact status code or a series mask. For example, to map `404` to a static HTML file, your directory structure would be as follows: -[indent=0,subs="verbatim"] +[source] ---- - src/ - +- main/ - +- java/ - | + - +- resources/ - +- public/ - +- error/ - | +- 404.html - +- +src/ + +- main/ + +- java/ + | + + +- resources/ + +- public/ + +- error/ + | +- 404.html + +- ---- To map all `5xx` errors by using a FreeMarker template, your directory structure would be as follows: -[indent=0,subs="verbatim"] +[source] ---- - src/ - +- main/ - +- java/ - | + - +- resources/ - +- templates/ - +- error/ - | +- 5xx.ftlh - +- +src/ + +- main/ + +- java/ + | + + +- resources/ + +- templates/ + +- error/ + | +- 5xx.ftlh + +- ---- For more complex mappings, you can also add beans that implement the `ErrorViewResolver` interface, as shown in the following example: -include::code:MyErrorViewResolver[] +include-code::MyErrorViewResolver[] -You can also use regular Spring MVC features such as {spring-framework-docs}/web/webmvc/mvc-servlet/exceptionhandlers.html[`@ExceptionHandler` methods] and {spring-framework-docs}/web/webmvc/mvc-controller/ann-advice.html[`@ControllerAdvice`]. +You can also use regular Spring MVC features such as {url-spring-framework-docs}/web/webmvc/mvc-servlet/exceptionhandlers.html[`@ExceptionHandler` methods] and {url-spring-framework-docs}/web/webmvc/mvc-controller/ann-advice.html[`@ControllerAdvice`]. The `ErrorController` then picks up any unhandled exceptions. [[web.servlet.spring-mvc.error-handling.error-pages-without-spring-mvc]] -===== Mapping Error Pages Outside of Spring MVC +==== Mapping Error Pages Outside of Spring MVC + For applications that do not use Spring MVC, you can use the `ErrorPageRegistrar` interface to directly register `ErrorPages`. This abstraction works directly with the underlying embedded servlet container and works even if you do not have a Spring MVC `DispatcherServlet`. -include::code:MyErrorPagesConfiguration[] +include-code::MyErrorPagesConfiguration[] NOTE: If you register an `ErrorPage` with a path that ends up being handled by a `Filter` (as is common with some non-Spring web frameworks, like Jersey and Wicket), then the `Filter` has to be explicitly registered as an `ERROR` dispatcher, as shown in the following example: -include::code:MyFilterConfiguration[] +include-code::MyFilterConfiguration[] Note that the default `FilterRegistrationBean` does not include the `ERROR` dispatcher type. [[web.servlet.spring-mvc.error-handling.in-a-war-deployment]] -===== Error Handling in a WAR Deployment +==== Error Handling in a WAR Deployment + When deployed to a servlet container, Spring Boot uses its error page filter to forward a request with an error status to the appropriate error page. This is necessary as the servlet specification does not provide an API for registering error pages. Depending on the container that you are deploying your war file to and the technologies that your application uses, some additional configuration may be required. @@ -433,19 +450,21 @@ You should disable this behavior by setting `com.ibm.ws.webcontainer.invokeFlush [[web.servlet.spring-mvc.cors]] -==== CORS Support +=== CORS Support + https://en.wikipedia.org/wiki/Cross-origin_resource_sharing[Cross-origin resource sharing] (CORS) is a https://www.w3.org/TR/cors/[W3C specification] implemented by https://caniuse.com/#feat=cors[most browsers] that lets you specify in a flexible way what kind of cross-domain requests are authorized, instead of using some less secure and less powerful approaches such as IFRAME or JSONP. -As of version 4.2, Spring MVC {spring-framework-docs}/web/webmvc-cors.html[supports CORS]. -Using {spring-framework-docs}/web/webmvc-cors.html#mvc-cors-controller[controller method CORS configuration] with {spring-framework-api}/web/bind/annotation/CrossOrigin.html[`@CrossOrigin`] annotations in your Spring Boot application does not require any specific configuration. -{spring-framework-docs}/web/webmvc-cors.html#mvc-cors-global[Global CORS configuration] can be defined by registering a `WebMvcConfigurer` bean with a customized `addCorsMappings(CorsRegistry)` method, as shown in the following example: +As of version 4.2, Spring MVC {url-spring-framework-docs}/web/webmvc-cors.html[supports CORS]. +Using {url-spring-framework-docs}/web/webmvc-cors.html#mvc-cors-controller[controller method CORS configuration] with {url-spring-framework-javadoc}/org/springframework/web/bind/annotation/CrossOrigin.html[`@CrossOrigin`] annotations in your Spring Boot application does not require any specific configuration. +{url-spring-framework-docs}/web/webmvc-cors.html#mvc-cors-global[Global CORS configuration] can be defined by registering a `WebMvcConfigurer` bean with a customized `addCorsMappings(CorsRegistry)` method, as shown in the following example: -include::code:MyCorsConfiguration[] +include-code::MyCorsConfiguration[] [[web.servlet.jersey]] -=== JAX-RS and Jersey +== JAX-RS and Jersey + If you prefer the JAX-RS programming model for REST endpoints, you can use one of the available implementations instead of Spring MVC. https://jersey.github.io/[Jersey] and https://cxf.apache.org/[Apache CXF] work quite well out of the box. CXF requires you to register its `Servlet` or `Filter` as a `@Bean` in your application context. @@ -453,23 +472,17 @@ Jersey has some native Spring support, so we also provide auto-configuration sup To get started with Jersey, include the `spring-boot-starter-jersey` as a dependency and then you need one `@Bean` of type `ResourceConfig` in which you register all the endpoints, as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/web/servlet/jersey/MyJerseyConfig.java[] ----- +include-code::MyJerseyConfig[] WARNING: Jersey's support for scanning executable archives is rather limited. -For example, it cannot scan for endpoints in a package found in a <> or in `WEB-INF/classes` when running an executable war file. +For example, it cannot scan for endpoints in a package found in a xref:deployment/installing.adoc[fully executable jar file] or in `WEB-INF/classes` when running an executable war file. To avoid this limitation, the `packages` method should not be used, and endpoints should be registered individually by using the `register` method, as shown in the preceding example. For more advanced customizations, you can also register an arbitrary number of beans that implement `ResourceConfigCustomizer`. All the registered endpoints should be `@Components` with HTTP resource annotations (`@GET` and others), as shown in the following example: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/web/servlet/jersey/MyEndpoint.java[] ----- +include-code::MyEndpoint[] Since the `Endpoint` is a Spring `@Component`, its lifecycle is managed by Spring and you can use the `@Autowired` annotation to inject dependencies and use the `@Value` annotation to inject external configuration. By default, the Jersey servlet is registered and mapped to `/*`. @@ -487,7 +500,8 @@ Both the servlet and the filter registrations can be given init parameters by us [[web.servlet.embedded-container]] -=== Embedded Servlet Container Support +== Embedded Servlet Container Support + For servlet application, Spring Boot includes support for embedded https://tomcat.apache.org/[Tomcat], https://www.eclipse.org/jetty/[Jetty], and https://github.com/undertow-io/undertow[Undertow] servers. Most developers use the appropriate "`Starter`" to obtain a fully configured instance. By default, the embedded server listens for HTTP requests on port `8080`. @@ -495,13 +509,15 @@ By default, the embedded server listens for HTTP requests on port `8080`. [[web.servlet.embedded-container.servlets-filters-listeners]] -==== Servlets, Filters, and Listeners +=== Servlets, Filters, and Listeners + When using an embedded servlet container, you can register servlets, filters, and all the listeners (such as `HttpSessionListener`) from the servlet spec, either by using Spring beans or by scanning for servlet components. [[web.servlet.embedded-container.servlets-filters-listeners.beans]] -===== Registering Servlets, Filters, and Listeners as Spring Beans +==== 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. @@ -518,16 +534,17 @@ If you cannot change the `Filter` class to add `@Order` or implement `Ordered`, Avoid configuring a filter that reads the request body at `Ordered.HIGHEST_PRECEDENCE`, since it might go against the character encoding configuration of your application. If a servlet filter wraps the request, it should be configured with an order that is less than or equal to `OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER`. -TIP: To see the order of every `Filter` in your application, enable debug level logging for the `web` <> (`logging.level.web=debug`). +TIP: To see the order of every `Filter` in your application, enable debug level logging for the `web` xref:features/logging.adoc#features.logging.log-groups[logging group] (`logging.level.web=debug`). Details of the registered filters, including their order and URL patterns, will then be logged at startup. WARNING: Take care when registering `Filter` beans since they are initialized very early in the application lifecycle. -If you need to register a `Filter` that interacts with other beans, consider using a {spring-boot-module-api}/web/servlet/DelegatingFilterProxyRegistrationBean.html[`DelegatingFilterProxyRegistrationBean`] instead. +If you need to register a `Filter` that interacts with other beans, consider using a xref:api:java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBean.html[`DelegatingFilterProxyRegistrationBean`] instead. [[web.servlet.embedded-container.context-initializer]] -==== Servlet Context Initialization +=== Servlet Context Initialization + Embedded servlet containers do not directly execute the `jakarta.servlet.ServletContainerInitializer` interface or Spring's `org.springframework.web.WebApplicationInitializer` interface. This is an intentional design decision intended to reduce the risk that third party libraries designed to run inside a war may break Spring Boot applications. @@ -537,7 +554,8 @@ The single `onStartup` method provides access to the `ServletContext` and, if ne [[web.servlet.embedded-container.context-initializer.scanning]] -===== Scanning for Servlets, Filters, and listeners +==== Scanning for Servlets, Filters, and listeners + When using an embedded container, automatic registration of classes annotated with `@WebServlet`, `@WebFilter`, and `@WebListener` can be enabled by using `@ServletComponentScan`. TIP: `@ServletComponentScan` has no effect in a standalone container, where the container's built-in discovery mechanisms are used instead. @@ -545,7 +563,8 @@ TIP: `@ServletComponentScan` has no effect in a standalone container, where the [[web.servlet.embedded-container.application-context]] -==== The ServletWebServerApplicationContext +=== The ServletWebServerApplicationContext + Under the hood, Spring Boot uses a different type of `ApplicationContext` for embedded servlet container support. The `ServletWebServerApplicationContext` is a special type of `WebApplicationContext` that bootstraps itself by searching for a single `ServletWebServerFactory` bean. Usually a `TomcatServletWebServerFactory`, `JettyServletWebServerFactory`, or `UndertowServletWebServerFactory` has been auto-configured. @@ -559,15 +578,13 @@ One way to get around this is to inject `ApplicationContext` as a dependency of Another way is to use a callback once the server has started. This can be done using an `ApplicationListener` which listens for the `ApplicationStartedEvent` as follows: -[source,java,indent=0,subs="verbatim"] ----- -include::{docs-java}/web/servlet/embeddedcontainer/applicationcontext/MyDemoBean.java[] ----- +include-code::MyDemoBean[] [[web.servlet.embedded-container.customizing]] -==== Customizing Embedded Servlet Containers +=== 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. @@ -576,19 +593,20 @@ Common server settings include: * Network settings: Listen port for incoming HTTP requests (`server.port`), interface address to bind to (`server.address`), and so on. * Session settings: Whether the session is persistent (`server.servlet.session.persistent`), session timeout (`server.servlet.session.timeout`), location of session data (`server.servlet.session.store-dir`), and session-cookie configuration (`server.servlet.session.cookie.*`). * Error management: Location of the error page (`server.error.path`) and so on. -* <> -* <> +* xref:how-to:webserver.adoc#howto.webserver.configure-ssl[SSL] +* xref:how-to:webserver.adoc#howto.webserver.enable-response-compression[HTTP compression] Spring Boot tries as much as possible to expose common settings, but this is not always possible. For those cases, dedicated namespaces offer server-specific customizations (see `server.tomcat` and `server.undertow`). -For instance, <> can be configured with specific features of the embedded servlet container. +For instance, xref:how-to:webserver.adoc#howto.webserver.configure-access-logs[access logs] can be configured with specific features of the embedded servlet container. -TIP: See the {spring-boot-autoconfigure-module-code}/web/ServerProperties.java[`ServerProperties`] class for a complete list. +TIP: See the {code-spring-boot-autoconfigure-src}/web/ServerProperties.java[`ServerProperties`] class for a complete list. [[web.servlet.embedded-container.customizing.samesite]] -===== SameSite Cookies +==== SameSite Cookies + The `SameSite` cookie attribute can be used by web browsers to control if and how cookies are submitted in cross-site requests. The attribute is particularly relevant for modern web browsers which have started to change the default value that is used when the attribute is missing. @@ -598,13 +616,13 @@ It is also used to configure Spring Session servlet based `SessionRepository` be For example, if you want your session cookie to have a `SameSite` attribute of `None`, you can add the following to your `application.properties` or `application.yaml` file: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - server: - servlet: - session: - cookie: - same-site: "none" +server: + servlet: + session: + cookie: + same-site: "none" ---- If you want to change the `SameSite` attribute on other cookies added to your `HttpServletResponse`, you can use a `CookieSameSiteSupplier`. @@ -613,25 +631,26 @@ The `CookieSameSiteSupplier` is passed a `Cookie` and may return a `SameSite` va There are a number of convenience factory and filter methods that you can use to quickly match specific cookies. For example, adding the following bean will automatically apply a `SameSite` of `Lax` for all cookies with a name that matches the regular expression `myapp.*`. -include::code:MySameSiteConfiguration[] +include-code::MySameSiteConfiguration[] [[web.servlet.embedded-container.customizing.encoding]] -===== Character Encoding +==== Character Encoding + The character encoding behavior of the embedded servlet container for request and response handling can be configured using the `server.servlet.encoding.*` configuration properties. When a request's `Accept-Language` header indicates a locale for the request it will be automatically mapped to a charset by the servlet container. Each container provides default locale to charset mappings and you should verify that they meet your application's needs. When they do not, use the configprop:server.servlet.encoding.mapping[] configuration property to customize the mappings, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - server: - servlet: - encoding: - mapping: - ko: "UTF-8" +server: + servlet: + encoding: + mapping: + ko: "UTF-8" ---- In the preceding example, the `ko` (Korean) locale has been mapped to `UTF-8`. @@ -640,34 +659,37 @@ This is equivalent to a `` entry in a `web.xml` fi [[web.servlet.embedded-container.customizing.programmatic]] -===== Programmatic Customization +==== Programmatic Customization + If you need to programmatically configure your embedded servlet container, you can register a Spring bean that implements the `WebServerFactoryCustomizer` interface. `WebServerFactoryCustomizer` provides access to the `ConfigurableServletWebServerFactory`, which includes numerous customization setter methods. The following example shows programmatically setting the port: -include::code:MyWebServerFactoryCustomizer[] +include-code::MyWebServerFactoryCustomizer[] `TomcatServletWebServerFactory`, `JettyServletWebServerFactory` and `UndertowServletWebServerFactory` are dedicated variants of `ConfigurableServletWebServerFactory` that have additional customization setter methods for Tomcat, Jetty and Undertow respectively. The following example shows how to customize `TomcatServletWebServerFactory` that provides access to Tomcat-specific configuration options: -include::code:MyTomcatWebServerFactoryCustomizer[] +include-code::MyTomcatWebServerFactoryCustomizer[] [[web.servlet.embedded-container.customizing.direct]] -===== Customizing ConfigurableServletWebServerFactory Directly +==== Customizing ConfigurableServletWebServerFactory Directly + For more advanced use cases that require you to extend from `ServletWebServerFactory`, you can expose a bean of such type yourself. Setters are provided for many configuration options. Several protected method "`hooks`" are also provided should you need to do something more exotic. -See the {spring-boot-module-api}/web/servlet/server/ConfigurableServletWebServerFactory.html[source code documentation] for details. +See the xref:api:java/org/springframework/boot/web/servlet/server/ConfigurableServletWebServerFactory.html[source code documentation] for details. NOTE: Auto-configured customizers are still applied on your custom factory, so use that option carefully. [[web.servlet.embedded-container.jsp-limitations]] -==== JSP Limitations +=== 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. @@ -676,5 +698,5 @@ 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. +* Creating a custom `error.jsp` page does not override the default view for xref:web/servlet.adoc#web.servlet.spring-mvc.error-handling[error handling]. + xref:web/servlet.adoc#web.servlet.spring-mvc.error-handling.error-pages[Custom error pages] should be used instead. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-graphql.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/web/spring-graphql.adoc similarity index 76% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-graphql.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/web/spring-graphql.adoc index 142ea5550c..74d9e8ead0 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-graphql.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/web/spring-graphql.adoc @@ -1,6 +1,7 @@ [[web.graphql]] -== Spring for GraphQL -If you want to build GraphQL applications, you can take advantage of Spring Boot's auto-configuration for {spring-graphql}[Spring for GraphQL]. += Spring for GraphQL + +If you want to build GraphQL applications, you can take advantage of Spring Boot's auto-configuration for {url-spring-graphql-site}[Spring for GraphQL]. The Spring for GraphQL project is based on https://github.com/graphql-java/graphql-java[GraphQL Java]. You'll need the `spring-boot-starter-graphql` starter at a minimum. Because GraphQL is transport-agnostic, you'll also need to have one or more additional starters in your application to expose your GraphQL API over the web: @@ -30,7 +31,8 @@ Because GraphQL is transport-agnostic, you'll also need to have one or more addi [[web.graphql.schema]] -=== GraphQL Schema +== GraphQL Schema + A Spring GraphQL application requires a defined schema at startup. By default, you can write ".graphqls" or ".gqls" schema files under `src/main/resources/graphql/**` and Spring Boot will pick them up automatically. You can customize the locations with configprop:spring.graphql.schema.locations[] and the file extensions with configprop:spring.graphql.schema.file-extensions[]. @@ -40,9 +42,9 @@ you can set configprop:spring.graphql.schema.locations[] to `+"classpath*:graphq In the following sections, we'll consider this sample GraphQL schema, defining two types and two queries: -[source,json,indent=0,subs="verbatim,quotes"] +[source,json,subs="verbatim,quotes"] ---- -include::{docs-resources}/graphql/schema.graphqls[] +include::ROOT:example$resources/graphql/schema.graphqls[] ---- NOTE: By default, https://spec.graphql.org/draft/#sec-Introspection[field introspection] will be allowed on the schema as it is required for tools such as GraphiQL. @@ -51,23 +53,25 @@ If you wish to not expose information about the schema, you can disable introspe [[web.graphql.runtimewiring]] -=== GraphQL RuntimeWiring +== GraphQL RuntimeWiring + The GraphQL Java `RuntimeWiring.Builder` can be used to register custom scalar types, directives, type resolvers, `DataFetcher`, and more. You can declare `RuntimeWiringConfigurer` beans in your Spring config to get access to the `RuntimeWiring.Builder`. -Spring Boot detects such beans and adds them to the {spring-graphql-docs}/#execution-graphqlsource[GraphQlSource builder]. +Spring Boot detects such beans and adds them to the {url-spring-graphql-docs}/#execution-graphqlsource[GraphQlSource builder]. -Typically, however, applications will not implement `DataFetcher` directly and will instead create {spring-graphql-docs}/#controllers[annotated controllers]. +Typically, however, applications will not implement `DataFetcher` directly and will instead create {url-spring-graphql-docs}/#controllers[annotated controllers]. Spring Boot will automatically detect `@Controller` classes with annotated handler methods and register those as ``DataFetcher``s. Here's a sample implementation for our greeting query with a `@Controller` class: -include::code:GreetingController[] +include-code::GreetingController[] [[web.graphql.data-query]] -=== Querydsl and QueryByExample Repositories Support +== Querydsl and QueryByExample Repositories Support + Spring Data offers support for both Querydsl and QueryByExample repositories. -Spring GraphQL can {spring-graphql-docs}/#data[configure Querydsl and QueryByExample repositories as `DataFetcher`]. +Spring GraphQL can {url-spring-graphql-docs}/#data[configure Querydsl and QueryByExample repositories as `DataFetcher`]. Spring Data repositories annotated with `@GraphQlRepository` and extending one of: @@ -79,13 +83,15 @@ Spring Data repositories annotated with `@GraphQlRepository` and extending one o are detected by Spring Boot and considered as candidates for `DataFetcher` for matching top-level queries. + [[web.graphql.transports]] -=== Transports +== Transports [[web.graphql.transports.http-websocket]] -==== HTTP and WebSocket +=== HTTP and WebSocket + The GraphQL HTTP endpoint is at HTTP POST `/graphql` by default. It also supports the `"text/event-stream"` media type over Server Sent Events for subscriptions only. The path can be customized with configprop:spring.graphql.path[]. @@ -99,58 +105,61 @@ The GraphQL WebSocket endpoint is off by default. To enable it: * For a WebFlux application, no additional dependency is required * For both, the configprop:spring.graphql.websocket.path[] application property must be set -Spring GraphQL provides a {spring-graphql-docs}/#web-interception[Web Interception] model. +Spring GraphQL provides a {url-spring-graphql-docs}/#web-interception[Web Interception] model. This is quite useful for retrieving information from an HTTP request header and set it in the GraphQL context or fetching information from the same context and writing it to a response header. With Spring Boot, you can declare a `WebInterceptor` bean to have it registered with the web transport. -{spring-framework-docs}/web/webmvc-cors.html[Spring MVC] and {spring-framework-docs}/web/webflux-cors.html[Spring WebFlux] support CORS (Cross-Origin Resource Sharing) requests. +{url-spring-framework-docs}/web/webmvc-cors.html[Spring MVC] and {url-spring-framework-docs}/web/webflux-cors.html[Spring WebFlux] support CORS (Cross-Origin Resource Sharing) requests. CORS is a critical part of the web config for GraphQL applications that are accessed from browsers using different domains. Spring Boot supports many configuration properties under the `spring.graphql.cors.*` namespace; here's a short configuration sample: -[source,yaml,indent=0,subs="verbatim",configblocks] +[configprops,yaml] ---- - spring: - graphql: - cors: - allowed-origins: "https://example.org" - allowed-methods: GET,POST - max-age: 1800s +spring: + graphql: + cors: + allowed-origins: "https://example.org" + allowed-methods: GET,POST + max-age: 1800s ---- [[web.graphql.transports.rsocket]] -==== RSocket +=== RSocket + RSocket is also supported as a transport, on top of WebSocket or TCP. -Once the <>, we can configure our GraphQL handler on a particular route using configprop:spring.graphql.rsocket.mapping[]. +Once the xref:messaging/rsocket.adoc#messaging.rsocket.server-auto-configuration[RSocket server is configured], we can configure our GraphQL handler on a particular route using configprop:spring.graphql.rsocket.mapping[]. For example, configuring that mapping as `"graphql"` means we can use that as a route when sending requests with the `RSocketGraphQlClient`. Spring Boot auto-configures a `RSocketGraphQlClient.Builder` bean that you can inject in your components: -include::code:RSocketGraphQlClientExample[tag=builder] +include-code::RSocketGraphQlClientExample[tag=builder] And then send a request: -include::code:RSocketGraphQlClientExample[tag=request] +include-code::RSocketGraphQlClientExample[tag=request] [[web.graphql.exception-handling]] -=== Exception Handling +== Exception Handling + Spring GraphQL enables applications to register one or more Spring `DataFetcherExceptionResolver` components that are invoked sequentially. -The Exception must be resolved to a list of `graphql.GraphQLError` objects, see {spring-graphql-docs}/#execution-exceptions[Spring GraphQL exception handling documentation]. +The Exception must be resolved to a list of `graphql.GraphQLError` objects, see {url-spring-graphql-docs}/#execution-exceptions[Spring GraphQL exception handling documentation]. Spring Boot will automatically detect `DataFetcherExceptionResolver` beans and register them with the `GraphQlSource.Builder`. [[web.graphql.graphiql]] -=== GraphiQL and Schema printer +== GraphiQL and Schema printer + Spring GraphQL offers infrastructure for helping developers when consuming or developing a GraphQL API. Spring GraphQL ships with a default https://github.com/graphql/graphiql[GraphiQL] page that is exposed at `"/graphiql"` by default. This page is disabled by default and can be turned on with the configprop:spring.graphql.graphiql.enabled[] property. Many applications exposing such a page will prefer a custom build. -A default implementation is very useful during development, this is why it is exposed automatically with <> during development. +A default implementation is very useful during development, this is why it is exposed automatically with xref:using/devtools.adoc[`spring-boot-devtools`] during development. You can also choose to expose the GraphQL schema in text format at `/graphql/schema` when the configprop:spring.graphql.schema.printer.enabled[] property is enabled. 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/antora/modules/reference/pages/web/spring-hateoas.adoc similarity index 98% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-hateoas.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/web/spring-hateoas.adoc index 0731b7067d..d49c34e5ff 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-hateoas.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/web/spring-hateoas.adoc @@ -1,5 +1,6 @@ [[web.spring-hateoas]] -== 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. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-security.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/web/spring-security.adoc similarity index 60% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-security.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/web/spring-security.adoc index b893db2472..233e877d20 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-security.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/web/spring-security.adoc @@ -1,18 +1,19 @@ [[web.security]] -== Spring Security -If {spring-security}[Spring Security] is on the classpath, then web applications are secured by default. += Spring Security + +If {url-spring-security-site}[Spring Security] is on the classpath, then web applications are secured by default. Spring Boot relies on Spring Security’s content-negotiation strategy to determine whether to use `httpBasic` or `formLogin`. To add method-level security to a web application, you can also add `@EnableGlobalMethodSecurity` with your desired settings. -Additional information can be found in the {spring-security-docs}/servlet/authorization/method-security.html[Spring Security Reference Guide]. +Additional information can be found in the {url-spring-security-docs}/servlet/authorization/method-security.html[Spring Security Reference Guide]. The default `UserDetailsService` has a single user. The user name is `user`, and the password is random and is printed at WARN level when the application starts, as shown in the following example: -[indent=0] +[source] ---- - Using generated security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35 +Using generated security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35 - This generated password is for development use only. Your security configuration must be updated before running your application in production. +This generated password is for development use only. Your security configuration must be updated before running your application in production. ---- NOTE: If you fine-tune your logging configuration, ensure that the `org.springframework.boot.autoconfigure.security` category is set to log `WARN`-level messages. @@ -22,7 +23,7 @@ You can change the username and password by providing a `spring.security.user.na The basic features you get by default in a web application are: -* A `UserDetailsService` (or `ReactiveUserDetailsService` in case of a WebFlux application) bean with in-memory store and a single user with a generated password (see {spring-boot-module-api}/autoconfigure/security/SecurityProperties.User.html[`SecurityProperties.User`] for the properties of the user). +* A `UserDetailsService` (or `ReactiveUserDetailsService` in case of a WebFlux application) bean with in-memory store and a single user with a generated password (see xref:api:java/org/springframework/boot/autoconfigure/security/SecurityProperties.User.html[`SecurityProperties.User`] for the properties of the user). * Form-based login or HTTP Basic security (depending on the `Accept` header in the request) for the entire application (including actuator endpoints if actuator is on the classpath). * A `DefaultAuthenticationEventPublisher` for publishing authentication events. @@ -31,7 +32,8 @@ You can provide a different `AuthenticationEventPublisher` by adding a bean for [[web.security.spring-mvc]] -=== MVC Security +== 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. @@ -54,7 +56,8 @@ Spring Boot provides convenience methods that can be used to override access rul [[web.security.spring-webflux]] -=== WebFlux Security +== WebFlux Security + Similar to Spring MVC applications, you can secure your WebFlux applications by adding the `spring-boot-starter-security` dependency. The default security configuration is implemented in `ReactiveSecurityAutoConfiguration` and `UserDetailsServiceAutoConfiguration`. `ReactiveSecurityAutoConfiguration` imports `WebFluxSecurityConfiguration` for web security and `UserDetailsServiceAutoConfiguration` configures authentication, which is also relevant in non-web applications. @@ -77,69 +80,71 @@ Spring Boot provides convenience methods that can be used to override access rul For example, you can customize your security configuration by adding something like: -include::code:MyWebFluxSecurityConfiguration[] +include-code::MyWebFluxSecurityConfiguration[] [[web.security.oauth2]] -=== OAuth2 +== OAuth2 + https://oauth.net/2/[OAuth2] is a widely used authorization framework that is supported by Spring. [[web.security.oauth2.client]] -==== Client +=== Client + If you have `spring-security-oauth2-client` on your classpath, you can take advantage of some auto-configuration to set up OAuth2/Open ID Connect clients. This configuration makes use of the properties under `OAuth2ClientProperties`. The same properties are applicable to both servlet and reactive applications. You can register multiple OAuth2 clients and providers under the `spring.security.oauth2.client` prefix, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - security: - oauth2: - client: - registration: - my-login-client: - client-id: "abcd" - client-secret: "password" - client-name: "Client for OpenID Connect" - provider: "my-oauth-provider" - scope: "openid,profile,email,phone,address" - redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}" - client-authentication-method: "client_secret_basic" - authorization-grant-type: "authorization_code" +spring: + security: + oauth2: + client: + registration: + my-login-client: + client-id: "abcd" + client-secret: "password" + client-name: "Client for OpenID Connect" + provider: "my-oauth-provider" + scope: "openid,profile,email,phone,address" + redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}" + client-authentication-method: "client_secret_basic" + authorization-grant-type: "authorization_code" - my-client-1: - client-id: "abcd" - client-secret: "password" - client-name: "Client for user scope" - provider: "my-oauth-provider" - scope: "user" - redirect-uri: "{baseUrl}/authorized/user" - client-authentication-method: "client_secret_basic" - authorization-grant-type: "authorization_code" + my-client-1: + client-id: "abcd" + client-secret: "password" + client-name: "Client for user scope" + provider: "my-oauth-provider" + scope: "user" + redirect-uri: "{baseUrl}/authorized/user" + client-authentication-method: "client_secret_basic" + authorization-grant-type: "authorization_code" - my-client-2: - client-id: "abcd" - client-secret: "password" - client-name: "Client for email scope" - provider: "my-oauth-provider" - scope: "email" - redirect-uri: "{baseUrl}/authorized/email" - client-authentication-method: "client_secret_basic" - authorization-grant-type: "authorization_code" + my-client-2: + client-id: "abcd" + client-secret: "password" + client-name: "Client for email scope" + provider: "my-oauth-provider" + scope: "email" + redirect-uri: "{baseUrl}/authorized/email" + client-authentication-method: "client_secret_basic" + authorization-grant-type: "authorization_code" - provider: - my-oauth-provider: - authorization-uri: "https://my-auth-server.com/oauth2/authorize" - token-uri: "https://my-auth-server.com/oauth2/token" - user-info-uri: "https://my-auth-server.com/userinfo" - user-info-authentication-method: "header" - jwk-set-uri: "https://my-auth-server.com/oauth2/jwks" - user-name-attribute: "name" + provider: + my-oauth-provider: + authorization-uri: "https://my-auth-server.com/oauth2/authorize" + token-uri: "https://my-auth-server.com/oauth2/token" + user-info-uri: "https://my-auth-server.com/userinfo" + user-info-authentication-method: "header" + jwk-set-uri: "https://my-auth-server.com/oauth2/jwks" + user-name-attribute: "name" ---- For OpenID Connect providers that support https://openid.net/specs/openid-connect-discovery-1_0.html[OpenID Connect discovery], the configuration can be further simplified. @@ -148,22 +153,22 @@ For example, if the `issuer-uri` provided is "https://example.com", then an "Ope The result is expected to be an "OpenID Provider Configuration Response". The following example shows how an OpenID Connect Provider can be configured with the `issuer-uri`: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - security: - oauth2: - client: - provider: - oidc-provider: - issuer-uri: "https://dev-123456.oktapreview.com/oauth2/default/" +spring: + security: + oauth2: + client: + provider: + oidc-provider: + issuer-uri: "https://dev-123456.oktapreview.com/oauth2/default/" ---- By default, Spring Security's `OAuth2LoginAuthenticationFilter` only processes URLs matching `/login/oauth2/code/*`. If you want to customize the `redirect-uri` to use a different pattern, you need to provide configuration to process that custom pattern. For example, for servlet applications, you can add your own `SecurityFilterChain` that resembles the following: -include::code:MyOAuthClientConfiguration[] +include-code::MyOAuthClientConfiguration[] TIP: Spring Boot auto-configures an `InMemoryOAuth2AuthorizedClientService` which is used by Spring Security for the management of client registrations. The `InMemoryOAuth2AuthorizedClientService` has limited capabilities and we recommend using it only for development environments. @@ -172,7 +177,8 @@ For production environments, consider using a `JdbcOAuth2AuthorizedClientService [[web.security.oauth2.client.common-providers]] -===== OAuth2 Client Registration for Common Providers +==== OAuth2 Client Registration for Common Providers + For common OAuth2 and OpenID providers, including Google, Github, Facebook, and Okta, we provide a set of provider defaults (`google`, `github`, `facebook`, and `okta`, respectively). If you do not need to customize these providers, you can set the `provider` attribute to the one for which you need to infer defaults. @@ -180,47 +186,48 @@ Also, if the key for the client registration matches a default supported provide In other words, the two configurations in the following example use the Google provider: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - security: - oauth2: - client: - registration: - my-client: - client-id: "abcd" - client-secret: "password" - provider: "google" - google: - client-id: "abcd" - client-secret: "password" +spring: + security: + oauth2: + client: + registration: + my-client: + client-id: "abcd" + client-secret: "password" + provider: "google" + google: + client-id: "abcd" + client-secret: "password" ---- [[web.security.oauth2.server]] -==== Resource Server +=== 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: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - security: - oauth2: - resourceserver: - jwt: - jwk-set-uri: "https://example.com/oauth2/default/v1/keys" +spring: + security: + oauth2: + resourceserver: + jwt: + jwk-set-uri: "https://example.com/oauth2/default/v1/keys" ---- -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - security: - oauth2: - resourceserver: - jwt: - issuer-uri: "https://dev-123456.oktapreview.com/oauth2/default/" +spring: + security: + oauth2: + resourceserver: + jwt: + issuer-uri: "https://dev-123456.oktapreview.com/oauth2/default/" ---- NOTE: If the authorization server does not support a JWK Set URI, you can configure the resource server with the Public Key used for verifying the signature of the JWT. @@ -229,15 +236,15 @@ This can be done using the configprop:spring.security.oauth2.resourceserver.jwt. The configprop:spring.security.oauth2.resourceserver.jwt.audiences[] property can be used to specify the expected values of the aud claim in JWTs. For example, to require JWTs to contain an aud claim with the value `my-audience`: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - security: - oauth2: - resourceserver: - jwt: - audiences: - - "my-audience" +spring: + security: + oauth2: + resourceserver: + jwt: + audiences: + - "my-audience" ---- The same properties are applicable for both servlet and reactive applications. @@ -245,16 +252,16 @@ Alternatively, you can define your own `JwtDecoder` bean for servlet application In cases where opaque tokens are used instead of JWTs, you can configure the following properties to validate tokens through introspection: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - security: - oauth2: - resourceserver: - opaquetoken: - introspection-uri: "https://example.com/check-token" - client-id: "my-client-id" - client-secret: "my-client-secret" +spring: + security: + oauth2: + resourceserver: + opaquetoken: + introspection-uri: "https://example.com/check-token" + client-id: "my-client-id" + client-secret: "my-client-secret" ---- Again, the same properties are applicable for both servlet and reactive applications. @@ -263,50 +270,51 @@ Alternatively, you can define your own `OpaqueTokenIntrospector` bean for servle [[web.security.oauth2.authorization-server]] -==== Authorization Server +=== Authorization Server + If you have `spring-security-oauth2-authorization-server` on your classpath, you can take advantage of some auto-configuration to set up a Servlet-based OAuth2 Authorization Server. You can register multiple OAuth2 clients under the `spring.security.oauth2.authorizationserver.client` prefix, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - security: - oauth2: - authorizationserver: - client: - my-client-1: - registration: - client-id: "abcd" - client-secret: "{noop}secret1" - client-authentication-methods: - - "client_secret_basic" - authorization-grant-types: - - "authorization_code" - - "refresh_token" - redirect-uris: - - "https://my-client-1.com/login/oauth2/code/abcd" - - "https://my-client-1.com/authorized" - scopes: - - "openid" - - "profile" - - "email" - - "phone" - - "address" - require-authorization-consent: true - my-client-2: - registration: - client-id: "efgh" - client-secret: "{noop}secret2" - client-authentication-methods: - - "client_secret_jwt" - authorization-grant-types: - - "client_credentials" - scopes: - - "user.read" - - "user.write" - jwk-set-uri: "https://my-client-2.com/jwks" - token-endpoint-authentication-signing-algorithm: "RS256" +spring: + security: + oauth2: + authorizationserver: + client: + my-client-1: + registration: + client-id: "abcd" + client-secret: "{noop}secret1" + client-authentication-methods: + - "client_secret_basic" + authorization-grant-types: + - "authorization_code" + - "refresh_token" + redirect-uris: + - "https://my-client-1.com/login/oauth2/code/abcd" + - "https://my-client-1.com/authorized" + scopes: + - "openid" + - "profile" + - "email" + - "phone" + - "address" + require-authorization-consent: true + my-client-2: + registration: + client-id: "efgh" + client-secret: "{noop}secret2" + client-authentication-methods: + - "client_secret_jwt" + authorization-grant-types: + - "client_credentials" + scopes: + - "user.read" + - "user.write" + jwk-set-uri: "https://my-client-2.com/jwks" + token-endpoint-authentication-signing-algorithm: "RS256" ---- NOTE: The `client-secret` property must be in a format that can be matched by the configured `PasswordEncoder`. @@ -327,73 +335,74 @@ TIP: Spring Boot auto-configures an `InMemoryRegisteredClientRepository` which i The `InMemoryRegisteredClientRepository` has limited capabilities and we recommend using it only for development environments. For production environments, consider using a `JdbcRegisteredClientRepository` or creating your own implementation of `RegisteredClientRepository`. -Additional information can be found in the {spring-authorization-server-docs}/getting-started.html[Getting Started] chapter of the {spring-authorization-server-docs}/index.html[Spring Authorization Server Reference Guide]. +Additional information can be found in the {url-spring-authorization-server-docs}/getting-started.html[Getting Started] chapter of the {url-spring-authorization-server-docs}[Spring Authorization Server Reference Guide]. [[web.security.saml2]] -=== SAML 2.0 +== SAML 2.0 [[web.security.saml2.relying-party]] -==== Relying Party +=== Relying Party + If you have `spring-security-saml2-service-provider` on your classpath, you can take advantage of some auto-configuration to set up a SAML 2.0 Relying Party. This configuration makes use of the properties under `Saml2RelyingPartyProperties`. A relying party registration represents a paired configuration between an Identity Provider, IDP, and a Service Provider, SP. You can register multiple relying parties under the `spring.security.saml2.relyingparty` prefix, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - security: - saml2: - relyingparty: - registration: - my-relying-party1: - signing: - credentials: - - private-key-location: "path-to-private-key" - certificate-location: "path-to-certificate" - decryption: - credentials: - - private-key-location: "path-to-private-key" - certificate-location: "path-to-certificate" - singlelogout: - url: "https://myapp/logout/saml2/slo" - response-url: "https://remoteidp2.slo.url" - binding: "POST" - assertingparty: - verification: - credentials: - - certificate-location: "path-to-verification-cert" - entity-id: "remote-idp-entity-id1" - sso-url: "https://remoteidp1.sso.url" +spring: + security: + saml2: + relyingparty: + registration: + my-relying-party1: + signing: + credentials: + - private-key-location: "path-to-private-key" + certificate-location: "path-to-certificate" + decryption: + credentials: + - private-key-location: "path-to-private-key" + certificate-location: "path-to-certificate" + singlelogout: + url: "https://myapp/logout/saml2/slo" + response-url: "https://remoteidp2.slo.url" + binding: "POST" + assertingparty: + verification: + credentials: + - certificate-location: "path-to-verification-cert" + entity-id: "remote-idp-entity-id1" + sso-url: "https://remoteidp1.sso.url" - my-relying-party2: - signing: - credentials: - - private-key-location: "path-to-private-key" - certificate-location: "path-to-certificate" - decryption: - credentials: - - private-key-location: "path-to-private-key" - certificate-location: "path-to-certificate" - assertingparty: - verification: - credentials: - - certificate-location: "path-to-other-verification-cert" - entity-id: "remote-idp-entity-id2" - sso-url: "https://remoteidp2.sso.url" - singlelogout: - url: "https://remoteidp2.slo.url" - response-url: "https://myapp/logout/saml2/slo" - binding: "POST" + my-relying-party2: + signing: + credentials: + - private-key-location: "path-to-private-key" + certificate-location: "path-to-certificate" + decryption: + credentials: + - private-key-location: "path-to-private-key" + certificate-location: "path-to-certificate" + assertingparty: + verification: + credentials: + - certificate-location: "path-to-other-verification-cert" + entity-id: "remote-idp-entity-id2" + sso-url: "https://remoteidp2.sso.url" + singlelogout: + url: "https://remoteidp2.slo.url" + response-url: "https://myapp/logout/saml2/slo" + binding: "POST" ---- For SAML2 logout, by default, Spring Security's `Saml2LogoutRequestFilter` and `Saml2LogoutResponseFilter` only process URLs matching `/logout/saml2/slo`. If you want to customize the `url` to which AP-initiated logout requests get sent to or the `response-url` to which an AP sends logout responses to, to use a different pattern, you need to provide configuration to process that custom pattern. For example, for servlet applications, you can add your own `SecurityFilterChain` that resembles the following: -include::code:MySamlRelyingPartyConfiguration[] +include-code::MySamlRelyingPartyConfiguration[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-session.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/web/spring-session.adoc similarity index 80% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-session.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/web/spring-session.adoc index ec7c2304b0..e3604ffecd 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/spring-session.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/pages/web/spring-session.adoc @@ -1,6 +1,7 @@ [[web.spring-session]] -== Spring Session -Spring Boot provides {spring-session}[Spring Session] auto-configuration for a wide range of data stores. += Spring Session + +Spring Boot provides {url-spring-session-site}[Spring Session] auto-configuration for a wide range of data stores. When building a servlet web application, the following stores can be auto-configured: * Redis @@ -8,7 +9,7 @@ When building a servlet web application, the following stores can be auto-config * Hazelcast * MongoDB -Additionally, {spring-boot-for-apache-geode}[Spring Boot for Apache Geode] provides {spring-boot-for-apache-geode-docs}#geode-session[auto-configuration for using Apache Geode as a session store]. +Additionally, {url-spring-boot-for-apache-geode-site}[Spring Boot for Apache Geode] provides {url-spring-boot-for-apache-geode-docs}#geode-session[auto-configuration for using Apache Geode as a session store]. The servlet auto-configuration replaces the need to use `@Enable*HttpSession`. @@ -39,12 +40,12 @@ Similar to the servlet configuration, if you have more than one implementation, Each store has specific additional settings. For instance, it is possible to customize the name of the table for the JDBC store, as shown in the following example: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - spring: - session: - jdbc: - table-name: "SESSIONS" +spring: + session: + jdbc: + table-name: "SESSIONS" ---- For setting the timeout of the session you can use the configprop:spring.session.timeout[] property. diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/partials/nav-reference.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/partials/nav-reference.adoc new file mode 100644 index 0000000000..d45f5cc335 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/reference/partials/nav-reference.adoc @@ -0,0 +1,91 @@ +* Reference Guides + +** xref:reference:using/index.adoc[] +*** xref:reference:using/build-systems.adoc[] +*** xref:reference:using/structuring-your-code.adoc[] +*** xref:reference:using/configuration-classes.adoc[] +*** xref:reference:using/auto-configuration.adoc[] +*** xref:reference:using/spring-beans-and-dependency-injection.adoc[] +*** xref:reference:using/using-the-springbootapplication-annotation.adoc[] +*** xref:reference:using/running-your-application.adoc[] +*** xref:reference:using/devtools.adoc[] +*** xref:reference:using/packaging-for-production.adoc[] + +** xref:reference:features/index.adoc[] +*** xref:reference:features/spring-application.adoc[] +*** xref:reference:features/external-config.adoc[] +*** xref:reference:features/profiles.adoc[] +*** xref:reference:features/logging.adoc[] +*** xref:reference:features/internationalization.adoc[] +*** xref:reference:features/aop.adoc[] +*** xref:reference:features/json.adoc[] +*** xref:reference:features/task-execution-and-scheduling.adoc[] +*** xref:reference:features/testing.adoc[] +*** xref:reference:features/docker-compose.adoc[] +*** xref:reference:features/testcontainers.adoc[] +*** xref:reference:features/developing-auto-configuration.adoc[] +*** xref:reference:features/kotlin.adoc[] +*** xref:reference:features/ssl.adoc[] + +** xref:reference:web/index.adoc[] +*** xref:reference:web/servlet.adoc[] +*** xref:reference:web/reactive.adoc[] +*** xref:reference:web/graceful-shutdown.adoc[] +*** xref:reference:web/spring-security.adoc[] +*** xref:reference:web/spring-session.adoc[] +*** xref:reference:web/spring-graphql.adoc[] +*** xref:reference:web/spring-hateoas.adoc[] + +** xref:reference:data/index.adoc[] +*** xref:reference:data/sql.adoc[] +*** xref:reference:data/nosql.adoc[] + +** xref:reference:io/index.adoc[] +*** xref:reference:io/caching.adoc[] +*** xref:reference:io/hazelcast.adoc[] +*** xref:reference:io/quartz.adoc[] +*** xref:reference:io/email.adoc[] +*** xref:reference:io/validation.adoc[] +*** xref:reference:io/rest-client.adoc[] +*** xref:reference:io/webservices.adoc[] +*** xref:reference:io/jta.adoc[] + +** xref:reference:messaging/index.adoc[] +*** xref:reference:messaging/jms.adoc[] +*** xref:reference:messaging/amqp.adoc[] +*** xref:reference:messaging/kafka.adoc[] +*** xref:reference:messaging/pulsar.adoc[] +*** xref:reference:messaging/rsocket.adoc[] +*** xref:reference:messaging/spring-integration.adoc[] +*** xref:reference:messaging/websockets.adoc[] + +** xref:reference:container-images/index.adoc[] +*** xref:reference:container-images/efficient-images.adoc[] +*** xref:reference:container-images/dockerfiles.adoc[] +*** xref:reference:container-images/cloud-native-buildpacks.adoc[] + +** xref:reference:actuator/index.adoc[] +*** xref:reference:actuator/enabling.adoc[] +*** xref:reference:actuator/endpoints.adoc[] +*** xref:reference:actuator/monitoring.adoc[] +*** xref:reference:actuator/jmx.adoc[] +*** xref:reference:actuator/observability.adoc[] +*** xref:reference:actuator/loggers.adoc[] +*** xref:reference:actuator/metrics.adoc[] +*** xref:reference:actuator/tracing.adoc[] +*** xref:reference:actuator/auditing.adoc[] +*** xref:reference:actuator/http-exchanges.adoc[] +*** xref:reference:actuator/process-monitoring.adoc[] +*** xref:reference:actuator/cloud-foundry.adoc[] + +** xref:reference:deployment/index.adoc[] +*** xref:reference:deployment/cloud.adoc[] +*** xref:reference:deployment/installing.adoc[] +*** xref:reference:deployment/efficient.adoc[] + +** xref:reference:native-image/index.adoc[] +*** xref:reference:native-image/introducing-graalvm-native-images.adoc[] +*** xref:reference:native-image/developing-your-first-application.adoc[] +*** xref:reference:native-image/testing-native-applications.adoc[] +*** xref:reference:native-image/advanced-topics.adoc[] + diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/configuration-metadata/annotation-processor.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/configuration-metadata/annotation-processor.adoc similarity index 78% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/configuration-metadata/annotation-processor.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/configuration-metadata/annotation-processor.adoc index 89360f2f73..d7504c81c5 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/configuration-metadata/annotation-processor.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/configuration-metadata/annotation-processor.adoc @@ -1,41 +1,43 @@ [[appendix.configuration-metadata.annotation-processor]] -== Generating Your Own Metadata by Using the Annotation Processor += Generating Your Own Metadata by Using the Annotation Processor + You can easily generate your own configuration metadata file from items annotated with `@ConfigurationProperties` by using the `spring-boot-configuration-processor` jar. The jar includes a Java annotation processor which is invoked as your project is compiled. [[appendix.configuration-metadata.annotation-processor.configuring]] -=== Configuring the Annotation Processor +== Configuring the Annotation Processor + To use the processor, include a dependency on `spring-boot-configuration-processor`. With Maven the dependency should be declared as optional, as shown in the following example: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - org.springframework.boot - spring-boot-configuration-processor - true - + + org.springframework.boot + spring-boot-configuration-processor + true + ---- With Gradle, the dependency should be declared in the `annotationProcessor` configuration, as shown in the following example: -[source,gradle,indent=0,subs="verbatim"] +[source,gradle] ---- - dependencies { - annotationProcessor "org.springframework.boot:spring-boot-configuration-processor" - } +dependencies { + annotationProcessor "org.springframework.boot:spring-boot-configuration-processor" +} ---- If you are using an `additional-spring-configuration-metadata.json` file, the `compileJava` task should be configured to depend on the `processResources` task, as shown in the following example: -[source,gradle,indent=0,subs="verbatim"] +[source,gradle] ---- - tasks.named('compileJava') { - inputs.files(tasks.named('processResources')) - } +tasks.named('compileJava') { + inputs.files(tasks.named('processResources')) +} ---- This dependency ensures that the additional metadata is available when the annotation processor runs during compilation. @@ -47,15 +49,15 @@ There are several ways to do this. With Maven, you can configure the `maven-apt-plugin` explicitly and add the dependency to the annotation processor only there. You could also let the AspectJ plugin run all the processing and disable annotation processing in the `maven-compiler-plugin` configuration, as follows: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - org.apache.maven.plugins - maven-compiler-plugin - - none - - + + org.apache.maven.plugins + maven-compiler-plugin + + none + + ---- ==== @@ -69,7 +71,8 @@ If you are not using this attribute, and annotation processors are picked up by [[appendix.configuration-metadata.annotation-processor.automatic-metadata-generation]] -=== Automatic Metadata Generation +== Automatic Metadata Generation + The processor picks up both classes and methods that are annotated with `@ConfigurationProperties`. If the class has a single parameterized constructor, one property is created per constructor parameter, unless the constructor is annotated with `@Autowired`. @@ -79,7 +82,7 @@ The annotation processor also supports the use of the `@Data`, `@Value`, `@Gette Consider the following example: -include::code:MyServerProperties[] +include-code::MyServerProperties[] This exposes three properties where `my.server.name` has no default and `my.server.ip` and `my.server.port` defaults to `"127.0.0.1"` and `9797` respectively. The Javadoc on fields is used to populate the `description` attribute. For instance, the description of `my.server.ip` is "IP address to listen to.". @@ -90,25 +93,25 @@ The annotation processor applies a number of heuristics to extract the default v Default values have to be provided statically. In particular, do not refer to a constant defined in another class. Also, the annotation processor cannot auto-detect default values for ``Enum``s and ``Collections``s. -For cases where the default value could not be detected, <> should be provided. +For cases where the default value could not be detected, xref:configuration-metadata/annotation-processor.adoc#appendix.configuration-metadata.annotation-processor.adding-additional-metadata[manual metadata] should be provided. Consider the following example: -include::code:MyMessagingProperties[] +include-code::MyMessagingProperties[] -In order to document default values for properties in the class above, you could add the following content to <>: +In order to document default values for properties in the class above, you could add the following content to xref:configuration-metadata/annotation-processor.adoc#appendix.configuration-metadata.annotation-processor.adding-additional-metadata[the manual metadata of the module]: -[source,json,indent=0,subs="verbatim"] +[source,json] ---- - {"properties": [ - { - "name": "my.messaging.addresses", - "defaultValue": ["a", "b"] - }, - { - "name": "my.messaging.container-type", - "defaultValue": "simple" - } - ]} +{"properties": [ + { + "name": "my.messaging.addresses", + "defaultValue": ["a", "b"] + }, + { + "name": "my.messaging.container-type", + "defaultValue": "simple" + } +]} ---- NOTE: Only the `name` of the property is required to document additional metadata for existing properties. @@ -116,12 +119,13 @@ NOTE: Only the `name` of the property is required to document additional metadat [[appendix.configuration-metadata.annotation-processor.automatic-metadata-generation.nested-properties]] -==== Nested Properties +=== Nested Properties + The annotation processor automatically considers inner classes as nested properties. Rather than documenting the `ip` and `port` at the root of the namespace, we could create a sub-namespace for it. Consider the updated example: -include::code:MyServerProperties[] +include-code::MyServerProperties[] The preceding example produces metadata information for `my.server.name`, `my.server.host.ip`, and `my.server.host.port` properties. You can use the `@NestedConfigurationProperty` annotation on a field to indicate that a regular (non-inner) class should be treated as if it were nested. @@ -131,7 +135,8 @@ TIP: This has no effect on collections and maps, as those types are automaticall [[appendix.configuration-metadata.annotation-processor.adding-additional-metadata]] -=== Adding Additional Metadata +== Adding Additional Metadata + Spring Boot's configuration file handling is quite flexible, and it is often the case that properties may exist that are not bound to a `@ConfigurationProperties` bean. You may also need to tune some attributes of an existing key. To support such cases and let you provide custom "hints", the annotation processor automatically merges items from `META-INF/additional-spring-configuration-metadata.json` into the main metadata file. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/configuration-metadata/format.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/configuration-metadata/format.adoc similarity index 83% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/configuration-metadata/format.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/configuration-metadata/format.adoc index b2ce6c5dae..47e99f521d 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/configuration-metadata/format.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/configuration-metadata/format.adoc @@ -1,78 +1,79 @@ [[appendix.configuration-metadata.format]] -== Metadata Format += Metadata Format + Configuration metadata files are located inside jars under `META-INF/spring-configuration-metadata.json`. They use a JSON format with items categorized under either "`groups`" or "`properties`" and additional values hints categorized under "hints", as shown in the following example: -[source,json,indent=0,subs="verbatim"] +[source,json] ---- - {"groups": [ - { - "name": "server", - "type": "org.springframework.boot.autoconfigure.web.ServerProperties", - "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties" - }, - { - "name": "spring.jpa.hibernate", - "type": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate", - "sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties", - "sourceMethod": "getHibernate()" - } - ... - ],"properties": [ - { - "name": "server.port", - "type": "java.lang.Integer", - "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties" - }, - { - "name": "server.address", - "type": "java.net.InetAddress", - "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties" - }, - { - "name": "spring.jpa.hibernate.ddl-auto", - "type": "java.lang.String", - "description": "DDL mode. This is actually a shortcut for the \"hibernate.hbm2ddl.auto\" property.", - "sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate" - } - ... - ],"hints": [ - { - "name": "spring.jpa.hibernate.ddl-auto", - "values": [ - { - "value": "none", - "description": "Disable DDL handling." - }, - { - "value": "validate", - "description": "Validate the schema, make no changes to the database." - }, - { - "value": "update", - "description": "Update the schema if necessary." - }, - { - "value": "create", - "description": "Create the schema and destroy previous data." - }, - { - "value": "create-drop", - "description": "Create and then destroy the schema at the end of the session." - } - ] - } - ]} +{"groups": [ + { + "name": "server", + "type": "org.springframework.boot.autoconfigure.web.ServerProperties", + "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties" + }, + { + "name": "spring.jpa.hibernate", + "type": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate", + "sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties", + "sourceMethod": "getHibernate()" + } + ... +],"properties": [ + { + "name": "server.port", + "type": "java.lang.Integer", + "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties" + }, + { + "name": "server.address", + "type": "java.net.InetAddress", + "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties" + }, + { + "name": "spring.jpa.hibernate.ddl-auto", + "type": "java.lang.String", + "description": "DDL mode. This is actually a shortcut for the \"hibernate.hbm2ddl.auto\" property.", + "sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate" + } + ... +],"hints": [ + { + "name": "spring.jpa.hibernate.ddl-auto", + "values": [ + { + "value": "none", + "description": "Disable DDL handling." + }, + { + "value": "validate", + "description": "Validate the schema, make no changes to the database." + }, + { + "value": "update", + "description": "Update the schema if necessary." + }, + { + "value": "create", + "description": "Create the schema and destroy previous data." + }, + { + "value": "create-drop", + "description": "Create and then destroy the schema at the end of the session." + } + ] + } +]} ---- Each "`property`" is a configuration item that the user specifies with a given value. For example, `server.port` and `server.address` might be specified in your `application.properties`/`application.yaml`, as follows: -[source,yaml,indent=0,subs="verbatim",configprops,configblocks] +[configprops,yaml] ---- - server: - port: 9090 - address: 127.0.0.1 +server: + port: 9090 + address: 127.0.0.1 ---- The "`groups`" are higher level items that do not themselves specify a value but instead provide a contextual grouping for properties. @@ -87,7 +88,8 @@ For example, when a developer is configuring the configprop:spring.jpa.hibernate [[appendix.configuration-metadata.format.group]] -=== Group Attributes +== Group Attributes + The JSON object contained in the `groups` array can contain the attributes shown in the following table: [cols="1,1,4"] @@ -128,7 +130,8 @@ The JSON object contained in the `groups` array can contain the attributes shown [[appendix.configuration-metadata.format.property]] -=== Property Attributes +== Property Attributes + The JSON object contained in the `properties` array can contain the attributes described in the following table: [cols="1,1,4"] @@ -213,7 +216,7 @@ Deprecation can also be specified declaratively in code by adding the `@Deprecat For instance, assume that the `my.app.target` property was confusing and was renamed to `my.app.name`. The following example shows how to handle that situation: -include::code:MyProperties[] +include-code::MyProperties[] NOTE: There is no way to set a `level`. `warning` is always assumed, since code is still handling the property. @@ -226,7 +229,8 @@ Doing so is particularly useful when a `replacement` is provided. [[appendix.configuration-metadata.format.hints]] -=== Hint Attributes +== Hint Attributes + The JSON object contained in the `hints` array can contain the attributes shown in the following table: [cols="1,1,4"] @@ -289,7 +293,8 @@ The JSON object contained in the `providers` attribute of each `hint` element ca [[appendix.configuration-metadata.format.repeated-items]] -=== Repeated Metadata Items +== Repeated Metadata Items + Objects with the same "`property`" and "`group`" name can appear multiple times within a metadata file. For example, you could bind two separate classes to the same prefix, with each having potentially overlapping property names. While the same names appearing in the metadata multiple times should not be common, consumers of metadata should take care to ensure that they support it. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/configuration-metadata.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/configuration-metadata/index.adoc similarity index 54% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/configuration-metadata.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/configuration-metadata/index.adoc index 193fd065b5..fb2d428165 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/configuration-metadata.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/configuration-metadata/index.adoc @@ -1,20 +1,9 @@ [appendix] [[appendix.configuration-metadata]] = Configuration Metadata -include::attributes.adoc[] - - Spring Boot jars include metadata files that provide details of all supported configuration properties. The files are designed to let IDE developers offer contextual help and "`code completion`" as users are working with `application.properties` or `application.yaml` files. The majority of the metadata file is generated automatically at compile time by processing all items annotated with `@ConfigurationProperties`. -However, it is possible to <> for corner cases or more advanced use cases. - - - -include::configuration-metadata/format.adoc[] - -include::configuration-metadata/manual-hints.adoc[] - -include::configuration-metadata/annotation-processor.adoc[] +However, it is possible to xref:configuration-metadata/annotation-processor.adoc#appendix.configuration-metadata.annotation-processor.adding-additional-metadata[write part of the metadata manually] for corner cases or more advanced use cases. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/configuration-metadata/manual-hints.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/configuration-metadata/manual-hints.adoc similarity index 74% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/configuration-metadata/manual-hints.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/configuration-metadata/manual-hints.adoc index a77666e60c..587e3f98a3 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/configuration-metadata/manual-hints.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/configuration-metadata/manual-hints.adoc @@ -1,5 +1,6 @@ [[appendix.configuration-metadata.manual-hints]] -== Providing Manual Hints += Providing Manual Hints + To improve the user experience and further assist the user in configuring a given property, you can provide additional metadata that: * Describes the list of potential values for a property. @@ -8,9 +9,10 @@ To improve the user experience and further assist the user in configuring a give [[appendix.configuration-metadata.manual-hints.value-hint]] -=== Value Hint +== Value Hint + The `name` attribute of each hint refers to the `name` of a property. -In the <>, we provide five values for the `spring.jpa.hibernate.ddl-auto` property: `none`, `validate`, `update`, `create`, and `create-drop`. +In the xref:configuration-metadata/format.adoc[initial example shown earlier], we provide five values for the `spring.jpa.hibernate.ddl-auto` property: `none`, `validate`, `update`, `create`, and `create-drop`. Each value may have a description as well. If your property is of type `Map`, you can provide hints for both the keys and the values (but not for the map itself). @@ -18,26 +20,26 @@ The special `.keys` and `.values` suffixes must refer to the keys and the values Assume a `my.contexts` maps magic `String` values to an integer, as shown in the following example: -include::code:MyProperties[] +include-code::MyProperties[] The magic values are (in this example) are `sample1` and `sample2`. -In order to offer additional content assistance for the keys, you could add the following JSON to <>: +In order to offer additional content assistance for the keys, you could add the following JSON to xref:configuration-metadata/annotation-processor.adoc#appendix.configuration-metadata.annotation-processor.adding-additional-metadata[the manual metadata of the module]: -[source,json,indent=0,subs="verbatim"] +[source,json] ---- - {"hints": [ - { - "name": "my.contexts.keys", - "values": [ - { - "value": "sample1" - }, - { - "value": "sample2" - } - ] - } - ]} +{"hints": [ + { + "name": "my.contexts.keys", + "values": [ + { + "value": "sample1" + }, + { + "value": "sample2" + } + ] + } +]} ---- TIP: We recommend that you use an `Enum` for those two values instead. @@ -46,7 +48,8 @@ If your IDE supports it, this is by far the most effective approach to auto-comp [[appendix.configuration-metadata.manual-hints.value-providers]] -=== Value Providers +== Value Providers + Providers are a powerful way to attach semantics to a property. In this section, we define the official providers that you can use for your own hints. However, your favorite IDE may implement some of these or none of them. @@ -72,7 +75,7 @@ The following table summarizes the list of supported providers: | Handles the property as if it were defined by the type defined by the mandatory `target` parameter. | `logger-name` -| Auto-completes valid logger names and <>. +| Auto-completes valid logger names and xref:reference:features/logging.adoc#features.logging.log-groups[logger groups]. Typically, package and class names available in the current project can be auto-completed as well as defined groups. | `spring-bean-reference` @@ -90,7 +93,8 @@ If no provider for a given property is supported, no special content assistance [[appendix.configuration-metadata.manual-hints.value-providers.any]] -==== Any +=== Any + The special **any** provider value permits any additional values to be provided. Regular value validation based on the property type should be applied if this is supported. @@ -98,26 +102,26 @@ This provider is typically used if you have a list of values and any extra value The following example offers `on` and `off` as auto-completion values for `system.state`: -[source,json,indent=0,subs="verbatim"] +[source,json] ---- - {"hints": [ - { - "name": "system.state", - "values": [ - { - "value": "on" - }, - { - "value": "off" - } - ], - "providers": [ - { - "name": "any" - } - ] - } - ]} +{"hints": [ + { + "name": "system.state", + "values": [ + { + "value": "on" + }, + { + "value": "off" + } + ], + "providers": [ + { + "name": "any" + } + ] + } +]} ---- Note that, in the preceding example, any other value is also allowed. @@ -125,7 +129,8 @@ Note that, in the preceding example, any other value is also allowed. [[appendix.configuration-metadata.manual-hints.value-providers.class-reference]] -==== Class Reference +=== Class Reference + The **class-reference** provider auto-completes classes available in the project. This provider supports the following parameters: @@ -149,27 +154,28 @@ This provider supports the following parameters: The following metadata snippet corresponds to the standard `server.servlet.jsp.class-name` property that defines the `JspServlet` class name to use: -[source,json,indent=0,subs="verbatim"] +[source,json] ---- - {"hints": [ - { - "name": "server.servlet.jsp.class-name", - "providers": [ - { - "name": "class-reference", - "parameters": { - "target": "jakarta.servlet.http.HttpServlet" - } +{"hints": [ + { + "name": "server.servlet.jsp.class-name", + "providers": [ + { + "name": "class-reference", + "parameters": { + "target": "jakarta.servlet.http.HttpServlet" } - ] - } - ]} + } + ] + } +]} ---- [[appendix.configuration-metadata.manual-hints.value-providers.handle-as]] -==== Handle As +=== Handle As + The **handle-as** provider lets you substitute the type of the property to a more high-level type. This typically happens when the property has a `java.lang.String` type, because you do not want your configuration classes to rely on classes that may not be on the classpath. This provider supports the following parameters: @@ -199,28 +205,29 @@ TIP: If multiple values can be provided, use a `Collection` or _Array_ type to t The following metadata snippet corresponds to the standard `spring.liquibase.change-log` property that defines the path to the changelog to use. It is actually used internally as a `org.springframework.core.io.Resource` but cannot be exposed as such, because we need to keep the original String value to pass it to the Liquibase API. -[source,json,indent=0,subs="verbatim"] +[source,json] ---- - {"hints": [ - { - "name": "spring.liquibase.change-log", - "providers": [ - { - "name": "handle-as", - "parameters": { - "target": "org.springframework.core.io.Resource" - } +{"hints": [ + { + "name": "spring.liquibase.change-log", + "providers": [ + { + "name": "handle-as", + "parameters": { + "target": "org.springframework.core.io.Resource" } - ] - } - ]} + } + ] + } +]} ---- [[appendix.configuration-metadata.manual-hints.value-providers.logger-name]] -==== Logger Name -The **logger-name** provider auto-completes valid logger names and <>. +=== Logger Name + +The **logger-name** provider auto-completes valid logger names and xref:reference:features/logging.adoc#features.logging.log-groups[logger groups]. Typically, package and class names available in the current project can be auto-completed. If groups are enabled (default) and if a custom logger group is identified in the configuration, auto-completion for it should be provided. Specific frameworks may have extra magic logger names that can be supported as well. @@ -243,70 +250,71 @@ The following metadata snippet corresponds to the standard `logging.level` prope Keys are _logger names_, and values correspond to the standard log levels or any custom level. As Spring Boot defines a few logger groups out-of-the-box, dedicated value hints have been added for those. -[source,json,indent=0,subs="verbatim"] +[source,json] ---- - {"hints": [ - { - "name": "logging.level.keys", - "values": [ - { - "value": "root", - "description": "Root logger used to assign the default logging level." - }, - { - "value": "sql", - "description": "SQL logging group including Hibernate SQL logger." - }, - { - "value": "web", - "description": "Web logging group including codecs." - } - ], - "providers": [ - { - "name": "logger-name" - } - ] - }, - { - "name": "logging.level.values", - "values": [ - { - "value": "trace" - }, - { - "value": "debug" - }, - { - "value": "info" - }, - { - "value": "warn" - }, - { - "value": "error" - }, - { - "value": "fatal" - }, - { - "value": "off" - } +{"hints": [ + { + "name": "logging.level.keys", + "values": [ + { + "value": "root", + "description": "Root logger used to assign the default logging level." + }, + { + "value": "sql", + "description": "SQL logging group including Hibernate SQL logger." + }, + { + "value": "web", + "description": "Web logging group including codecs." + } + ], + "providers": [ + { + "name": "logger-name" + } + ] + }, + { + "name": "logging.level.values", + "values": [ + { + "value": "trace" + }, + { + "value": "debug" + }, + { + "value": "info" + }, + { + "value": "warn" + }, + { + "value": "error" + }, + { + "value": "fatal" + }, + { + "value": "off" + } - ], - "providers": [ - { - "name": "any" - } - ] - } - ]} + ], + "providers": [ + { + "name": "any" + } + ] + } +]} ---- [[appendix.configuration-metadata.manual-hints.value-providers.spring-bean-reference]] -==== Spring Bean Reference +=== Spring Bean Reference + The **spring-bean-reference** provider auto-completes the beans that are defined in the configuration of the current project. This provider supports the following parameters: @@ -323,21 +331,21 @@ This provider supports the following parameters: The following metadata snippet corresponds to the standard `spring.jmx.server` property that defines the name of the `MBeanServer` bean to use: -[source,json,indent=0,subs="verbatim"] +[source,json] ---- - {"hints": [ - { - "name": "spring.jmx.server", - "providers": [ - { - "name": "spring-bean-reference", - "parameters": { - "target": "javax.management.MBeanServer" - } +{"hints": [ + { + "name": "spring.jmx.server", + "providers": [ + { + "name": "spring-bean-reference", + "parameters": { + "target": "javax.management.MBeanServer" } - ] - } - ]} + } + ] + } +]} ---- NOTE: The binder is not aware of the metadata. @@ -346,21 +354,22 @@ If you provide that hint, you still need to transform the bean name into an actu [[appendix.configuration-metadata.manual-hints.value-providers.spring-profile-name]] -==== Spring Profile Name +=== Spring Profile Name + The **spring-profile-name** provider auto-completes the Spring profiles that are defined in the configuration of the current project. The following metadata snippet corresponds to the standard `spring.profiles.active` property that defines the name of the Spring profile(s) to enable: -[source,json,indent=0,subs="verbatim"] +[source,json] ---- - {"hints": [ - { - "name": "spring.profiles.active", - "providers": [ - { - "name": "spring-profile-name" - } - ] - } - ]} +{"hints": [ + { + "name": "spring.profiles.active", + "providers": [ + { + "name": "spring-profile-name" + } + ] + } +]} ---- diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/executable-jar/alternatives.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/executable-jar/alternatives.adoc similarity index 91% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/executable-jar/alternatives.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/executable-jar/alternatives.adoc index 30d4bbc6f2..e94a71dc77 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/executable-jar/alternatives.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/executable-jar/alternatives.adoc @@ -1,5 +1,6 @@ [[appendix.executable-jar.alternatives]] -== Alternative Single Jar Solutions += Alternative Single Jar Solutions + If the preceding restrictions mean that you cannot use Spring Boot Loader, consider the following alternatives: * https://maven.apache.org/plugins/maven-shade-plugin/[Maven Shade Plugin] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/executable-jar.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/executable-jar/index.adoc similarity index 61% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/executable-jar.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/executable-jar/index.adoc index 49bb31a01a..2c6940ea17 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/executable-jar.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/executable-jar/index.adoc @@ -1,25 +1,8 @@ [appendix] [[appendix.executable-jar]] = The Executable Jar Format -include::attributes.adoc[] - - The `spring-boot-loader` modules lets Spring Boot support executable jar and war files. If you use the Maven plugin or the Gradle plugin, executable jars are automatically generated, and you generally do not need to know the details of how they work. If you need to create executable jars from a different build system or if you are just curious about the underlying technology, this appendix provides some background. - - - -include::executable-jar/nested-jars.adoc[] - -include::executable-jar/jarfile-class.adoc[] - -include::executable-jar/launching.adoc[] - -include::executable-jar/property-launcher.adoc[] - -include::executable-jar/restrictions.adoc[] - -include::executable-jar/alternatives.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/executable-jar/jarfile-class.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/executable-jar/jarfile-class.adoc similarity index 72% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/executable-jar/jarfile-class.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/executable-jar/jarfile-class.adoc index b1db0c8726..acf4a073de 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/executable-jar/jarfile-class.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/executable-jar/jarfile-class.adoc @@ -1,20 +1,21 @@ [[appendix.executable-jar.jarfile-class]] -== Spring Boot's "`NestedJarFile`" Class += Spring Boot's "`NestedJarFile`" Class + The core class used to support loading nested jars is `org.springframework.boot.loader.jar.NestedJarFile`. It lets you load jar content from nested child jar data. When first loaded, the location of each `JarEntry` is mapped to a physical file offset of the outer jar, as shown in the following example: -[indent=0] +[source] ---- - myapp.jar - +-------------------+-------------------------+ - | /BOOT-INF/classes | /BOOT-INF/lib/mylib.jar | - |+-----------------+||+-----------+----------+| - || A.class ||| B.class | C.class || - |+-----------------+||+-----------+----------+| - +-------------------+-------------------------+ - ^ ^ ^ - 0063 3452 3980 +myapp.jar ++-------------------+-------------------------+ +| /BOOT-INF/classes | /BOOT-INF/lib/mylib.jar | +|+-----------------+||+-----------+----------+| +|| A.class ||| B.class | C.class || +|+-----------------+||+-----------+----------+| ++-------------------+-------------------------+ + ^ ^ ^ + 0063 3452 3980 ---- The preceding example shows how `A.class` can be found in `/BOOT-INF/classes` in `myapp.jar` at position `0063`. @@ -26,7 +27,8 @@ We do not need to unpack the archive, and we do not need to read all entry data [[appendix.executable-jar.jarfile-class.compatibility]] -=== Compatibility With the Standard Java "`JarFile`" +== Compatibility With the Standard Java "`JarFile`" + Spring Boot Loader strives to remain compatible with existing code and libraries. `org.springframework.boot.loader.jar.NestedJarFile` extends from `java.util.jar.JarFile` and should work as a drop-in replacement. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/executable-jar/launching.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/executable-jar/launching.adoc similarity index 84% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/executable-jar/launching.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/executable-jar/launching.adoc index 690b85c438..30b51f5059 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/executable-jar/launching.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/executable-jar/launching.adoc @@ -1,5 +1,6 @@ [[appendix.executable-jar.launching]] -== Launching Executable Jars += Launching Executable Jars + The `org.springframework.boot.loader.launch.Launcher` class is a special bootstrap class that is used as an executable jar's main entry point. It is the actual `Main-Class` in your jar file, and it is used to setup an appropriate `ClassLoader` and ultimately call your `main()` method. @@ -15,24 +16,25 @@ You can add additional locations by setting an environment variable called `LOAD [[appendix.executable-jar.launching.manifest]] -=== Launcher Manifest +== Launcher Manifest + You need to specify an appropriate `Launcher` as the `Main-Class` attribute of `META-INF/MANIFEST.MF`. The actual class that you want to launch (that is, the class that contains a `main` method) should be specified in the `Start-Class` attribute. The following example shows a typical `MANIFEST.MF` for an executable jar file: -[indent=0] +[source,manifest] ---- - Main-Class: org.springframework.boot.loader.launch.JarLauncher - Start-Class: com.mycompany.project.MyApplication +Main-Class: org.springframework.boot.loader.launch.JarLauncher +Start-Class: com.mycompany.project.MyApplication ---- For a war file, it would be as follows: -[indent=0] +[source,manifest] ---- - Main-Class: org.springframework.boot.loader.launch.WarLauncher - Start-Class: com.mycompany.project.MyApplication +Main-Class: org.springframework.boot.loader.launch.WarLauncher +Start-Class: com.mycompany.project.MyApplication ---- NOTE: You need not specify `Class-Path` entries in your manifest file. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/executable-jar/nested-jars.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/executable-jar/nested-jars.adoc similarity index 72% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/executable-jar/nested-jars.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/executable-jar/nested-jars.adoc index 2c580bb4d9..e08d8e9f96 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/executable-jar/nested-jars.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/executable-jar/nested-jars.adoc @@ -1,5 +1,6 @@ [[appendix.executable-jar.nested-jars]] -== Nested JARs += Nested JARs + Java does not provide any standard way to load nested jar files (that is, jar files that are themselves contained within a jar). This can be problematic if you need to distribute a self-contained application that can be run from the command line without unpacking. @@ -12,28 +13,29 @@ Spring Boot takes a different approach and lets you actually nest jars directly. [[appendix.executable-jar.nested-jars.jar-structure]] -=== The Executable Jar File Structure +== The Executable Jar File Structure + Spring Boot Loader-compatible jar files should be structured in the following way: -[indent=0] +[source] ---- - example.jar - | - +-META-INF - | +-MANIFEST.MF - +-org - | +-springframework - | +-boot - | +-loader - | +- - +-BOOT-INF - +-classes - | +-mycompany - | +-project - | +-YourClasses.class - +-lib - +-dependency1.jar - +-dependency2.jar +example.jar + | + +-META-INF + | +-MANIFEST.MF + +-org + | +-springframework + | +-boot + | +-loader + | +- + +-BOOT-INF + +-classes + | +-mycompany + | +-project + | +-YourClasses.class + +-lib + +-dependency1.jar + +-dependency2.jar ---- Application classes should be placed in a nested `BOOT-INF/classes` directory. @@ -42,32 +44,33 @@ Dependencies should be placed in a nested `BOOT-INF/lib` directory. [[appendix.executable-jar.nested-jars.war-structure]] -=== The Executable War File Structure +== The Executable War File Structure + Spring Boot Loader-compatible war files should be structured in the following way: -[indent=0] +[source] ---- - example.war - | - +-META-INF - | +-MANIFEST.MF - +-org - | +-springframework - | +-boot - | +-loader - | +- - +-WEB-INF - +-classes - | +-com - | +-mycompany - | +-project - | +-YourClasses.class - +-lib - | +-dependency1.jar - | +-dependency2.jar - +-lib-provided - +-servlet-api.jar - +-dependency3.jar +example.war + | + +-META-INF + | +-MANIFEST.MF + +-org + | +-springframework + | +-boot + | +-loader + | +- + +-WEB-INF + +-classes + | +-com + | +-mycompany + | +-project + | +-YourClasses.class + +-lib + | +-dependency1.jar + | +-dependency2.jar + +-lib-provided + +-servlet-api.jar + +-dependency3.jar ---- Dependencies should be placed in a nested `WEB-INF/lib` directory. @@ -76,7 +79,8 @@ Any dependencies that are required when running embedded but are not required wh [[appendix.executable-jar.nested-jars.index-files]] -=== Index Files +== Index Files + Spring Boot Loader-compatible jar and war archives can include additional index files under the `BOOT-INF/` directory. A `classpath.idx` file can be provided for both jars and wars, and it provides the ordering that jars should be added to the classpath. The `layers.idx` file can be used only for jars, and it allows a jar to be split into logical layers for Docker/OCI image creation. @@ -87,7 +91,8 @@ These files, however, are _not_ parsed internally as YAML and they must be writt [[appendix.executable-jar.nested-jars.classpath-index]] -=== Classpath Index +== Classpath Index + The classpath index file can be provided in `BOOT-INF/classpath.idx`. Typically, it is generated automatically by Spring Boot's Maven and Gradle build plugins. It provides a list of jar names (including the directory) in the order that they should be added to the classpath. @@ -96,32 +101,33 @@ Each line must start with dash space (`"-·"`) and names must be in double q For example, given the following jar: -[indent=0] +[source] ---- - example.jar - | - +-META-INF - | +-... - +-BOOT-INF - +-classes - | +... - +-lib - +-dependency1.jar - +-dependency2.jar +example.jar + | + +-META-INF + | +-... + +-BOOT-INF + +-classes + | +... + +-lib + +-dependency1.jar + +-dependency2.jar ---- The index file would look like this: -[indent=0] +[source] ---- - - "BOOT-INF/lib/dependency2.jar" - - "BOOT-INF/lib/dependency1.jar" +- "BOOT-INF/lib/dependency2.jar" +- "BOOT-INF/lib/dependency1.jar" ---- [[appendix.executable-jar.nested-jars.layer-index]] -=== Layer Index +== Layer Index + The layers index file can be provided in `BOOT-INF/layers.idx`. It provides a list of layers and the parts of the jar that should be contained within them. Layers are written in the order that they should be added to the Docker/OCI image. @@ -132,12 +138,12 @@ When a directory name is used it means that all files inside that directory are A typical example of a layers index would be: -[indent=0] +[source] ---- - - "dependencies": - - "BOOT-INF/lib/dependency1.jar" - - "BOOT-INF/lib/dependency2.jar" - - "application": - - "BOOT-INF/classes/" - - "META-INF/" +- "dependencies": + - "BOOT-INF/lib/dependency1.jar" + - "BOOT-INF/lib/dependency2.jar" +- "application": + - "BOOT-INF/classes/" + - "META-INF/" ---- diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/executable-jar/property-launcher.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/executable-jar/property-launcher.adoc similarity index 99% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/executable-jar/property-launcher.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/executable-jar/property-launcher.adoc index ba6ae905b8..2ecc34fda3 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/executable-jar/property-launcher.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/executable-jar/property-launcher.adoc @@ -1,5 +1,6 @@ [[appendix.executable-jar.property-launcher]] -== PropertiesLauncher Features += PropertiesLauncher Features + `PropertiesLauncher` has a few special features that can be enabled with external properties (System properties, environment variables, manifest entries, or `loader.properties`). The following table describes these properties: diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/executable-jar/restrictions.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/executable-jar/restrictions.adoc similarity index 96% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/executable-jar/restrictions.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/executable-jar/restrictions.adoc index 0d35f1c294..f0745b21d6 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/executable-jar/restrictions.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/pages/executable-jar/restrictions.adoc @@ -1,5 +1,6 @@ [[appendix.executable-jar.restrictions]] -== Executable Jar Restrictions += Executable Jar Restrictions + You need to consider the following restrictions when working with a Spring Boot Loader packaged application: diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/partials/nav-specification.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/partials/nav-specification.adoc new file mode 100644 index 0000000000..1f48d4c8b9 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/specification/partials/nav-specification.adoc @@ -0,0 +1,14 @@ +* Specifications + +** xref:specification:configuration-metadata/index.adoc[] +*** xref:specification:configuration-metadata/format.adoc[] +*** xref:specification:configuration-metadata/manual-hints.adoc[] +*** xref:specification:configuration-metadata/annotation-processor.adoc[] + +** xref:specification:executable-jar/index.adoc[] +*** xref:specification:executable-jar/nested-jars.adoc[] +*** xref:specification:executable-jar/jarfile-class.adoc[] +*** xref:specification:executable-jar/launching.adoc[] +*** xref:specification:executable-jar/property-launcher.adoc[] +*** xref:specification:executable-jar/restrictions.adoc[] +*** xref:specification:executable-jar/alternatives.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-started/first-application.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/tutorial/pages/first-application/index.adoc similarity index 57% rename from spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-started/first-application.adoc rename to spring-boot-project/spring-boot-docs/src/docs/antora/modules/tutorial/pages/first-application/index.adoc index 3556aed2c0..bf28f4a669 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-started/first-application.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/tutorial/pages/first-application/index.adoc @@ -1,5 +1,6 @@ [[getting-started.first-application]] -== Developing Your First Spring Boot Application += Developing Your First Spring Boot Application + This section describes how to develop a small "`Hello World!`" web application that highlights some of Spring Boot's key features. You can choose between Maven or Gradle as the build system. @@ -9,22 +10,23 @@ The https://spring.io[spring.io] website contains many "`Getting Started`" https If you need to solve a specific problem, check there first. You can shortcut the steps below by going to https://start.spring.io and choosing the "Web" starter from the dependencies searcher. -Doing so generates a new project structure so that you can <>. +Doing so generates a new project structure so that you can xref:tutorial:first-application/index.adoc#getting-started.first-application.code[start coding right away]. Check the https://github.com/spring-io/start.spring.io/blob/main/USING.adoc[start.spring.io user guide] for more details. ==== [[getting-started.first-application.prerequisites]] -=== Prerequisites +== Prerequisites + Before we begin, open a terminal and run the following commands to ensure that you have a valid version of Java installed: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ java -version - openjdk version "17.0.4.1" 2022-08-12 LTS - OpenJDK Runtime Environment (build 17.0.4.1+1-LTS) - OpenJDK 64-Bit Server VM (build 17.0.4.1+1-LTS, mixed mode, sharing) +$ java -version +openjdk version "17.0.4.1" 2022-08-12 LTS +OpenJDK Runtime Environment (build 17.0.4.1+1-LTS) +OpenJDK 64-Bit Server VM (build 17.0.4.1+1-LTS, mixed mode, sharing) ---- NOTE: This sample needs to be created in its own directory. @@ -33,93 +35,96 @@ Subsequent instructions assume that you have created a suitable directory and th [[getting-started.first-application.prerequisites.maven]] -==== Maven +=== Maven + If you want to use Maven, ensure that you have Maven installed: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ mvn -v - Apache Maven 3.8.5 (3599d3414f046de2324203b78ddcf9b5e4388aa0) - Maven home: usr/Users/developer/tools/maven/3.8.5 - Java version: 17.0.4.1, vendor: BellSoft, runtime: /Users/developer/sdkman/candidates/java/17.0.4.1-librca +$ mvn -v +Apache Maven 3.8.5 (3599d3414f046de2324203b78ddcf9b5e4388aa0) +Maven home: usr/Users/developer/tools/maven/3.8.5 +Java version: 17.0.4.1, vendor: BellSoft, runtime: /Users/developer/sdkman/candidates/java/17.0.4.1-librca ---- [[getting-started.first-application.prerequisites.gradle]] -==== Gradle +=== Gradle + If you want to use Gradle, ensure that you have Gradle installed: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ gradle --version +$ gradle --version - ------------------------------------------------------------ - Gradle 8.1.1 - ------------------------------------------------------------ +------------------------------------------------------------ +Gradle 8.1.1 +------------------------------------------------------------ - Build time: 2023-04-21 12:31:26 UTC - Revision: 1cf537a851c635c364a4214885f8b9798051175b +Build time: 2023-04-21 12:31:26 UTC +Revision: 1cf537a851c635c364a4214885f8b9798051175b - Kotlin: 1.8.10 - Groovy: 3.0.15 - Ant: Apache Ant(TM) version 1.10.11 compiled on July 10 2021 - JVM: 17.0.7 (BellSoft 17.0.7+7-LTS) - OS: Linux 6.2.12-200.fc37.aarch64 aarch64 +Kotlin: 1.8.10 +Groovy: 3.0.15 +Ant: Apache Ant(TM) version 1.10.11 compiled on July 10 2021 +JVM: 17.0.7 (BellSoft 17.0.7+7-LTS) +OS: Linux 6.2.12-200.fc37.aarch64 aarch64 ---- [[getting-started.first-application.pom]] -=== Setting up the project with Maven +== Setting up the project with Maven + We need to start by creating a Maven `pom.xml` file. The `pom.xml` is the recipe that is used to build your project. Open your favorite text editor and add the following: -[source,xml,indent=0,subs="verbatim,attributes"] +[source,xml,subs="verbatim,attributes"] ---- - - - 4.0.0 + + + 4.0.0 - com.example - myproject - 0.0.1-SNAPSHOT + com.example + myproject + 0.0.1-SNAPSHOT - - org.springframework.boot - spring-boot-starter-parent - {spring-boot-version} - + + org.springframework.boot + spring-boot-starter-parent + {version-spring-boot} + - + ifeval::["{artifact-release-type}" != "release"] - - - - spring-snapshots - https://repo.spring.io/snapshot - true - - - spring-milestones - https://repo.spring.io/milestone - - - - - spring-snapshots - https://repo.spring.io/snapshot - - - spring-milestones - https://repo.spring.io/milestone - - + + + + spring-snapshots + https://repo.spring.io/snapshot + true + + + spring-milestones + https://repo.spring.io/milestone + + + + + spring-snapshots + https://repo.spring.io/snapshot + + + spring-milestones + https://repo.spring.io/milestone + + endif::[] - + ---- The preceding listing should give you a working build. @@ -131,34 +136,35 @@ For simplicity, we continue to use a plain text editor for this example. [[getting-started.first-application.gradle]] -=== Setting up the project with Gradle +== Setting up the project with Gradle + We need to start by creating a Gradle `build.gradle` file. The `build.gradle` is the build script that is used to build your project. Open your favorite text editor and add the following: -[source,gradle,indent=0,subs="verbatim,attributes"] +[source,gradle,subs="verbatim,attributes"] ---- - plugins { - id 'java' - id 'org.springframework.boot' version '{spring-boot-version}' - } +plugins { + id 'java' + id 'org.springframework.boot' version '{version-spring-boot}' +} - apply plugin: 'io.spring.dependency-management' +apply plugin: 'io.spring.dependency-management' - group = 'com.example' - version = '0.0.1-SNAPSHOT' - sourceCompatibility = '17' +group = 'com.example' +version = '0.0.1-SNAPSHOT' +sourceCompatibility = '17' - repositories { - mavenCentral() +repositories { + mavenCentral() ifeval::["{artifact-release-type}" != "release"] - maven { url 'https://repo.spring.io/milestone' } - maven { url 'https://repo.spring.io/snapshot' } + maven { url 'https://repo.spring.io/milestone' } + maven { url 'https://repo.spring.io/snapshot' } endif::[] - } +} - dependencies { - } +dependencies { +} ---- The preceding listing should give you a working build. @@ -170,40 +176,42 @@ For simplicity, we continue to use a plain text editor for this example. [[getting-started.first-application.dependencies]] -=== Adding Classpath Dependencies +== Adding Classpath Dependencies + Spring Boot provides a number of "`Starters`" that let you add jars to your classpath. "`Starters`" provide dependencies that you are likely to need when developing a specific type of application. [[getting-started.first-application.dependencies.maven]] -==== Maven +=== Maven + Most Spring Boot applications use the `spring-boot-starter-parent` in the `parent` section of the POM. The `spring-boot-starter-parent` is a special starter that provides useful Maven defaults. -It also provides a <> section so that you can omit `version` tags for "`blessed`" dependencies. +It also provides a xref:reference:using/build-systems.adoc#using.build-systems.dependency-management[`dependency-management`] section so that you can omit `version` tags for "`blessed`" dependencies. Since we are developing a web application, we add a `spring-boot-starter-web` dependency. Before that, we can look at what we currently have by running the following command: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ mvn dependency:tree +$ mvn dependency:tree - [INFO] com.example:myproject:jar:0.0.1-SNAPSHOT +[INFO] com.example:myproject:jar:0.0.1-SNAPSHOT ---- The `mvn dependency:tree` command prints a tree representation of your project dependencies. You can see that `spring-boot-starter-parent` provides no dependencies by itself. To add the necessary dependencies, edit your `pom.xml` and add the `spring-boot-starter-web` dependency immediately below the `parent` section: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - - org.springframework.boot - spring-boot-starter-web - - + + + org.springframework.boot + spring-boot-starter-web + + ---- If you run `mvn dependency:tree` again, you see that there are now a number of additional dependencies, including the Tomcat web server and Spring Boot itself. @@ -211,34 +219,35 @@ If you run `mvn dependency:tree` again, you see that there are now a number of a [[getting-started.first-application.dependencies.gradle]] -==== Gradle +=== Gradle + Most Spring Boot applications use the `org.springframework.boot` Gradle plugin. This plugin provides useful defaults and Gradle tasks. -The `io.spring.dependency-management` Gradle plugin provides <> so that you can omit `version` tags for "`blessed`" dependencies. +The `io.spring.dependency-management` Gradle plugin provides xref:reference:using/build-systems.adoc#using.build-systems.dependency-management[dependency management] so that you can omit `version` tags for "`blessed`" dependencies. Since we are developing a web application, we add a `spring-boot-starter-web` dependency. Before that, we can look at what we currently have by running the following command: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ gradle dependencies +$ gradle dependencies - > Task :dependencies +> Task :dependencies - ------------------------------------------------------------ - Root project 'myproject' - ------------------------------------------------------------ +------------------------------------------------------------ +Root project 'myproject' +------------------------------------------------------------ ---- The `gradle dependencies` command prints a tree representation of your project dependencies. Right now, the project has no dependencies. To add the necessary dependencies, edit your `build.gradle` and add the `spring-boot-starter-web` dependency in the `dependencies` section: -[source,gradle,indent=0,subs="verbatim"] +[source,gradle] ---- - dependencies { - implementation 'org.springframework.boot:spring-boot-starter-web' - } +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-web' +} ---- If you run `gradle dependencies` again, you see that there are now a number of additional dependencies, including the Tomcat web server and Spring Boot itself. @@ -246,12 +255,13 @@ If you run `gradle dependencies` again, you see that there are now a number of a [[getting-started.first-application.code]] -=== Writing the Code +== Writing the Code + To finish our application, we need to create a single Java file. By default, Maven and Gradle compile sources from `src/main/java`, so you need to create that directory structure and then add a file named `src/main/java/MyApplication.java` to contain the following code: [chomp_package_replacement=com.example] -include::code:MyApplication[] +include-code::MyApplication[] Although there is not much code here, quite a lot is going on. We step through the important parts in the next few sections. @@ -259,7 +269,8 @@ We step through the important parts in the next few sections. [[getting-started.first-application.code.mvc-annotations]] -==== The @RestController and @RequestMapping Annotations +=== The @RestController and @RequestMapping Annotations + The first annotation on our `MyApplication` class is `@RestController`. This is known as a _stereotype_ annotation. It provides hints for people reading the code and for Spring that the class plays a specific role. @@ -270,12 +281,13 @@ It tells Spring that any HTTP request with the `/` path should be mapped to the The `@RestController` annotation tells Spring to render the resulting string directly back to the caller. TIP: The `@RestController` and `@RequestMapping` annotations are Spring MVC annotations (they are not specific to Spring Boot). -See the {spring-framework-docs}/web/webmvc.html[MVC section] in the Spring Reference Documentation for more details. +See the {url-spring-framework-docs}/web/webmvc.html[MVC section] in the Spring Reference Documentation for more details. [[getting-started.first-application.code.spring-boot-application]] -==== The @SpringBootApplication Annotation +=== The @SpringBootApplication Annotation + The second class-level annotation is `@SpringBootApplication`. This annotation is known as a _meta-annotation_, it combines `@SpringBootConfiguration`, `@EnableAutoConfiguration` and `@ComponentScan`. @@ -293,7 +305,8 @@ Spring Boot still does its best to auto-configure your application. [[getting-started.first-application.code.main-method]] -==== The "`main`" Method +=== The "`main`" Method + The final part of our application is the `main` method. This is a standard method that follows the Java convention for an application entry point. Our main method delegates to Spring Boot's `SpringApplication` class by calling `run`. @@ -304,39 +317,40 @@ The `args` array is also passed through to expose any command-line arguments. [[getting-started.first-application.run]] -=== Running the Example +== Running the Example [[getting-started.first-application.run.maven]] -==== Maven +=== Maven + At this point, your application should work. Since you used the `spring-boot-starter-parent` POM, you have a useful `run` goal that you can use to start the application. Type `mvn spring-boot:run` from the root project directory to start the application. You should see output similar to the following: -[source,shell,indent=0,subs="verbatim,attributes"] +[source,shell,subs="verbatim,attributes"] ---- - $ mvn spring-boot:run +$ mvn spring-boot:run - . ____ _ __ _ _ - /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ - ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ - \\/ ___)| |_)| | | | | || (_| | ) ) ) ) - ' |____| .__|_| |_|_| |_\__, | / / / / - =========|_|==============|___/=/_/_/_/ - :: Spring Boot :: (v{spring-boot-version}) - ....... . . . - ....... . . . (log output here) - ....... . . . - ........ Started MyApplication in 0.906 seconds (process running for 6.514) + . ____ _ __ _ _ + /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ +( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ + \\/ ___)| |_)| | | | | || (_| | ) ) ) ) + ' |____| .__|_| |_|_| |_\__, | / / / / + =========|_|==============|___/=/_/_/_/ + :: Spring Boot :: (v{version-spring-boot}) +....... . . . +....... . . . (log output here) +....... . . . +........ Started MyApplication in 0.906 seconds (process running for 6.514) ---- If you open a web browser to `http://localhost:8080`, you should see the following output: -[indent=0] +[source] ---- - Hello World! +Hello World! ---- To gracefully exit the application, press `ctrl-c`. @@ -344,34 +358,35 @@ To gracefully exit the application, press `ctrl-c`. [[getting-started.first-application.run.gradle]] -==== Gradle +=== Gradle + At this point, your application should work. Since you used the `org.springframework.boot` Gradle plugin, you have a useful `bootRun` goal that you can use to start the application. Type `gradle bootRun` from the root project directory to start the application. You should see output similar to the following: -[source,shell,indent=0,subs="verbatim,attributes"] +[source,shell,subs="verbatim,attributes"] ---- - $ gradle bootRun +$ gradle bootRun - . ____ _ __ _ _ - /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ - ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ - \\/ ___)| |_)| | | | | || (_| | ) ) ) ) - ' |____| .__|_| |_|_| |_\__, | / / / / - =========|_|==============|___/=/_/_/_/ - :: Spring Boot :: (v{spring-boot-version}) - ....... . . . - ....... . . . (log output here) - ....... . . . - ........ Started MyApplication in 0.906 seconds (process running for 6.514) + . ____ _ __ _ _ + /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ +( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ + \\/ ___)| |_)| | | | | || (_| | ) ) ) ) + ' |____| .__|_| |_|_| |_\__, | / / / / + =========|_|==============|___/=/_/_/_/ + :: Spring Boot :: (v{version-spring-boot}) +....... . . . +....... . . . (log output here) +....... . . . +........ Started MyApplication in 0.906 seconds (process running for 6.514) ---- If you open a web browser to `http://localhost:8080`, you should see the following output: -[indent=0] +[source] ---- - Hello World! +Hello World! ---- To gracefully exit the application, press `ctrl-c`. @@ -379,7 +394,8 @@ To gracefully exit the application, press `ctrl-c`. [[getting-started.first-application.executable-jar]] -=== Creating an Executable Jar +== Creating an Executable Jar + We finish our example by creating a completely self-contained executable jar file that we could run in production. Executable jars (sometimes called "`uber jars`" or "`fat jars`") are archives containing your compiled classes along with all of the jar dependencies that your code needs to run. @@ -393,60 +409,61 @@ An uber jar packages all the classes from all the application's dependencies int The problem with this approach is that it becomes hard to see which libraries are in your application. It can also be problematic if the same filename is used (but with different content) in multiple jars. -Spring Boot takes a <> and lets you actually nest jars directly. +Spring Boot takes a xref:specification:executable-jar/index.adoc[different approach] and lets you actually nest jars directly. **** [[getting-started.first-application.executable-jar.maven]] -==== Maven +=== Maven + To create an executable jar, we need to add the `spring-boot-maven-plugin` to our `pom.xml`. To do so, insert the following lines just below the `dependencies` section: -[source,xml,indent=0,subs="verbatim"] +[source,xml] ---- - - - - org.springframework.boot - spring-boot-maven-plugin - - - + + + + org.springframework.boot + spring-boot-maven-plugin + + + ---- NOTE: The `spring-boot-starter-parent` POM includes `` configuration to bind the `repackage` goal. If you do not use the parent POM, you need to declare this configuration yourself. -See the {spring-boot-maven-plugin-docs}#getting-started[plugin documentation] for details. +See the xref:maven-plugin:getting-started.adoc[plugin documentation] for details. Save your `pom.xml` and run `mvn package` from the command line, as follows: -[source,shell,indent=0,subs="verbatim,attributes"] +[source,shell,subs="verbatim,attributes"] ---- - $ mvn package +$ mvn package - [INFO] Scanning for projects... - [INFO] - [INFO] ------------------------------------------------------------------------ - [INFO] Building myproject 0.0.1-SNAPSHOT - [INFO] ------------------------------------------------------------------------ - [INFO] .... .. - [INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ myproject --- - [INFO] Building jar: /Users/developer/example/spring-boot-example/target/myproject-0.0.1-SNAPSHOT.jar - [INFO] - [INFO] --- spring-boot-maven-plugin:{spring-boot-version}:repackage (default) @ myproject --- - [INFO] ------------------------------------------------------------------------ - [INFO] BUILD SUCCESS - [INFO] ------------------------------------------------------------------------ +[INFO] Scanning for projects... +[INFO] +[INFO] ------------------------------------------------------------------------ +[INFO] Building myproject 0.0.1-SNAPSHOT +[INFO] ------------------------------------------------------------------------ +[INFO] .... .. +[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ myproject --- +[INFO] Building jar: /Users/developer/example/spring-boot-example/target/myproject-0.0.1-SNAPSHOT.jar +[INFO] +[INFO] --- spring-boot-maven-plugin:{version-spring-boot}:repackage (default) @ myproject --- +[INFO] ------------------------------------------------------------------------ +[INFO] BUILD SUCCESS +[INFO] ------------------------------------------------------------------------ ---- If you look in the `target` directory, you should see `myproject-0.0.1-SNAPSHOT.jar`. The file should be around 18 MB in size. If you want to peek inside, you can use `jar tvf`, as follows: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ jar tvf target/myproject-0.0.1-SNAPSHOT.jar +$ jar tvf target/myproject-0.0.1-SNAPSHOT.jar ---- You should also see a much smaller file named `myproject-0.0.1-SNAPSHOT.jar.original` in the `target` directory. @@ -454,21 +471,21 @@ This is the original jar file that Maven created before it was repackaged by Spr To run that application, use the `java -jar` command, as follows: -[source,shell,indent=0,subs="verbatim,attributes"] +[source,shell,subs="verbatim,attributes"] ---- - $ java -jar target/myproject-0.0.1-SNAPSHOT.jar +$ java -jar target/myproject-0.0.1-SNAPSHOT.jar - . ____ _ __ _ _ - /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ - ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ - \\/ ___)| |_)| | | | | || (_| | ) ) ) ) - ' |____| .__|_| |_|_| |_\__, | / / / / - =========|_|==============|___/=/_/_/_/ - :: Spring Boot :: (v{spring-boot-version}) - ....... . . . - ....... . . . (log output here) - ....... . . . - ........ Started MyApplication in 0.999 seconds (process running for 1.253) + . ____ _ __ _ _ + /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ +( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ + \\/ ___)| |_)| | | | | || (_| | ) ) ) ) + ' |____| .__|_| |_|_| |_\__, | / / / / + =========|_|==============|___/=/_/_/_/ + :: Spring Boot :: (v{version-spring-boot}) +....... . . . +....... . . . (log output here) +....... . . . +........ Started MyApplication in 0.999 seconds (process running for 1.253) ---- As before, to exit the application, press `ctrl-c`. @@ -476,43 +493,44 @@ As before, to exit the application, press `ctrl-c`. [[getting-started.first-application.executable-jar.gradle]] -==== Gradle +=== Gradle + To create an executable jar, we need to run `gradle bootJar` from the command line, as follows: -[source,shell,indent=0,subs="verbatim,attributes"] +[source,shell,subs="verbatim,attributes"] ---- - $ gradle bootJar +$ gradle bootJar - BUILD SUCCESSFUL in 639ms - 3 actionable tasks: 3 executed +BUILD SUCCESSFUL in 639ms +3 actionable tasks: 3 executed ---- If you look in the `build/libs` directory, you should see `myproject-0.0.1-SNAPSHOT.jar`. The file should be around 18 MB in size. If you want to peek inside, you can use `jar tvf`, as follows: -[source,shell,indent=0,subs="verbatim"] +[source,shell] ---- - $ jar tvf build/libs/myproject-0.0.1-SNAPSHOT.jar +$ jar tvf build/libs/myproject-0.0.1-SNAPSHOT.jar ---- To run that application, use the `java -jar` command, as follows: -[source,shell,indent=0,subs="verbatim,attributes"] +[source,shell] ---- - $ java -jar build/libs/myproject-0.0.1-SNAPSHOT.jar +$ java -jar build/libs/myproject-0.0.1-SNAPSHOT.jar - . ____ _ __ _ _ - /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ - ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ - \\/ ___)| |_)| | | | | || (_| | ) ) ) ) - ' |____| .__|_| |_|_| |_\__, | / / / / - =========|_|==============|___/=/_/_/_/ - :: Spring Boot :: (v{spring-boot-version}) - ....... . . . - ....... . . . (log output here) - ....... . . . - ........ Started MyApplication in 0.999 seconds (process running for 1.253) + . ____ _ __ _ _ + /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ +( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ + \\/ ___)| |_)| | | | | || (_| | ) ) ) ) + ' |____| .__|_| |_|_| |_\__, | / / / / + =========|_|==============|___/=/_/_/_/ + :: Spring Boot :: (v{version-spring-boot}) +....... . . . +....... . . . (log output here) +....... . . . +........ Started MyApplication in 0.999 seconds (process running for 1.253) ---- As before, to exit the application, press `ctrl-c`. diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/tutorial/pages/index.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/tutorial/pages/index.adoc new file mode 100644 index 0000000000..7a8e6fab1d --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/tutorial/pages/index.adoc @@ -0,0 +1,3 @@ += Tutorials + +This section provides tutorials to help you get started using Spring Boot. \ No newline at end of file diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/modules/tutorial/partials/nav-tutorial.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/tutorial/partials/nav-tutorial.adoc new file mode 100644 index 0000000000..cdcb9807d6 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/modules/tutorial/partials/nav-tutorial.adoc @@ -0,0 +1,2 @@ +* xref:tutorial:index.adoc[] +** xref:tutorial:first-application/index.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/antora/nav.adoc b/spring-boot-project/spring-boot-docs/src/docs/antora/nav.adoc new file mode 100644 index 0000000000..c7a6113d18 --- /dev/null +++ b/spring-boot-project/spring-boot-docs/src/docs/antora/nav.adoc @@ -0,0 +1,10 @@ +include::ROOT:partial$nav-root.adoc[] +include::tutorial:partial$nav-tutorial.adoc[] +include::reference:partial$nav-reference.adoc[] +include::how-to:partial$nav-how-to.adoc[] +include::build-tool-plugin:partial$nav-build-tool-plugin.adoc[] +include::cli:partial$nav-cli.adoc[] +include::api:partial$nav-rest-api.adoc[] +include::api:partial$nav-java-api.adoc[] +include::specification:partial$nav-specification.adoc[] +include::appendix:partial$nav-appendix.adoc[] 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 deleted file mode 100644 index 9bef63c8b6..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator.adoc +++ /dev/null @@ -1,36 +0,0 @@ - -[[actuator]] -= Production-ready Features -include::attributes.adoc[] - - - -Spring Boot includes a number of additional features to help you monitor and manage your application when you push it to production. -You can choose to manage and monitor your application by using HTTP endpoints or with JMX. -Auditing, health, and metrics gathering can also be automatically applied to your application. - -include::actuator/enabling.adoc[] - -include::actuator/endpoints.adoc[] - -include::actuator/monitoring.adoc[] - -include::actuator/jmx.adoc[] - -include::actuator/observability.adoc[] - -include::actuator/loggers.adoc[] - -include::actuator/metrics.adoc[] - -include::actuator/tracing.adoc[] - -include::actuator/auditing.adoc[] - -include::actuator/http-exchanges.adoc[] - -include::actuator/process-monitoring.adoc[] - -include::actuator/cloud-foundry.adoc[] - -include::actuator/whats-next.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/whats-next.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/whats-next.adoc deleted file mode 100644 index 42e0ed3cbd..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/actuator/whats-next.adoc +++ /dev/null @@ -1,5 +0,0 @@ -[[actuator.whats-next]] -== What to Read Next -You might want to read about graphing tools such as https://graphiteapp.org[Graphite]. - -Otherwise, you can continue on to read about <> or jump ahead for some in-depth information about Spring Boot's <>. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/application-properties.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/application-properties.adoc deleted file mode 100644 index ab3b79f7eb..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/application-properties.adoc +++ /dev/null @@ -1,52 +0,0 @@ -[appendix] -[[appendix.application-properties]] -= Common Application Properties -include::attributes.adoc[] - - - -Various properties can be specified inside your `application.properties` file, inside your `application.yaml` file, or as command line switches. -This appendix provides a list of common Spring Boot properties and references to the underlying classes that consume them. - -TIP: Spring Boot provides various conversion mechanism with advanced value formatting, make sure to review <>. - -NOTE: Property contributions can come from additional jar files on your classpath, so you should not consider this an exhaustive list. -Also, you can define your own properties. - - - -include::application-properties/core.adoc[] - -include::application-properties/cache.adoc[] - -include::application-properties/mail.adoc[] - -include::application-properties/json.adoc[] - -include::application-properties/data.adoc[] - -include::application-properties/transaction.adoc[] - -include::application-properties/data-migration.adoc[] - -include::application-properties/integration.adoc[] - -include::application-properties/web.adoc[] - -include::application-properties/templating.adoc[] - -include::application-properties/server.adoc[] - -include::application-properties/security.adoc[] - -include::application-properties/rsocket.adoc[] - -include::application-properties/actuator.adoc[] - -include::application-properties/devtools.adoc[] - -include::application-properties/docker-compose.adoc[] - -include::application-properties/testcontainers.adoc[] - -include::application-properties/testing.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/attributes.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/attributes.adoc deleted file mode 100644 index d0a5ad56a4..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/attributes.adoc +++ /dev/null @@ -1,116 +0,0 @@ -:doctype: book -:idprefix: -:idseparator: - -:toc: left -:toclevels: 4 -:tabsize: 4 -:numbered: -:sectanchors: -:sectnums: -:hide-uri-scheme: -:docinfo: shared,private -:attribute-missing: warn -:chomp: default headers packages -:artifact-release-type: snapshot -:github-tag: main -:spring-boot-version: current -:github-repo: spring-projects/spring-boot -:github-raw: https://raw.githubusercontent.com/{github-repo}/{github-tag} -:github-issues: https://github.com/{github-repo}/issues/ -:github-wiki: https://github.com/{github-repo}/wiki -:docs-java: {docdir}/../main/java/org/springframework/boot/docs -:docs-kotlin: {docdir}/../main/kotlin/org/springframework/boot/docs -:docs-groovy: {docdir}/../main/groovy/org/springframework/boot/docs -:docs-resources: {docdir}/../main/resources -:spring-boot-code: https://github.com/{github-repo}/tree/{github-tag} -:spring-boot-api: https://docs.spring.io/spring-boot/docs/{spring-boot-version}/api -:spring-boot-docs: https://docs.spring.io/spring-boot/docs/{spring-boot-version}/reference -:spring-boot-latest-code: https://github.com/{github-repo}/tree/main -:spring-boot-current-docs: https://docs.spring.io/spring-boot/docs/current/reference/ -:spring-boot-actuator-restapi-docs: https://docs.spring.io/spring-boot/docs/{spring-boot-version}/actuator-api/htmlsingle -:spring-boot-actuator-restapi-pdfdocs: https://docs.spring.io/spring-boot/docs/{spring-boot-version}/actuator-api/pdf/spring-boot-actuator-web-api.pdf -:spring-boot-maven-plugin-docs: https://docs.spring.io/spring-boot/docs/{spring-boot-version}/maven-plugin/reference/htmlsingle/ -:spring-boot-maven-plugin-pdfdocs: https://docs.spring.io/spring-boot/docs/{spring-boot-version}/maven-plugin/reference/pdf/spring-boot-maven-plugin-reference.pdf -:spring-boot-maven-plugin-api: https://docs.spring.io/spring-boot/docs/{spring-boot-version}/maven-plugin/api/ -:spring-boot-gradle-plugin-docs: https://docs.spring.io/spring-boot/docs/{spring-boot-version}/gradle-plugin/reference/htmlsingle/ -:spring-boot-gradle-plugin-pdfdocs: https://docs.spring.io/spring-boot/docs/{spring-boot-version}/gradle-plugin/reference/pdf/spring-boot-gradle-plugin-reference.pdf -:spring-boot-gradle-plugin-api: https://docs.spring.io/spring-boot/docs/{spring-boot-version}/gradle-plugin/api/ -:spring-boot-module-code: {spring-boot-code}/spring-boot-project/spring-boot/src/main/java/org/springframework/boot -:spring-boot-module-api: {spring-boot-api}/org/springframework/boot -:spring-boot-autoconfigure-module-code: {spring-boot-code}/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure -:spring-boot-autoconfigure-module-api: {spring-boot-api}/org/springframework/boot/autoconfigure -:spring-boot-actuator-module-code: {spring-boot-code}/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate -:spring-boot-actuator-module-api: {spring-boot-api}/org/springframework/boot/actuate -:spring-boot-actuator-autoconfigure-module-code: {spring-boot-code}/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure -:spring-boot-actuator-autoconfigure-module-api: : {spring-boot-api}/org/springframework/boot/actuate/autoconfigure -:spring-boot-cli-module-code: {spring-boot-code}/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli -:spring-boot-cli-module-api: {spring-boot-api}/org/springframework/boot/cli -:spring-boot-devtools-module-code: {spring-boot-code}/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools -:spring-boot-devtools-module-api: {spring-boot-api}/org/springframework/boot/devtools -:spring-boot-for-apache-geode: https://github.com/spring-projects/spring-boot-data-geode -:spring-boot-for-apache-geode-docs: https://docs.spring.io/spring-boot-data-geode-build/2.0.x/reference/html5/ -:spring-boot-test-module-code: {spring-boot-code}/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test -:spring-boot-test-module-api: {spring-boot-api}/org/springframework/boot/test -:spring-boot-test-autoconfigure-module-code: {spring-boot-code}/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure -:spring-boot-test-autoconfigure-module-api: {spring-boot-api}/org/springframework/boot/test/autoconfigure -:spring-amqp-api: https://docs.spring.io/spring-amqp/docs/{spring-amqp-version}/api/org/springframework/amqp -:spring-batch: https://spring.io/projects/spring-batch -:spring-batch-api: https://docs.spring.io/spring-batch/docs/{spring-batch-version}/org/springframework/batch -:spring-batch-docs: https://docs.spring.io/spring-batch/reference/{spring-batch-version-antora} -:spring-data: https://spring.io/projects/spring-data -:spring-data-cassandra: https://spring.io/projects/spring-data-cassandra -:spring-data-commons-api: https://docs.spring.io/spring-data/commons/docs/{spring-data-commons-version}/api/org/springframework/data -:spring-data-couchbase: https://spring.io/projects/spring-data-couchbase -:spring-data-couchbase-docs: https://docs.spring.io/spring-data/couchbase/docs/{spring-data-couchbase-version}/reference/html/ -:spring-data-elasticsearch: https://spring.io/projects/spring-data-elasticsearch -:spring-data-elasticsearch-docs: https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/ -:spring-data-envers: https://spring.io/projects/spring-data-envers -:spring-data-gemfire: https://spring.io/projects/spring-data-gemfire -:spring-data-geode: https://spring.io/projects/spring-data-geode -:spring-data-jpa: https://spring.io/projects/spring-data-jpa -:spring-data-jpa-api: https://docs.spring.io/spring-data/jpa/docs/{spring-data-jpa-version}/api/org/springframework/data/jpa -:spring-data-jpa-docs: https://docs.spring.io/spring-data/jpa/reference/{spring-data-jpa-version}/ -:spring-data-jdbc-docs: https://docs.spring.io/spring-data/jdbc/docs/{spring-data-jdbc-version}/reference/html/ -:spring-data-ldap: https://spring.io/projects/spring-data-ldap -:spring-data-mongodb: https://spring.io/projects/spring-data-mongodb -:spring-data-mongodb-api: https://docs.spring.io/spring-data/mongodb/docs/{spring-data-mongodb-version}/api/org/springframework/data/mongodb -:spring-data-neo4j: https://spring.io/projects/spring-data-neo4j -:spring-data-neo4j-docs: https://docs.spring.io/spring-data/neo4j/docs/{spring-data-neo4j-version}/reference/html/ -:spring-data-r2dbc-api: https://docs.spring.io/spring-data/r2dbc/docs/{spring-data-r2dbc-version}/api/org/springframework/data/r2dbc -:spring-data-r2dbc-docs: https://docs.spring.io/spring-data/r2dbc/docs/{spring-data-r2dbc-version}/reference/html/ -:spring-data-redis: https://spring.io/projects/spring-data-redis -:spring-data-rest-api: https://docs.spring.io/spring-data/rest/docs/{spring-data-rest-version}/api/org/springframework/data/rest -:spring-framework: https://spring.io/projects/spring-framework -:spring-framework-api: https://docs.spring.io/spring-framework/docs/{spring-framework-version}/javadoc-api/org/springframework -:spring-framework-docs: https://docs.spring.io/spring-framework/reference/{spring-framework-version-antora} -:spring-graphql: https://spring.io/projects/spring-graphql -:spring-graphql-docs: https://docs.spring.io/spring-graphql/reference/{spring-graphql-version-antora} -:spring-integration: https://spring.io/projects/spring-integration -:spring-integration-docs: https://docs.spring.io/spring-integration/reference/{spring-integration-version-antora} -:spring-kafka-docs: https://docs.spring.io/spring-kafka/docs/{spring-kafka-version}/reference/ -:spring-pulsar-docs: https://docs.spring.io/spring-pulsar/docs/{spring-pulsar-version}/reference/ -:spring-restdocs: https://spring.io/projects/spring-restdocs -:spring-security: https://spring.io/projects/spring-security -:spring-security-docs: https://docs.spring.io/spring-security/reference/{spring-security-version-antora} -:spring-authorization-server: https://spring.io/projects/spring-authorization-server -:spring-authorization-server-docs: https://docs.spring.io/spring-authorization-server/reference/{spring-authorization-server-version-antora} -:spring-session: https://spring.io/projects/spring-session -:spring-webservices-docs: https://docs.spring.io/spring-ws/docs/{spring-webservices-version}/reference/html/ -:ant-docs: https://ant.apache.org/manual -:dependency-management-plugin-code: https://github.com/spring-gradle-plugins/dependency-management-plugin -:dynatrace-docs: https://docs.dynatrace.com/docs/shortlink -:gradle-docs: https://docs.gradle.org/current/userguide -:hibernate-docs: https://docs.jboss.org/hibernate/orm/{hibernate-version}/userguide/html_single/Hibernate_User_Guide.html -:java-api: https://docs.oracle.com/en/java/javase/17/docs/api -:jooq-docs: https://www.jooq.org/doc/{jooq-version}/manual-single-page -:junit5-docs: https://junit.org/junit5/docs/current/user-guide -:kotlin-docs: https://kotlinlang.org/docs/reference/ -:lettuce-docs: https://lettuce.io/core/{lettuce-version}/reference/index.html -:micrometer-docs: https://docs.micrometer.io/micrometer/reference -:micrometer-concepts-docs: {micrometer-docs}/concepts -:micrometer-implementation-docs: {micrometer-docs}/implementations -:micrometer-tracing-docs: https://docs.micrometer.io/tracing/reference -:tomcat-docs: https://tomcat.apache.org/tomcat-{tomcat-version}-doc -:graal-version: 22.3 -:graal-native-image-docs: https://www.graalvm.org/{graal-version}/reference-manual/native-image -:liberica-nik-download: https://bell-sw.com/pages/downloads/native-image-kit/#/nik-22-17 diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/authors.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/authors.adoc deleted file mode 100644 index 3f3392961a..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/authors.adoc +++ /dev/null @@ -1 +0,0 @@ -Phillip Webb; Dave Syer; Josh Long; Stéphane Nicoll; Rob Winch; Andy Wilkinson; Marcel Overdijk; Christian Dupuis; Sébastien Deleuze; Michael Simons; Vedran Pavić; Jay Bryant; Madhura Bhave; Eddú Meléndez; Scott Frederick; Moritz Halbritter diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/build-tool-plugins.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/build-tool-plugins.adoc deleted file mode 100644 index 1fff3b6bf0..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/build-tool-plugins.adoc +++ /dev/null @@ -1,22 +0,0 @@ -[[build-tool-plugins]] -= Build Tool Plugins -include::attributes.adoc[] - - - -Spring Boot provides build tool plugins for Maven and Gradle. -The plugins offer a variety of features, including the packaging of executable jars. -This section provides more details on both plugins as well as some help should you need to extend an unsupported build system. -If you are just getting started, you might want to read "`<>`" from the "`<>`" section first. - - - -include::build-tool-plugins/maven.adoc[] - -include::build-tool-plugins/gradle.adoc[] - -include::build-tool-plugins/antlib.adoc[] - -include::build-tool-plugins/other-build-systems.adoc[] - -include::build-tool-plugins/whats-next.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/build-tool-plugins/gradle.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/build-tool-plugins/gradle.adoc deleted file mode 100644 index fa3c28c2dc..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/build-tool-plugins/gradle.adoc +++ /dev/null @@ -1,8 +0,0 @@ -[[build-tool-plugins.gradle]] -== Spring Boot Gradle Plugin -The Spring Boot Gradle Plugin provides Spring Boot support in Gradle, letting you package executable jar or war archives, run Spring Boot applications, and use the dependency management provided by `spring-boot-dependencies`. -It requires Gradle 7.x (7.5 or later) or 8.x. -See the plugin's documentation to learn more: - -* Reference ({spring-boot-gradle-plugin-docs}[HTML] and {spring-boot-gradle-plugin-pdfdocs}[PDF]) -* {spring-boot-gradle-plugin-api}[API] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/build-tool-plugins/maven.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/build-tool-plugins/maven.adoc deleted file mode 100644 index 2db61aa9ca..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/build-tool-plugins/maven.adoc +++ /dev/null @@ -1,9 +0,0 @@ -[[build-tool-plugins.maven]] -== Spring Boot Maven Plugin -The Spring Boot Maven Plugin provides Spring Boot support in Maven, letting you package executable jar or war archives and run an application "`in-place`". -To use it, you must use Maven 3.6.3 or later. - -See the plugin's documentation to learn more: - -* Reference ({spring-boot-maven-plugin-docs}[HTML] and {spring-boot-maven-plugin-pdfdocs}[PDF]) -* {spring-boot-maven-plugin-api}[API] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/build-tool-plugins/whats-next.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/build-tool-plugins/whats-next.adoc deleted file mode 100644 index 2bdb01de04..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/build-tool-plugins/whats-next.adoc +++ /dev/null @@ -1,6 +0,0 @@ -[[build-tool-plugins.whats-next]] -== What to Read Next -If you are interested in how the build tool plugins work, you can look at the {spring-boot-code}/spring-boot-project/spring-boot-tools[`spring-boot-tools`] module on GitHub. -More technical details of the executable jar format are covered in <>. - -If you have specific build-related questions, see the "`<>`" guides. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/cli/installation.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/cli/installation.adoc deleted file mode 100644 index e4c1cdd9b1..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/cli/installation.adoc +++ /dev/null @@ -1,4 +0,0 @@ -[[cli.installation]] -== Installing the CLI -The Spring Boot CLI (Command-Line Interface) can be installed manually by using SDKMAN! (the SDK Manager) or by using Homebrew or MacPorts if you are an OSX user. -See _<>_ in the "`Getting started`" section for comprehensive installation instructions. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/cli/using-the-cli.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/cli/using-the-cli.adoc deleted file mode 100644 index 2544ccf50f..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/cli/using-the-cli.adoc +++ /dev/null @@ -1,174 +0,0 @@ -[[cli.using-the-cli]] -== Using the CLI -Once you have installed the CLI, you can run it by typing `spring` and pressing Enter at the command line. -If you run `spring` without any arguments, a help screen is displayed, as follows: - -[source,shell,indent=0,subs="verbatim"] ----- - $ spring - usage: spring [--help] [--version] - [] - - Available commands are: - - init [options] [location] - Initialize a new project using Spring Initializr (start.spring.io) - - encodepassword [options] - Encode a password for use with Spring Security - - shell - Start a nested shell - - Common options: - - --debug Verbose mode - Print additional status information for the command you are running - - - See 'spring help ' for more information on a specific command. ----- - -You can type `spring help` to get more details about any of the supported commands, as shown in the following example: - -[source,shell,indent=0,subs="verbatim"] ----- - $ spring help init - spring init - Initialize a new project using Spring Initializr (start.spring.io) - - usage: spring init [options] [location] - - Option Description - ------ ----------- - -a, --artifact-id Project coordinates; infer archive name (for - example 'test') - -b, --boot-version Spring Boot version (for example '1.2.0.RELEASE') - --build Build system to use (for example 'maven' or - 'gradle') (default: maven) - -d, --dependencies Comma-separated list of dependency identifiers to - include in the generated project - --description Project description - -f, --force Force overwrite of existing files - --format Format of the generated content (for example - 'build' for a build file, 'project' for a - project archive) (default: project) - -g, --group-id Project coordinates (for example 'org.test') - -j, --java-version Language level (for example '1.8') - -l, --language Programming language (for example 'java') - --list List the capabilities of the service. Use it to - discover the dependencies and the types that are - available - -n, --name Project name; infer application name - -p, --packaging Project packaging (for example 'jar') - --package-name Package name - -t, --type Project type. Not normally needed if you use -- - build and/or --format. Check the capabilities of - the service (--list) for more details - --target URL of the service to use (default: https://start. - spring.io) - -v, --version Project version (for example '0.0.1-SNAPSHOT') - -x, --extract Extract the project archive. Inferred if a - location is specified without an extension - - examples: - - To list all the capabilities of the service: - $ spring init --list - - To creates a default project: - $ spring init - - To create a web my-app.zip: - $ spring init -d=web my-app.zip - - To create a web/data-jpa gradle project unpacked: - $ spring init -d=web,jpa --build=gradle my-dir ----- - -The `version` command provides a quick way to check which version of Spring Boot you are using, as follows: - -[source,shell,indent=0,subs="verbatim,attributes"] ----- - $ spring version - Spring CLI v{spring-boot-version} ----- - - - -[[cli.using-the-cli.initialize-new-project]] -=== Initialize a New Project -The `init` command lets you create a new project by using https://start.spring.io without leaving the shell, as shown in the following example: - -[source,shell,indent=0,subs="verbatim"] ----- - $ spring init --dependencies=web,data-jpa my-project - Using service at https://start.spring.io - Project extracted to '/Users/developer/example/my-project' ----- - -The preceding example creates a `my-project` directory with a Maven-based project that uses `spring-boot-starter-web` and `spring-boot-starter-data-jpa`. -You can list the capabilities of the service by using the `--list` flag, as shown in the following example: - -[source,shell,indent=0,subs="verbatim"] ----- - $ spring init --list - ======================================= - Capabilities of https://start.spring.io - ======================================= - - Available dependencies: - ----------------------- - actuator - Actuator: Production ready features to help you monitor and manage your application - ... - web - Web: Support for full-stack web development, including Tomcat and spring-webmvc - websocket - Websocket: Support for WebSocket development - ws - WS: Support for Spring Web Services - - Available project types: - ------------------------ - gradle-build - Gradle Config [format:build, build:gradle] - gradle-project - Gradle Project [format:project, build:gradle] - maven-build - Maven POM [format:build, build:maven] - maven-project - Maven Project [format:project, build:maven] (default) - - ... ----- - -The `init` command supports many options. -See the `help` output for more details. -For instance, the following command creates a Gradle project that uses Java 17 and `war` packaging: - -[source,shell,indent=0,subs="verbatim"] ----- - $ spring init --build=gradle --java-version=17 --dependencies=websocket --packaging=war sample-app.zip - Using service at https://start.spring.io - Content saved to 'sample-app.zip' ----- - - - -[[cli.using-the-cli.embedded-shell]] -=== Using the Embedded Shell -Spring Boot includes command-line completion scripts for the BASH and zsh shells. -If you do not use either of these shells (perhaps you are a Windows user), you can use the `shell` command to launch an integrated shell, as shown in the following example: - -[source,shell,indent=0,subs="verbatim,quotes,attributes"] ----- - $ spring shell - *Spring Boot* (v{spring-boot-version}) - Hit TAB to complete. Type \'help' and hit RETURN for help, and \'exit' to quit. ----- - -From inside the embedded shell, you can run other commands directly: - -[source,shell,indent=0,subs="verbatim,attributes"] ----- - $ version - Spring CLI v{spring-boot-version} ----- - -The embedded shell supports ANSI color output as well as `tab` completion. -If you need to run a native command, you can use the `!` prefix. -To exit the embedded shell, press `ctrl-c`. - - 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 deleted file mode 100644 index 651b15a4e7..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images.adoc +++ /dev/null @@ -1,13 +0,0 @@ -[[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[] - -include::container-images/whats-next.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images/whats-next.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images/whats-next.adoc deleted file mode 100644 index 9d0645f4a5..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/container-images/whats-next.adoc +++ /dev/null @@ -1,5 +0,0 @@ -[[container-images.whats-next]] -== What to Read Next -Once you've learned how to build efficient container images, you can read about <>, such as Kubernetes. - - 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 deleted file mode 100644 index 3015216815..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data.adoc +++ /dev/null @@ -1,11 +0,0 @@ -[[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[] - -include::data/whats-next.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data/whats-next.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data/whats-next.adoc deleted file mode 100644 index 70791bdeb7..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/data/whats-next.adoc +++ /dev/null @@ -1,4 +0,0 @@ -[[data.whats-next]] -== What to Read Next -You should now have a feeling for how to use Spring Boot with various data technologies. -From here, you can read about Spring Boot's support for various <> and how to enable them in your application. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment/whats-next.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment/whats-next.adoc deleted file mode 100644 index a7b8327728..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/deployment/whats-next.adoc +++ /dev/null @@ -1,7 +0,0 @@ -[[deployment.whats-next]] -== What to Read Next -See the https://www.cloudfoundry.org/[Cloud Foundry], https://www.heroku.com/[Heroku], https://www.openshift.com[OpenShift], and https://boxfuse.com[Boxfuse] web sites for more information about the kinds of features that a PaaS can offer. -These are just four of the most popular Java PaaS providers. -Since Spring Boot is so amenable to cloud-based deployment, you can freely consider other providers as well. - -The next section goes on to cover the _<>_, or you can jump ahead to read about the _<>_ or our _<>_. 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 deleted file mode 100644 index d61170bc48..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation.adoc +++ /dev/null @@ -1,39 +0,0 @@ -include::attributes.adoc[] - - - -[[documentation]] -= Documentation Overview -include::attributes.adoc[] - - - -This section provides a brief overview of Spring Boot reference documentation. -It serves as a map for the rest of the document. - -The latest copy of this document is available at {spring-boot-current-docs}. - - -include::documentation/first-steps.adoc[] - -include::documentation/upgrading.adoc[] - -include::documentation/using.adoc[] - -include::documentation/features.adoc[] - -include::documentation/web.adoc[] - -include::documentation/data.adoc[] - -include::documentation/messaging.adoc[] - -include::documentation/io.adoc[] - -include::documentation/container-images.adoc[] - -include::documentation/actuator.adoc[] - -include::documentation/native-images.adoc[] - -include::documentation/advanced.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/actuator.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/actuator.adoc deleted file mode 100644 index 32342c7428..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/actuator.adoc +++ /dev/null @@ -1,7 +0,0 @@ -[[documentation.actuator]] -== Moving to Production -When you are ready to push your Spring Boot application to production, we have <> that you might like: - -* *Management endpoints:* <> -* *Connection options:* <> | <> -* *Monitoring:* <> | <> | <> | <> diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/advanced.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/advanced.adoc deleted file mode 100644 index a24d258215..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/advanced.adoc +++ /dev/null @@ -1,7 +0,0 @@ -[[documentation.advanced]] -== Advanced Topics -Finally, we have a few topics for more advanced users: - -* *Spring Boot Applications Deployment:* <> | <> -* *Build tool plugins:* <> | <> -* *Appendix:* <> | <> | <> | <> | <> | <> 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 deleted file mode 100644 index 62a373430a..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/container-images.adoc +++ /dev/null @@ -1,7 +0,0 @@ -[[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:* <> 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 deleted file mode 100644 index 3a0a7dd820..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/data.adoc +++ /dev/null @@ -1,6 +0,0 @@ -[[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 deleted file mode 100644 index 846e23e67c..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/features.adoc +++ /dev/null @@ -1,9 +0,0 @@ -[[documentation.features]] -== Learning About Spring Boot Features -Need more details about Spring Boot's core features? -<>: - -* *Spring Application:* <> -* *External Configuration:* <> -* *Profiles:* <> -* *Logging:* <> diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/first-steps.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/first-steps.adoc deleted file mode 100644 index fb396ffd34..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/first-steps.adoc +++ /dev/null @@ -1,7 +0,0 @@ -[[documentation.first-steps]] -== First Steps -If you are getting started with Spring Boot or 'Spring' in general, start with <>: - -* *From scratch:* <> | <> | <> -* *Tutorial:* <> | <> -* *Running your example:* <> | <> 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 deleted file mode 100644 index 462d2d68d0..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/io.adoc +++ /dev/null @@ -1,11 +0,0 @@ -[[documentation.io]] -== IO -If your application needs IO capabilities, see one or more of the following sections: - -* *Caching:* <> -* *Quartz:* <> -* *Mail:* <> -* *Validation:* <> -* *REST Clients:* <> -* *Webservices:* <> -* *JTA:* <> 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 deleted file mode 100644 index 0ccc798988..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/messaging.adoc +++ /dev/null @@ -1,10 +0,0 @@ -[[documentation.messaging]] -== Messaging -If your application uses any messaging protocol, see one or more of the following sections: - -* *JMS:* <> -* *AMQP:* <> -* *Kafka:* <> -* *Pulsar:* <> -* *RSocket:* <> -* *Spring Integration:* <> diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/native-images.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/native-images.adoc deleted file mode 100644 index f19f743722..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/native-images.adoc +++ /dev/null @@ -1,9 +0,0 @@ -[[documentation.native-images]] -== GraalVM Native Images -Spring Boot applications can be converted into native executables using GraalVM. -You can read more about our native image support here: - -* *GraalVM Native Images:* <> | <> | <> -* *Getting Started:* <> | <> -* *Testing:* <> | <> -* *Advanced Topics:* <> | <> | <> diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/upgrading.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/upgrading.adoc deleted file mode 100644 index cd31169cf3..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/upgrading.adoc +++ /dev/null @@ -1,11 +0,0 @@ -[[documentation.upgrading]] -== Upgrading From an Earlier Version - -You should always ensure that you are running a {github-wiki}/Supported-Versions[supported version] of Spring Boot. - -Depending on the version that you are upgrading to, you can find some additional tips here: - -* *From 1.x:* <> -* *To a new feature release:* <> -* *Spring Boot CLI:* <> - diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/using.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/using.adoc deleted file mode 100644 index c5a30914f8..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/using.adoc +++ /dev/null @@ -1,9 +0,0 @@ -[[documentation.using]] -== Developing With Spring Boot -Ready to actually start using Spring Boot? <>: - -* *Build systems:* <> | <> | <> | <> -* *Best practices:* <> | <> | <> | <> -* *Running your code:* <> | <> | <> | <> -* *Packaging your app:* <> -* *Spring Boot CLI:* <> 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 deleted file mode 100644 index a2705125fa..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/documentation/web.adoc +++ /dev/null @@ -1,10 +0,0 @@ -[[documentation.web]] -== Web -If you develop 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:* <> 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 deleted file mode 100644 index 55d96c714e..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features.adoc +++ /dev/null @@ -1,41 +0,0 @@ -[[features]] -= Core Features -include::attributes.adoc[] - - - -This section dives into the details of Spring Boot. -Here you can learn about the key features that you may want to use and customize. -If you have not already done so, you might want to read the "<>" and "<>" sections, so that you have a good grounding of the basics. - - - -include::features/spring-application.adoc[] - -include::features/external-config.adoc[] - -include::features/profiles.adoc[] - -include::features/logging.adoc[] - -include::features/internationalization.adoc[] - -include::features/aop.adoc[] - -include::features/json.adoc[] - -include::features/task-execution-and-scheduling.adoc[] - -include::features/testing.adoc[] - -include::features/docker-compose.adoc[] - -include::features/testcontainers.adoc[] - -include::features/developing-auto-configuration.adoc[] - -include::features/kotlin.adoc[] - -include::features/ssl.adoc[] - -include::features/whats-next.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/whats-next.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/whats-next.adoc deleted file mode 100644 index 8affb1c76a..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/whats-next.adoc +++ /dev/null @@ -1,6 +0,0 @@ -[[features.whats-next]] -== What to Read Next -If you want to learn more about any of the classes discussed in this section, see the {spring-boot-api}/[Spring Boot API documentation] or you can browse the {spring-boot-code}[source code directly]. -If you have specific questions, see the <> section. - -If you are comfortable with Spring Boot's core features, you can continue on and read about <>. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-started.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-started.adoc deleted file mode 100644 index 57ea7dbd2d..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-started.adoc +++ /dev/null @@ -1,23 +0,0 @@ -[[getting-started]] -= Getting Started -include::attributes.adoc[] - - - -If you are getting started with Spring Boot, or "`Spring`" in general, start by reading this section. -It answers the basic "`what?`", "`how?`" and "`why?`" questions. -It includes an introduction to Spring Boot, along with installation instructions. -We then walk you through building your first Spring Boot application, discussing some core principles as we go. - - - -include::getting-started/introducing-spring-boot.adoc[] - -include::getting-started/system-requirements.adoc[] - -include::getting-started/installing.adoc[] - -include::getting-started/first-application.adoc[] - -include::getting-started/whats-next.adoc[] - diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-started/whats-next.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-started/whats-next.adoc deleted file mode 100644 index 63dae39f0c..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/getting-started/whats-next.adoc +++ /dev/null @@ -1,8 +0,0 @@ -[[getting-started.whats-next]] -== What to Read Next -Hopefully, this section provided some of the Spring Boot basics and got you on your way to writing your own applications. -If you are a task-oriented type of developer, you might want to jump over to https://spring.io and follow some of the https://spring.io/guides/[getting started] guides that solve specific "`How do I do that with Spring?`" problems. -We also have Spring Boot-specific "`<>`" reference documentation. - -Otherwise, the next logical step is to read _<>_. -If you are really impatient, you could also jump ahead and read about _<>_. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto.adoc deleted file mode 100644 index 3a94bf4a84..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto.adoc +++ /dev/null @@ -1,56 +0,0 @@ -[[howto]] -= "`How-to`" Guides -include::attributes.adoc[] - - - -This section provides answers to some common '`how do I do that...`' questions that often arise when using Spring Boot. -Its coverage is not exhaustive, but it does cover quite a lot. - -If you have a specific problem that we do not cover here, you might want to check https://stackoverflow.com/tags/spring-boot[stackoverflow.com] to see if someone has already provided an answer. -This is also a great place to ask new questions (please use the `spring-boot` tag). - -We are also more than happy to extend this section. -If you want to add a '`how-to`', send us a {spring-boot-code}[pull request]. - - - -include::howto/application.adoc[] - -include::howto/properties-and-configuration.adoc[] - -include::howto/webserver.adoc[] - -include::howto/spring-mvc.adoc[] - -include::howto/jersey.adoc[] - -include::howto/http-clients.adoc[] - -include::howto/logging.adoc[] - -include::howto/data-access.adoc[] - -include::howto/data-initialization.adoc[] - -include::howto/nosql.adoc[] - -include::howto/messaging.adoc[] - -include::howto/batch.adoc[] - -include::howto/actuator.adoc[] - -include::howto/security.adoc[] - -include::howto/hotswapping.adoc[] - -include::howto/testing.adoc[] - -include::howto/build.adoc[] - -include::howto/aot.adoc[] - -include::howto/traditional-deployment.adoc[] - -include::howto/docker-compose.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/aot.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/aot.adoc deleted file mode 100644 index 8ed5cae642..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/aot.adoc +++ /dev/null @@ -1,53 +0,0 @@ -[[howto.aot]] -== Ahead-of-time processing - -A number of questions often arise when people use the ahead-of-time processing of Spring Boot applications. -This section addresses those questions. - -[[howto.aot.conditions]] -=== Conditions - -Ahead-of-time processing optimizes the application and evaluates {spring-framework-api}/context/annotation/Conditional.html[conditions] based on the environment at build time. -<> are implemented through conditions and are therefore affected, too. - -If you want beans that are created based on a condition in an ahead-of-time optimized application, you have to set up the environment when building the application. -The beans which are created while ahead-of-time processing at build time are then always created when running the application and can't be switched off. -To do this, you can set the profiles which should be used when building the application. - -For Maven, this works by setting the `profiles` configuration of the `spring-boot-maven-plugin:process-aot` execution: - -[source,xml,indent=0,subs="verbatim"] ----- - - native - - - - - org.springframework.boot - spring-boot-maven-plugin - - - process-aot - - profile-a,profile-b - - - - - - - - ----- - -For Gradle, you need to configure the `ProcessAot` task: - -[source,gradle,indent=0,subs="verbatim"] ----- - tasks.withType(org.springframework.boot.gradle.tasks.aot.ProcessAot).configureEach { - args('--spring.profiles.active=profile-a,profile-b') - } ----- - -Profiles which only change configuration properties that don't influence conditions are supported without limitations when running ahead-of-time optimized applications. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/index-docinfo.xml b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/index-docinfo.xml deleted file mode 100644 index 39652531d3..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/index-docinfo.xml +++ /dev/null @@ -1,13 +0,0 @@ -Spring Boot -{spring-boot-version} - - 2012-2024 - - - - Copies of this document may be made for your own use and for distribution to - others, provided that you do not charge any fee for such copies and further - provided that each copy contains this Copyright Notice, whether distributed in - print or electronically. - - 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 deleted file mode 100644 index 4966c197d1..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/index.adoc +++ /dev/null @@ -1,39 +0,0 @@ -[[index]] -= Spring Boot Reference Documentation -include::authors.adoc[] -v{spring-boot-version} -include::attributes.adoc[] - -This document is also available as {spring-boot-docs}/htmlsingle/[a single HTML page] and as {spring-boot-docs}/pdf/spring-boot-reference.pdf[a PDF]. - -The reference documentation consists of the following sections: - -[horizontal] -<> :: Legal information. -<> :: Resources for getting help. -<> :: About the Documentation, First Steps, and more. -<> :: Introducing Spring Boot, System Requirements, Servlet Containers, Installing Spring Boot, and Developing Your First Spring Boot Application -<> :: Upgrading from 1.x, Upgrading to a new feature release, and Upgrading the Spring Boot CLI. -<> :: Build Systems, Structuring Your Code, Configuration, Spring Beans and Dependency Injection, DevTools, and more. -<> :: Profiles, Logging, Internationalization, Task Execution and Scheduling, 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, Apache Kafka, Apache Pulsar, RSocket, WebSocket, and Spring Integration. -<> :: Efficient container images and Building container images with Dockerfiles and Cloud Native Buildpacks. -<> :: Monitoring, Metrics, Auditing, and more. -<> :: Deploying to the Cloud, and Installing as a Unix application. -<> :: Create a native executable from your application using GraalVM -<> :: Installing the CLI, Using the CLI, Configuring the CLI, and more. -<> :: Maven Plugin, Gradle Plugin, Antlib, and more. -<> :: Application Development, Configuration, Embedded Servers, Data Access, and many more. - -The reference documentation has the following appendices: - -[horizontal] -<> :: Common application properties that you can use to configure your application. -<> :: Metadata that you can use to describe configuration properties. -<> :: Auto-configuration classes provided by Spring Boot. -<> :: Test auto-configuration annotations that you can use to test slices of your application. -<> :: Spring Boot's executable jars, their launchers, and their format. -<> :: Details of the dependencies that are managed by Spring Boot. 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 deleted file mode 100644 index debab3c58f..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/index.singleadoc +++ /dev/null @@ -1,66 +0,0 @@ -[[spring-boot-reference-documentation]] -= Spring Boot Reference Documentation -include::authors.adoc[] -v{spring-boot-version} -include::attributes.adoc[] - -ifdef::backend-spring-html[] -This document is also available as {spring-boot-docs}/html/[multiple HTML pages] and as {spring-boot-docs}/pdf/spring-boot-reference.pdf[a PDF]. -endif::[] -ifdef::backend-spring-pdf[] -This document is also available as {spring-boot-docs}/html/[multiple HTML pages] and as {spring-boot-docs}/htmlsingle/[a single HTML page]. -endif::[] - -include::legal.adoc[leveloffset=+1] - -include::getting-help.adoc[leveloffset=+1] - -include::documentation.adoc[leveloffset=+1] - -include::getting-started.adoc[leveloffset=+1] - -include::upgrading.adoc[leveloffset=+1] - -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] - -include::native-image.adoc[leveloffset=+1] - -include::cli.adoc[leveloffset=+1] - -include::build-tool-plugins.adoc[leveloffset=+1] - -include::howto.adoc[leveloffset=+1] - - - -:sectnums!: -[[appendix]] -== Appendices - -include::application-properties.adoc[leveloffset=+2] - -include::configuration-metadata.adoc[leveloffset=+2] - -include::auto-configuration-classes.adoc[leveloffset=+2] - -include::test-auto-configuration.adoc[leveloffset=+2] - -include::executable-jar.adoc[leveloffset=+2] - -include::dependency-versions.adoc[leveloffset=+2] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/whats-next.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/whats-next.adoc deleted file mode 100644 index 442122c666..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/whats-next.adoc +++ /dev/null @@ -1,6 +0,0 @@ -[[io.whats-next]] -== What to Read Next -You should now have a good understanding of Spring Boot's <> and the various technologies that Spring Boot provides support for through auto-configuration. - -The next few sections go into detail about deploying applications to cloud platforms. -You can read about <> in the next section or skip to the <> section. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/legal.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/legal.adoc deleted file mode 100644 index 628bb5cd42..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/legal.adoc +++ /dev/null @@ -1,9 +0,0 @@ -[[legal]] -= Legal - -Copyright © 2012-2024 - -Copies of this document may be made for your own use and for distribution to -others, provided that you do not charge any fee for such copies and further -provided that each copy contains this Copyright Notice, whether distributed in -print or electronically. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/websockets.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/websockets.adoc deleted file mode 100644 index 4a3e0f23d5..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/websockets.adoc +++ /dev/null @@ -1,16 +0,0 @@ -[[messaging.websockets]] -== WebSockets -Spring Boot provides WebSockets auto-configuration for embedded Tomcat, Jetty, and Undertow. -If you deploy a war file to a standalone container, Spring Boot assumes that the container is responsible for the configuration of its WebSocket support. - -Spring Framework provides {spring-framework-docs}/web/websocket.html[rich WebSocket support] for MVC web applications that can be easily accessed through the `spring-boot-starter-websocket` module. - -WebSocket support is also available for {spring-framework-docs}/web/webflux-websocket.html[reactive web applications] and requires to include the WebSocket API alongside `spring-boot-starter-webflux`: - -[source,xml,indent=0,subs="verbatim"] ----- - - jakarta.websocket - jakarta.websocket-api - ----- diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/whats-next.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/whats-next.adoc deleted file mode 100644 index 36841ba1a1..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/messaging/whats-next.adoc +++ /dev/null @@ -1,4 +0,0 @@ -[[messaging.whats-next]] -== What to Read Next -The next section describes how to enable <> in your application. -You can read about <>, <>, <>, <> and more in this section. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/native-image/whats-next.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/native-image/whats-next.adoc deleted file mode 100644 index ad8fbd8a54..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/native-image/whats-next.adoc +++ /dev/null @@ -1,8 +0,0 @@ -[[native-image.whats-next]] -== What to Read Next -If you want to learn more about the ahead-of-time processing provided by our build plugins, see the {spring-boot-maven-plugin-docs}[Maven] and {spring-boot-gradle-plugin-docs}[Gradle] plugin documentation. -To learn more about the APIs used to perform the processing, browse the `org.springframework.aot.generate` and `org.springframework.beans.factory.aot` packages of the Spring Framework sources. - -For known limitations with Spring and GraalVM, please see the {github-wiki}/Spring-Boot-with-GraalVM[Spring Boot wiki]. - -The next section goes on to cover the _<>_. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading.adoc deleted file mode 100644 index 1292c64da3..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading.adoc +++ /dev/null @@ -1,17 +0,0 @@ -[[upgrading]] -= Upgrading Spring Boot -include::attributes.adoc[] - -Instructions for how to upgrade from earlier versions of Spring Boot are provided on the project {github-wiki}[wiki]. -Follow the links in the {github-wiki}#release-notes[release notes] section to find the version that you want to upgrade to. - -Upgrading instructions are always the first item in the release notes. -If you are more than one release behind, please make sure that you also review the release notes of the versions that you jumped. - -include::upgrading/from-1x.adoc[] - -include::upgrading/to-feature.adoc[] - -include::upgrading/cli.adoc[] - -include::upgrading/whats-next.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading/cli.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading/cli.adoc deleted file mode 100644 index b6b3ea2026..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading/cli.adoc +++ /dev/null @@ -1,5 +0,0 @@ -[[upgrading.cli]] -== Upgrading the Spring Boot CLI - -To upgrade an existing CLI installation, use the appropriate package manager command (for example, `brew upgrade`). -If you manually installed the CLI, follow the <>, remembering to update your `PATH` environment variable to remove any older references. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading/from-1x.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading/from-1x.adoc deleted file mode 100644 index e899fe09ac..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading/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. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading/to-feature.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading/to-feature.adoc deleted file mode 100644 index c901c572e1..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading/to-feature.adoc +++ /dev/null @@ -1,19 +0,0 @@ -[[upgrading.to-feature]] -== Upgrading to a New Feature Release - -When upgrading to a new feature release, some properties may have been renamed or removed. -Spring Boot provides a way to analyze your application's environment and print diagnostics at startup, but also temporarily migrate properties at runtime for you. -To enable that feature, add the following dependency to your project: - -[source,xml,indent=0,subs="verbatim"] ----- - - org.springframework.boot - spring-boot-properties-migrator - runtime - ----- - -WARNING: Properties that are added late to the environment, such as when using `@PropertySource`, will not be taken into account. - -NOTE: Once you finish the migration, please make sure to remove this module from your project's dependencies. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading/whats-next.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading/whats-next.adoc deleted file mode 100644 index ff0bd6e768..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/upgrading/whats-next.adoc +++ /dev/null @@ -1,5 +0,0 @@ -[[upgrading.whats-next]] -== What to Read Next -Once you've decided to upgrade your application, you can find detailed information regarding specific features in the rest of the document. - -Spring Boot's documentation is specific to that version, so any information that you find in here will contain the most up-to-date changes that are in that version. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using.adoc deleted file mode 100644 index 832abd9e86..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using.adoc +++ /dev/null @@ -1,34 +0,0 @@ -[[using]] -= Developing with Spring Boot -include::attributes.adoc[] - - - -This section goes into more detail about how you should use Spring Boot. -It covers topics such as build systems, auto-configuration, and how to run your applications. -We also cover some Spring Boot best practices. -Although there is nothing particularly special about Spring Boot (it is just another library that you can consume), there are a few recommendations that, when followed, make your development process a little easier. - -If you are starting out with Spring Boot, you should probably read the _<>_ guide before diving into this section. - - - -include::using/build-systems.adoc[] - -include::using/structuring-your-code.adoc[] - -include::using/configuration-classes.adoc[] - -include::using/auto-configuration.adoc[] - -include::using/spring-beans-and-dependency-injection.adoc[] - -include::using/using-the-springbootapplication-annotation.adoc[] - -include::using/running-your-application.adoc[] - -include::using/devtools.adoc[] - -include::using/packaging-for-production.adoc[] - -include::using/whats-next.adoc[] diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/whats-next.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/whats-next.adoc deleted file mode 100644 index 6aaf2da0ba..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/using/whats-next.adoc +++ /dev/null @@ -1,4 +0,0 @@ -[[using.whats-next]] -== What to Read Next -You should now understand how you can use Spring Boot and some best practices that you should follow. -You can now go on to learn about specific _<>_ in depth, or you could skip ahead and read about the "`<>`" aspects of Spring Boot. diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/whats-next.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/whats-next.adoc deleted file mode 100644 index 94ddb16080..0000000000 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/web/whats-next.adoc +++ /dev/null @@ -1,5 +0,0 @@ -[[web.whats-next]] -== What to Read Next -You should now have a good understanding of how to develop web applications with Spring Boot. -The next few sections describe how Spring Boot integrates with various <>, <>, and other IO capabilities. -You can pick any of these based on your application's needs.