@Configuration
public class Test1 {
@Autowired
private Test3 test3;
}
@Configuration
public class Test2 {
@Autowired
private Test3 test3;
@Bean(name = "test3 ")
Test3 test3 () {
return new Test3();
}
}
上面的代码给出了以下错误。
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'test1': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private Test3 com.package.name.Test1.test3;
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'test2': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private Test3 com.package.name.Test2.test3;
nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'test3': Requested bean is currently in creation: Is there an unresolvable circular reference?
这是一个循环依赖的例子吗?如果是,有任何解决此问题的想法。
最佳答案
您不需要 Autowiring 在同一类中定义的 bean,因为您可以通过调用初始化方法 test3() 直接引用该 bean。
@Configuration
public class Test2{
@Bean(name = "test3 ")
Test3 test3 () {
return new Test3();
}
public void exampleOfUsingTest3Bean() {
System.out.println("My test3 bean is" + test3().toString());
}
}
事实上,您不应该做您想要做的事情,因为 @Autowired 字段在类构造时被注入(inject)到类中,并且此时不存在名为 Test3 的 bean,因为它是由正在构造的类的方法定义的。理论上,您可以将此 @Bean 方法定义为静态,并且它应该可用于 Autowiring ,但您不应该这样做。
@Bean(name = "test3 ")
public static Test3 test3 () {
return new Test3();
}
关于java - 当 @Autowired 和 @Bean 出现在同一个类中时出现 BeanCurrentlyInCreationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49148529/