Spring從Bean獲取的實例從單例變成多例

用Spring框架進行一對多賦值時,在給List增加Bean的實例總是輸出最後一個。
eg:

package Test;

import org.springframework.context.ApplicationContext;
import java.util.*;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import domain.*;

public class Client {
	public static void main(String[] args) {
		ApplicationContext act = new ClassPathXmlApplicationContext("Application.xml");
		Employee emp1 = (Employee) act.getBean("emp"),emp2 = (Employee) act.getBean("emp");
		Department dept = (Department) act.getBean("dept");
		dept.setTDepartmentId(1);
		dept.setTDepartmentName("開發一部");
		List<Employee> list = new ArrayList<Employee>();
		emp1.setNo("20520");
		emp1.setName("王朝");
		list.add(emp1);
		emp2.setNo("20521");
		emp2.setName("馬漢");
		list.add(emp2);
		dept.setList(list);
		System.out.println(dept.getTDepartmentId());
		System.out.println(dept.getTDepartmentName());
		for (Employee e : dept.getList())
			System.out.println(e.getNo() + "\n" + e.getName());
	}
}

在這裏插入圖片描述
可以發現遍歷Department.list這個集合時,輸出的是兩個馬漢,第一個王朝也隨着更改了。
這是因爲Bean默認是單例模式,可以更換scope="prototype"原型模式,這樣就可以獲取多例了

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" 
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
	<bean id="emp" class="domain.Employee" scope="prototype" ></bean>
	<bean id="dept" class="domain.Department"></bean>
</beans>

再運行:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章