user593029
user593029

Reputation: 521

constructor injection with value provided by another bean

I want to pass value to constructor(type string) with value provided by another bean.

Class BeanOne () { BeanOne (String message) { ... } }

Below declaration will work

<bean id="beanOne"
    class="com.abc.BeanOne">
    <constructor-arg index="0" type="java.lang.String"
        value="Hi There" /> // instead of value="Hi There", i want to use bean property (value="someBean.message")
</bean>

However I want another bean (say BeanTwo) to set value for message property for BeanOne. I tried nested property as given below but it does not work. Also message property is not visible directly in the class & is referred internally by another constructor & then by the method so i cannot use property injection& have to use only constructor injection

Upvotes: 3

Views: 4454

Answers (1)

Adam B
Adam B

Reputation: 1774

You can use the MethodInvokingFactoryBean to get your string value and then inject that into your bean.

         <bean id="message" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
            <property name="targetObject"><ref local="someBean"></property>
            <property name="targetMethod"><value>getMessage</value></property>
         </bean>

         <bean id="beanOne"  class="com.abc.BeanOne">
            <constructor-arg index="0" type="java.lang.String" ref="message"/>
         </bean>

Upvotes: 4

Related Questions