此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Framework 6.2.10spring-doc.cadn.net.cn

使用 Groovy 脚本进行上下文配置

要加载ApplicationContext对于使用使用 Groovy Bean 定义 DSL 的 Groovy 脚本进行测试,您可以对 您的测试类使用@ContextConfiguration并配置locationsvalue属性,其中包含 Groovy 脚本的资源位置的数组。资源 Groovy 脚本的查找语义与 XML 配置文件描述的语义相同。spring-doc.cadn.net.cn

启用 Groovy 脚本支持
支持使用 Groovy 脚本加载ApplicationContext在Spring 如果 Groovy 在类路径上,则会自动启用 TestContext 框架。

以下示例显示了如何指定 Groovy 配置文件:spring-doc.cadn.net.cn

@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from "/AppConfig.groovy" and
// "/TestConfig.groovy" in the root of the classpath
@ContextConfiguration({"/AppConfig.groovy", "/TestConfig.Groovy"}) (1)
class MyTest {
	// class body...
}
1 指定 Groovy 配置文件的位置。
@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from "/AppConfig.groovy" and
// "/TestConfig.groovy" in the root of the classpath
@ContextConfiguration("/AppConfig.groovy", "/TestConfig.Groovy") (1)
class MyTest {
	// class body...
}
1 指定 Groovy 配置文件的位置。

如果同时省略locationsvalue属性@ContextConfiguration注释时,TestContext 框架会尝试检测默认的 Groovy 脚本。 具体说来GenericGroovyXmlContextLoaderGenericGroovyXmlWebContextLoader根据测试类的名称检测默认位置。如果您的类名为com.example.MyTest,Groovy 上下文加载器从"classpath:com/example/MyTestContext.groovy".以下示例演示如何使用 默认值:spring-doc.cadn.net.cn

@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from
// "classpath:com/example/MyTestContext.groovy"
@ContextConfiguration (1)
class MyTest {
	// class body...
}
1 从默认位置加载配置。
@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from
// "classpath:com/example/MyTestContext.groovy"
@ContextConfiguration (1)
class MyTest {
	// class body...
}
1 从默认位置加载配置。
同时声明 XML 配置和 Groovy 脚本

您可以使用以下命令同时声明 XML 配置文件和 Groovy 脚本 这locationsvalue属性@ContextConfiguration.如果 配置的资源位置以.xml,则使用XmlBeanDefinitionReader.否则,它将使用GroovyBeanDefinitionReader.spring-doc.cadn.net.cn

以下列表显示了如何在集成测试中组合两者:spring-doc.cadn.net.cn

@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from
// "/app-config.xml" and "/TestConfig.groovy"
@ContextConfiguration({ "/app-config.xml", "/TestConfig.groovy" })
class MyTest {
	// class body...
}
@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from
// "/app-config.xml" and "/TestConfig.groovy"
@ContextConfiguration("/app-config.xml", "/TestConfig.groovy")
class MyTest {
	// class body...
}