此版本仍在开发中,尚未视为稳定版。如需最新稳定版本,请使用 Spring Boot 4.0.4spring-doc.cadn.net.cn

开发时服务

开发时服务提供运行应用程序所需的外部依赖项。 它们仅在开发过程中使用,并在应用程序部署时禁用。spring-doc.cadn.net.cn

Spring Boot 提供了两种开发时服务的支持,分别是 Docker Compose 和 Testcontainers。 接下来的章节将提供更多关于它们的细节。spring-doc.cadn.net.cn

Docker Compose 支持

Docker Compose 是一种流行的技术,可以用于定义和管理应用程序所需服务的多个容器。 一个 compose.yml 文件通常会紧挨着应用创建,并定义和服务容器的配置。spring-doc.cadn.net.cn

使用 Docker Compose 的典型工作流是运行 docker compose up,在此期间与启动的服务进行交互以开发您的应用程序,完成后运行 docker compose downspring-doc.cadn.net.cn

The spring-boot-docker-compose 模块可以包含在项目中,以提供使用 Docker Compose 处理容器的支持。 在构建中添加该模块依赖项,如下所示的 Maven 和 Gradle 列表所展示的:spring-doc.cadn.net.cn

Maven
<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-docker-compose</artifactId>
		<optional>true</optional>
	</dependency>
</dependencies>
Gradle
dependencies {
	developmentOnly("org.springframework.boot:spring-boot-docker-compose")
}

当此模块作为依赖项包含时,Spring Boot 将执行以下操作:spring-doc.cadn.net.cn

如果在启动应用时 Docker Compose 服务已经运行,Spring Boot 将只为每个受支持的容器创建服务连接 bean。 它不会再次调用 docker compose up,也不会在应用关闭时调用 docker compose stopspring-doc.cadn.net.cn

重新打包的归档文件默认不包含 Spring Boot 的 Docker Compose 支持。 如果您想使用此功能,需要显式包含它。 当使用 Maven 插件时,请将 excludeDockerCompose 属性设置为 false。 当使用 Gradle 插件时,配置任务的类路径以包含 developmentOnly 配置

前置条件

您需要将 dockerdocker compose(或 docker-compose)命令行应用程序添加到路径中。
支持的最低 Docker Compose 版本是 2.2.0。spring-doc.cadn.net.cn

服务连接

服务连接是指与任何远程服务的连接。 Spring Boot 的自动配置可以消费服务连接的详细信息,并利用这些信息建立与远程服务的连接。 在此过程中,连接细节优先于任何相关的配置属性。spring-doc.cadn.net.cn

当使用 Spring Boot 的 Docker Compose 支持时,服务连接将建立到容器映射的端口。spring-doc.cadn.net.cn

Docker compose is usually used in such a way that the ports inside the container are mapped to ephemeral ports on your computer. For example, a Postgres server may run inside the container using port 5432 but be mapped to a totally different port locally. The service connection will always discover and use the locally mapped port.

服务连接是通过使用容器的镜像名称建立的。 当前支持以下服务连接:spring-doc.cadn.net.cn

连接详细信息 匹配于

ActiveMQConnectionDetailsspring-doc.cadn.net.cn

容器名为 "symptoma/activemq" 或 "apache/activemq-classic"spring-doc.cadn.net.cn

ArtemisConnectionDetailsspring-doc.cadn.net.cn

容器名为“apache/activemq-artemis”spring-doc.cadn.net.cn

CassandraConnectionDetailsspring-doc.cadn.net.cn

容器名为 "cassandra"、"bitnami/cassandra" 或 "bitnamilegacy/cassandra"spring-doc.cadn.net.cn

ElasticsearchConnectionDetailsspring-doc.cadn.net.cn

容器名为 "elasticsearch"、"bitnami/elasticsearch" 或 "bitnamilegacy/elasticsearch"spring-doc.cadn.net.cn

HazelcastConnectionDetailsspring-doc.cadn.net.cn

容器名为 "hazelcast/hazelcast"。spring-doc.cadn.net.cn

JdbcConnectionDetailsspring-doc.cadn.net.cn

容器名为 "clickhouse/clickhouse-server"、"bitnami/clickhouse"、"bitnamilegacy/clickhouse"、"gvenzl/oracle-free"、"gvenzl/oracle-xe"、"mariadb"、"bitnami/mariadb"、"bitnamilegacy/mariadb"、"mssql/server"、"mysql"、"bitnami/mysql"、"bitnamilegacy/mysql"、"postgres"、"bitnami/postgresql" 或 "bitnamilegacy/postgresql"spring-doc.cadn.net.cn

LdapConnectionDetailsspring-doc.cadn.net.cn

容器名为spring-doc.cadn.net.cn

MongoConnectionDetailsspring-doc.cadn.net.cn

容器名为“mongo”、“bitnami/mongodb”或“bitnamilegacy/mongodb”spring-doc.cadn.net.cn

Neo4jConnectionDetailsspring-doc.cadn.net.cn

容器名为 "neo4j"、"bitnami/neo4j" 或 "bitnamilegacy/neo4j"spring-doc.cadn.net.cn

OtlpLoggingConnectionDetailsspring-doc.cadn.net.cn

容器名为spring-doc.cadn.net.cn

OtlpMetricsConnectionDetailsspring-doc.cadn.net.cn

容器名为spring-doc.cadn.net.cn

OtlpTracingConnectionDetailsspring-doc.cadn.net.cn

容器名为spring-doc.cadn.net.cn

PulsarConnectionDetailsspring-doc.cadn.net.cn

容器名为“apachepulsar/pulsar”spring-doc.cadn.net.cn

R2dbcConnectionDetailsspring-doc.cadn.net.cn

容器名为 "clickhouse/clickhouse-server"、"bitnami/clickhouse"、"bitnamilegacy/clickhouse"、"gvenzl/oracle-free"、"gvenzl/oracle-xe"、"mariadb"、"bitnami/mariadb"、"bitnamilegacy/mariadb"、"mssql/server"、"mysql"、"bitnami/mysql"、"bitnamilegacy/mysql"、"postgres"、"bitnami/postgresql" 或 "bitnamilegacy/postgresql"spring-doc.cadn.net.cn

RabbitConnectionDetailsspring-doc.cadn.net.cn

容器名为 "rabbitmq"、"bitnami/rabbitmq" 或 "bitnamilegacy/rabbitmq"spring-doc.cadn.net.cn

RedisConnectionDetailsspring-doc.cadn.net.cn

容器名为 "redis"、"bitnami/redis"、"bitnamilegacy/redis" 或 "redis/redis-stack"、"redis/redis-stack-server"spring-doc.cadn.net.cn

ZipkinConnectionDetailsspring-doc.cadn.net.cn

容器名为"openzipkin/zipkin"。spring-doc.cadn.net.cn

SSL 支持

一些图片默认启用了SSL,或者你可能希望为容器启用SSL以镜像你的生产环境。 Spring Boot 支持对支持的服务连接进行 SSL 配置。 请注意,你仍需要在运行于容器内的服务上手动启用 SSL,此功能仅在应用客户端配置 SSL。spring-doc.cadn.net.cn

以下服务连接支持 SSL:spring-doc.cadn.net.cn

要为服务启用 SSL 支持,您可以使用服务标签spring-doc.cadn.net.cn

对于基于JKS的密钥库和信任库,您可以使用以下容器标签:spring-doc.cadn.net.cn

这些标签对应的是SSL 证书包 中可用的属性。spring-doc.cadn.net.cn

对于基于PEM的密钥库和信任库,您可以使用以下容器标签:spring-doc.cadn.net.cn

这些标签对应的是SSL 证书包 中可用的属性。spring-doc.cadn.net.cn

以下示例为 Redis 容器启用 SSL:spring-doc.cadn.net.cn

services:
  redis:
    image: 'redis:latest'
    ports:
      - '6379'
    secrets:
      - ssl-ca
      - ssl-key
      - ssl-cert
    command: 'redis-server --tls-port 6379 --port 0 --tls-cert-file /run/secrets/ssl-cert --tls-key-file /run/secrets/ssl-key --tls-ca-cert-file /run/secrets/ssl-ca'
    labels:
      - 'org.springframework.boot.sslbundle.pem.keystore.certificate=client.crt'
      - 'org.springframework.boot.sslbundle.pem.keystore.private-key=client.key'
      - 'org.springframework.boot.sslbundle.pem.truststore.certificate=ca.crt'
secrets:
  ssl-ca:
    file: 'ca.crt'
  ssl-key:
    file: 'server.key'
  ssl-cert:
    file: 'server.crt'

自定义图像

有时您可能需要使用自己版本的图片来提供服务。 您可以使用任何自定义图片,只要它表现与标准图片相同即可。 具体来说,标准图片支持的所有环境变量也必须在您的自定义图片中使用。spring-doc.cadn.net.cn

如果您的图像使用不同的名称,您可以在compose.yml文件中使用一个标签,以便Spring Boot能够提供服务连接。 使用名为org.springframework.boot.service-connection的标签来提供服务名称。spring-doc.cadn.net.cn

services:
  redis:
    image: 'mycompany/mycustomredis:7.0'
    ports:
      - '6379'
    labels:
      org.springframework.boot.service-connection: redis

跳过特定容器

如果在你的compose.yml中定义了一个容器镜像,但你不想将其连接到你的应用程序,可以使用标签来忽略它。 任何标记有org.springframework.boot.ignore的容器都将被Spring Boot忽略。spring-doc.cadn.net.cn

services:
  redis:
    image: 'redis:7.0'
    ports:
      - '6379'
    labels:
      org.springframework.boot.ignore: true

使用特定的 Compose 文件

如果您的 Docker 组合文件不在与应用程序相同的目录中,或者名称不同,您可以在 spring.docker.compose.fileapplication.properties 中使用 application.yaml 指向不同的文件。 属性可以定义为确切路径或相对于应用程序的路径。spring-doc.cadn.net.cn

spring.docker.compose.file=../my-compose.yml
spring:
  docker:
    compose:
      file: "../my-compose.yml"

等待容器就绪

Docker Compose 启动的容器可能需要一些时间才能完全就绪。 检查就绪状态的最佳方法是在您的 healthcheck 文件中的服务定义下添加一个 compose.yml 部分。spring-doc.cadn.net.cn

由于healthcheck配置在compose.yml文件中被省略的情况并不少见,Spring Boot 也会直接检查服务的就绪状态。 默认情况下,当能够建立到容器映射端口的TCP/IP连接时,该容器就被认为是就绪的。spring-doc.cadn.net.cn

您可以通过在org.springframework.boot.readiness-check.tcp.disable文件中添加compose.yml标签来逐个容器禁用此功能。spring-doc.cadn.net.cn

services:
  redis:
    image: 'redis:7.0'
    ports:
      - '6379'
    labels:
      org.springframework.boot.readiness-check.tcp.disable: true

您也可以在您的application.propertiesapplication.yaml文件中更改超时值:spring-doc.cadn.net.cn

spring.docker.compose.readiness.tcp.connect-timeout=10s
spring.docker.compose.readiness.tcp.read-timeout=5s
spring:
  docker:
    compose:
      readiness:
        tcp:
          connect-timeout: 10s
          read-timeout: 5s

整体超时可以使用spring.docker.compose.readiness.timeout进行配置。spring-doc.cadn.net.cn

控制 Docker Compose 生命周期

默认情况下,Spring Boot 在应用程序启动时会调用 docker compose up,在关闭时调用 docker compose stop。 如果您希望有不同的生命周期管理,可以使用 spring.docker.compose.lifecycle-management 属性。spring-doc.cadn.net.cn

支持以下值:spring-doc.cadn.net.cn

除了可以使用spring.docker.compose.start.command属性来更改是使用docker compose up还是docker compose start外, 还可以使用spring.docker.compose.stop.command属性来配置是使用docker compose down还是docker compose stopspring-doc.cadn.net.cn

您也可以向 Docker Compose 命令传递额外的参数。 spring.docker.compose.arguments 属性允许您指定传递给所有 Docker Compose 命令的参数。 spring.docker.compose.start.arguments 属性允许您指定仅传递给 up(或 start)命令的参数,而 spring.docker.compose.stop.arguments 属性允许您指定仅传递给 down(或 stop)命令的参数。spring-doc.cadn.net.cn

以下示例展示了如何配置生命周期管理:spring-doc.cadn.net.cn

spring.docker.compose.lifecycle-management=start-and-stop
spring.docker.compose.arguments[0]=--project-name=myapp
spring.docker.compose.arguments[1]=--progress=auto
spring.docker.compose.start.command=up
spring.docker.compose.start.arguments[0]=--build
spring.docker.compose.start.arguments[1]=--force-recreate
spring.docker.compose.stop.command=down
spring.docker.compose.stop.timeout=1m
spring.docker.compose.stop.arguments[0]=--volumes
spring.docker.compose.stop.arguments[1]=--remove-orphans
spring:
  docker:
    compose:
      lifecycle-management: start-and-stop
      arguments:
        - "--project-name=myapp"
        - "--progress=auto"
      start:
        command: up
        arguments:
          - "--build"
          - "--force-recreate"
      stop:
        command: down
        timeout: 1m
        arguments:
          - "--volumes"
          - "--remove-orphans"

激活 Docker Compose 配置文件

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 spring.docker.compose.profiles.active property in your application.properties or application.yaml file:spring-doc.cadn.net.cn

spring.docker.compose.profiles.active=myprofile
spring:
  docker:
    compose:
      profiles:
        active: "myprofile"

在测试中使用 Docker Compose

默认情况下,Spring Boot 的 Docker Compose 支持在运行测试时是禁用的。spring-doc.cadn.net.cn

要启用测试中的 Docker Compose 支持,请将 spring.docker.compose.skip.in-tests 设置为 falsespring-doc.cadn.net.cn

使用 Gradle 时,您还需要将 spring-boot-docker-compose 依赖的配置从 developmentOnly 更改为 testAndDevelopmentOnly:spring-doc.cadn.net.cn

Gradle
dependencies {
	testAndDevelopmentOnly("org.springframework.boot:spring-boot-docker-compose")
}

Testcontainers 支持

除了在集成测试中使用 Testcontainers 之外,也可以在开发阶段使用它们。 接下来的章节将提供更多相关细节。spring-doc.cadn.net.cn

在开发阶段使用 Testcontainers

此方法允许开发者快速启动应用程序所依赖的服务容器,无需手动配置如数据库服务器等资源。 使用这种方式的 Testcontainers 提供了类似于 Docker Compose 的功能,不同之处在于你的容器配置是用 Java 编写的而不是 YAML。spring-doc.cadn.net.cn

要在开发时使用 Testcontainers,您需要通过“test”类路径而不是“main”来启动您的应用程序。 这将允许您访问所有声明的测试依赖项,并为您提供编写测试配置的自然位置。spring-doc.cadn.net.cn

要创建一个可测试的应用程序版本,您应该在 src/test 目录中创建一个“Application”类。 例如,如果您主应用程序位于 src/main/java/com/example/MyApplication.java,则应创建 src/test/java/com/example/TestMyApplication.javaspring-doc.cadn.net.cn

The TestMyApplication 类可以使用 SpringApplication.from(…​) 方法来启动真正的应用:spring-doc.cadn.net.cn

import org.springframework.boot.SpringApplication;

public class TestMyApplication {

	public static void main(String[] args) {
		SpringApplication.from(MyApplication::main).run(args);
	}

}
import org.springframework.boot.fromApplication

fun main(args: Array<String>) {
	fromApplication<MyApplication>().run(*args)
}

您还需要定义希望随应用程序一起启动的 Container 实例。 为此,您需要确保已将 spring-boot-testcontainers 模块作为 test 依赖项添加。 完成此操作后,您可以创建一个 @TestConfiguration 类,该类声明用于您要启动的容器的 @Bean 方法。spring-doc.cadn.net.cn

您还可以使用 @ServiceConnection 注解您的 @Bean 方法,以创建 ConnectionDetails Bean。 有关支持的技术详情,请参阅 服务连接 部分。spring-doc.cadn.net.cn

一个典型的Testcontainers配置会这样写:spring-doc.cadn.net.cn

import org.testcontainers.containers.Neo4jContainer;

import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.context.annotation.Bean;

@TestConfiguration(proxyBeanMethods = false)
public class MyContainersConfiguration {

	@Bean
	@ServiceConnection
	public Neo4jContainer<?> neo4jContainer() {
		return new Neo4jContainer<>("neo4j:5");
	}

}
import org.springframework.boot.test.context.TestConfiguration
import org.springframework.boot.testcontainers.service.connection.ServiceConnection
import org.springframework.context.annotation.Bean
import org.testcontainers.containers.Neo4jContainer

@TestConfiguration(proxyBeanMethods = false)
class MyContainersConfiguration {

	@Bean
	@ServiceConnection
	fun neo4jContainer(): Neo4jContainer<*> {
		return Neo4jContainer("neo4j:5")
	}

}
Container Bean 的生命周期由 Spring Boot 自动管理。 容器将自动启动和停止。
您可以通过设置spring.testcontainers.beans.startup 属性来更改容器启动的方式。 默认情况下使用 sequential 启动方式,但如果您希望并行启动多个容器,也可以选择 parallel

一旦您定义了测试配置,就可以使用with(…​)方法将其附加到您的测试Starters中:spring-doc.cadn.net.cn

import org.springframework.boot.SpringApplication;

public class TestMyApplication {

	public static void main(String[] args) {
		SpringApplication.from(MyApplication::main).with(MyContainersConfiguration.class).run(args);
	}

}
import org.springframework.boot.fromApplication
import org.springframework.boot.with

fun main(args: Array<String>) {
	fromApplication<MyApplication>().with(MyContainersConfiguration::class).run(*args)
}

您可以现在像运行普通的Java TestMyApplication 方法应用程序一样启动 main,以启动您的应用程序及其所需的容器。spring-doc.cadn.net.cn

您可以从命令行使用 Maven 目标 spring-boot:test-run 或 Gradle 任务 bootTestRun 来实现这一点。

在开发时贡献动态属性

如果您希望在开发时从您的 Container @Bean 方法中贡献动态属性,请定义一个额外的 DynamicPropertyRegistrar Bean。 该注册器应使用一个 @Bean 方法进行定义,该方法将注入作为参数的容器,属性将从该容器中获取。 这种安排确保在使用属性之前容器已经启动。spring-doc.cadn.net.cn

典型的配置可能如下所示:spring-doc.cadn.net.cn

import org.testcontainers.containers.MongoDBContainer;

import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.DynamicPropertyRegistrar;

@TestConfiguration(proxyBeanMethods = false)
public class MyContainersConfiguration {

	@Bean
	public MongoDBContainer mongoDbContainer() {
		return new MongoDBContainer("mongo:5.0");
	}

	@Bean
	public DynamicPropertyRegistrar mongoDbProperties(MongoDBContainer container) {
		return (properties) -> {
			properties.add("spring.data.mongodb.host", container::getHost);
			properties.add("spring.data.mongodb.port", container::getFirstMappedPort);
		};
	}

}
import org.springframework.boot.test.context.TestConfiguration
import org.springframework.context.annotation.Bean
import org.springframework.test.context.DynamicPropertyRegistrar;
import org.testcontainers.containers.MongoDBContainer

@TestConfiguration(proxyBeanMethods = false)
class MyContainersConfiguration {

	@Bean
	fun mongoDbContainer(): MongoDBContainer {
		return MongoDBContainer("mongo:5.0")
	}
	
	@Bean
	fun mongoDbProperties(container: MongoDBContainer): DynamicPropertyRegistrar {
		return DynamicPropertyRegistrar { properties ->
			properties.add("spring.data.mongodb.host") { container.host }
			properties.add("spring.data.mongodb.port") { container.firstMappedPort }
		}
	}

}
只要可能,建议使用 @ServiceConnection,然而,对于尚不支持 @ServiceConnection 的技术,动态属性可以作为一种有用的后备方案。

导入 Testcontainers 声明类

使用 Testcontainers 时的一个常见模式是将 Container 实例声明为静态字段。 通常,这些字段直接定义在测试类上。 它们也可以声明在父类或测试所实现的接口上。spring-doc.cadn.net.cn

例如,以下 MyContainers 接口声明了 mongoneo4j 容器:spring-doc.cadn.net.cn

import org.testcontainers.containers.MongoDBContainer;
import org.testcontainers.containers.Neo4jContainer;
import org.testcontainers.junit.jupiter.Container;

import org.springframework.boot.testcontainers.service.connection.ServiceConnection;

public interface MyContainers {

	@Container
	@ServiceConnection
	MongoDBContainer mongoContainer = new MongoDBContainer("mongo:5.0");

	@Container
	@ServiceConnection
	Neo4jContainer<?> neo4jContainer = new Neo4jContainer<>("neo4j:5");

}
import org.springframework.boot.testcontainers.service.connection.ServiceConnection
import org.testcontainers.containers.MongoDBContainer
import org.testcontainers.containers.Neo4jContainer
import org.testcontainers.junit.jupiter.Container

interface MyContainers {

	companion object {

		@Container
		@ServiceConnection
		@JvmField
		val mongoContainer = MongoDBContainer("mongo:5.0")

		@Container
		@ServiceConnection
		@JvmField
		val neo4jContainer = Neo4jContainer("neo4j:5")

	}

}

如果您已经以这种方式定义了容器,或者您更喜欢这种风格,您可以导入这些声明类,而不是将容器定义为 @Bean 方法。 为此,请在您的测试配置类中添加 @ImportTestcontainers 注解:spring-doc.cadn.net.cn

import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.testcontainers.context.ImportTestcontainers;

@TestConfiguration(proxyBeanMethods = false)
@ImportTestcontainers(MyContainers.class)
public class MyContainersConfiguration {

}
import org.springframework.boot.test.context.TestConfiguration
import org.springframework.boot.testcontainers.context.ImportTestcontainers

@TestConfiguration(proxyBeanMethods = false)
@ImportTestcontainers(MyContainers::class)
class MyContainersConfiguration
如果您不打算使用服务连接功能,但希望改用@DynamicPropertySource,请从Container字段中移除@ServiceConnection注解。 您也可以在声明类中添加带有@DynamicPropertySource注解的方法。

在开发时使用 DevTools 和 Testcontainers

使用 devtools 时,您可以使用 @RestartScope 注解 Bean 和 Bean 方法。 此类 Bean 在 devtools 重启应用程序时不会被重新创建。 这对于 Container Bean 尤其有用,因为尽管应用程序重启,它们仍能保持其状态。spring-doc.cadn.net.cn

import org.testcontainers.containers.MongoDBContainer;

import org.springframework.boot.devtools.restart.RestartScope;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.context.annotation.Bean;

@TestConfiguration(proxyBeanMethods = false)
public class MyContainersConfiguration {

	@Bean
	@RestartScope
	@ServiceConnection
	public MongoDBContainer mongoDbContainer() {
		return new MongoDBContainer("mongo:5.0");
	}

}
import org.springframework.boot.devtools.restart.RestartScope
import org.springframework.boot.test.context.TestConfiguration
import org.springframework.boot.testcontainers.service.connection.ServiceConnection
import org.springframework.context.annotation.Bean
import org.testcontainers.containers.MongoDBContainer

@TestConfiguration(proxyBeanMethods = false)
class MyContainersConfiguration {

	@Bean
	@RestartScope
	@ServiceConnection
	fun mongoDbContainer(): MongoDBContainer {
		return MongoDBContainer("mongo:5.0")
	}

}
如果使用 Gradle 并希望使用此功能,需要将 spring-boot-devtools 依赖项的配置从 developmentOnly 更改为 testAndDevelopmentOnly。 默认情况下,developmentOnly 的作用域会使 bootTestRun 任务不识别代码更改,因为 devtools 处于非活动状态。