tags:

views:

16

answers:

2

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> 
+1  A: 

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> 
axtavt
Thanks, worked like a charm! I was not aware of the expression language syntax.
wolfcastle
A: 

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"&gt;

...

<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>
gpeche
I added the util namespace, but still got parse exceptions on the file.
wolfcastle
Which version of Spring are you using? This is for Spring 2.x
gpeche
ah, I'm using Spring 3.x
wolfcastle