此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Framework 6.2.10! |
@ContextConfiguration
@ContextConfiguration
是一个注解,可以应用于测试类以配置元数据,用于确定如何加载和配置ApplicationContext
为 集成测试。 具体说来@ContextConfiguration
声明应用程序上下文 资源locations
或组件classes
用于加载上下文。
资源位置通常是位于类路径中的 XML 配置文件或 Groovy 脚本,而组件类通常是@Configuration
类。 然而 资源位置也可以引用文件系统中的文件和脚本,组件类可以是@Component
类@Service
类,依此类推。有关更多详细信息,请参阅组件类。
以下示例显示了@ContextConfiguration
引用 XML 的注释 文件:
-
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
.
以下示例同时使用位置和加载器:
-
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
javadocs 了解更多详情。