对于最新的稳定版本,请使用 Spring Framework 7.0.6!spring-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 value 属性支持 locations 属性的别名功能。因此,如果您不需要在 @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 文件。

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