在Spring中创建实例化bean列表

时间:2012-12-07 17:20:11

标签: spring

我有一个bean Employee:

public class Employee {
    private int empId;
    public int getEmpId() {
        return empId;
    }
    public void setEmpId(int empId) {
        this.empId = empId;
    }
}

一个看似如下的EmployeeList类:

public class EmployeeList {
    @Autowired
    public Employee[] empList;
}

spring配置文件:

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

    <context:annotation-config/>

 <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

    <bean id="empBean" class="Employee" scope="prototype">
    </bean>
    <bean id="empBeanList" class="EmployeeList">
    </bean>
 </beans>

主要方法类:

public class App 
{

    public static void main( String[] args )
    {
        ApplicationContext empContext = new ClassPathXmlApplicationContext(
                "employee-module.xml");

        EmployeeList objList = (EmployeeList) empContext.getBean("empBeanList");

        Employee obj = (Employee) empContext.getBean("empBean");
        obj.setEmpId(1);
        System.out.println(obj.getEmpId());
        System.out.println("length " + objList.empList.length);

        Employee obj1 = (Employee) empContext.getBean("empBean");
        obj1.setEmpId(2);
        System.out.println(obj1.getEmpId());
        System.out.println("length " + objList.empList.length);

        Employee obj2 = (Employee) empContext.getBean("empBean");
        System.out.println("length " + objList.empList.length);
    }
}

我得到的Employee实例的数量总是1.当我多次获取bean实例时,为什么它不会增加。 Employee bean的范围是原型。

1 个答案:

答案 0 :(得分:3)

因为获取一个新的原型实例并没有神奇地将它添加到以前实例化的bean数组中。

当上下文启动时,将实例化单个employee bean并将其注入empBeanList bean,然后创建empList bean并且不再更改。