Spring Bean的生命周期详细介绍

这篇文章主要介绍了Spring Bean的生命周期的相关资料,需要的朋友可以参考下

Spring作为当前Java最流行、最强大的轻量级框架,受到了程序员的热烈欢迎。准确的了解Spring Bean的生命周期是非常必要的。我们通常使用ApplicationContext作为spring容器。这里,我们讲的也是 ApplicationContext中Bean的生命周期。而实际上beanfactory也是差不多的,只不过处理器需要手动注册

一、生命周期流程图:

Spring Bean的完整生命周期从创建spring容器开始,直到最终spring容器销毁Bean,这其中包含了一系列关键点。

若容器注册了以上各种接口,程序那么将会按照以上的流程进行。下面将仔细讲解各接口作用。

二、各种接口方法分类

Bean的完整生命周期经历了各种方法调用,这些方法可以划分为以下几类:

1、Bean自身的方法:这个包括了Bean本身调用方法和通过配置文件中的init-method和destroy-method指定的方法

2、Bean级生命周期接口方法:这个包括了BeanNameAware、beanfactoryAware、InitializingBean和DiposableBean这些接口的方法

3、容器级生命周期接口方法:这个包括了InstantiationAwareBeanPostProcessor 和 BeanPostProcessor 这两个接口实现,一般称它们的实现类为“后处理器”。

4、工厂后处理器接口方法:这个包括了AspectJWeavingEnabler, ConfigurationClasspostProcessor, CustomAutowireConfigurer等等非常有用的工厂后处理器接口的方法。工厂后处理器也是容器级的。在应用上下文装配配置文件之后立即调用

三、演示

我们用一个简单的Spring Bean来演示一下Spring Bean的生命周期。

1、首先是一个简单的Spring Bean,调用Bean自身的方法和Bean级生命周期接口方法,为了方便演示,它实现了BeanNameAware、beanfactoryAware、InitializingBean和DiposableBean这4个接口,同时有2个方法,对应配置文件中的init-method和destroy-method。如下:

package springBeanTest; 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; /** * @author qsk */ public class Person implements beanfactoryAware, BeanNameAware, InitializingBean, disposableBean { private String name; private String address; private int phone; private beanfactory beanfactory; private String beanName; public Person() { System.out.println("【构造器】调用Person的构造器实例化"); } public String getName() { return name; } public void setName(String name) { System.out.println("【注入属性】注入属性name"); this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { System.out.println("【注入属性】注入属性address"); this.address = address; } public int getPhone() { return phone; } public void setPhone(int phone) { System.out.println("【注入属性】注入属性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("【beanfactoryAware接口】调用beanfactoryAware.setbeanfactory()"); this.beanfactory = arg0; } // 这是BeanNameAware接口方法 @Override public void setBeanName(String arg0) { System.out.println("【BeanNameAware接口】调用BeanNameAware.setBeanName()"); this.beanName = arg0; } // 这是InitializingBean接口方法 @Override public void afterPropertiesSet() throws Exception { System.out .println("【InitializingBean接口】调用InitializingBean.afterPropertiesSet()"); } // 这是DiposibleBean接口方法 @Override public void destroy() throws Exception { System.out.println("【DiposibleBean接口】调用DiposibleBean.destory()"); } // 通过的init-method属性指定的初始化方法 public void myInit() { System.out.println("【init-method】调用的init-method属性指定的初始化方法"); } // 通过的destroy-method属性指定的初始化方法 public void myDestory() { System.out.println("【destroy-method】调用的destroy-method属性指定的初始化方法"); } }

 2、接下来是演示BeanPostProcessor接口的方法,如下:

package springBeanTest; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; public class MyBeanPostProcessor implements BeanPostProcessor { public MyBeanPostProcessor() { super(); System.out.println("这是BeanPostProcessor实现类构造器!!"); // Todo Auto-generated constructor stub } @Override public Object postProcessAfterInitialization(Object arg0, String arg1) throws BeansException { System.out .println("BeanPostProcessor接口方法postProcessAfterInitialization对属性进行更改!"); return arg0; } @Override public Object postProcessBeforeInitialization(Object arg0, String arg1) throws BeansException { System.out .println("BeanPostProcessor接口方法postProcessBeforeInitialization对属性进行更改!"); return arg0; } }

如上,BeanPostProcessor接口包括2个方法postProcessAfterInitialization和postProcessBeforeInitialization,这两个方法的第一个参数都是要处理的Bean对象,第二个参数都是Bean的name。返回值也都是要处理的Bean对象。这里要注意。 

3、InstantiationAwareBeanPostProcessor 接口本质是BeanPostProcessor的子接口,一般我们继承Spring为其提供的适配器类InstantiationAwareBeanPostProcessor Adapter来使用它,如下:

package springBeanTest; 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、演示工厂后处理器接口方法,如下:

package springBeanTest; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanDeFinition; import org.springframework.beans.factory.config.beanfactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListablebeanfactory; public class MybeanfactoryPostProcessor implements beanfactoryPostProcessor { public MybeanfactoryPostProcessor() { super(); System.out.println("这是beanfactoryPostProcessor实现类构造器!!"); } @Override public void postProcessbeanfactory(ConfigurableListablebeanfactory arg0) throws BeansException { System.out .println("beanfactoryPostProcessor调用postProcessbeanfactory方法"); BeanDeFinition bd = arg0.getBeanDeFinition("person"); bd.getPropertyValues().addPropertyValue("phone", "110"); } }

 5、配置文件如下beans.xml,很简单,使用ApplicationContext,处理器不用手动注册

6、下面测试一下:

package springBeanTest; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClasspathXmlApplicationContext; public class BeanLifeCycle { public static void main(String[] args) { System.out.println("现在开始初始化容器"); ApplicationContext factory = new ClasspathXmlApplicationContext("springBeanTest/beans.xml"); System.out.println("容器初始化成功"); //得到Preson,并使用 Person person = factory.getBean("person",Person.class); System.out.println(person); System.out.println("现在开始关闭容器!"); ((ClasspathXmlApplicationContext)factory).registerShutdownHook(); } }

关闭容器使用的是实际是AbstractApplicationContext的钩子方法

我们来看一下结果:

现在开始初始化容器 2014-5-18 15:46:20 org.springframework.context.support.AbstractApplicationContext prepareRefresh 信息: Refreshing org.springframework.context.support.ClasspathXmlApplicationContext@19a0c7c: startup date [Sun May 18 15:46:20 CST 2014]; root of context hierarchy 2014-5-18 15:46:20 org.springframework.beans.factory.xml.XmlBeanDeFinitionReader loadBeanDeFinitions 信息: Loading XML bean deFinitions from class path resource [springBeanTest/beans.xml] 这是beanfactoryPostProcessor实现类构造器!! beanfactoryPostProcessor调用postProcessbeanfactory方法 这是BeanPostProcessor实现类构造器!! 这是InstantiationAwareBeanPostProcessorAdapter实现类构造器!! 2014-5-18 15:46:20 org.springframework.beans.factory.support.DefaultListablebeanfactory preInstantiateSingletons 信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListablebeanfactory@9934d4: defining beans [beanPostProcessor,instantiationAwareBeanPostProcessor,beanfactoryPostProcessor,person]; root of factory hierarchy InstantiationAwareBeanPostProcessor调用postProcessBeforeInstantiation方法 【构造器】调用Person的构造器实例化 InstantiationAwareBeanPostProcessor调用postProcesspropertyValues方法 【注入属性】注入属性address 【注入属性】注入属性name 【注入属性】注入属性phone 【BeanNameAware接口】调用BeanNameAware.setBeanName() 【beanfactoryAware接口】调用beanfactoryAware.setbeanfactory() BeanPostProcessor接口方法postProcessBeforeInitialization对属性进行更改! 【InitializingBean接口】调用InitializingBean.afterPropertiesSet() 【init-method】调用的init-method属性指定的初始化方法 BeanPostProcessor接口方法postProcessAfterInitialization对属性进行更改! InstantiationAwareBeanPostProcessor调用postProcessAfterInitialization方法 容器初始化成功 Person [address=广州, name=张三, phone=110] 现在开始关闭容器! 【DiposibleBean接口】调用DiposibleBean.destory() 【destroy-method】调用的destroy-method属性指定的初始化方法

以上就是对Java Spring Bean 生命周期的资料整理,后续继续补充相关资料,谢谢大家对本站的支持

相关文章

HashMap是Java中最常用的集合类框架,也是Java语言中非常典型...
在EffectiveJava中的第 36条中建议 用 EnumSet 替代位字段,...
介绍 注解是JDK1.5版本开始引入的一个特性,用于对代码进行说...
介绍 LinkedList同时实现了List接口和Deque接口,也就是说它...
介绍 TreeSet和TreeMap在Java里有着相同的实现,前者仅仅是对...
HashMap为什么线程不安全 put的不安全 由于多线程对HashMap进...