Spring容器管理的bean在默認情況下是單例的,即一個bean只會創建一個對象,存在map中,之后無論獲取多少次該bean,都返回同一個對象。
Spring默認采用單例方式,減少了對象的創建,從而減少了內存的消耗。
但是在實際開發中是存在多例的需求的,Spring也提供了選項可以將bean設置為多例模式。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd" > <!-- scope屬性控制當前bean的創建模式: singleton:則當前bean處在單例模式中,默認就是此模式 prototype:則當前bean處在多例模式中 --> <bean id="cart" class="cn.tedu.beans.Cart" scope="prototype"></bean> </beans>
@Test /** * SpringIOC 單例 多例 */ public void test8(){ /* <bean id="cart" class="cn.tedu.beans.Cart" scope="prototype"></bean> */ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Cart zsfcart = (Cart) context.getBean("cart"); Cart zwgcart = (Cart) context.getBean("cart"); System.out.println(zsfcart); System.out.println(zwgcart); }
結果:
Cart init...
Cart init...
cn.tedu.beans.Cart@28787c16
cn.tedu.beans.Cart@7e1a9d1b
bean在單例模式下的生命周期:
bean在單例模式下,spring容器啟動時解析xml發現該bean標簽后,直接創建該bean的對象存入內部map中保存,此后無論調用多少次getBean()獲取該bean都是從map中獲取該對象返回,一直是一個對象。此對象一直被Spring容器持有,直到容器退出時,隨着容器的退出對象被銷毀。
bean在多例模式下的生命周期:
bean在多例模式下,spring容器啟動時解析xml發現改bean標簽后,只是將該bean進行管理,並不會創建對象,此后每次使用 getBean()獲取該bean時,spring都會重新創建該對象返回,每次都是一個新的對象。這個對象spring容器並不會持有,什么銷毀取決於使用該對象的用戶自己什么時候銷毀該對象
