在spring框架应用,容器初始化时候,默认会构建所有由spring管理的Bean对象.但假如这些对象长时间不使用还占用着内存就会造成一定的资源浪费.为了解决这个问题,spring中提供了一种延迟加载机制.通过这种机制来提高系统资源的有效使用.
Spring中的延迟加载需要通过bean元素中lazy-init属性或beans元素的default-lazy-init="true"属性进行设置.两者应用的不同点:
- lazy-init: 应用在bean标签中用于指定这个bean的加载策略.
- default-lazy-init:应用在beans标签中用于指定所有bean的加载策略.
延迟加载是一种按需加载,对象需要用的时候加载,不需要的时候不加载。
对象一启动就创建,但是长时间不用会造成资源浪费。
对象初始化后不用会造成资源浪费。何时需要何时创建。
beans default-lazy-init="false"
在加载后面的xml元素后创建对象
beans default-lazy-init="true"
在加载下面的xml元素后不创建对象
<?xml version="1.0" encoding="UTF-8"?>
<beans default-lazy-init="true"
xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.3.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- Spring通过bean标签描述由它管理的对象 id属性值为bean对象的唯一标识 class属性的值是类全名(包名+类名)权限命名 -->
<bean id="helloService" class="beans.HelloService"></bean>
</beans>