Context Configuration with Context Initializers
如需使用上下文初始值设置器为测试配置 ApplicationContext
,请使用 @ContextConfiguration
对测试类进行注释,并使用包含实现 ApplicationContextInitializer
类的引用数组来配置 initializers
属性。然后,声明的上下文初始值设置器用于初始化为测试加载的 ConfigurableApplicationContext
。请注意,每个声明的初始值设置器所支持的具体 ConfigurableApplicationContext
类型必须与由所使用的 SmartContextLoader
创建的 ApplicationContext
的类型兼容(通常为 GenericApplicationContext
)。此外,初始值设置器的调用顺序取决于它们是否实现 Spring 的 Ordered
接口,或用 Spring 的 @Order
注释或标准 @Priority
注释进行注释。以下示例演示了如何使用初始值设置器:
To configure an ApplicationContext
for your tests by using context initializers,
annotate your test class with @ContextConfiguration
and configure the initializers
attribute with an array that contains references to classes that implement
ApplicationContextInitializer
. The declared context initializers are then used to
initialize the ConfigurableApplicationContext
that is loaded for your tests. Note that
the concrete ConfigurableApplicationContext
type supported by each declared initializer
must be compatible with the type of ApplicationContext
created by the
SmartContextLoader
in use (typically a GenericApplicationContext
). Furthermore, the
order in which the initializers are invoked depends on whether they implement Spring’s
Ordered
interface or are annotated with Spring’s @Order
annotation or the standard
@Priority
annotation. The following example shows how to use initializers:
- Java
-
@ExtendWith(SpringExtension.class) // ApplicationContext will be loaded from TestConfig // and initialized by TestAppCtxInitializer @ContextConfiguration( classes = TestConfig.class, initializers = TestAppCtxInitializer.class) (1) class MyTest { // class body... }
1 | Specifying configuration by using a configuration class and an initializer.
|
2 | Specifying configuration by using a configuration class and an initializer. |
你也可以完全省略 @ContextConfiguration
中 XML 配置文件、Groovy 脚本或组件类的声明,只需声明 ApplicationContextInitializer
类,这些类负责在上下文中注册 bean,例如通过以编程方式从 XML 文件或配置文件加载 bean 定义。以下示例演示如何执行此操作:
You can also omit the declaration of XML configuration files, Groovy scripts, or
component classes in @ContextConfiguration
entirely and instead declare only
ApplicationContextInitializer
classes, which are then responsible for registering beans
in the context — for example, by programmatically loading bean definitions from XML
files or configuration classes. The following example shows how to do so:
- Java
-
@ExtendWith(SpringExtension.class) // ApplicationContext will be initialized by EntireAppInitializer // which presumably registers beans in the context @ContextConfiguration(initializers = EntireAppInitializer.class) 1 class MyTest { // class body... }
1 | Specifying configuration by using only an initializer.
|
2 | Specifying configuration by using only an initializer. |