首页 > 解决方案 > ComponentScan 代码有异味?运行单元测试时,我得到 Error created bean, no qualifying bean of type,即使 bean 存在于 Spring beans 列表中

问题描述

我在配置包中有一个配置类,如下所示:

package com.x.y.appName.config

@ComponentScan(basePackageClasses = { Application.class })
@Configuration
public class AppConfig {

我的项目在使用 AppConfig bean 的 SomeClass 中构建失败,说:

Error creating bean with name 'someClass': Unsatisfied dependency 
expressed through field 'appConfig'; nested exception is 
org.springframework.beans.factory.NoSuchBeanDefinitionException: No 
qualifying bean of type

但是当我 stdout 打印 Spring 知道的 bean 列表时,它会在那里列出 appConfig

SomeClass 也在 config 包中,如下所示:

package com.x.y.appName.config;

@Configuration
public class SomeClass implements WebMvcConfigurer {

@Autowired
AppConfig appConfig;

但是如果我将它添加到 SomeClass 中,它构建得很好并且所有测试都通过了:

@ComponentScan("com.x.y.appName.config")

在过去,我从来不需要 ComponentScan 同一个包,另一个 bean 也在其中声明

再次澄清一下,我可以很好地启动应用程序,但是这个弹簧错误是在构建或测试期间抛出的。我需要在单元测试中添加一些东西吗?我没有对上述任何一个类进行单元测试,因为它们太轻浮了。那么可能会发生什么?我需要在某处注释其他单元测试吗?

标签: javaspringspring-bootgradle

解决方案


推荐阅读