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

使用 XML 资源进行上下文配置

要通过使用 XML 配置文件为您的测试加载 ApplicationContext,请使用 @ContextConfiguration 注解您的测试类,并将 locations 属性配置为一个包含 XML 配置元数据资源位置的数组。普通路径或相对路径(例如 context.xml)被视为相对于定义测试类的包的路径资源。以斜杠开头的路径被视为绝对类路径位置(例如 /org/example/config.xml)。表示资源 URL 的路径(即以 classpath:file:http: 等前缀开头的路径)将原样使用。spring-doc.cadn.net.cn

@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from "/app-config.xml" and
// "/test-config.xml" in the root of the classpath
@ContextConfiguration(locations = {"/app-config.xml", "/test-config.xml"}) (1)
class MyTest {
	// class body...
}
1 将 locations 属性设置为一个 XML 文件列表。
@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from "/app-config.xml" and
// "/test-config.xml" in the root of the classpath
@ContextConfiguration(locations = ["/app-config.xml", "/test-config.xml"]) (1)
class MyTest {
	// class body...
}
1 将 locations 属性设置为一个 XML 文件列表。

@ContextConfiguration 通过标准的 Java locations 属性为 value 属性提供了一个别名。因此,如果你不需要在 @ContextConfiguration 中声明其他属性,就可以省略 locations 属性名的声明,而采用如下示例中所示的简写格式来指定资源位置:spring-doc.cadn.net.cn

@ExtendWith(SpringExtension.class)
@ContextConfiguration({"/app-config.xml", "/test-config.xml"}) (1)
class MyTest {
	// class body...
}
1 在不使用 locations 属性的情况下指定 XML 文件。
@ExtendWith(SpringExtension::class)
@ContextConfiguration("/app-config.xml", "/test-config.xml") (1)
class MyTest {
	// class body...
}
1 在不使用 locations 属性的情况下指定 XML 文件。

如果你在 locations 注解中同时省略了 value@ContextConfiguration 属性,TestContext 框架会尝试自动检测一个默认的 XML 资源位置。具体来说,GenericXmlContextLoaderGenericXmlWebContextLoader 会根据测试类的名称来确定默认位置。例如,如果你的类名为 com.example.MyTest,那么 GenericXmlContextLoader 会从 "classpath:com/example/MyTest-context.xml" 加载你的应用上下文。以下示例展示了如何实现这一点:spring-doc.cadn.net.cn

@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from
// "classpath:com/example/MyTest-context.xml"
@ContextConfiguration (1)
class MyTest {
	// class body...
}
1 从默认位置加载配置。
@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from
// "classpath:com/example/MyTest-context.xml"
@ContextConfiguration (1)
class MyTest {
	// class body...
}
1 从默认位置加载配置。