此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.2.0! |
@ContextConfiguration
@ContextConfiguration
定义用于确定如何
加载并配置ApplicationContext
用于集成测试。具体说来@ContextConfiguration
声明应用程序上下文资源locations
或
元件classes
用于加载上下文。
资源位置通常是 XML 配置文件或位于
classpath 的@Configuration
类。然而
资源位置还可以引用文件系统和组件中的文件和脚本
类可以是@Component
类@Service
类,依此类推。有关更多详细信息,请参阅 Component Classes 。
以下示例显示了@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
策略设置为
井。但请注意,您通常不需要显式配置 loader,
由于默认 loader 支持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 提供对继承资源位置的支持,或者
配置类以及由超类声明的上下文初始化器
或封闭类。 |
请参阅 Context Management,@Nested
test 类配置和@ContextConfiguration
javadocs 了解更多详细信息。