如何在applicationContext.xml中使用嵌套属性构造bean?

时间:2010-09-17 18:39:39

标签: java spring

我有这样的Java类:

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 )
}

鉴于SomeBean,我会像这样构建BeanToConstruct:

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

我如何在applicationContext.xml中执行此操作?这基本上就是我想要做的,但它显然不起作用。我可以把整个Config对象拉到自己的bean中,但是我不希望有这个额外的bean,只需要构建BeanToConstruct就可以了。

<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> 

2 个答案:

答案 0 :(得分:2)

在Spring 3.x中,您可以使用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> 

答案 1 :(得分:1)

我认为您可以使用util:property-path:

<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>