2013-04-05 51 views
3

可以使用構造函數從另一個集合對象創建集合對象。在Spring中使用集合

List<Student> list = new ArrayList<Student>(someStudentList); 

這可以在春季完成。

 <bean id="stdArrayList" class="java.util.ArrayList"> 
     <constructor-arg > 
      <list> 
       <ref bean="student1" /> 
       <ref bean="student2" /> 
       <ref bean="student3" /> 
      </list> 
     </constructor-arg> 
    </bean> 
    <bean id="student1" class="mawia.test.Student" 
    .... 

如何在春季添加項目?

Set<Student> set= new TreeSet<Student>(); 
     set.add(new Student(5, "Mawia")); 
     ... 

這樣我就可以使用接受比較對象的構造函數。

Set<Student> set= new TreeSet<Student>(new MyComparator()); 
     set.add(new Student(5, "Mawia")); 
     ... 

回答

4

我懷疑最簡單的方法是創建的TreeSet一個微不足道的子類,它提供了兩個參數的構造:

public class MyTreeSet<T> extends TreeSet<T> { 
    public MyTreeSet(Comparator<? super T> cmp, Collection<? extends T> coll) { 
    super(cmp); 
    addAll(coll); 
    } 
} 

,並以此作爲你的bean的類型,通過二者的比較和初始值爲<constructor-arg>值。或

<bean id="studentSet" class="com.example.MyTreeSet"> 
    <constructor-arg index="0"> 
    <bean class="com.example.MyComparator" /> 
    </constructor-arg> 
    <constructor-arg index="1"> 
    <list> 
     <ref bean="student1" /> 
     <ref bean="student2" /> 
     <ref bean="student3" /> 
    </list> 
    </constructor-arg> 
</bean> 

,而不是TreeSet一個子類,你可以寫你自己的FactoryBean

要做到這一點,而無需編寫任何額外的代碼,你可以使用第二個bean定義做加法

<bean id="studentSet" class="java.util.TreeSet"> 
    <constructor-arg> 
    <bean class="com.example.MyComparator" /> 
    </constructor-arg> 
</bean> 

<bean id="studentSetFiller" factory-bean="studentSet" factory-method="addAll"> 
    <constructor-arg> 
    <list> 
     <ref bean="student1" /> 
     <ref bean="student2" /> 
     <ref bean="student3" /> 
    </list> 
    </constructor-arg> 
</bean> 

但你注入studentSet成任何其他bean需要一個額外的depends-on="studentSetFiller"以確保集在目標bean嘗試使用它之前填充。

+0

太棒了!非常感謝。 – Mawia 2013-04-05 11:49:42

1

你也許可以使用這樣的util模式來做到這一點;

<util:set id="emails" set-class="java.util.TreeSet"> 
    <value>[email protected]</value> 
    <value>[email protected]</value> 
    <value>[email protected]</value> 
    <value>[email protected]</value> 
</util:set> 

(從http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/xsd-config.html#xsd-config-body-schemas-util-set拍攝)

我將測試如果可以添加構造函數指定參數和確認。

0

TreeSet不提供組合構造函數來傳遞Comparator以及數據。所以我想你只能通過注射器做一個。

其他部分你應該嘗試通過屬性注入,如果它的暴露。