赞
踩
前言
这其实是一道面试题,是我在面试百度的时候被问到的,当时没有答出来(因为自己真的很菜),后来在网上寻找答案,看到也是一头雾水,直到看到了《Spring in action》这本书,书上有对Bean声明周期的大致解释,但是没有代码分析,所以就自己上网寻找资料,一定要把这个Bean生命周期弄明白!
网上大部分都是验证的Bean 在面试问的生命周期,其实查阅JDK还有一个完整的Bean生命周期,这同时也验证了书是具有片面性的,最fresh 的资料还是查阅原始JDK!!!
一、Bean 的完整生命周期
在传统的Java应用中,bean的生命周期很简单,使用Java关键字 new 进行Bean 的实例化,然后该Bean 就能够使用了。一旦bean不再被使用,则由Java自动进行垃圾回收。
相比之下,Spring管理Bean的生命周期就复杂多了,正确理解Bean 的生命周期非常重要,因为Spring对Bean的管理可扩展性非常强,下面展示了一个Bean的构造过程
Bean 的生命周期
如上图所示,Bean 的生命周期还是比较复杂的,下面来对上图每一个步骤做文字描述:
上面是Spring 中Bean的核心接口和生命周期,面试回答上述过程已经足够了。但是翻阅JavaDoc文档发现除了以上接口外,还有另外的初始化过程涉及的接口:摘自org.springframework.beans.factory.BeanFactory, 全部相关接口如下,上述已有的就不用着重标注,把额外的相关接口着重标注下
Bean 完整的生命周期
文字解释如下:
————————————初始化————————————
————————————销毁————————————
在BeanFactory 关闭的时候,Bean的生命周期会调用如下方法:
二、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
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
- <!-- 扫描bean -->
- <context:component-scan base-package="com.bean.lifecycle"/>
- <!-- 实现了用户自定义初始化和销毁方法 -->
- <bean id="book" class="com.bean.lifecycle.Book" init-method="myPostConstruct" destroy-method="myPreDestory">
- <!-- 注入bean 属性名称 -->
- <property name="bookName" value="thingking in java" />
- </bean>
- <!--引入自定义的BeanPostProcessor-->
- <bean class="com.bean.lifecycle.MyBeanPostProcessor"/>
- </beans>
做一个启动类的测试,新建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
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
- <bean id="bookClass" class="com.bean.lifecycle.SubBookClass" init-method="myPostConstruct" destroy-method="myPreDestory">
- <property name="bookSystem" value="Java System" />
- </bean>
- <bean class="com.bean.lifecycle.MyBeanPostProcessor"/>
- </beans>
完整的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-----------------
后记:这篇文章是我翻阅各种书籍和从网上查找资料,包括国外一些网站从而得到的结论,记录下来,但是我没有发现Spring Bean的生命周期(非常详细) 这篇文章中InstantiationAwareBeanPostProcessorAdapter 这个类和工厂后置处理器接口方法,知道的朋友欢迎指教,感谢。
欢迎工作一到五年的Java工程师朋友们加入Java程序员开发: 721575865
群内提供免费的Java架构学习资料(里面有高可用、高并发、高性能及分布式、Jvm性能调优、Spring源码,MyBatis,Netty,Redis,Kafka,Mysql,Zookeeper,Tomcat,Docker,Dubbo,Nginx等多个知识点的架构资料)合理利用自己每一分每一秒的时间来学习提升自己,不要再用"没有时间“来掩饰自己思想上的懒惰!趁年轻,使劲拼,给未来的自己一个交代!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。