我會建議編寫自己的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的回答。
難道這只是把列表本身的Comp的任務屬性?這是如何幫助用Simple類型的所有bean填充列表本身的? – rudolfson 2009-06-03 07:27:43