Search code examples
javaspringinversion-of-controlspring-bean

Java Spring IOC bean creation value


I need a bean like this

<bean id="studentWithSchool" class="com.model.Student" scope="prototype">       
    <property name="school">
        <bean class="com.model.School" scope="prototype"/>
    </property>
</bean> 

This is OK.

My problem is I have the student returning from a method from a different bean.

I usually load the bean like this when is a property.

<property name='beanProperty' value='#{anotherBean.getBeanProperty()}'/>

But in this case I need the new bean itself being set from the other bean method (School object is returned from another bean method).

This is what I try, and of course this is wrong:

<bean id="studentWithSchool" class="com.model.Student" scope="prototype" value='#{anotherBean.getBeanProperty()}'>      
    <property name="school">
        <bean class="com.model.School" scope="prototype"/>
    </property>
</bean> 

Is there any workaround?


Solution

  • If I understand you correctly, the studentWithSchool is created and returned by a method in anotherBean. If that's the case, you can use a factory-method:

    <bean id="studentWithSchool" factory-bean="anotherBean" factory-method="getBeanProperty" scope="prototype" />