javascript
Spring的lazy-init详解
Spring中l(wèi)azy-init詳解
ApplicationContext實(shí)現(xiàn)的默認(rèn)行為就是在啟動服務(wù)器時將所有singleton bean提前進(jìn)行實(shí)例化
(也就是依賴注入)。提前實(shí)例化意味著作為初始化過程的一部分,applicationContext實(shí)例會創(chuàng)
建并配置所有的singleton bean。通常情況下這是一件好事,因為這樣在配置中的任何錯誤就會
被立刻實(shí)現(xiàn)(否則的話可能要話幾個小時甚至幾天)。
<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啟動時,立刻進(jìn)行實(shí)例化。
有時候這種默認(rèn)處理可能并不是你想要的。
如果你不想讓一個singleton bean在ApplicationContext
實(shí)現(xiàn)初始化時被提前實(shí)例化,那么可以將bean設(shè)置為延時實(shí)例化。
<bean id="testBean" calss="cn.itcast.test.TestBean" lazy-init="true" /> (或者@Lazy(true))延時加載,設(shè)置為lazy
的bean將不會在ApplicationContext啟動時提前被實(shí)例化,而是第一次向容器通過getBean索取bean時實(shí)例化的。
如果一個設(shè)置了立即加載的bean1,引用了一個延時加載的bean2,那么bean1在容器啟動時被實(shí)例化,而bean2
由于被bean1引用,所以也被實(shí)例化,這種情況也符合延時加載的bean在第一次調(diào)用時才被實(shí)例化的規(guī)則。
在容器層次中通過在<beans/>元素上使用'default-lazy-init'屬性來控制延時初始化也是可能的。如下面配置:
<beans default-lazy-init="true"><!-- no beans will be eagerly pre-instantiated... --></beans>
注意:
如果一個bean的scope屬性為scope="pototype"時,即使設(shè)置了lazy-init="false",容器啟動時不實(shí)例化bean,
而是調(diào)用getBean方法實(shí)例化的
另外說明:
.init-method屬性指定初始化時執(zhí)行的方法,distory-method屬性指定bean銷毀時執(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详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 1_HDFS理论及安装部署
- 下一篇: 【Maven3教程】Maven多工程、多