• Spring懒加载机制


    Spring默认会在容器初始化的过程中,解析xml,并将单例的bean创建并保存到map中,这样的机制在bean比较少时问题不大,但一旦bean非常多时,spring需要在启动的过程中花费大量的时间来创建bean 花费大量的空间存储bean,但这些bean可能很久都用不上,这种在启动时在时间和空间上的浪费显得非常的不值得。
    所以Spring提供了懒加载机制。所谓的懒加载机制就是可以规定指定的bean不在启动时立即创建,而是在后续第一次用到时才创建,从而减轻在启动过程中对时间和内存的消耗。

    懒加载机制只对单例bean有作用,对于多例bean设置懒加载没有意义。

    懒加载的配置方式

    1.为指定bean配置懒加载 

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
            xsi:schemaLocation="http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd" >
            
            <bean id="user" class="com.spring.demo.User" lazy-init="true"></bean>
    </beans>

    2.为全局配置懒加载

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
            xsi:schemaLocation="http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"
            default-lazy-init="true" >
            
            <bean id="user" class="com.spring.demo.User"></bean>
    </beans>

    注意:如果同时设定全局和指定bean的懒加载机制,且配置不相同,则对于该bean局部配置覆盖全局配置。

  • 相关阅读:
    luogu2394 yyy loves Chemistry I
    luogu2393 yyy loves Maths II
    2018年01月刷题学习日记
    luogu2590 [ZJOI2008]树的统计
    HDU 2087 剪花布条
    HDU 1686 Oulippo
    HDU 1711 Number Sequence(KMP模板)
    HDU 3336 Count the String(KMP+DP)
    UVa 1614 奇怪的股市
    UVa 12174 Shuffle(滑动窗口)
  • 原文地址:https://www.cnblogs.com/jumpkin1122/p/11595457.html
Copyright © 2020-2023  润新知