Spring 容器中的 Bean 是有生命周期的,Spring 允许在 Bean 在初始化完成后以及 Bean 销毁前执行特定的操作,常用的设定方式有以下十种:

  1. 通过实现 InitializingBean 接口来定制初始化之后的操作方法;
  2. 通过实现DisposableBean 接口来定制销毁之前的操作方法;
  3. 通过元素的 init-method属性指定初始化之后调用的操作方法;
  4. 通过元素的 destroy-method属性指定销毁之前调用的操作方法;
  5. 在指定方法上加上 @PostConstruct 注解来制定该方法是在初始化之后调用;
  6. 在指定方法上加上 @PreDestroy 注解来制定该方法是在销毁之前调用;
  7. 实现BeanNameAware接口设置Bean的ID或者Name;
  8. 实现BeanFactoryAware接口设置BeanFactory;
  9. 实现ApplicationContextAware接口设置ApplicationContext;
  10. 注册实现了BeanPostProcessor的Bean后处理器,通过postProcessBeforeInitialization和postProcessAfterInitialization 方法对初始化的Bean进行自定义处理;

那么这十种方式所定义方法执的行顺序是什么?
鄙人经过大量的代码实验得到了一些结果记录下来,以供用到时查阅。

初始化过程中各方法的执行顺序如下:

  1. 调用构造器 Bean.constructor,进行实例化;
  2. 调用 Setter 方法,设置属性值;
  3. 调用 BeanNameAware.setBeanName,设置Bean的ID或者Name;
  4. 调用 BeanFactoryAware.setBeanFactory,设置BeanFactory;
  5. 调用 ApplicationContextAware.setApplicationContext,置ApplicationContext;
  6. 调用BeanPostProcessor的预先初始化方法,如下:
    BeanPostProcessor1.postProcessBeforeInitialization
    BeanPostProcessor2.postProcessBeforeInitialization
    BeanPostProcessor3.postProcessBeforeInitialization
    ……
  7. 调用由 @PostConstruct 注解的方法;
  8. 调用 InitializingBean.afterPropertiesSet;
  9. 调用 Bean.init-mehod 初始化方法;
  10. 调用BeanPostProcessor的后初始化方法,如下:
    BeanPostProcessor1.postProcessAfterInitialization
    BeanPostProcessor2.postProcessAfterInitialization
    BeanPostProcessor3.postProcessAfterInitialization
    ……

容器关闭时,Bean销毁过程中各方法的执行顺序如下:

  1. 调用由 @PreDestroy 注解的方法
  2. 调用DisposableBean的destroy();
  3. 调用定制的destroy-method方法;

实验代码如下:

文件 bean.xml 的代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
"
default-init-method="init_method" default-destroy-method="destroy_method">
<context:component-scan base-package="spring" />
<bean class="spring.InitHelloWorld2"/>
<bean class="spring.InitHelloWorld"/>
<bean id="hello" class="spring.Hello1" >
<property name="message" value="ccccccccc"/>
</bean>
</beans>

文件 Hello1.java 的代码如下:

package spring;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
public class Hello1 implements InitializingBean, BeanNameAware,BeanFactoryAware,ApplicationContextAware,DisposableBean{
private String message;
public String getMessage(){
return message;
}
public void setMessage(String message){
System.out.println("Hello1 setMessage");
this.message = message;
}
public Hello1(){
System.out.println("Hello1 构造器");
}
public void hello(){
System.out.println("Hello1 我是:" + message);
}
public void init_method(){
System.out.println("Hello1 init-method ");
}
@PostConstruct
public void postConstruct(){
System.out.println("Hello1 @PostConstruct");
}
@Override
public void afterPropertiesSet() throws Exception{
System.out.println("Hello1 InitializingBean.afterPropertiesSet");
}
@Override
public void setBeanName(String s){
System.out.println("Hello1 setBeanName " + s);
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException{
System.out.println("Hello1 setBeanFactory " );
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException{
System.out.println("Hello1 setApplicationContext " );
}
@Override
public void destroy() throws Exception{
System.out.println("Hello1 DisposableBean.destroy " );
}
public void destroy_method() throws Exception{
System.out.println("Hello1 destroy-method " );
}
@PreDestroy
public void preDestroy() throws Exception{
System.out.println("Hello1 @PreDestroy " );
}
}

文件 InitHelloWord.java 的代码如下:

package spring;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.Ordered;
public class InitHelloWorld implements BeanPostProcessor,Ordered{
@Override
public Object postProcessBeforeInitialization(Object o, String s) throws BeansException{
System.out.println("BeanPostProcessor1.postProcessBeforeInitialization:" + s);
return o;
}
@Override
public Object postProcessAfterInitialization(Object o, String s) throws BeansException{
System.out.println("BeanPostProcessor1.postProcessAfterInitialization:" + s);
return o;
}
@Override
public int getOrder(){
return 10;
}
}

文件 InitHelloWord2.java 的代码如下:

package spring;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.Ordered;
public class InitHelloWorld2 implements BeanPostProcessor,Ordered{
@Override
public Object postProcessBeforeInitialization(Object o, String s) throws BeansException{
System.out.println("BeanPostProcessor2.postProcessBeforeInitialization:" + s);
return o;
}
@Override
public Object postProcessAfterInitialization(Object o, String s) throws BeansException{
System.out.println("BeanPostProcessor2.postProcessAfterInitialization:" + s);
return o;
}
@Override
public int getOrder(){
return 20;
}
}

文件 MainApp.java 代码如下:

package spring;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp{
public static void main(String... args){
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
Hello1 hello = (Hello1) ctx.getBean("hello");
hello.hello();
ctx.close();
}
}

代码执行结果如下:

Hello1 构造器
Hello1 setMessage
Hello1 setBeanName hello
Hello1 setBeanFactory
Hello1 setApplicationContext
BeanPostProcessor1.postProcessBeforeInitialization:hello
BeanPostProcessor2.postProcessBeforeInitialization:hello
Hello1 @PostConstruct
Hello1 InitializingBean.afterPropertiesSet
Hello1 init-method
BeanPostProcessor1.postProcessAfterInitialization:hello
BeanPostProcessor2.postProcessAfterInitialization:hello
Hello1 我是:ccccccccc
Hello1 @PreDestroy
Hello1 DisposableBean.destroy
Hello1 destroy-method

链接:https://www.jianshu.com/p/80d4fa132747

在Spring Bean的生命周期中各方法的执行顺序的更多相关文章

  1. Spring Bean的生命周期,《Spring 实战》书中的官方说法

    连着两天的面试 ,都问到了 Spring 的Bean的生命周期,其中还包括 昨晚一波阿里的电话面试.这里找到了Spring 实战中的官方说法.希望各位要面试的小伙伴记住,以后有可能,或者是有时间 去看 ...

  2. 你知道Spring是怎么将AOP应用到Bean的生命周期中的吗?

    聊一聊Spring是怎么将AOP应用到Bean的生命周期中的? 本系列文章: 听说你还没学Spring就被源码编译劝退了?30+张图带你玩转Spring编译 读源码,我们可以从第一行读起 你知道Spr ...

  3. Spring Bean的生命周期(非常详细)

    Spring作为当前Java最流行.最强大的轻量级框架,受到了程序员的热烈欢迎.准确的了解Spring Bean的生命周期是非常必要的.我们通常使用ApplicationContext作为Spring ...

  4. Spring Bean的生命周期相关博客

    最近得面试题一直 问 Spring 得生命周期,鉴于自己还未阅读过源码 所以只能是自己 背一波了.属实不懂硬背得作用,但是无奈被各位面试官打败了.等以后有时间了 一定要阅读几遍spring的 源码 有 ...

  5. Spring学习手札(四)谈谈Spring Bean的生命周期及作用域

    在Spring中,那些组成应用程序的主体以及由Spring IoC容器所管理的对象,被称之为Bean.Bean与应用程序中其他对象(比如自己创建类)的区别就是,Bean是由IoC容器创建于销毁的.在S ...

  6. Spring Bean的生命周期详解(转)

    Spring作为当前Java最流行.最强大的轻量级框架,受到了程序员的热烈欢迎.准确的了解Spring Bean的生命周期是非常必要的.我们通常使用ApplicationContext作为Spring ...

  7. Spring动态代理及Spring Bean的生命周期

    数组添加值 public class DiTest { /** * 数组 */ private String [] arrays; /** * List:集合 */ private List<I ...

  8. Spring(三)--Spring bean的生命周期

    Spring bean的生命周期 ApplicationContext Bean生命周期流程 1.需要的实体类 ackage com.xdf.bean; import org.springframew ...

  9. 第37讲 谈谈Spring Bean的生命周期和作用域

    在企业应用软件开发中,Java 是毫无争议的主流语言,开放的 Java EE 规范和强大的开源框架功不可没,其中 Spring 毫无疑问已经成为企业软件开发的事实标准之一.今天这一讲,我将补充 Spr ...

随机推荐

  1. 关于idea的一些快捷键

    最近在用idea写代码,熟悉一些快捷键的使用能够让写代码的速度提高,以下快捷键是默认idea的快捷键,当然我们可以自己修改的: 自动补全代码快捷键:CTRL+alt+V 自动格式化代码:CTRL+al ...

  2. egret的WebView实现

    需求 在egret中嵌入网页,类似 . 网上大概有两种思路吧,一种是直接在body里面加入iframe,如:[Egret]里使用iframe标签达到内嵌多个web界面;另一种就是通过模仿htmlinp ...

  3. MongoDB快速入门教程 (3.3)

    3.4.聚合 3.4.1.什么是聚合? MongoDB中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果.有点类似sql语句中的 count(*) 例如上图 ...

  4. oracle闪回,找回已提交修改的记录

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/qq_24521431/article/details/84580166 例如删除ward_id为96 ...

  5. jquery 获取页面和滚动条的高度

    1.获取浏览器显示区域的高度 : $(window).height(); 2.获取浏览器显示区域的宽度 : $(window).width(); 3.获取页面的文档高度 : $(document).h ...

  6. Java工具类——数学相关的类

    Java工具类--数学相关的类 在上一篇文章中,我们系统学习了 Java 里面的包装类,那么这篇文章,我们就来学习一下Java提供好的类--数学相关的类. 一.数学类介绍 在最早期学习 Java 基础 ...

  7. MACOS使用VScode进行C语言编程

    [B站有同步视频教程] 安装VScode 从官网下载vscode安装https://code.visualstudio.com/ 安装code runner插件 配置code runner从终端输出 ...

  8. Fetch.AI的最新发布speaks your language

    更新增强长期网络的稳定性 包括新的Etch功能,使我们的代码比以往对开发人员更加友好.我们现在支持太阳下的每一种语言,包括普通话,希腊语和希伯来语-甚至表情符号 介绍我们很高兴地宣布我们最新的技术更新 ...

  9. call_user_func的使用

    <?php function demo01($a) { echo $a; } call_user_func("demo01", "hello world" ...

  10. 深入理解JVM(③)学习Java的内存模型

    前言 Java内存模型(Java Memory Model)用来屏蔽各种硬件和操作系统的内存访问差异,这使得Java能够变得非常灵活而不用考虑各系统间的兼容性等问题.定义Java内存模型并非一件容易的 ...