java - Using Collections in Spring -
a collection object can created collection object using constructor.
list<student> list = new arraylist<student>(somestudentlist);
which can done in spring.
<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" ....
how can way of adding item in spring?
set<student> set= new treeset<student>(); set.add(new student(5, "mawia")); ...
so can use constructor accept comparator object.
set<student> set= new treeset<student>(new mycomparator()); set.add(new student(5, "mawia")); ...
i suspect simplest approach create trivial subclass of treeset
provides two-argument constructor:
public class mytreeset<t> extends treeset<t> { public mytreeset(comparator<? super t> cmp, collection<? extends t> coll) { super(cmp); addall(coll); } }
and use type of bean, passing both comparator , initial values <constructor-arg>
values.
<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>
or instead of subclass of treeset
write own factorybean
.
to without writing additional code use second bean definition adding
<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>
but other bean inject studentset
needs additional depends-on="studentsetfiller"
make sure set populated before target bean tries use it.
Comments
Post a Comment