let’s say that I have structure like this :

As most you may see it, it’s a composite pattern. How do instantiate this pattern using Spring? For instance, if I have the following code :
<bean id="leaf1">
<constructor-arg name="Name" value="leaf1" />
</bean>
<bean id="leaf2">
<constructor-arg name="Name" value="leaf2" />
</bean>
<bean id="leaf3">
<constructor-arg name="Name" value="leaf3" />
</bean>
<bean id="composite1">
<constructor-arg>
<set>
<ref bean="composite2" />
<ref bean="leaf2" />
</set>
</constructor-arg>
</bean>
<bean id="composite2">
<constructor-arg>
<set>
<ref bean="leaf3" />
<ref bean="leaf1" />
</set>
</constructor-arg>
</bean>
As you may see here, this configuration will raise and org.springframework.beans.factory.BeanCreationException because there is a circular reference. A composite contains a list of Component and a component is composed of Leaf and Composite. How do I solve this problem using Spring?
The answer to this kind of problem is not spring-specific and is the same if you were coding this in straight java using regular constructors.
A simple solution is to allow your composite to be configured using setter injection, so that it breaks the cycle of references needed in construction, but this detracts from the constructor injection idealism. An alternative is to create a subclass of Composite that delegates to another Composite. This will allow you to fill in the actual reference later, although not ideal, you can use the spring @postContstruct method to check that the reference has indeed been set, which providies similar safeguards as using a regular constructor.
There are frameworks that handle this circular constructor case automatigally for you (e.g. nanocontainer) by injecting proxies, but this is really just hiding a design-smell with transient freshener. Ultimately, you need two-stage construction to achieve this – it’s not possible with pure constructors in java, since breaking the dependency cycle requires using a non-constructor initializer.
Writing functional tests for these classes working together may help highlight the design problem from another perspective.