7.4.4 Lazy-initialized beans

By default, ApplicationContext implementations eagerly create and configure all singleton beans as part of the initialization process. Generally, this pre-instantiation is desirable, because errors in the configuration or surrounding environment are discovered immediately, as opposed to hours or even days later. When this behavior is not desirable, you can prevent pre-instantiation of a singleton bean by marking the bean definition as lazy-initialized. A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup.

通常情况下, ApplicationContext 的实现在初始化进程中迫切地创建和配置所有单例bean.通常,这个预先实例化是令人满意的,因为配置中的错误或环境问题会立即被发现,而不是几小时或者甚至是几天后.当这个行为不令人满意的时候,你可以通过标记这个bean定义为懒实例化来阻止单例bean的预先实例化.

In XML, this behavior is controlled by the lazy-init attribute on the <bean/> element; for example:一个懒实例化bean告诉IoC容器去创建一个bean实例当它被第一次请求的时候,而不是在容器启动的时候.

<bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/>
<bean name="not.lazy" class="com.foo.AnotherBean"/>

When the preceding configuration is consumed by an ApplicationContext, the bean namedis not eagerly pre-instantiated when the ApplicationContext is starting up, whereas the not.lazy bean is eagerly pre-instantiated.

当前面的配置被 ApplicationContext消费的时候,在 ApplicationContext 启动的时候,名为 lazy 的bean不会迫切的预先实例化,反之名为 not.lazy 的bean会迫切的预先实例化.

However, when a lazy-initialized bean is a dependency of a singleton bean that is not lazy-initialized, the ApplicationContext creates the lazy-initialized bean at startup, because it must satisfy the singleton’s dependencies. The lazy-initialized bean is injected into a singleton bean elsewhere that is not lazy-initialized.

然而,当一个懒实例化bean是一个单例bean的依赖的时候,它不会被懒实例化, ApplicationContext 会在启动的时候去创建懒实例化bean,因为它必须满足这个单例的依赖.这个懒实例化bean被注入到单例bean那里,它不会被懒实例化.

You can also control lazy-initialization at the container level by using the default-lazy-init attribute on the <beans/> element; for example:

你也可以控制懒实例化在整个容器级别,通过使用 <beans/> 元素中的 default-lazy-init 元素;例如:

<beans default-lazy-init="true">
    <!-- no beans will be pre-instantiated... -->
</beans>

猜你喜欢

转载自blog.csdn.net/weixin_41648566/article/details/80886802