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

使用组件类进行上下文配置

要使用组件类(参见基于 Java 的容器配置)为您的测试加载 ../../../core/beans/java.html,您可以使用 @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 指定组件类。
组件类

“组件类”这一术语可以指以下任意一种:spring-doc.cadn.net.cn

  • 一个使用 @Configuration 注解的类。spring-doc.cadn.net.cn

  • 一个组件(即,使用 @Component@Service@Repository 或其他构造型注解标注的类)。spring-doc.cadn.net.cn

  • 一个符合 JSR-330 规范并使用 jakarta.inject 注解进行标注的类。spring-doc.cadn.net.cn

  • 任何包含 @Bean 方法的类。spring-doc.cadn.net.cn

  • 任何其他打算注册为 Spring 组件(即 ApplicationContext 中的 Spring Bean)的类,可能会利用自动装配单一构造函数的功能,而无需使用 Spring 注解。spring-doc.cadn.net.cn

请参阅 @Configuration@Bean 的 Javadoc,以获取有关组件类的配置和语义的更多信息,并特别注意关于 @Bean 轻量模式的讨论。spring-doc.cadn.net.cn

如果您从 @ContextConfiguration 注解中省略 classes 属性, TestContext 框架将尝试检测默认配置类的存在。 具体而言,AnnotationConfigContextLoaderAnnotationConfigWebContextLoader 会检测测试类中所有符合配置类实现要求的 static 内部类, 具体要求参见 @Configuration 的 Javadoc。 请注意,配置类的名称是任意的。此外,如果需要,一个测试类可以包含多个 static 内部配置类。在以下示例中, OrderServiceTest 类声明了一个名为 Configstatic 内部配置类, 该类将自动用于为测试类加载 ApplicationContextspring-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 类中加载配置信息。