吹静静

欢迎QQ交流:592590682

懒加载机制

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);
    }

 

posted on 2018-10-14 16:49  吹静静  阅读(546)  评论(0编辑  收藏  举报