跳到主要内容

使用组件类配置上下文

DeepSeek V3 中英对照 Context Configuration with Component Classes

要通过使用组件类为测试加载 ApplicationContext(请参阅 基于 Java 的容器配置),您可以使用 @ContextConfiguration 注解您的测试类,并通过包含组件类引用的数组配置 classes 属性。以下示例展示了如何实现这一点:

@ExtendWith(SpringExtension.class)
// ApplicationContext 将会从 AppConfig 和 TestConfig 加载
@ContextConfiguration(classes = {AppConfig.class, TestConfig.class}) 1
class MyTest {
// 类体...
}
java
  • 指定组件类。

提示

组件类

术语“组件类”可以指以下任意一种:

  • 使用 @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

@SpringJUnitConfig 1
// ApplicationContext 将从静态嵌套的 Config 类中加载
class OrderServiceTest {

@Configuration
static class Config {

// 这个 bean 将被注入到 OrderServiceTest 类中
@Bean
OrderService orderService() {
OrderService orderService = new OrderServiceImpl();
// 设置属性等
return orderService;
}
}

@Autowired
OrderService orderService;

@Test
void testOrderService() {
// 测试 orderService
}

}
java
  • 从嵌套的 Config 类加载配置信息。