Bean的作用域
.singleton
在每個Spring IoC容器中一個bean定義只有一個對象實例。默認情況下會在容器啟動時初始化bean,但我們可以指定Bean節點的lazy-init=“true”來延遲初始化bean,這時候,只有第一次獲取bean會才初始化bean。如:
<bean id="xxx" class="cn.itcast.OrderServiceBean" lazy-init="true"/>
如果想對所有bean都應用延遲初始化,可以在根節點beans設置default-lazy-init=“true“,如下:
<beans default-lazy-init="true“ ...>
.prototype
每次從容器獲取bean都是新的對象。
.request
.session
.global session
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersionSevice ps=(PersionSevice)ctx.getBean("persionServiceBean");
PersionSevice ps2=(PersionSevice)ctx.getBean("persionServiceBean");
System.out.println(ps==ps2);
輸出:true
可見spring容器默認的bean的產生方式是單例
改
<bean id="persionServiceBean" class="cn.com.xinli.service.impl.PersionServiceBean" scope="prototype"></bean>
這時候輸出:false ,顯然ps與ps2就不一樣。