[英]How to define a bean for an (non-static) inner class in Spring? Avoiding circular dependency
I am having a class with an inner class like this: 我有一个这样的内部类的类:
package myPackage;
public class A {
private B b;
public void setB(B b) { this.b = b; }
public B getB() { return this.b; }
public class B {
}
}
And I have my spring configuration as follow: 我的弹簧配置如下:
<bean id="a" class="myPackage.A" autowire="byName" scope="prototype">
<property name="b">
<bean class="myPackage.A$B" name="b" autowire="byName" scope="prototype">
<constructor-arg ref="a"/>
</bean>
</property>
</bean>
But I am facing this error: 但是我面临着这个错误:
org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'a': Requested bean is currently in creation: Is there an unresolvable circular reference?
Of course it is obvious that I am having a circular reference, but how can I have a spring bean for my inner class? 当然,很明显,我有一个循环引用,但是如何为内部类提供一个spring bean?
I'm not sure this can be resolved at the Spring level if you need a
to be scoped as prototype. 我不确定这是否可以在Spring级别解决,如果您需要将
a
作为原型进行范围划分。 The issue is that you're trying to create an instance of a
, which requires a reference to a b
, which in turn is referencing a different instance of a
(because prototype gives you a new instance every time you inject the bean), and so on. 问题是,你想创建的实例
a
,这需要一个参考b
,而这又是引用的不同实例a
(你注入豆,因为原型为您提供了一个新的实例每次),和以此类推。 If what you really want is for the a
to be a prototype bean containing a b
that refers to the same enclosing instance of a
then you'll have to use Java config or a factory bean. 如果你真正想要的是针对
a
是包含一个原型的bean b
是指同一类实例a
,那么你将不得不使用Java配置或工厂bean。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.