开发者

Can I have a reference to a nested bean in Spring?

开发者 https://www.devze.com 2023-02-25 13:24 出处:网络
I want to have a bean of type com.a.A which has several addressable properties of type com.a.B. <bean id=\"myCompound\" class=\"com.a.A\">

I want to have a bean of type com.a.A which has several addressable properties of type com.a.B.

<bean id="myCompound" class="com.a.A">
    <property name="first">
        <bean class="com.a.B"/> <!-- Anything else needed here? -->
    </property>
     <property name="second">
        <bean class="com.a.B"/> <!-- Anything else needed here? -->
    </property>

In addressable I mean, that I would like to be able to have a reference to either one of these nested beans, from another bean:

<bean id="myCollaborator" class="com.a.C">
    <property name="target" ref="myCompound.first"/>
</bean>

This structure doesn't work, and it seems to me that Spring does not resolve compound properties in <ref> elements. Is that so? Can someone think of a way to开发者_StackOverflow社区 work around this?


If I understand your question correctly, then Spring 3.0's EL support provides exactly what you're looking for:

<bean id='one' class  = 'a.b.C.One' >
  <property name='property1' value ='43433' />
</bean>

<bean class = 'a.b.c.Two'>
 <property name = 'property2' value = "#{ one.property1 }"/>
</bean>

and, of course, in Java-style configuration, this is trivial

@Configuration 
public class MyConfiguration {
    @Bean 
    public One one(){ 
     One o = new One();
     o.setProperty1(24324);
     return o;
    }

    @Bean 
    public Two two (){ 
     Two t =new Two();
     t.setProperty2( one().getProperty1());
     return t;
    }
}


Here's a simple workaround.

<bean id="firstB" class="com.a.B"/>
<bean id="secondB" class="com.a.B"/>

<bean id="myCompound" class="com.a.A">
    <property name="first" ref="firstB"/>
    <property name="second" ref="secondB"/>
</bean>

<bean id="myCollaborator" class="com.a.C">
    <property name="target" ref="firstB"/>
</bean>
0

精彩评论

暂无评论...
验证码 换一张
取 消