Spring bean的生命周期



Spring   bean的生命周期

为什么总是一个生命周期当做一个重点?

Servlet -> servlet生命周期 init() destory()

java对象生命周期.

 

Spring <wbr> <wbr> <wbr>bean的生命周期
Spring <wbr> <wbr> <wbr>bean的生命周期

①     实例化(当我们的程序加载beans.xml文件),把我们的bean(前提是scope=singleton)实例化到内存

②     调用set方法设置属性

③     如果你实现了bean名字关注接口(BeanNameAware) 则,可以通过setBeanName获取id号

④     如果你实现了 bean工厂关注接口,(BeanFactoryAware),则可以获取BeanFactory

⑤     如果你实现了 ApplicationContextAware接口,则调用方法

//该方法传递ApplicationContext

      public void setApplicationContext(ApplicationContext arg0)

                    throws BeansException {

             // TODO Auto-generated method stub

             System.out.println(“setApplicationContext”+arg0);

            

      }

⑥     如果bean 和 一个后置处理器关联,则会自动去调用 Object postProcessBeforeInitialization方法

⑦     如果你实现InitializingBean 接口,则会调用 afterPropertiesSet

⑧     如果自己在<bean init-method=”init” /> 则可以在bean定义自己的初始化方法.

⑨     如果bean 和 一个后置处理器关联,则会自动去调用 Object postProcessAfterInitialization方法

⑩     使用我们的bean

11. 容器关闭

12. 可以通过实现DisposableBean 接口来调用方法 destory

13. 可以在<bean destory-method=”fun1”/> 调用定制的销毁方法

小结: 我们实际开发中往往,没有用的这么的过程,常见的是:

1->2->6->10->9->11

package com.ru.service;

 

import org.springframework.beans.BeansException;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.BeanFactoryAware;

import org.springframework.beans.factory.BeanNameAware;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ApplicationContextAware;

 

public class BeanLife implements BeanNameAware, BeanFactoryAware,ApplicationContextAware {

private String username;

 

public BeanLife() {

System.out.println(“1.实例化beanlife”);

}


 

public String getUsername() {

return username;

}

 

public void setUsername(String username) {

System.out.println(“2.设置属性值”);

this.username = username;

}

public void sayhello(){

System.out.println(“hello”+username);

}

 

@Override

public void setBeanName(String arg0) {

// TODO Auto-generated method stub

System.out.println(“3.如果继承了BeanNameAware,返回beanname—” + arg0);

}

 

@Override

public void setBeanFactory(BeanFactory arg0) throws BeansException {

// TODO Auto-generated method stub

System.out

.println(“4.如果继承了BeanFactoryAware,返回—” + arg0.getBean(“bl”));

}

 

@Override

public void setApplicationContext(ApplicationContext arg0)

throws BeansException {

// TODO Auto-generated method stub

System.out

.println(“5.如果继承了ApplicationContextAware,返回—” + arg0);

}

 

}
配置文件

<bean id=”bl”>

<property name=”username”>

<value>如哥</value>

</property>

</bean>

<bean id=”mbpp”></bean>

http://blog.sina.com.cn/s/blog_976e495701013fzs.html