@ContextConfiguration

@ContextConfiguration 定义了类级元数据,用于确定如何为集成测试加载和配置 ApplicationContext。 具体来说,@ContextConfiguration 声明了用于加载上下文的应用程序上下文资源 locations 或组件 classes

资源位置通常是位于类路径中的 XML 配置文件或 Groovy 脚本,而组件类通常是 @Configuration 类。 但是,资源位置也可以引用文件系统中的文件和脚本,组件类可以是 @Component 类、@Service 类等。 有关更多详细信息,请参阅 组件类

以下示例显示了一个引用 XML 文件的 @ContextConfiguration 注解:

  • Java

@ContextConfiguration("/test-config.xml") (1)
class XmlApplicationContextTests {
  // 类体...
}
1 引用 XML 文件。

以下示例显示了一个引用类的 @ContextConfiguration 注解:

  • Java

@ContextConfiguration(classes = TestConfig.class) (1)
class ConfigClassApplicationContextTests {
  // 类体...
}
1 引用类。

作为声明资源位置或组件类的替代或补充,您可以使用 @ContextConfiguration 来声明 ApplicationContextInitializer 类。 以下示例显示了这种情况:

  • Java

@ContextConfiguration(initializers = CustomContextInitializer.class) (1)
class ContextInitializerTests {
  // 类体...
}
1 声明初始化器类。

您还可以选择使用 @ContextConfiguration 来声明 ContextLoader 策略。 但请注意,您通常不需要显式配置加载器,因为默认加载器支持 initializers 以及资源 locations 或组件 classes

以下示例同时使用了位置和加载器:

  • Java

@ContextConfiguration(locations = "/test-context.xml", loader = CustomContextLoader.class) (1)
class CustomLoaderXmlApplicationContextTests {
  // 类体...
}
1 同时配置位置和自定义加载器。
@ContextConfiguration 提供对继承由超类或封闭类声明的资源位置或配置类以及上下文初始化器的支持。

有关更多详细信息,请参阅 上下文管理@Nested 测试类配置@ContextConfiguration javadocs。