zoukankan      html  css  js  c++  java
  • Spring IOC

    懒加载机制

    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="cart" class="cn.tedu.beans.Cart" 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="cart" class="cn.tedu.beans.Cart"></bean>
        
    </beans>

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

    实验

    通过断点调试,验证懒加载机制的执行过程

    package cn.tedu.beans;
    
    public class Cart {
        public Cart(){
            System.out.println("Cart init...");
        }
    }
    <?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="cart" class="cn.tedu.beans.Cart"></bean>
        
    </beans>
        @Test
        /**
         * SpringIOC 懒加载机制
         */
        public void test9(){
             
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            Cart cart1 = (Cart) context.getBean("cart");
            Cart cart2 = (Cart) context.getBean("cart");
            System.out.println(cart1 == cart2);
        }
  • 相关阅读:
    2017.04.05-2017.07.14封闭开发总结
    Android读取Manifest文件下Application等节点下的metadata自定义数据
    MyEclipse Hibernate Reverse Engineering 找不到项目错误
    web服务器决定支持多少人同时在线的因素
    配置servers时,错误:Setting property 'source' to 'org.eclipse.jst.jee.server:hczm' did not find a matching property
    查看端口被占用
    高德开发 android 出现 key 鉴权失败
    Android EventBus
    javascript 中的数据驱动页面模式
    读书笔记之
  • 原文地址:https://www.cnblogs.com/chuijingjing/p/9786857.html
Copyright © 2011-2022 走看看