码迷,mamicode.com
首页 > 编程语言 > 详细

Spring系列【11】配置Bean的初始化行为

时间:2014-12-15 00:09:05      阅读:302      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   使用   sp   strong   on   

对某个Bean添加lazy-init属性:lazy-init 设置只对scop属性为singleton的bean起作用

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
 6         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
 7 
 8     <bean id="user" class="com.lh.entity.User" lazy-init="true"></bean>
 9     <bean id="printInfo" class="com.lh.util.PrintInfo" autowire="byName">
10     </bean>
11 </beans>

在容器层次中通过在<beans/>元素上使用‘default-lazy-init‘属性来控制延迟初始化也是可能的。如下面的配置:

<?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-4.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"
    default-lazy-init="true">

    <bean id="user" class="com.lh.entity.User"></bean>
    <bean id="printInfo" class="com.lh.util.PrintInfo" autowire="byName">
    </bean>
</beans>

ApplicationContext实现的默认行为就是在启动时将所有singleton bean提前进行实例化(也就是依赖注入)。提前实例化意味着作为初始化过程的一部分,ApplicationContext实例会创建并配置所有的singleton bean。通常情况下这是件好事,因为这样在配置中的任何错误就会即刻被发现(否则的话可能要花几个小时甚至几天)。

Spring系列【11】配置Bean的初始化行为

标签:style   blog   http   io   color   使用   sp   strong   on   

原文地址:http://www.cnblogs.com/jikoy/p/4163864.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!