Spring3.0学习札记一Spring IOC控制反转(3)

16 篇文章 0 订阅

Bean的作用域

Bean的作用域对Bean的生命周期和创建方式产生影响。Spring Framework支持五种作用域。

![Bean作用域类型](https://img-blog.csdn.net/20150802214922793)
Singleton作用域
当把一个bean定义设置为singlton作用域时,Spring IoC容器只会创建该bean定义的唯一实例。这个单一实例会被存储到单例缓存(singleton cache)中,并且所有针对该bean的后续请求和引用都将返回被缓存的对象实例。bean作用域默认为Singleton。
<!--验证-->
// beans.xml中配置
<bean id="personService" class="com.test.PersonServiceBean" ></bean> 
//测试代码
public class SpringTest01 {   
    @Test   
    public void instanceSpring(){  
    ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");  
    PersonService personService1 = (PersonService)ctx.getBean("personService");  
    PersonService personService2 = (PersonService)ctx.getBean("personService");  
    System.out.println(personService1==personService2);  
    }  
}  
// 运行结果输出为true
Prototype作用域
  Prototype作用域的bean会导致在每次对该bean请求(将其注入到另一个bean中,或者以程序的方式调用容器的getBean()方法)时都会创建一个新的bean实例 。
  根据经验,对有状态的bean应该使用prototype作用域,而对无状态的bean则应该使用singleton作用域。
<bean id="personService" class="com.test.PersonServiceBean" scope="prototype"></bean>  
//按这样配置,则运行上面测试,则输出 false

Bean的生命周期

初始化
当scope=singleton,即默认情况,会在容器初始化时实例化。但我们可以指定Bean节点的lazy-init=”true”来延迟初始化bean,这时候,只有第一次获取bean才会初始化bean,即第一次请求该bean时才初始化。
//延迟初始化,第一次获取时才初始化
<bean id=”xxx” class=”examples.test.OrderServiceBean” lazy-init=”true” />  
// 若想对所有Beany延迟,则可在根节点Beans设置
<beans default-lazy-init=”true” …>  
生命周期
 构造器、init方法、获取bean后的操作、destroy方法(ctx.close时执行).
public class PersonServiceBean implements PersonService {  
    public void init(){  
        System.out.println("Get the database connection and initialize other beans!");  
    }  
    public PersonServiceBean(){  
        System.out.println("PersonServiceBean is initialized!");  
    }  
    public void destroy(){  
        System.out.println("close the database connection!");  
    }  
}  
    注意:如果bean的scope设为prototype时,当ctx.close时,destroy方法不会被调用.
    对于prototype作用域的bean,有一点非常重要,那就是Spring不能对一个prototype bean的整个生命周期负责:容器在初始化、配置、装饰或者是装配完一个prototype实例后,将它交给客户端,随后就对该prototype实例不闻不问了。不管何种作用域,容器都会调用所有对象的初始化生命周期回调方法。但对prototype而言,任何配置好的析构生命周期回调方法都将不会 被调用
//beans.xml配置
<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean" init-method="init" destroy-method="destroy"/>  
//测试代码

public class SpringTest {  
    @Test   
    public void instanceSpring(){  
         AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");  
         System.out.println("------------------");  
         PersonService personService = (PersonServiceBean)ctx.getBean("personService");  
         ctx.close();  
  }  
}
按上述配置后,初始化时会调用 init()方法,ctx.close()时会调用destroy()方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值