Spring作为当前Java最流行、最强大的轻量级框架,受到了程序员的热烈欢迎。准确的了解Spring Bean的生命周期是非常必要的。我们通常使用ApplicationContext作为Spring容器。这里,我们讲的也是 ApplicationContext中Bean的生命周期。而实际上BeanFactory也是差不多的,只不过处理器需要手动注册。
转载请注明地址 http://www.cnblogs.com/zrtqsk/p/3735273.html,谢谢。
一、生命周期流程图:
Spring Bean的完整生命周期从创建Spring容器开始,直到最终Spring容器销毁Bean,这其中包含了一系列关键点。
若容器注册了以上各种接口,程序那么将会按照以上的流程进行。下面将仔细讲解各接口作用。
二、具体源码
ApplicationContext factory = new ClassPathXmlApplicationContext("com/spring/beanlife/beans.xml");//创建bean上下文
源码:
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[] {configLocation}, true, null);
}
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();//具体是在该方法中
}
}
public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. prepareRefresh(); // Tell the subclass to refresh the internal bean factory. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();//创建beanFactory,并且加载
//BeanDefintion信息 // Prepare the bean factory for use in this context. prepareBeanFactory(beanFactory);//准备beanFactory try { // Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory(beanFactory); // Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);// Register bean processors that intercept bean creation.//触发BeanFactoryPostProcessor,实例化BeanFactoryPostProcessor,并且执行postProcessBeanFactory方法
//实例化BeanPostProcessor和InstantiationAwareBeanPostProcessor registerBeanPostProcessors(beanFactory); // Initialize message source for this context. initMessageSource(); // Initialize event multicaster for this context. initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses. onRefresh(); // Check for listener beans and register them. registerListeners(); // Instantiate all remaining (non-lazy-init) singletons. finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event. finishRefresh(); } catch (BeansException ex) { // Destroy already created singletons to avoid dangling resources. destroyBeans(); // Reset 'active' flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } } }
二、各种接口方法分类
Bean的完整生命周期经历了各种方法调用,这些方法可以划分为以下几类:
1、Bean自身的方法 : 这个包括了Bean本身调用的方法和通过配置文件中<bean>的init-method和destroy-method指定的方法
2、Bean级生命周期接口方法 : 这个包括了BeanNameAware、BeanFactoryAware、InitializingBean和DiposableBean这些接口的方法
3、容器级生命周期接口方法 : 这个包括了InstantiationAwareBeanPostProcessor 和 BeanPostProcessor 这两个接口实现,一般称它们的实现类为“后处理器”。
4、工厂后处理器接口方法 : 这个包括了AspectJWeavingEnabler, ConfigurationClassPostProcessor, CustomAutowireConfigurer等等非常有用的工厂后处理器 接口的方法。工厂后处理器也是容器级的。在应用上下文装配配置文件之后立即调用。
5:Spring 的aware接口有:
BeanNameAware ,可以再Bean中得到它在IOC容器中的Bean的实例名称
BeanFactoryAware,ApplicationContextAware,MessageSourceAware,ApplicationEventPublisherAware,ResourceLoaderAwate
三、演示
我们用一个简单的Spring Bean来演示一下Spring Bean的生命周期。
1、首先是一个简单的Spring Bean,调用Bean自身的方法和Bean级生命周期接口方法,为了方便演示,它实现了BeanNameAware、BeanFactoryAware、InitializingBean和DiposableBean这4个接口,同时有2个方法,对应配置文件中<bean>的init-method和destroy-method。如下:
package com.spring.beanlife; 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.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; /** 11 * @author qsk 12 */ public class Person implements BeanFactoryAware, BeanNameAware, InitializingBean, DisposableBean { private String name; private String address; private int phone; public static BeanFactory getBeanFactory() { return beanFactory; } private static BeanFactory beanFactory; private String beanName; public Person() { System.out.println("Person 【构造器】调用Person的构造器实例化"); } public String getName() { return name; } public void setName(String name) { System.out.println("Person 【注入属性】注入属性name"); this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { System.out.println("Person 【注入属性】注入属性address"); this.address = address; } public int getPhone() { return phone; } public void setPhone(int phone) { System.out.println("Person 【注入属性】注入属性phone"); this.phone = phone; } @Override public String toString() { return "Person [address=" + address + ", name=" + name + ", phone=" + phone + "]"; } // 这是BeanFactoryAware接口方法 @Override public void setBeanFactory(BeanFactory arg0) throws BeansException { System.out .println("Person 【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()"); this.beanFactory = arg0; } // 这是BeanNameAware接口方法 @Override public void setBeanName(String arg0) { System.out.println("Person 【BeanNameAware接口】调用BeanNameAware.setBeanName()"); this.beanName = arg0; } // 这是InitializingBean接口方法 @Override public void afterPropertiesSet() throws Exception { System.out .println("Person 【InitializingBean接口】调用InitializingBean.afterPropertiesSet()"); } // 这是DiposibleBean接口方法 @Override public void destroy() throws Exception { System.out.println("Person 【DiposibleBean接口】调用DiposibleBean.destory()"); } // 通过<bean>的init-method属性指定的初始化方法 public void myInit() { System.out.println("Person 【init-method】调用<bean>的init-method属性指定的初始化方法"); } // 通过<bean>的destroy-method属性指定的初始化方法 public void myDestory() { System.out.println("Person 【destroy-method】调用<bean>的destroy-method属性指定的初始化方法"); } }
2、接下来是演示BeanPostProcessor接口的方法,如下:
如上,BeanPostProcessor接口包括2个方法postProcessAfterInitialization和postProcessBeforeInitialization,这两个方法的第一个参数都是要处理的Bean对象,第二个参数都是Bean的name。返回值也都是要处理的Bean对象。这里要注意。
3、InstantiationAwareBeanPostProcessor 接口本质是BeanPostProcessor的子接口,一般我们继承Spring为其提供的适配器类InstantiationAwareBeanPostProcessor Adapter来使用它,如下:
package com.spring.beanlife; import java.beans.PropertyDescriptor; import org.springframework.beans.BeansException; import org.springframework.beans.PropertyValues; import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter; public class MyInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter { public MyInstantiationAwareBeanPostProcessor() { super(); System.out .println("这是InstantiationAwareBeanPostProcessorAdapter实现类构造器!!"); } // 接口方法、实例化Bean之前调用 @Override public Object postProcessBeforeInstantiation(Class beanClass, String beanName) throws BeansException { System.out .println("InstantiationAwareBeanPostProcessor调用postProcessBeforeInstantiation方法"); return null; } // 接口方法、实例化Bean之后调用 @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out .println("InstantiationAwareBeanPostProcessor调用postProcessAfterInitialization方法"); return bean; } // 接口方法、设置某个属性时调用 @Override public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException { System.out .println("InstantiationAwareBeanPostProcessor调用postProcessPropertyValues方法"); return pvs; } }
这个有3个方法,其中第二个方法postProcessAfterInitialization就是重写了BeanPostProcessor的方法。第三个方法postProcessPropertyValues用来操作属性,返回值也应该是PropertyValues对象。
4、演示工厂后处理器接口方法,如下:
5、配置文件如下beans.xml,很简单,使用ApplicationContext,处理器不用手动注册:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"> <bean id="beanPostProcessor" class="com.spring.beanlife.MyBeanPostProcessor"> </bean> <bean id="instantiationAwareBeanPostProcessor" class="com.spring.beanlife.MyInstantiationAwareBeanPostProcessor"> </bean> <bean id="beanFactoryPostProcessor" class="com.spring.beanlife.MyBeanFactoryPostProcessor"> </bean> <bean id = "myApplicationContextAware" lazy-init="true" class="com.spring.beanlife.MyApplicationContextAware"></bean> <bean id="person" class="com.spring.beanlife.Person" lazy-init="true" init-method="myInit" destroy-method="myDestory" scope="singleton" p:name="张三" p:address="广州" p:phone="15900000000" /> <!-- <bean id="friend" class="com.spring.beanlife.Friend" lazy-init="true" init-method="myInit" destroy-method="myDestory" scope="singleton" p:name="李四" p:address="深圳" p:phone="1666666" /> --> </beans>
6:MyApplicationContextAware
package com.spring.beanlife;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class MyApplicationContextAware implements ApplicationContextAware{
private static ApplicationContext applicationContext = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
// TODO Auto-generated method stub
System.out.println("-------------设置applicationContext");
this.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext(){
return applicationContext;
}
}
6、下面测试一下:
import org.springframework.beans.factory.BeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Application { public static void main(String[] args) { System.out.println("现在开始初始化容器"); ApplicationContext factory = new ClassPathXmlApplicationContext("com/spring/beanlife/beans.xml"); System.out.println("容器初始化成功"); ApplicationContext applicationContext = MyApplicationContextAware.getApplicationContext(); //得到Preson,并使用 factory.getBean("myApplicationContextAware"); Person person = factory.getBean("person",Person.class); /*BeanFactory factory2 = Person.getBeanFactory(); Person person = factory2.getBean("person",Person.class);*/ //System.out.println(person); System.out.println("现在开始关闭容器!"); //((ClassPathXmlApplicationContext)factory).registerShutdownHook(); } }
关闭容器使用的是实际是AbstractApplicationContext的钩子方法。
我们来看一下结果:
这是BeanFactoryPostProcessor实现类构造器!!
BeanFactoryPostProcessor调用postProcessBeanFactory方法
这是BeanPostProcessor实现类构造器!!
这是InstantiationAwareBeanPostProcessorAdapter实现类构造器!!
容器初始化成功
//MyApplicationContextAware Bean的初始化,如果在配置中增加Lazy-init=“true”则不会有此,具体可以查看 方法AbstractApplicationContext.finishBeanFactoryInitialization(beanFactory);
InstantiationAwareBeanPostProcessor调用postProcessBeforeInstantiation方法
InstantiationAwareBeanPostProcessor调用postProcessPropertyValues方法
-------------设置applicationContext
BeanPostProcessor接口方法postProcessBeforeInitialization对属性进行更改!
BeanPostProcessor接口方法postProcessAfterInitialization对属性进行更改!
InstantiationAwareBeanPostProcessor调用postProcessAfterInitialization方法
InstantiationAwareBeanPostProcessor调用postProcessBeforeInstantiation方法
Person 【构造器】调用Person的构造器实例化
InstantiationAwareBeanPostProcessor调用postProcessPropertyValues方法
Person 【注入属性】注入属性address
Person 【注入属性】注入属性name
Person 【注入属性】注入属性phone
Person 【BeanNameAware接口】调用BeanNameAware.setBeanName()
Person 【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()
BeanPostProcessor接口方法postProcessBeforeInitialization对属性进行更改!
Person 【InitializingBean接口】调用InitializingBean.afterPropertiesSet()
Person 【init-method】调用<bean>的init-method属性指定的初始化方法
BeanPostProcessor接口方法postProcessAfterInitialization对属性进行更改!
InstantiationAwareBeanPostProcessor调用postProcessAfterInitialization方法
现在开始关闭容器!