使用元件類進行上下文配置

要使用元件類為測試載入 ApplicationContext(參見基於 Java 的容器配置),你可以使用 @ContextConfiguration 註解測試類,並透過一個包含元件類引用的陣列配置其 classes 屬性。以下示例展示瞭如何實現:

  • Java

  • Kotlin

@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 指定元件類。
元件類

“元件類”一詞可以指代以下任何一種:

  • 使用 @Configuration 註解的類。

  • 一個元件(即,使用 @Component, @Service, @Repository 或其他原型註解註解的類)。

  • 一個符合 JSR-330 標準、使用 jakarta.inject 註解註解的類。

  • 任何包含 @Bean 方法的類。

  • 任何其他旨在註冊為 Spring 元件(即,ApplicationContext 中的 Spring bean)的類,該類可能利用了單個建構函式的自動裝配,即使未使用 Spring 註解。

有關元件類的配置和語義的更多資訊,請參見 @Configuration@Bean 的 javadoc,特別注意關於 @Bean Lite 模式的討論。

如果省略 @ContextConfiguration 註解中的 classes 屬性,TestContext 框架會嘗試檢測預設配置類的存在。具體來說,AnnotationConfigContextLoaderAnnotationConfigWebContextLoader 會檢測測試類的所有 static 巢狀類,這些巢狀類符合 @Configuration javadoc 中指定的配置類實現要求。請注意,配置類的名稱是任意的。此外,如果需要,一個測試類可以包含多個 static 巢狀配置類。在以下示例中,OrderServiceTest 類聲明瞭一個名為 Configstatic 巢狀配置類,該類會自動用於為測試類載入 ApplicationContext

  • Java

  • Kotlin

@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 類載入配置資訊。