在Spring中初始化对象数组

时间:2015-10-17 07:21:12

标签: java arrays spring object

Student.java

package org.manan.student;

public class Student {
    String stName;
    int stId;

public String getStName() {
    return stName;
}
public void setStName(String stName) {
    this.stName = stName;
}
public int getStId() {
    return stId;
}
public void setStId(int stId) {
    this.stId = stId;
}}

MainApplication.java

public static void main(String[] args) {
    Student[] student = new Student[3];

    for(int i = 0; i < student.length; i++) {
        student[i] = new Student();
    }

}

现在我的问题是,如何在beans.xml文件中初始化上面的student数组?

的beans.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">


<bean id="mainApplication" class="org.manan.main.MainApplication">
    <property name="student">
        <list>
            <ref bean="student" />
        </list> 
    </property>
</bean>

<bean id="student" class="org.manan.student.Student">
</bean> 
</beans>

简而言之,如何配置     学生[]学生=新生[3]; 进入Beans.xml文件?

2 个答案:

答案 0 :(得分:0)

尝试添加

<bean id="student" class="org.manan.student.Student" scope="prototype"> </bean>

如果你不这样做,引用将是相同的对象(singelton) 然后再多次参考它

<list> 
<ref bean="student" /> 
<ref bean="student" />
<ref bean="student" />
</list>

答案 1 :(得分:0)

使用prototype,每次引用bean时,它都是新实例。默认情况下,它将是单例,甚至您多次引用它,所有三个元素将包含相同的对象

<bean id="mainApplication" class="org.manan.main.MainApplication">
    <property name="student">
        <list>
            <ref bean="student" />
            <ref bean="student" />
            <ref bean="student" />
        </list> 
    </property>
</bean>

<bean id="student" class="org.manan.student.Student" scope="prototype">
</bean>