java - 是否可以在上下文配置中指定一个 @Component 类,以便自动解析它的依赖项?

标签 java spring spring-boot spring-test

我想在我的 Spring Boot 应用程序中执行单个服务的集成测试。因此,我只想将此服务及其依赖项添加到测试应用程序上下文中。

假设我在不同的包 AB 中有两个类(A 有对 B 的引用)用@Component注释标记。当我运行应用程序时,@SpringBootApplication 会找到我的所有 bean,并使用隐式 @ComponentScan 将它们添加到上下文中。

在我的测试配置中,我只想指定一个类 A 并让 Spring Boot 解析它的依赖项 (B) 并将其添加到上下文中。

是否可以使用 Spring Boot 2 或者最适合我的选项来创建一个单独的 @Configuration 并显式声明所需的类? (实际上不止2个,所以我才问)

最佳答案

In my test configuration I would like to specify only one class A and make Spring Boot to resolve it's dependencies (B) and add it to the context.

不,不幸的是这是不可能的,因为 Spring 不知道如何找到依赖项和/或您实际想要的具体类型。

Is it possible with Spring Boot 2 or the most suitable option for me would to create a separate @Configuration with required classes declared explicitly?

是的,您可以声明一个专门用于此目的的专用测试@Configuration类;但是,您可能会发现在测试类中简单地重用一组通用配置类更有益,以便从Spring TestContext Framework中的上下文缓存支持中受益。

关于java - 是否可以在上下文配置中指定一个 @Component 类,以便自动解析它的依赖项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47612321/

相关文章:

java - Spring MVC 之前的 JSP 和 servlet

Java - Hibernate 一个类可以引用多个类之一

java - 出现 "No services have been found."错误

spring - 使用spring-boot-starter-data-redis时,驱逐策略如何设置? LFU 或 LRU 等?

java - 无法创建类 org.apache.logging.log4j.core.impl.Log4jContextFactory

java - 实体的某些属性需要全文搜索,而其他属性则不需要

java - java中延迟后调用特定函数

java - spring-data-redis 1.7.2 注入(inject) redisTemplate 失败

java - MetadataGenerator 中的动态 entityBaseUrl

java - 表 'acme_ms.hibernate_sequence' 不存在