@ContextConfiguration

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

资源位置通常是位于类路径中的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

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

  • 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。