javascript
Spring的lazy-init详解
Spring中l(wèi)azy-init詳解
ApplicationContext實(shí)現(xiàn)的默認(rèn)行為就是在啟動(dòng)服務(wù)器時(shí)將所有singleton bean提前進(jìn)行實(shí)例化
(也就是依賴注入)。提前實(shí)例化意味著作為初始化過程的一部分,applicationContext實(shí)例會(huì)創(chuàng)
建并配置所有的singleton bean。通常情況下這是一件好事,因?yàn)檫@樣在配置中的任何錯(cuò)誤就會(huì)
被立刻實(shí)現(xiàn)(否則的話可能要話幾個(gè)小時(shí)甚至幾天)。
<bean id="testBean" class="cn.itcast.test.TestBean" />
該bean默認(rèn)的設(shè)置為:
<bean id="testBean" calss="cn.itcast.test.TestBean" lazy-init="false" />
lazy-init="false"
立即加載,表示在spring啟動(dòng)時(shí),立刻進(jìn)行實(shí)例化。
有時(shí)候這種默認(rèn)處理可能并不是你想要的。
如果你不想讓一個(gè)singleton bean在ApplicationContext
實(shí)現(xiàn)初始化時(shí)被提前實(shí)例化,那么可以將bean設(shè)置為延時(shí)實(shí)例化。
<bean id="testBean" calss="cn.itcast.test.TestBean" lazy-init="true" /> (或者@Lazy(true))延時(shí)加載,設(shè)置為lazy
的bean將不會(huì)在ApplicationContext啟動(dòng)時(shí)提前被實(shí)例化,而是第一次向容器通過getBean索取bean時(shí)實(shí)例化的。
如果一個(gè)設(shè)置了立即加載的bean1,引用了一個(gè)延時(shí)加載的bean2,那么bean1在容器啟動(dòng)時(shí)被實(shí)例化,而bean2
由于被bean1引用,所以也被實(shí)例化,這種情況也符合延時(shí)加載的bean在第一次調(diào)用時(shí)才被實(shí)例化的規(guī)則。
在容器層次中通過在<beans/>元素上使用'default-lazy-init'屬性來控制延時(shí)初始化也是可能的。如下面配置:
<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í)例化的
另外說明:
.init-method屬性指定初始化時(shí)執(zhí)行的方法,distory-method屬性指定bean銷毀時(shí)執(zhí)行的方法。
用途: 通常用于解決spring循環(huán)引用的問題: (A->B->A,A->B->C->A)
This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching – consider using ‘getBeanNamesOfType’ with the ‘a(chǎn)llowEagerInit’ flag turned off, for example.
轉(zhuǎn)載于:https://www.cnblogs.com/brant/p/5723932.html
總結(jié)
以上是生活随笔為你收集整理的Spring的lazy-init详解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 1_HDFS理论及安装部署
- 下一篇: 【Maven3教程】Maven多工程、多