I have a bean Employee as:
public class Employee {
private int empId;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
}
An EmployeeList class which has looks like:
public class EmployeeList {
@Autowired
public Employee[] empList;
}
The spring config file:
<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>
The main method class:
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);
}
}
The count of Employee instances I get is always 1. Why it is not incremented when I get the bean instance multiple times. The Employee bean has scope as prototype.
Because getting a new prototype instance doesn’t magically add it to a previously instantiated bean array.
When the context starts up, a single employee bean is instantiated and injected in the
empBeanListbean, and then the empList bean is created and doesn’t change anymore.