org.springframework.beans.factory.UnsatisfiedDependencyException

问题描述 投票:0回答:1

我的环境出现异常,但我的服务在本地运行良好。

org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为“portfolioCommonServiceImpl”的bean时出错:通过字段“portfolioFolderDao”表达的依赖关系不满足;嵌套异常是 org.springframework.beans.factory.BeanCurrentlyInCreationException:创建名称为“portfolioFolderDaoImpl”的 bean 时出错:名称为“portfolioFolderDaoImpl”的 Bean 已作为循环引用的一部分注入其原始版本中的其他 bean [portfolioServiceImpl],但已注入最终被包裹。这意味着所述其他 bean 不使用该 bean 的最终版本。这通常是过度渴望类型匹配的结果 - 例如,考虑使用“getBeanNamesForType”并关闭“allowEagerInit”标志。

尝试在

@Lazy
上应用
portfolioFolderDao
但还是一样。

java spring google-cloud-platform
1个回答
0
投票

有很多方法可以解决这个问题。但是,您可以尝试使用以下一些解决方法通过循环依赖来解决此问题:

  1. 我知道您已将 @Lazy 应用于您的配置类。作为参考,我们需要确定哪个 @Autowired 属性是循环依赖的原因并破坏应用程序。
@Autowired 
private SampleService sampleService;

一旦确定,请在 @Autowired 注释之上使用 @Lazy。

@Lazy
@Autowired
private SampleService sampleService;
  1. 确保应用程序与扫描包放置在同一目录中。链接:

    https://docs.spring.io/spring-boot/docs/1.5.22.RELEASE/reference/html/using-boot-structuring-your-code.html#using-boot- located-the-main-班级

    package com.example.parent.customer 
    
    @SpringBootApplication(scanBasePackages={"com.example.parent"}) 
    public class SpringBootApp { 
    //main method 
    }
    
    
  2. 确保您使用受支持的依赖项版本,因为 Spring boot 2.4 中已弃用了某些类、方法和属性。你可以在这里找到它:

    https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.6-Release-Notes#circular-references-prohibited-by-default

  3. 查看这篇文章,其中介绍了 Spring Boot 中 BeanCreationException 异常的常见原因及其解决方案。链接:https://www.javaguides.net/2023/08/beancreationexception-in-spring-boot.html

  4. 您可以尝试通过引入第三个 Bean 或重新配置 Bean 来避免循环引用,从而打破循环引用。链接:https://www.springcloud.io/post/2022-08/async-circular-dependency/#gsc.tab=0

  5. 我发现这篇文章(https://www.baeldung.com/circular-dependency-in-spring)讨论了使用 Spring 创建 Bean 的 Setter/Field Injection 来帮助解决 Spring 中的循环依赖,但是依赖关系直到需要它们时才会注入,而@PostConstruct是打破循环的另一种方法,方法是在其中一个bean上使用@Autowired注入依赖项,然后使用用@PostConstruct注释的方法来设置另一个依赖项。

使用 Setter/字段注入

@Autowired
    ApplicationContext context;

    @Bean
    public CircularDependencyA getCircularDependencyA() {
        return new CircularDependencyA();
    }

    @Bean
    public CircularDependencyB getCircularDependencyB() {
        return new CircularDependencyB();
    }

    @Test
    public void givenCircularDependency_whenSetterInjection_thenItWorks() {
        CircularDependencyA circA = context.getBean(CircularDependencyA.class);

        Assert.assertEquals("Hi!", circA.getCircB().getMessage());
   }
}

使用@PostConstruct

@Autowired
    private CircularDependencyB circB;

    @PostConstruct
    public void init() {
        circB.setCircA(this);

另外,请查看这些可以帮助通过循环引用解决您的问题的答案:

如果这些解决方法都不能解决您的问题,请告诉我并分享您的配置类。

© www.soinside.com 2019 - 2024. All rights reserved.