|
对于最新稳定版本,请使用 Spring Framework 7.0.6! |
@ContextConfiguration
@ContextConfiguration 定义了类级别的元数据,用于确定如何为集成测试加载和配置 ApplicationContext。具体来说,@ContextConfiguration 声明了用于加载上下文的应用上下文资源 locations 或组件 classes。
资源位置通常是位于类路径(classpath)中的 XML 配置文件或 Groovy 脚本,而组件类通常是 @Configuration 类。然而,资源位置也可以指向文件系统中的文件和脚本,组件类也可以是 @Component 类、@Service 类等等。更多详细信息,请参见组件类。
以下示例展示了一个引用 XML 文件的 @ContextConfiguration 注解:
-
Java
-
Kotlin
@ContextConfiguration("/test-config.xml") (1)
class XmlApplicationContextTests {
// class body...
}
| 1 | 引用一个 XML 文件。 |
@ContextConfiguration("/test-config.xml") (1)
class XmlApplicationContextTests {
// class body...
}
| 1 | 引用一个 XML 文件。 |
以下示例展示了一个引用类的 @ContextConfiguration 注解:
-
Java
-
Kotlin
@ContextConfiguration(classes = TestConfig.class) (1)
class ConfigClassApplicationContextTests {
// class body...
}
| 1 | 引用一个类。 |
@ContextConfiguration(classes = [TestConfig::class]) (1)
class ConfigClassApplicationContextTests {
// class body...
}
| 1 | 引用一个类。 |
作为声明资源位置或组件类的替代方式或补充方式,您可以使用 @ContextConfiguration 来声明 ApplicationContextInitializer 类。
以下示例展示了这种情况:
-
Java
-
Kotlin
@ContextConfiguration(initializers = CustomContextInitializer.class) (1)
class ContextInitializerTests {
// class body...
}
| 1 | 声明一个初始化器类。 |
@ContextConfiguration(initializers = [CustomContextInitializer::class]) (1)
class ContextInitializerTests {
// class body...
}
| 1 | 声明一个初始化器类。 |
你也可以选择使用 @ContextConfiguration 来声明 ContextLoader 策略。
但请注意,通常你无需显式配置加载器,因为默认的加载器支持 initializers 以及资源 locations 或组件 classes。
以下示例同时使用了位置(location)和加载器(loader):
-
Java
-
Kotlin
@ContextConfiguration(locations = "/test-context.xml", loader = CustomContextLoader.class) (1)
class CustomLoaderXmlApplicationContextTests {
// class body...
}
| 1 | 同时配置一个位置和一个自定义加载器。 |
@ContextConfiguration("/test-context.xml", loader = CustomContextLoader::class) (1)
class CustomLoaderXmlApplicationContextTests {
// class body...
}
| 1 | 同时配置一个位置和一个自定义加载器。 |
@ContextConfiguration 提供了对继承资源位置或配置类以及由超类或外部类声明的上下文初始化器的支持。 |
请参阅 上下文管理、
@Nested 测试类配置,以及 @ContextConfiguration
Javadoc 以获取更多详细信息。