这其实是一道面试题,是我在面试百度的时候被问到的,当时没有答出来(因为自己真的很菜),后来在网上寻找答案,看到也是一头雾水,直到看到了《Spring in action》这本书,书上有对Bean声明周期的大致解释,但是没有代码分析,所以就自己上网寻找资料,一定要把这个Bean生命周期弄明白!
网上大部分都是验证的Bean 在面试问的生命周期,其实查阅JDK还有一个完整的Bean生命周期,这同时也验证了书是具有片面性的,最fresh 的资料还是查阅原始JDK!!!
在传统的Java应用中,bean的生命周期很简单,使用Java关键字 new 进行Bean 的实例化,然后该Bean 就能够使用了。一旦bean不再被使用,则由Java自动进行垃圾回收。
相比之下,Spring管理Bean的生命周期就复杂多了,正确理解Bean 的生命周期非常重要,因为Spring对Bean的管理可扩展性非常强,下面展示了一个Bean的构造过程
如上图所示,Bean 的生命周期还是比较复杂的,下面来对上图每一个步骤做文字描述:
上面是Spring 中Bean的核心接口和生命周期,面试回答上述过程已经足够了。但是翻阅JavaDoc文档发现除了以上接口外,还有另外的初始化过程涉及的接口:
摘自org.springframework.beans.factory.BeanFactory, 全部相关接口如下,上述已有的就不用着重标注,把额外的相关接口着重标注下
文字解释如下:
————————————初始化————————————
————————————销毁————————————
在BeanFactory 关闭的时候,Bean的生命周期会调用如下方法:
为了验证Bean生命周期的过程,有两种形式:一种是为面试而准备的,一种是为了解全过程而准备的,下面来看代码:
Book.class
public class Book implements BeanNameAware,BeanFactoryAware, ApplicationContextAware,InitializingBean,DisposableBean { private String bookName; public Book(){ System.out.println("Book Initializing "); } public void setBeanFactory(BeanFactory beanFactory) throws BeansException { System.out.println("Book.setBeanFactory invoke"); } public void setBeanName(String name) { System.out.println("Book.setBeanName invoke"); } public void destroy() throws Exception { System.out.println("Book.destory invoke"); } public void afterPropertiesSet() throws Exception { System.out.println("Book.afterPropertiesSet invoke"); } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { System.out.println("Book.setApplicationContext invoke"); } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; System.out.println("setBookName: Book name has set."); } public void myPostConstruct(){ System.out.println("Book.myPostConstruct invoke"); } // 自定义初始化方法 @PostConstruct public void springPostConstruct(){ System.out.println("@PostConstruct"); } public void myPreDestory(){ System.out.println("Book.myPreDestory invoke"); System.out.println("---------------destroy-----------------"); } // 自定义销毁方法 @PreDestroy public void springPreDestory(){ System.out.println("@PreDestory"); } @Override protected void finalize() throws Throwable { System.out.println("------inside finalize-----"); } }
自定义实现BeanPostProcessor 的MyBeanPostProcessor:
public class MyBeanPostProcessor implements BeanPostProcessor { // 容器加载的时候会加载一些其他的bean,会调用初始化前和初始化后方法 // 这次只关注book(bean)的生命周期 public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if(bean instanceof Book){ System.out.println("MyBeanPostProcessor.postProcessBeforeInitialization"); } return bean; } public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if(bean instanceof Book){ System.out.println("MyBeanPostProcessor.postProcessAfterInitialization"); } return bean; } }
在resources 目录下新建Bean-Lifecycle.xml
做一个启动类的测试,新建SpringBeanLifecycleApplication
public class SpringBeanLifecycleApplication { public static void main(String[] args) throws InterruptedException { // 为面试而准备的Bean生命周期加载过程 ApplicationContext context = new ClassPathXmlApplicationContext("Bean-Lifecycle.xml"); Book book = (Book)context.getBean("book"); System.out.println("Book name = " + book.getBookName()); ((ClassPathXmlApplicationContext) context).destroy(); } }
启动测试,输出结果如下:
Book Initializing
setBookName: Book name has set.
Book.setBeanName invoke
Book.setBeanFactory invoke
Book.setApplicationContext invoke
MyBeanPostProcessor.postProcessBeforeInitialization
@PostConstruct
Book.afterPropertiesSet invoke
Book.myPostConstruct invoke
MyBeanPostProcessor.postProcessAfterInitialization
Book name = thingking in java
@PreDestory
Book.destory invoke
Book.myPreDestory invoke
---------------destroy-----------------
为了验证Bean完整的生命周期,需要新建一个SubBookClass 继承Book类
public class SubBookClass extends Book implements BeanClassLoaderAware, EnvironmentAware,EmbeddedValueResolverAware,ResourceLoaderAware, ApplicationEventPublisherAware,MessageSourceAware{ private String bookSystem; public String getBookSystem() { return bookSystem; } public void setBookSystem(String bookSystem) { System.out.println("设置BookSystem 的属性值"); this.bookSystem = bookSystem; } public void setBeanClassLoader(ClassLoader classLoader) { System.out.println("SubBookClass.setBeanClassLoader() 方法被调用了"); } public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { System.out.println("SubBookClass.setApplicationEventPublisher() 方法被调用了"); } public void setEmbeddedValueResolver(StringValueResolver resolver) { System.out.println("SubBookClass.setEmbeddedValueResolver() 方法被调用了"); } public void setEnvironment(Environment environment) { System.out.println("SubBookClass.setEnvironment() 方法被调用了"); } public void setMessageSource(MessageSource messageSource) { System.out.println("SubBookClass.setMessageSource() 方法被调用了"); } public void setResourceLoader(ResourceLoader resourceLoader) { System.out.println("SubBookClass.setResourceLoader() 方法被调用了"); } }
上述SubBookClass类与Book是互补关系。
新建一个SubBean-Lifecycle.xml,注入SubBookClass
完整的SpringBeanLifecycleApplication 如下:
public class SpringBeanLifecycleApplication { public static void main(String[] args) throws InterruptedException { // 为面试而准备的Bean生命周期加载过程 ApplicationContext context = new ClassPathXmlApplicationContext("Bean-Lifecycle.xml"); Book book = (Book)context.getBean("book"); System.out.println("Book name = " + book.getBookName()); ((ClassPathXmlApplicationContext) context).destroy(); // 完整的加载过程,当然了解的越多越好 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("SubBean-Lifecycle.xml"); SubBookClass subBookClass = (SubBookClass) applicationContext.getBean("bookClass"); System.out.println("BookSystemName = " + subBookClass.getBookSystem()); ((ClassPathXmlApplicationContext) applicationContext).registerShutdownHook(); } }
输出完整的结果:
Book Initializing
setBookName: Book name has set.
Book.setBeanName invoke
Book.setBeanFactory invoke
Book.setApplicationContext invoke
MyBeanPostProcessor.postProcessBeforeInitialization
@PostConstruct
Book.afterPropertiesSet invoke
Book.myPostConstruct invoke
MyBeanPostProcessor.postProcessAfterInitialization
Book name = thingking in java
@PreDestory
Book.destory invoke
Book.myPreDestory invoke
---------------destroy-----------------
Book Initializing
设置BookSystem 的属性值
Book.setBeanName invoke
SubBookClass.setBeanClassLoader() 方法被调用了
Book.setBeanFactory invoke
SubBookClass.setEnvironment() 方法被调用了
SubBookClass.setEmbeddedValueResolver() 方法被调用了
SubBookClass.setResourceLoader() 方法被调用了
SubBookClass.setApplicationEventPublisher() 方法被调用了
SubBookClass.setMessageSource() 方法被调用了
Book.setApplicationContext invoke
MyBeanPostProcessor.postProcessBeforeInitialization
Book.afterPropertiesSet invoke
Book.myPostConstruct invoke
MyBeanPostProcessor.postProcessAfterInitialization
BookSystemName = Java System
Book.destory invoke
Book.myPreDestory invoke
---------------destroy-----------------
有需要源码的朋友,添加小助手VX:xuanwo008 领取资料备注好“CSDN”信息!即可免费领取!!!