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

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

要使用采用Groovy Bean 定义 DSL的 Groovy 脚本为您的测试加载../../../core/beans/basics.html#groovy-bean-definition-dsl,您可以使用@ContextConfiguration注解标注您的测试类,并将locationsvalue属性配置为包含 Groovy 脚本资源位置的数组。Groovy 脚本的资源查找语义与XML 配置文件中描述的语义相同。spring-doc.cadn.net.cn

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

以下示例展示了如何指定 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 配置文件的位置。

如果从 locations 注解中同时省略 value@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 脚本

你可以通过使用 locations 注解的 value@ContextConfiguration 属性,同时声明 XML 配置文件和 Groovy 脚本。如果所配置资源路径以 .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...
}