2011-04-12 97 views
1

我想有型com.a.A具有型com.a.B的幾個尋址性質的豆。我可以在Spring中引用一個嵌套的bean嗎?

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

尋址我的意思是,我希望能有一個參考到這些嵌套豆之一,從另一個bean:

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

這種結構不起作用,並且在我看來,Spring不能解析<ref>元素中的化合物屬性。是這樣嗎?有人可以想辦法解決這個問題嗎?

+0

難道你不能給'''指定顯式的'id'並在'myCollaborator'中使用它們嗎?或者甚至更好,在外部定義'' – 2011-04-12 14:02:36

+0

@tomasz:我需要的是讓內部bean代表'com.a.A'的**內部類**。根據@jb的建議,定義一個頂層Bean引發嵌套bean的想法是有效的:我使用'factory-bean =「myCompound」factory-method =「getFirst」'定義了一個頂級bean來獲取引用內部bean。 – Oded 2011-04-13 07:16:32

回答

0

下面是一個簡單的解決方法。

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

如果我正確理解你的問題,那麼Spring 3.0的EL支持提供你在尋找什麼:

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

,當然,在Java風格的配置,這是微不足道

@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; 
    } 
} 
相關問題