继续 Spring 复盘,今天看了下 Spring 的 Bean 生命周期。java
在传统的 Java 应用中,bean 的生命周期很简单,使用 Java 关键字 new 进行Bean 的实例化,而后该 Bean 就可以使用了。一旦 bean 再也不被使用,则由 Java 自动进行垃圾回收,简直不要太简单。git
相比之下,Spring 管理 Bean 的生命周期就复杂多了,正确理解 Bean 的生命周期很是重要,由于 Spring 对 Bean 的管理可扩展性很是强,下面展现了一个 Bea 的构造过程。程序员
以上图片出自 《Spring 实战(第四版)》一书,图片描述了一个经典的 Spring Bean 的生命周期,书中随他的解释以下:github
1.Spring对bean进行实例化;
2.Spring将值和bean的引用注入到bean对应的属性中;
3.若是bean实现了BeanNameAware接口,Spring将bean的ID传递给
setBean-Name()方法;
4.若是bean实现了BeanFactoryAware接口,Spring将调
用setBeanFactory()方法,将BeanFactory容器实例传入;
5.若是bean实现了ApplicationContextAware接口,Spring将调
用setApplicationContext()方法,将bean所在的应用上下文的
引用传入进来;
6.若是bean实现了BeanPostProcessor接口,Spring将调用它们
的post-ProcessBeforeInitialization()方法;
7.若是bean实现了InitializingBean接口,Spring将调用它们的
after-PropertiesSet()方法。相似地,若是bean使用init-
method声明了初始化方法,该方法也会被调用;
8.若是bean实现了BeanPostProcessor接口,Spring将调用它们
的post-ProcessAfterInitialization()方法;
9.此时,bean已经准备就绪,能够被应用程序使用了,它们将一直
驻留在应用上下文中,直到该应用上下文被销毁;
10.若是bean实现了DisposableBean接口,Spring将调用它的
destroy()接口方法。一样,若是bean使用destroy-method声明
了销毁方法,该方法也会被调用。
写了下代码验证以上说法,首先建立一个 Person 类,它就是咱们要验证的 Bean ,为方便测试,他实现了 BeanNameAware, BeanFactoryAware, ApplicationContextAware, InitializingBean, DisposableBean。代码以下:面试
package com.nasus.bean; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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.beans.factory.config.BeanPostProcessor; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Scope; /** * Project Name:review_spring <br/> * Package Name:PACKAGE_NAME <br/> * Date:2019/9/1 16:29 <br/> * * @author <a href="turodog@foxmail.com">chenzy</a><br/> */ @Scope("ProtoType") public class Person implements BeanNameAware, BeanFactoryAware, ApplicationContextAware, InitializingBean, DisposableBean { private static final Logger LOGGER = LoggerFactory.getLogger(Person.class); private String name; public Person(){ System.out.println("一、开始实例化 person "); } public String getName() { return name; } public void setName(String name) { this.name = name; System.out.println("二、设置 name 属性"); } @Override public void setBeanName(String beanId) { System.out.println("三、Person 实现了 BeanNameAware 接口,Spring 将 Person 的 " + "ID=" + beanId + "传递给 setBeanName 方法"); } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { System.out.println("四、Person 实现了 BeanFactoryAware 接口,Spring 调" + "用 setBeanFactory()方法,将 BeanFactory 容器实例传入"); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { System.out.println("五、Person 实现了 ApplicationContextAware 接口,Spring 调" + "用 setApplicationContext()方法,将 person 所在的应用上下文的" + "引用传入进来"); } @Override public void afterPropertiesSet() throws Exception { System.out.println("八、Person 实现了 InitializingBean 接口,Spring 调用它的" + "afterPropertiesSet()方法。相似地,若是 person 使用 init-" + "method 声明了初始化方法,该方法也会被调用"); } @Override public void destroy() throws Exception { System.out.println("1三、Person 实现了 DisposableBean 接口,Spring 调用它的" + "destroy() 接口方法。一样,若是 person 使用 destroy-method 声明" + "了销毁方法,该方法也会被调用"); } /** * xml 中声明的 init-method 方法 */ public void initMethod(){ System.out.println("九、xml 中声明的 init-method 方法"); } /** * xml 中声明的 destroy-method 方法 */ public void destroyMethod(){ System.out.println("1四、xml 中声明的 destroy-method 方法"); System.out.println("end---------------destroy-----------------"); } // 自定义初始化方法 @PostConstruct public void springPostConstruct(){ System.out.println("七、@PostConstruct 调用自定义的初始化方法"); } // 自定义销毁方法 @PreDestroy public void springPreDestory(){ System.out.println("十二、@PreDestory 调用自定义销毁方法"); } @Override protected void finalize() throws Throwable { System.out.println("finalize 方法"); } }
除此以外,建立了一个 MyBeanPostProcessor 类继承自 BeanPostProcessor 这个类只关心 Person 初始化先后要作的事情。好比,初始化以前,加载其余 Bean。代码以下:spring
package com.nasus.lifecycle; import com.nasus.bean.Person; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; /** * Project Name:review_spring <br/> * Package Name:PACKAGE_NAME <br/> * Date:2019/9/1 16:25 <br/> * * @author <a href="turodog@foxmail.com">chenzy</a><br/> */ public class MyBeanPostProcessor implements BeanPostProcessor { // 容器加载的时候会加载一些其余的 bean,会调用初始化前和初始化后方法 // 此次只关注 Person 的生命周期 public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if(bean instanceof Person){ System.out.println("六、初始化 Person 以前执行的方法"); } return bean; } public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if(bean instanceof Person){ System.out.println("十、初始化 Person 完成以后执行的方法"); } return bean; } }
resource 文件夹下新建一个 bean_lifecycle.xml 文件注入相关 bean ,代码以下:app
<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.nasus"/> <!-- 实现了用户自定义初始化和销毁方法 --> <bean id="person" class="com.nasus.bean.Person" init-method="initMethod" destroy-method="destroyMethod"> <!-- 注入bean 属性名称 --> <property name="name" value="nasus" /> </bean> <!--引入自定义的BeanPostProcessor--> <bean class="com.nasus.lifecycle.MyBeanPostProcessor"/> </beans>
测试类,获取 person 这个 Bean 并使用它,代码以下:框架
import com.nasus.bean.Person; import java.awt.print.Book; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Project Name:review_spring <br/> * Package Name:PACKAGE_NAME <br/> * Date:2019/9/1 16:38 <br/> * * @author <a href="turodog@foxmail.com">chenzy</a><br/> */ public class lifeCycleTest { @Test public void testLifeCycle(){ // 为面试而准备的Bean生命周期加载过程 ApplicationContext context = new ClassPathXmlApplicationContext("bean_lifecycle.xml"); Person person = (Person)context.getBean("person"); // 使用属性 System.out.println("十一、实例化完成使用属性:Person name = " + person.getName()); // 关闭容器 ((ClassPathXmlApplicationContext) context).close(); } }
lifeCycleTest 方法最后关闭了容器,关闭的同时控制台日志输出以下:ide
一、开始实例化 person 二、设置 name 属性 三、Person 实现了 BeanNameAware 接口,Spring 将 Person 的 ID=person传递给 setBeanName 方法 四、Person 实现了 BeanFactoryAware 接口,Spring 调用 setBeanFactory()方法,将 BeanFactory 容器实例传入 五、Person 实现了 ApplicationContextAware 接口,Spring 调用 setApplicationContext()方法,将 person 所在的应用上下文的引用传入进来 六、初始化 Person 以前执行的方法 七、@PostConstruct 调用自定义的初始化方法 八、Person 实现了 InitializingBean 接口,Spring 调用它的afterPropertiesSet()方法。相似地,若是 person 使用 init-method 声明了初始化方法,该方法也会被调用 九、xml 中声明的 init-method 方法 十、初始化 Person 完成以后执行的方法 十一、实例化完成使用属性:Person name = nasus 十二、@PreDestory 调用自定义销毁方法 1三、Person 实现了 DisposableBean 接口,Spring 调用它的destroy() 接口方法。一样,若是 person 使用 destroy-method 声明了销毁方法,该方法也会被调用 1四、xml 中声明的 destroy-method 方法 end---------------destroy-----------------
由以上日志可知,当 person 默认是单例模式时,bean 的生命周期与容器的生命周期同样,容器初始化,bean 也初始化。容器销毁,bean 也被销毁。那若是,bean 是非单例呢?post
有时咱们须要在 Bean 属性值 set 好以后和 Bean 销毁以前作一些事情,好比检查 Bean 中某个属性是否被正常的设置好值了。Spring 框架提供了多种方法让咱们能够在 Spring Bean 的生命周期中执行 initialization 和 pre-destroy 方法。这些方法我在上面已经测试过了,以上代码实现了多种方法,它是重复,开发中选如下其一便可,好比:
上面测试中的 person 默认是 singleton 的,如今咱们将 person 改成 protoType 模式,bean_lifecycle.xml 作以下代码修改,其他类保持不变:
<!-- 实现了用户自定义初始化和销毁方法 --> <bean id="person" scope="prototype" class="com.nasus.bean.Person" init-method="initMethod" destroy-method="destroyMethod"> <!-- 注入bean 属性名称 --> <property name="name" value="nasus" /> </bean>
此时的日志输出以下:
一、开始实例化 person 二、设置 name 属性 三、Person 实现了 BeanNameAware 接口,Spring 将 Person 的 ID=person传递给 setBeanName 方法 四、Person 实现了 BeanFactoryAware 接口,Spring 调用 setBeanFactory()方法,将 BeanFactory 容器实例传入 五、Person 实现了 ApplicationContextAware 接口,Spring 调用 setApplicationContext()方法,将 person 所在的应用上下文的引用传入进来 六、初始化 Person 以前执行的方法 七、@PostConstruct 调用自定义的初始化方法 八、Person 实现了 InitializingBean 接口,Spring 调用它的afterPropertiesSet()方法。相似地,若是 person 使用 init-method 声明了初始化方法,该方法也会被调用 九、xml 中声明的 init-method 方法 十、初始化 Person 完成以后执行的方法 十一、实例化完成使用属性:Person name = nasus
此时,容器关闭,person 对象并无销毁。缘由在于,单实例模式下,bean 的生命周期由容器管理,容器生,bean 生;容器死,bean 死。而在多实例模式下,Spring 就管不了那么多了,bean 的生命周期,交由客户端也就是程序员或者 JVM 来进行管理。
首先说说单实例,单实例模式下,bean 在容器加载那一刻起,就已经完成实例化了,证实以下,我启用 debug 模式,在 20 行打了一个断点,而日志却以下所示,说明了 bean 在 19 行,初始化容器的时候,已经完成实例化了。
再说多实例模式下,这个模式下,bean 在须要用到 bean 的时候才进行初始化,证实以下,一样执行完 19 行,多实例模式下,控制台一片空白,说明此时的 bean 是未被加载的。
debug 走到 23 行时,须要用到 bean 时,bean 才被加载了,验证以下。在开发中,咱们把这种加载叫作懒加载,它的用处就是减轻程序开销,等到要用时才加载,而不是一上来就加载所有。
只需在 xml 中加上 lazy-init 属性为 true 便可。以下,它的加载方式就变成了懒加载。
<!-- 实现了用户自定义初始化和销毁方法 --> <bean id="person" lazy-init="true" class="com.nasus.bean.Person" init-method="initMethod" destroy-method="destroyMethod"> <!-- 注入bean 属性名称 --> <property name="name" value="nasus" /> </bean>
若是想对全部的默认单例 bean 都应用延迟初始化,能够在根节点 beans 设置 default-lazy-init 属性为 true,以下所示:
<beans default-lazy-init="true" …>
https://github.com/turoDog/review_spring
推荐阅读:
一、java | 什么是动态代理