Error creating bean with name 'XXX': Bean with name 'senseOneToSomeFeignImpl' has been injected into other beans [XXXXXX] in its raw version as part of a circular reference

关于Spring框架中的循环依赖问题,您可以尝试以下几种方法来解决:

  1. 重新定义Bean依赖:重构代码以消除循环依赖。这可能涉及重新设计类,使它们不相互依赖即可运行。
  2. 使用Setter注入:与构造函数注入相比,使用setter注入。Spring可以更好地处理setter注入的循环依赖,因为对象引用是在对象构造之后设置的。
  3. 实现InitializingBean接口:如果您需要在所有依赖项注入后执行初始化,可以让您的bean实现InitializingBean接口,并重写afterPropertiesSet()方法。
  4. 延迟初始化:将其中一个bean标记为延迟。这意味着该bean将在首次访问时才初始化,而不是在启动时。
  5. 使用@PostConstruct注解:对于需要在依赖注入完成后执行的方法,使用@PostConstruct注解进行任何初始化。

在Spring框架中设置延迟初始化,您可以通过以下几种方法:

在Spring框架中设置延迟初始化,您可以通过以下几种方法:

  1. 全局延迟初始化:

    • application.yml配置文件中设置:
      spring:
        main:
          lazy-initialization: true
      
    • 或者,在application.properties文件中设置:
      spring.main.lazy-initialization=true
      
  2. 局部延迟初始化:

    • 在需要延迟初始化的@Component类上添加@Lazy注解:
      @Lazy
      @Component
      public class YourClass {
        // ...
      }
      
    • @Configuration类中配置@Bean时添加@Lazy注解:
      @Configuration
      public class YourConfig {
        @Lazy
        @Bean
        public YourClass yourClass() {
          return new YourClass();
        }
        // ...
      }
      
    • 使用@ComponentScan配置时,设置lazyInittrue
      @ComponentScan(value = "your.package", lazyInit = true)
      @Configuration
      public class YourConfig {
        // ...
      }
      
    • 在XML配置文件中,直接在<bean>标签上设置lazy-init属性为true
      <bean id="yourBean" class="your.package.YourClass" lazy-init="true"/>
      

选择适合您应用程序需求的方法进行配置。如果您有任何疑问或需要进一步的帮助,请随时告诉我。🌟

(1) Spring Boot 2中的延迟初始化 - CSDN博客. https://blog.csdn.net/niugang0920/article/details/116696506.
(2) Spring--延迟加载(@Lazy注解等)--使用/原理-CSDN博客. https://blog.csdn.net/feiying0canglang/article/details/120468261.
(3) springboot延迟加载 - 掘金. https://juejin.cn/post/7114861324164661284.
(4) spring3: 延迟初始化Bean - 穆晟铭 - 博客园. https://www.cnblogs.com/achengmu/p/8422174.html.

posted @ 2024-02-29 13:46  好奇成传奇  阅读(239)  评论(0编辑  收藏  举报