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

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

启用 Groovy 脚本支持
支持使用 Groovy 脚本加载ApplicationContext在Spring 如果 Groovy 在 Classpath 上,则会自动启用 TestContext Framework。

下面的示例展示了如何指定 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 脚本

您可以使用 这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...
}