对于最新稳定版本,请使用 Spring Framework 7.0.6spring-doc.cadn.net.cn

使用动态属性源进行上下文配置

从 Spring Framework 5.2.5 起,TestContext 框架通过 @DynamicPropertySource 注解提供了对动态属性的支持。该注解可用于集成测试中,当需要将具有动态值的属性添加到为集成测试所加载的 PropertySourcesEnvironment 中的 ApplicationContext 集合时。spring-doc.cadn.net.cn

@DynamicPropertySource 注解及其配套基础设施最初是为了让基于 Testcontainers 的测试能够轻松地将属性暴露给 Spring 集成测试而设计的。然而,该功能也可用于任何生命周期在测试的 ApplicationContext 之外进行管理的外部资源。spring-doc.cadn.net.cn

与应用于类级别的 @TestPropertySource 注解不同,@DynamicPropertySource 必须应用于一个 static 方法,该方法接受单个 DynamicPropertyRegistry 参数,用于向 Environment 添加名称 - 值对。值是动态的,通过仅在解析属性时调用的 Supplier 提供。通常使用方法引用来提供值,如下例所示,该示例使用 Testcontainers 项目在 Spring ApplicationContext 之外管理 Redis 容器。被管理的 Redis 容器的 IP 地址和端口通过 redis.hostredis.port 属性提供给测试的 ApplicationContext 内的组件。这些属性可以通过 Spring 的 Environment 抽象进行访问,或直接注入到 Spring 管理的组件中——例如,分别通过 @Value("${redis.host}")@Value("${redis.port}")spring-doc.cadn.net.cn

如果您在基类中使用 @DynamicPropertySource,并发现子类中的测试因动态属性在子类之间发生变化而失败,则可能需要使用 @DirtiesContext 注解您的基类,以确保每个子类都获得具有正确动态属性的自有 ApplicationContextspring-doc.cadn.net.cn

@SpringJUnitConfig(/* ... */)
@Testcontainers
class ExampleIntegrationTests {

	@Container
	static GenericContainer redis =
		new GenericContainer("redis:5.0.3-alpine").withExposedPorts(6379);

	@DynamicPropertySource
	static void redisProperties(DynamicPropertyRegistry registry) {
		registry.add("redis.host", redis::getHost);
		registry.add("redis.port", redis::getFirstMappedPort);
	}

	// tests ...

}
@SpringJUnitConfig(/* ... */)
@Testcontainers
class ExampleIntegrationTests {

	companion object {

		@Container
		@JvmStatic
		val redis: GenericContainer =
			GenericContainer("redis:5.0.3-alpine").withExposedPorts(6379)

		@DynamicPropertySource
		@JvmStatic
		fun redisProperties(registry: DynamicPropertyRegistry) {
			registry.add("redis.host", redis::getHost)
			registry.add("redis.port", redis::getFirstMappedPort)
		}
	}

	// tests ...

}

优先级

动态属性的优先级高于通过 @TestPropertySource、操作系统环境变量、Java 系统属性,或通过 @PropertySource 声明式地或以编程方式由应用程序添加的属性源所加载的属性。因此,动态属性可用于有选择地覆盖通过 @TestPropertySource、系统属性源和应用程序属性源加载的属性。spring-doc.cadn.net.cn