|
对于最新的稳定版本,请使用 Spring Framework 6.2.7! |
@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,@Nestedtest 类配置和@ContextConfigurationjavadocs 了解更多详细信息。