上一博客主要学习了下bean的配置、注入、自定义属性编辑器,今天来熟悉bean的生命周期。在开发中生命周期是一个很常见的名词,基本每种编程语言都能找到与它关联的。关于bean的生命周期我在网上也找了好多,基本都差不多。这里我主要是想通过代码来验证,毕竟学的知识都是一样的,都是学的Java,最重要的是动手练习,这样印象更深。下面是它生命周期的描述,我们通过demo来进行验证。下图是它执行的顺序。
一、创建LiftCycle类实现BeanFactoryAware,BeanNameAware,InitializingBean,DisposableBean,ApplicationContextAware5个接口方法
package Cuiyw.Spring.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.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class LifeCycle implements BeanFactoryAware,BeanNameAware,InitializingBean,DisposableBean,ApplicationContextAware{ private String name; public String getName() { System.out.println("getNamecolor: #000000">name); return name; } public void setName(String name) { System.out.println("setNamecolor: #000000">name); this.name = name; } public void afterPropertiesSet() throws Exception { // TODO Auto-generated method stub System.out.println("InitializingBean.afterPropertiesSet()"); } public void setBeanName(String arg0) { // TODO Auto-generated method stub System.out.println("BeanNameAware.setBeanName"); } public void setBeanFactory(BeanFactory arg0) throws BeansException { // TODO Auto-generated method stub System.out.println("BeanFactoryAware.setBeanFactory"); } public void destroy() throws Exception { // TODO Auto-generated method stub System.out.println("DisposableBean.destroy"); } public void myInit() { System.out.println("【init-method】调用<bean>的init-method属性指定的初始化方法"); } public void myDestory() { System.out.println("【destroy-method】调用<bean>的destroy-method属性指定的初始化方法"); } public void setApplicationContext(ApplicationContext arg0) throws BeansException { // TODO Auto-generated method stub System.out.println("ApplicationContextAware.setApplicationContext"); } }