wolfcastle
wolfcastle

Reputation: 5930

How to construct a bean using nested properties in applicationContext.xml?

I have Java classes like this:

public class Config {
    public Config1 getConfigOpt1();
    public Config2 getConfigOpt2();
}

public class SomeBean {
    public Config getEntireConfig();
}

public class BeanToConstruct {

    public static BeanToConstruct createAndStart( Config1 config1, Config2 config2 )
}

Given SomeBean, I would construct BeanToConstruct like this:

SomeBean someBean = ....
BeanToConstruct bean = BeanToConstruct.createAndStart( 
    someBean.getEntireConfig().getConfigOpt1(),
    someBean.getEntireConfig().getConfigOpt2() )

How can I do this inside my applicationContext.xml? This is basically what I want to do, but it obviously doesn't work. I could pull the entire Config object out into its own bean, but I don't want to have this extra bean around that is really only needed to make constructing BeanToConstruct possible.

<bean class="com.example.SomeBean" id="someBean"/>
<bean class="com.example.BeanToConstruct" factory-method="createAndStart" id="myBean">
    <constructor-arg>
        <bean factory-bean="someBean" factory-method="getEntireConfig().getConfigOpt1()"/>
    </constructor-arg>
    <constructor-arg>
        <bean factory-bean="someBean" factory-method="getEntireConfig().getConfigOpt2()"/>
    </constructor-arg>
</bean> 

Upvotes: 1

Views: 3003

Answers (2)

gpeche
gpeche

Reputation: 22514

I think you can use util:property-path for this:

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:util="http://www.springframework.org/schema/util"
   xsi:schemaLocation="
   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
   http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd">

...

<bean class="com.example.SomeBean" id="someBean"/>
<bean class="com.example.BeanToConstruct" factory-method="createAndStart" id="myBean">
    <constructor-arg>
        <util:property-path path="someBean.entireConfig.configOpt1"/>
    </constructor-arg>
    <constructor-arg>
        <util:property-path path="someBean.entireConfig.configOpt2"/>
    </constructor-arg>
</bean>

....
</beans>

Upvotes: 1

axtavt
axtavt

Reputation: 242686

In Spring 3.x you may use expression language:

<bean class="com.example.BeanToConstruct" factory-method="createAndStart" id="myBean"> 
    <constructor-arg value = "#{someBean.entireConfig.configOpt1}" /> 
    <constructor-arg value = "#{someBean.entireConfig.configOpt2}" /> 
</bean> 

Upvotes: 2

Related Questions