gpt4 book ai didi

java - org.springframework.beans.factory.BeanCurrentlyInCreationException : Spring cyclic dependency - constructor Autowiring

转载 作者:行者123 更新时间:2023-11-29 08:36:02 24 4
gpt4 key购买 nike

旧代码:

@Component("someFactory")
public class SomeFactoryImpl implements SomeFactory{

@Autowired
private List<SomeTransformer<?, ?>> someTransformers;

新代码:

@Component("someFactory")
public class SomeFactoryImpl implements SomeFactory {

private List<SomeTransformer<?, ?>> someTransformers;

@Autowired
public SomeFactoryImpl(List<SomeTransformer<?, ?>> someTransformers) {
this.someTransformers = someTransformers;
}

我得到了:

org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'someFactory': Requested bean is currently in creation: Is there an unresolvable circular reference?

Spring 在通过构造函数 Autowiring 时是否有一些问题?

最佳答案

检查 Spring documentation (查找“循环依赖项”)。

Unlike the typical case (with no circular dependencies), a circular dependency between bean A and bean B forces one of the beans to be injected into the other prior to being fully initialized itself (a classic chicken/egg scenario).

区别在于:

Setter 注入(inject) 中,bean 引用只会在需要时才构建。当使用 @Required 注释 setter 时,您可能会重新创建与 setter 注入(inject)相同的问题,因为这将导致立即创建 bean。

构造函数注入(inject)中,Spring 无法决定首先创建哪个 bean,因为它们相互依赖。问题立即暴露。一种可能的解决方法是使用带有 @Lazy 注释的构造函数注入(inject);

@Component
public class CircularClassA {

private CircularClassB classB;

@Autowired
public CircularDependencyB(@Lazy CircularClassB classB) {
this.classB = classB;
}
}

这将只创建 classB 的代理,而不是完全初始化它。它会在需要时完全初始化,就像 setter 注入(inject)一样。

关于java - org.springframework.beans.factory.BeanCurrentlyInCreationException : Spring cyclic dependency - constructor Autowiring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44064165/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com