DEBUG.WIKI
IPPeak:从目标地区访问网页,住宅代理、SEO 监测、广告验证
阿里云;从建站到云上业务;云服务器 · 数据库 · 对象存储;查看产品 →
搬瓦工;先看线路,再选 VPS;CN2 GIA · 对应线路套餐;查看线路 →

解决 Spring Boot 报错 BeanCreationException 依赖注入失败修复

排查 Spring Boot 应用启动抛出 BeanCreationException: Error creating bean with name ... Injection of autowired dependencies failed,排查循环依赖与包扫描。

问题现象

Spring Boot 应用在启动上下文刷新阶段突发崩溃:

org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'orderService': 
Injection of autowired dependencies failed; 
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type 'com.example.repo.OrderRepository' available

触发根因

  1. 包扫描路径不匹配(Package Scan Miss):主应用启动类(带 @SpringBootApplication 注解的类)所在的包路径没有处于被注入类的上层,导致目标 Bean(如 @Repository、@Service)未被 Spring 容器扫描注册;
  2. 两个 Bean 之间存在直接强循环依赖(Circular Dependency),在 Spring Boot 2.6+ 默认禁止循环依赖的配置下引发启动失败;
  3. 多数据源配置下缺少 @Primary 候选标记。

解决步骤

1. 调整启动类目录层级或显式声明 scanBasePackages

确保启动类位于项目代码的最外层根包路径,或者在注解上显式声明扫描包范围:

@SpringBootApplication(scanBasePackages = "com.example")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

2. 解除循环依赖(使用 @Lazy 或重构设计)

若两个服务类存在互相依赖,重构架构提取公用服务,或在注入点添加 @Lazy 注解实现延迟代理加载:

@Service
public class OrderService {
    private final PaymentService paymentService;

    @Autowired
    public OrderService(@Lazy PaymentService paymentService) {
        this.paymentService = paymentService;
    }
}

验证确认

执行单元测试或启动命令:

./mvnw spring-boot:run

控制台打印 Started Application in 2.852 seconds (process running for 3.14),应用容器成功就绪。