2009-06-03 47 views
10

我有以下XML配置:如何使用Spring XML配置來設置具有某種類型的所有bean的列表的bean屬性?

<bean id="bean1" class="Simple"/> 
<bean id="bean2" class="Simple"/> 

<bean id="tasks" class="java.util.ArrayList"> 
    <constructor-arg> 
     <list> 
      <ref bean="bean1" /> 
      <ref bean="bean2" />     
     </list> 
    </constructor-arg> 
</bean> 

<bean id="list" class="Comp"> 
    <property name="tasks" ref="tasks"/> 
</bean> 

的「任務」中包含的簡單類型的所有豆類。這個問題是我可能忘記添加一個簡單的bean,我已經配置到列表中。

我能做到這一點編程方式使用

Map map = context.getBeansOfType(Simple.class); 

,並設置列表豆與檢索到的豆。

是否有任何方式使用XML配置來做到這一點?

回答

8

你的環境文件,應該是這樣的:

<bean id="bean1" class="Simple"/> 
<bean id="bean2" class="Simple"/> 

<bean id="list" class="Comp" autowire="byType"/> 

注意autowire="byType"此外,和the autowiring documentation

+0

難道這只是把列表本身的Comp的任務屬性?這是如何幫助用Simple類型的所有bean填充列表本身的? – rudolfson 2009-06-03 07:27:43

3

我會建議編寫自己的FactoryBean來創建這樣一個列表。這將是可重用的,然後僅使用XML進行配置。該FactoryBean看起來像

import java.util.ArrayList; 
import java.util.List; 

import org.springframework.beans.factory.FactoryBean; 
import org.springframework.context.ApplicationContext; 
import org.springframework.context.ApplicationContextAware; 
import org.springframework.util.Assert; 

public class CollectingListFactoryBean implements FactoryBean, ApplicationContextAware { 
    private ApplicationContext appCtx; 
    private Class type; 

    public Object getObject() { 
     Assert.notNull(type, "type must be initialized"); 
     List result = new ArrayList(); 
     result.addAll(appCtx.getBeansOfType(type).values()); 
     return result; 
    } 

    public Class getObjectType() { 
     return List.class; 
    } 

    public boolean isSingleton() { 
     return false; 
    } 

    public void setApplicationContext(ApplicationContext applicationContext) { 
     this.appCtx = applicationContext; 
    } 

    public void setType(Class type) { 
     this.type = type; 
    } 
} 

那麼你的XML配置將

<bean id="bean1" class="Simple"/> 
<bean id="bean2" class="Simple"/> 

<bean id="tasks" class="CollectingListFactoryBean"> 
    <property name="type" value="Simple" /> 
</bean> 

<bean id="list" class="Comp"> 
    <property name="tasks" ref="tasks"/> 
</bean> 

注:我沒有測試上面的例子中的時間。我只是使用我已有的代碼作爲模板。 ;)特別是我不確定type屬性是以Class作爲Class參數通過Simple這種方式工作的。試試吧。在最壞的情況下,您必須使用String作爲房產類型,並使用Class.forName(type)來獲得您的課程。但我的猜測是,Spring爲你做了這個轉變。

編輯即使這個解決方案應該工作,我推薦Robert Munteanu的回答。

相關問題