Spring懒加载机制

Spring默认会在容器初始化的过程当中,解析xml,并将单例的bean建立并保存到map中,这样的机制在bean比较少时问题不大,但一旦bean很是多时,spring须要在启动的过程当中花费大量的时间来建立bean 花费大量的空间存储bean,但这些bean可能好久都用不上,这种在启动时在时间和空间上的浪费显得很是的不值得。
因此Spring提供了懒加载机制。所谓的懒加载机制就是能够规定指定的bean不在启动时当即建立,而是在后续第一次用到时才建立,从而减轻在启动过程当中对时间和内存的消耗。spring

懒加载机制只对单例bean有做用,对于多例bean设置懒加载没有意义。spa

懒加载的配置方式

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="user" class="com.spring.demo.User" 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="user" class="com.spring.demo.User"></bean>
</beans>

注意:若是同时设定全局和指定bean的懒加载机制,且配置不相同,则对于该bean局部配置覆盖全局配置。code

相关文章
相关标签/搜索