您的位置:首页 > 编程语言 > Java开发

Spring中Bean的生命周期

2014-08-05 20:25 330 查看
一、当Bean的作用域是单例(scope="singleton"或者没有scope属性)的时候:

当容器实例化的时候,Bean也同时实例化了。

如下代码是配置文件beans.xml

<span style="font-size:14px;"><bean id="personService class="cn.itcast.service.impl.PersonServiceBean"></bean></span>


配置文件的作用域是单例的,没有配置scope属性,默认scope的属性值为"singleton"

PersonServiceBean.java文件:

<span style="font-size:14px;">public class PersonServiceBean implements PersonService{
   public PersonServiceBean(){
     System.out.println("我被实例化了");
  }
}</span>
测试文件SpringTest.java

<span style="font-size:14px;">public void instanceSpring() {
<span style="white-space:pre">	</span>ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
}</span>
当测试的时候,Console控制台会输出“我被实例化了”字符串,可以证明当容器实例化的时候,作用域为单例的Bean也会被实例化。

另外,如果当bean的lazy-init属性设置为true的时候,会延迟初始化,即在调用getBean()方法的时候初始化Bean

<span style="font-size:14px;"><bean id="personService class="cn.itcast.service.impl.PersonServiceBean" lazy-init="true"></bean></span>


不过,不建议用此种方法。

二、当Bean的作用域是(scope="prototype")的时候:

当调用getBean()方法的时候,Bean才会被实例化。

如下代码是配置文件beans.xml

<span style="font-size:14px;"><bean id="personService class="cn.itcast.service.impl.PersonServiceBean" scope="prototype"></bean></span>


PersonServiceBean.java文件:

<span style="font-size:14px;">public class PersonServiceBean implements PersonService{
   public PersonServiceBean(){
     System.out.println("我被实例化了");
  }
}</span>


测试文件SpringTest.java

<span style="font-size:14px;">public void instanceSpring() {
<span>	</span>ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");                                                                        PersonService personService = (PsersonService)ctx.getBean("personService");
}</span>


在测试的时候,Console控制台会输出“我被实例化了”的字符串,可以证明当容器实例化的时候,作用域为prototype的Bean也会被实例化。

三、如何正常关闭容器IOC

<span style="font-size:14px;">public void instanceSpring(){
 <span style="white-space:pre">	</span>AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
<span style="white-space:pre">	</span>ctx.close();
}</span>


对于所有的Bean实例有几个属性,init-method方法和destroy-method方法。

init-method方法是在实例化Bean之后,调用此方法(这是通过IOC容器反射技术实现的)

destroy-method方法是在容器关闭之后,调用此方法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: