zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    总结C# 调用c++ 开源代码使用问题
    nodejs v14使用await async
    一个简单的js文件,在ts中使用的方法
    ts项目+webpack+juuery 插件的引入
    js 立即执行的多种写法
    在webgl2上使用fabric做标记
    comobox 绑定datatable ,无法获取选择值问题
    axios 请求拦截并在 token 过期后自动续订后重调当前请求
    javascript hook 一个函数(不定参数个数)
    java Date 大坑
  • 原文地址:https://www.cnblogs.com/brant/p/5723932.html
Copyright © 2011-2022 走看看