情况1: No qualifying bean of type […] found for dependency
- 如果在 Spring 上下文中找不到对应的定义,就会抛出 NoSuchBeanDefinitionException(比如没有标注 @ Component,@Repository,@Service, @Controller等注解)
- 所在的包没有被 Spring 扫描到。
情况2: No qualifying bean of type […] is defined
有两个实现类同时实现同一个接口
解决方案:
- 注入的时候加上 @Qualifier("自己定义的名称")
@Component public class personA implements BeanPerson { // } @Component public class personB implements BeanPerson { // } @Component public class TestBean { @Autowired @Qualifier("personA") private BeanPerson beanPerson; }
- 将其中一个 Bean 加上
@Primary
的注解,优先注入加了 Primary 注解的 Bean ,不会抛异常@Component @Primary public class personA implements BeanPerson { // }
情况3: No Bean Named […] is defined
- 从 Spring 上下文中通过名字获取一个 Bean 时抛出
@Component public class BeanPerson implements InitializingBean { @Autowired private ApplicationContext context; @Override public void afterPropertiesSet() { context.getBean("xxxBean"); } }
- 报错如下:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'xxxBean' is defined
情况4: 调用外部服务配置的别名有问题
- alias别名后面多了空格,别名不合法,导致初始化外部依赖服务实例时失败