可以使用构造函数从另一个集合对象创建一个集合对象。
List<Student> list = new ArrayList<Student>(someStudentList);
这可以在 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"
....
在Spring中如何实现这种添加item的方式?
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"));
...
最佳答案
我怀疑最简单的方法是创建一个 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>
然后是你注入(inject) studentSet
的任何其他 bean需要额外的 depends-on="studentSetFiller"
以确保在目标 bean 尝试使用它之前填充该集合。
关于java - 在 Spring 中使用集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15832438/