前言
-
问题
Spring的IOC容器默认在启动时就创建所有的bean,但这样会影响程序的运行效率。
-
延迟加载的好处
- 开启延迟加载⼀定程度提⾼容器启动和运转性能
- 对于不常使⽤的 Bean 设置延迟加载,这样偶尔使⽤的时候再加载,不必要从⼀开始该 Bean 就占用资源
使用方法
修改applicationContext.xml中的配置
- 单个bean设置延迟加载
<bean id="demoBean" class="com.lb.Demo.DemoBean" lazy-init="true"></bean>
设置 lazy-init 为 true 的 bean 将不会在 ApplicationContext 启动时提前被实例化,而是第⼀次向容器 通过 getBean 索取 bean 时实例化的。
注意:不设置此属性时默认为不延迟加载
- 全部bean设置延迟加载
<beans default-lazy-init="true"
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
注意
当scope = "prototype"时,设置 lazy-init=“false”,容器启动时也不会实例化bean,而是调⽤ getBean ⽅法实例化的。