|
对于最新的稳定版本,请使用 Spring Framework 6.2.10! |
使用 XML 资源进行上下文配置
要加载ApplicationContext对于使用 XML 配置文件进行的测试,请注释
您的测试类使用@ContextConfiguration并配置locations属性替换为
包含 XML 配置元数据的资源位置的数组。普通或
相对路径(例如context.xml) 被视为类路径资源,即
相对于定义测试类的包。以斜杠开头的路径
被视为绝对类路径位置(例如,/org/example/config.xml).一个
表示资源 URL 的路径(即,以classpath:,file:,http:等)按原样使用。
-
Java
-
Kotlin
@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,您可以省略locations属性名称,并使用简写格式声明资源位置
如以下示例所示:
-
Java
-
Kotlin
@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属性。 |
如果同时省略locations和value属性@ContextConfiguration注释,TestContext 框架会尝试检测默认的
XML 资源位置。具体说来GenericXmlContextLoader和GenericXmlWebContextLoader根据测试名称检测默认位置
类。如果您的类名为com.example.MyTest,GenericXmlContextLoader加载您的
应用程序上下文"classpath:com/example/MyTest-context.xml".以下内容
示例显示了如何执行此作:
-
Java
-
Kotlin
@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 | 从默认位置加载配置。 |