boaz shor
boaz shor

Reputation: 299

How to pass a constructor arg of one bean to a nested bean

I have two classes A and B. A holds B as a class field b.

A has two arguments in its constructor : public A(C c, D d){}.

B has two arguments in its constructor : public B(C c, D d){}.

A has a setter for B.

in the spring xml, I defined the Bean B nested inside A :

<bean id="B" class="java.util.B"/>

<bean id="A" class="java.util.A>
   <property name="b" ref="B"/>
</bean>

if I load A as follows:

(A)SpringManager.getInstance().loadBean("A",new Object[] {c,d}) 

(assume that c and d are defined in the class that calles the loadBean function)

How do I pass the args that A got to B's constructor?

Upvotes: 0

Views: 745

Answers (1)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298818

You can't. Either you are in charge or Spring is. What you are doing is wiring objects manually instead of using Spring to manage them. You can't expect Spring to provide magic to enable you to do that.

So you'll have to instantiate B first and then pass it to A:

B b = (B)SpringManager.getInstance().loadBean("B",new Object[] {c,d});
A a = (A)SpringManager.getInstance().loadBean("A",new Object[] {c,d});
a.setB(b);

And quite frankly: if you do it like that, I don't see why you are using Spring in the first place.

Upvotes: 2

Related Questions