---
title: "6.Spring管理的Bean的生命周期"
author: "polokang"
date: "2010-04-04T23:33:59Z"
tags: []
categories: ["企业架构"]
slug: "6-spring-bean"
draft: false
lastmod: "2010-04-14T06:54:42Z"
id: 632892
url: "https://polokang.iteye.com/blog/632892"
---

一.Bean在什么时候被实例化的？
1.在单例作用域(Singleton)情况下，即默认情况下，Bean的实例化是在Spring容器被实例化的时候，就被实例化了。
2.在scope="prototype"时，Bean 是在我们调用ctx.getBean("xxx")方法时才被实例化的。

二.延迟加载

> <bean id=.... lazy-init="true"></bean>

在延迟加载的情况下，bean 只有在ctx.getBean("xxx")的时候才会被实例化。

> 
> <beans ... default-lazy-init="true"></bean>
> 表示在此配置文件中的所有bean都延迟加载
> 

PS:延迟加载一般不用，因为我们希望在应用启动时就可以根据日志查看Bean 实例化是否正常，而不是在应用运行期间才发现Bean实例化问题。

三.指定bean初始化方法

> <bean id=... init-method="init"></bean>


四.指定bean的销毁方法

> <bean id=... destroy-method="destory"></bean>



```xml

<bean id="personService" class="com.spring.service.impl.PersonServiceBean" init-method="init" destroy-method="destory"></bean>

```



```java

public class PersonServiceBean implements PersonService
{
    public void init()
    {
        System.out.println("我被初始化了！");
    }
    public PersonServiceBean()
    {
        System.out.println("我被实例化了！");
    }
    public void save()
    {
        System.out.println("我是Save方法 ！");
    }
    public void destory()
    {
        System.out.println("关闭资源文件!");
    }
}

```



```java

AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonService personservice = (PersonService)ctx.getBean("personService");
ctx.close();

```