对于最新的稳定版本,请使用 Spring Framework 6.2.0spring-doc.cadn.net.cn

使用组件类的上下文配置

要加载ApplicationContext对于使用组件类的测试(请参阅基于 Java 的容器配置),您可以对测试 class 替换为@ContextConfiguration并配置classes属性替换为数组 ,其中包含对组件类的引用。以下示例显示了如何执行此作:spring-doc.cadn.net.cn

@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from AppConfig and TestConfig
@ContextConfiguration(classes = {AppConfig.class, TestConfig.class}) (1)
class MyTest {
	// class body...
}
1 指定组件类。
@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from AppConfig and TestConfig
@ContextConfiguration(classes = [AppConfig::class, TestConfig::class]) (1)
class MyTest {
	// class body...
}
1 指定组件类。
组件类

术语 “component class” 可以指以下任何内容:spring-doc.cadn.net.cn

请参阅 javadoc@Configuration@Bean了解更多信息 关于组件类的配置和语义,请特别注意 到讨论@BeanLite 模式。spring-doc.cadn.net.cn

如果省略classes属性@ContextConfigurationannotation、 TestContext 框架尝试检测是否存在默认配置类。 具体说来AnnotationConfigContextLoaderAnnotationConfigWebContextLoader检测全部static满足 configuration 类实现,如@Configurationjavadoc 的 请注意,配置类的名称是任意的。此外,测试类可以 包含多个staticnested configuration 类。在以下 示例中,OrderServiceTestclass 声明一个static嵌套配置类 叫Config,它会自动用于加载ApplicationContext用于测试 类:spring-doc.cadn.net.cn

@SpringJUnitConfig (1)
// ApplicationContext will be loaded from the static nested Config class
class OrderServiceTest {

	@Configuration
	static class Config {

		// this bean will be injected into the OrderServiceTest class
		@Bean
		OrderService orderService() {
			OrderService orderService = new OrderServiceImpl();
			// set properties, etc.
			return orderService;
		}
	}

	@Autowired
	OrderService orderService;

	@Test
	void testOrderService() {
		// test the orderService
	}

}
1 从嵌套的Config类。
@SpringJUnitConfig (1)
// ApplicationContext will be loaded from the nested Config class
class OrderServiceTest {

	@Autowired
	lateinit var orderService: OrderService

	@Configuration
	class Config {

		// this bean will be injected into the OrderServiceTest class
		@Bean
		fun orderService(): OrderService {
			// set properties, etc.
			return OrderServiceImpl()
		}
	}

	@Test
	fun testOrderService() {
		// test the orderService
	}
}
1 从嵌套的Config类。