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

使用 XML 资源的上下文配置

要加载ApplicationContext对于使用 XML 配置文件的测试,请注释 你的 test 类替换为@ContextConfiguration并配置locations属性替换为 一个包含 XML 配置元数据的资源位置的数组。普通或 相对路径(例如,context.xml) 被视为类路径资源,即 相对于定义测试类的 package。以斜杠开头的路径 被视为绝对 Classpath 位置(例如/org/example/config.xml).一个 path 表示资源 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支持locations属性通过 标准 Javavalue属性。因此,如果您不需要声明额外的 属性@ContextConfiguration,您可以省略locationsattribute name 并使用简写格式声明资源位置 以下示例演示:spring-doc.cadn.net.cn

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

如果同时省略locationsvalue属性@ContextConfiguration注解中,TestContext 框架会尝试检测默认的 XML 资源位置。具体说来GenericXmlContextLoaderGenericXmlWebContextLoader根据测试名称检测默认位置 类。如果您的类名为com.example.MyTest,GenericXmlContextLoader加载您的 application context from"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 从默认位置加载配置。