Spring的lazy-init详解

Spring中lazy-init详解
ApplicationContext实现的默认行为就是在启动服务器时将所有singleton bean提前进行实例化
(也就是依赖注入)。提前实例化意味着作为初始化过程的一部分,applicationContext实例会创
建并配置所有的singleton bean。通常情况下这是一件好事,因为这样在配置中的任何错误就会
被立刻实现(否则的话可能要话几个小时甚至几天)。

<bean id="testBean" class="cn.itcast.test.TestBean" />

该bean默认的设置为:

<bean id="testBean" calss="cn.itcast.test.TestBean" lazy-init="false" />

lazy-init="false"
立即加载,表示在spring启动时,立刻进行实例化。

有时候这种默认处理可能并不是你想要的。

如果你不想让一个singleton bean在ApplicationContext
实现初始化时被提前实例化,那么可以将bean设置为延时实例化。

<bean id="testBean" calss="cn.itcast.test.TestBean" lazy-init="true" /> (或者@Lazy(true))延时加载,设置为lazy
的bean将不会在ApplicationContext启动时提前被实例化,而是第一次向容器通过getBean索取bean时实例化的。

如果一个设置了立即加载的bean1,引用了一个延时加载的bean2,那么bean1在容器启动时被实例化,而bean2
由于被bean1引用,所以也被实例化,这种情况也符合延时加载的bean在第一次调用时才被实例化的规则。

在容器层次中通过在<beans/>元素上使用'default-lazy-init'属性来控制延时初始化也是可能的。如下面配置:
<beans default-lazy-init="true"><!-- no beans will be eagerly pre-instantiated... --></beans>

注意:

如果一个bean的scope属性为scope="pototype"时,即使设置了lazy-init="false",容器启动时不实例化bean,
而是调用getBean方法实例化的
另外说明:
.init-method属性指定初始化时执行的方法,distory-method属性指定bean销毁时执行的方法。

用途: 通常用于解决spring循环引用的问题: (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 ‘allowEagerInit’ flag turned off, for example.

猜你喜欢

转载自blog.csdn.net/xiao1_1bing/article/details/81082096