技术分享 SPRING SPRING CORE 查看内容

Spring 中的default-lazy-init 和 lazy-init

老高 | 发布于 2016-04-04 10:35| 浏览()| 评论() | 收藏() | 点赞() | 打印

摘要: spring在启动的时候,会默认加载会默认加载整个对象实例图,从初始化ACTION配置、到 service配置到dao配置、乃至到数据库连接、事务等等。这样可以减少web服务器在运行时的负担,但是对于开发者来说无疑是效率极低的一个设置了。

1、spring的default-lazy-init参数 

spring在启动的时候,会默认加载会默认加载整个对象实例图,从初始化ACTION配置、到 service配置到dao配置、乃至到数据库连接、事务等等。这样可以减少web服务器在运行时的负担,但是对于开发者来说无疑是效率极低的一个设置了。 

spring提供了default-lazy-init属性,其配置形式如下,applicationContext.xml中: 

<beans  default-lazy-init ="true">   
</beans>

我用以前一个office项目测试了下,因为office的spring文件很多,我就配置了下,启动时间减少60%左右。

2、Spring 中lazy-init 和abstract 属性 

1.lazy-init 

<beans> 
      <bean id="service1" type="bean路径" lazy-init="true"/> 
      <bean id="service2" type="bean路径" lazy-init="false"> 
             <property name="service1" ref="service1"/> 
      </bean> 
</beans>

以上两个bean,一个lazy-init属性为true,一个为false,由什么区别呢 

当 IoC容器启动时,service2会实例化,而service1则不会;但是但容器实例化service2时,service1也被实例化了,为什么呢,因为service2需要它。也就是说lazy-init="true"的bean,IoC容器启动时不会实例化该bean,只有当容器需要用到时才实例化它。lazy-init有利于容器效率,对于不需要的bean可以先不管。 

2.abstract 

<bean id="baseTxService"  class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"  abstract="true"> 
</bean>

bean abstract="true"时,该bean不会被实例化,上面的bean是个模板 

在同一个文件中<bean />里面设置的优先级大于<beans />里设置的优先级:

3、多个配置文件作用范围

<beans />                <bean />            immediately  
<beans />                <bean lazy-init="true" />   lazy      
<beans />                <bean lazy-init="false"/>   immediately           
<beans default-lazy-init="true"/>  <bean />          lazy  
<beans default-lazy-init="true"/>  <bean lazy-init="true" />     lazy  
<beans default-lazy-init="true"/>  <bean lazy-init="false" />    immediately  
<beans default-lazy-init="false"/>  <bean />             immediately  
<beans default-lazy-init="false"/>  <bean lazy-init="true" />    lazy  
<beans default-lazy-init="false"/>  <bean lazy-init="false" />   immediately

如果在一个spring配置文件中引入另外的配置文件,如:<import resource="classpath:beans.xml"/>

则以被引入文件(beans.xml)中设置的<beans />里的设置为准,与引入文件中的设置无关。

<bean id="testInit" lazy-init="true" init-method="init" class="com.test.Test">  
</bean>

One thing to understand about lazy-initialization is that even though a bean definition may be marked up as being lazy-initialized, if the lazy-initialized bean is the dependency of a singleton bean that is not lazy-initialized, when the ApplicationContext is eagerly pre-instantiating the singleton, it will have to satisfy all of the singletons dependencies, one of which will be the lazy-initialized bean! So don't be confused if the IoC container creates one of the beans that you have explicitly configured as lazy-initialized at startup; all that means is that the lazy-initialized bean is being injected into a non-lazy-initialized singleton bean elsewhere.

发表评论(对文章涉及的知识点还有疑问,可以在这里留言,老高看到后会及时回复的。)

表情