我想在我的 Spring Boot 应用程序中执行单个服务的集成测试。因此,我只想将此服务及其依赖项添加到测试应用程序上下文中。
假设我在不同的包 A
和 B
中有两个类(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/