Spring懒加载和非懒加载

用lazy-init。告诉spring容器是否以懒加载的方式创造对象。用的时候才加载构造,不用的时候不加载
懒加载:取值:true(懒,真正调用到的时候再加载);default(懒);
非懒加载:false(非懒,已启动spring容器就创建对象);

<bean id="test1" class="cn.java.ioc1.YelloMouseWolf" lazy-init="default" ></bean>
<bean id="startQuertz" lazy-init="false"
          class="org.springframework.scheduling.quartz.SchedulerFactoryBean"></bean>

也可以为一组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" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd" 
default-lazy-init="true" default-init-method="init">
    <bean id = "computer" class="com.zlc.test.Computer">
         <constructor-arg index="0" ref="date"></constructor-arg>
    </bean>
    <bean id="date" class="java.util.Date">
    </bean>
</beans>

懒加载与非懒加载的优缺点:

懒加载:对象使用的时候(使用getBean()方法时)才去创建,节省资源,但是不利于提前发现错误。

非懒加载:容器启动(创建spring容器时)的时候立刻创建对象。消耗资源。利于提前发现错误。

当scope=“prototype” (多例)时,默认以懒加载的方式产生对象。

当scope=“singleton” (单例)时,默认以非懒加载的方式产生对象。

猜你喜欢

转载自blog.csdn.net/wenmin_111/article/details/112789732