spring中lazy-init详解
ApplicationContext實(shí)現(xiàn)的默認(rèn)行為就是在啟動(dòng)時(shí)將所有singleton bean提前進(jìn)行實(shí)例化(也就是依賴(lài)注入)。提前實(shí)例化意味著作為初始化過(guò)程的一部分,ApplicationContext實(shí)例會(huì)創(chuàng)建并配置所有的singleton bean。通常情況下這是件好事,因?yàn)檫@樣在配置中的任何錯(cuò)誤就會(huì)即刻被發(fā)現(xiàn)(否則的話(huà)可能要花幾個(gè)小時(shí)甚至幾天)。
<bean id="testBean" class="com.fhx.TestBean">?該bean默認(rèn)的設(shè)置為:
<bean id="testBean" class="com.fhx.TestBean" lazy-init="false">??? lazy-init="false" 立退加載,?表示spring啟動(dòng)時(shí),立刻進(jìn)行實(shí)例化。
?(lazy-init 設(shè)置只對(duì)scop屬性為singleton的bean起作用)
?
有時(shí)候這種默認(rèn)處理可能并不是你想要的。如果你不想讓一個(gè)singleton bean在ApplicationContext實(shí)現(xiàn)在初始化時(shí)被提前實(shí)例化,那么可以將bean設(shè)置為延遲實(shí)例化。
<bean id="testBean" class="com.fhx.TestBean" lazy-init="true">,?? lazy-init="true"> 延遲加載?,設(shè)置為lazy的bean將不會(huì)在ApplicationContext啟動(dòng)時(shí)提前被實(shí)例化,而是在第一次向容器通過(guò)getBean索取bean時(shí)實(shí)例化的。
?
如果一個(gè)設(shè)置了立即加載的bean1,引用了一個(gè)延遲加載的bean2,那么bean1在容器啟動(dòng)時(shí)被實(shí)例化,而bean2由于被bean1引用,所以也被實(shí)例化,這種情況也符合延遲加載的bean在第一次調(diào)用時(shí)才被實(shí)例化的規(guī)則。
?
在容器層次中通過(guò)在<beans/>元素上使用'default-lazy-init'屬性來(lái)控制延遲初始化也是可能的。如下面的配置:
<beans default-lazy-init="true"><!-- no beans will be eagerly pre-instantiated... --></beans>
?
如果一個(gè)bean的scope屬性為scope=“pototype“時(shí),即使設(shè)置了lazy-init="false",容器啟動(dòng)時(shí)不實(shí)例化bean,而是調(diào)用getBean方法是實(shí)例化的
另外加以說(shuō)明:
.init-method屬性指定初始化時(shí)執(zhí)行的方法,distory-method屬性指定bean銷(xiāo)毀時(shí)執(zhí)行的方法。
總結(jié)
以上是生活随笔為你收集整理的spring中lazy-init详解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Spring中bean的scope详解
- 下一篇: ExtJs xtype一览