zoukankan      html  css  js  c++  java
  • the dependencies of some of the beans in the application context form a cycle

    1.1 Bug场景:

    1.1 启动Spring Boot项目时报循环依赖错误:The dependencies of some of the beans in the application context form a cycle


    ┌─────┐
    | userServiceImpl defined in file [D:liyhpro_newdiich-ecologydiich-bizdiich-biz-coreoutproductionclassescomdiichizservicecoreUserServiceImpl.class] ↑ ↓ | favoriteServiceImpl defined in file [D:liyhpro_newdiich-ecologydiich-bizdiich-biz-coreoutproductionclassescomdiichizservicecoreFavoriteServiceImpl.class]
    └─────┘

    1.2 SpringBoot中自定义DataSource数据源时报循环依赖错误:The dependencies of some of the beans in the application context form a cycle

      
    org.springframework.boot.actuate.autoconfigure.jdbc.DataSourceHealthIndicatorAutoConfiguration ┌─────┐
    | dataSource ↑ ↓ | scopedTarget.dataSource defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class] ↑ ↓ | org.springframework.boot.autoconfigure.jdbc.DataSourceInitializerInvoker └─────┘

    2.1 Bug原因:

    以两个对象的相互依赖为例:

    从异常信息可以看出,这是循环依赖问题。这种通常会出现在两个类注入Bean时互相使用了构造函数注入对方。Spring IoC容器在运行时检测到此循环引用就会报错。

    在SpringBoot多模块项目中,两个项目互相引入对方的依赖,就会报这样的错误。

    3.1 解决方法:

    1.在实例变量上使用@Autowired注解,让Spring决定在合适的时机注入,而非在初始化类的时候就注入。

    2.用基于setter方法的依赖注入取代基于构造函数的依赖注入来解决循环依赖。

    3.排除Spring Boot数据源自动配置类

    // 自定义数据源一定要排除SpringBoot自动配置数据源,不然会出现循环引用的问题,The dependencies of some of the beans in the application context form a cycle
    @EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})

    4.在application.properties 文件中加入一行代码  

     spring.datasource.initialize=false

    5.避免两个项目互相引入对方的依赖

  • 相关阅读:
    你拿什么保护我的版权(写在中移动MM商用之前)
    体验Windows Mobile 6.5 (模拟器)
    Mobile Market试用后感受
    制作Windows Mobile程序安装包
    自定义.NET CF控件,美化Windows Mobile程序界面
    记《虞美人盛开的山坡》
    剑风传奇 黄金时代篇1:霸王之卵
    发现IGame中又一个大坑
    【翻译】【西川善司】3D图形的概念和渲染管线(5回完)
    【翻译】西川善司为了3D游戏粉丝的[生化危机5]图形讲座(后篇)
  • 原文地址:https://www.cnblogs.com/liyhbk/p/14230598.html
Copyright © 2011-2022 走看看