ITeye博客

6.Spring管理的Bean的生命周期

polokang · 2010-04-04 23:33 · Spring2.5学习(33章) · 企业架构 · Markdown

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

二.延迟加载

在延迟加载的情况下,bean 只有在ctx.getBean("xxx")的时候才会被实例化。

<beans ... default-lazy-init="true"> 表示在此配置文件中的所有bean都延迟加载

PS:延迟加载一般不用,因为我们希望在应用启动时就可以根据日志查看Bean 实例化是否正常,而不是在应用运行期间才发现Bean实例化问题。

三.指定bean初始化方法

四.指定bean的销毁方法


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


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("关闭资源文件!");
    }
}


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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。