每个都为测试实例提供上下文管理和缓存支持 它负责。测试实例不会自动接收对 配置。但是,如果测试类实现接口,则会提供对 到测试实例。请注意,并实现,因此, 自动提供对 的访问。TestContextApplicationContextApplicationContextAwareApplicationContextAbstractJUnit4SpringContextTestsAbstractTestNGSpringContextTestsApplicationContextAwareApplicationContextSpring中文文档

@Autowired ApplicationContext

作为实现接口的替代方法,您可以注入 测试类的应用程序上下文,通过对任一的注释 字段或 setter 方法,如以下示例所示:ApplicationContextAware@AutowiredSpring中文文档

@SpringJUnitConfig
class MyTest {

	@Autowired (1)
	ApplicationContext applicationContext;

	// class body...
}
1 注入 .ApplicationContext
@SpringJUnitConfig
class MyTest {

	@Autowired (1)
	lateinit var applicationContext: ApplicationContext

	// class body...
}
1 注入 .ApplicationContext

同样,如果您的测试配置为加载 ,则可以注入 将 Web 应用程序上下文添加到测试中,如下所示:WebApplicationContextSpring中文文档

@SpringJUnitWebConfig (1)
class MyWebAppTest {

	@Autowired (2)
	WebApplicationContext wac;

	// class body...
}
1 配置 .WebApplicationContext
2 注入 .WebApplicationContext
@SpringJUnitWebConfig (1)
class MyWebAppTest {

	@Autowired (2)
	lateinit var wac: WebApplicationContext
	// class body...
}
1 配置 .WebApplicationContext
2 注入 .WebApplicationContext

依赖注入由 提供 ,默认配置 (请参阅测试夹具的依赖注入)。@AutowiredDependencyInjectionTestExecutionListenerSpring中文文档

@Autowired ApplicationContext

作为实现接口的替代方法,您可以注入 测试类的应用程序上下文,通过对任一的注释 字段或 setter 方法,如以下示例所示:ApplicationContextAware@AutowiredSpring中文文档

@SpringJUnitConfig
class MyTest {

	@Autowired (1)
	ApplicationContext applicationContext;

	// class body...
}
1 注入 .ApplicationContext
@SpringJUnitConfig
class MyTest {

	@Autowired (1)
	lateinit var applicationContext: ApplicationContext

	// class body...
}
1 注入 .ApplicationContext

同样,如果您的测试配置为加载 ,则可以注入 将 Web 应用程序上下文添加到测试中,如下所示:WebApplicationContextSpring中文文档

@SpringJUnitWebConfig (1)
class MyWebAppTest {

	@Autowired (2)
	WebApplicationContext wac;

	// class body...
}
1 配置 .WebApplicationContext
2 注入 .WebApplicationContext
@SpringJUnitWebConfig (1)
class MyWebAppTest {

	@Autowired (2)
	lateinit var wac: WebApplicationContext
	// class body...
}
1 配置 .WebApplicationContext
2 注入 .WebApplicationContext

依赖注入由 提供 ,默认配置 (请参阅测试夹具的依赖注入)。@AutowiredDependencyInjectionTestExecutionListenerSpring中文文档

1 注入 .ApplicationContext
1 注入 .ApplicationContext
1 配置 .WebApplicationContext
2 注入 .WebApplicationContext
1 配置 .WebApplicationContext
2 注入 .WebApplicationContext

使用 TestContext 框架的测试类不需要扩展任何特定的 类或实现特定接口来配置其应用程序上下文。相反 配置是通过在 班级水平。如果测试类未显式声明应用程序上下文资源 位置或组件类,配置决定了如何加载一个 来自默认位置或默认配置类的上下文。除了上下文 资源位置和组件类,也可以配置应用程序上下文 通过应用程序上下文初始值设定项。@ContextConfigurationContextLoaderSpring中文文档

以下各节解释了如何使用 Spring 的注解来执行以下操作 使用 XML 配置文件、Groovy 脚本配置测试、 组件类(通常是类)或上下文初始值设定项。 或者,您可以实现和配置自己的自定义 高级用例。@ContextConfigurationApplicationContext@ConfigurationSmartContextLoaderSpring中文文档