0

我有一个bean员工:

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;
}

弹簧配置文件:

<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 具有作为原型的作用域。

4

1 回答 1

3

因为获得一个新的原型实例并不会神奇地将它添加到先前实例化的 bean 数组中。

当上下文启动时,单个员工 bean 被实例化并注入到empBeanListbean 中,然后创建 empList bean 并且不再更改。

于 2012-12-07T17:51:34.077 回答