前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Bean 的生命周期

Bean 的生命周期

作者头像
灰太狼学Java
发布2022-06-17 09:46:41
1990
发布2022-06-17 09:46:41
举报
文章被收录于专栏:Java学习驿站Java学习驿站

前言

在我们没有使用 Spring 框架之前,创建对象一般都是使用 new 关键字进行创建,当然除了 new 关键字外,还有

  • 运用反射手段,使用 Class 类的 newInstance 方法 或者 Constructor 类中的 newInstance 方法
  • 使用 clone 方法
  • 使用反序列化(ObjectInputStream)

一旦对象不再被使用的时候,将有可能被 JVM 垃圾回收器进行回收。

但是在 Spring 通过 IOC 容器进行管理之后,Bean 的生命周期就变得更加复杂了,下图展示了 Bean 的构造过程

Bean 的生命周期

我们对上图的每个步骤进行文字说明

  • Spring 启动,查找并加载需要被 Spring 管理的 bean,进行 Bean 的实例化
  • Bean 实例化后对将 Bean 的引入和值注入到 Bean 的属性中
  • 如果 Bean 实现了 BeanNameAware 接口的话,Spring 将 Bean 的 Id 传递给 setBeanName() 方法
  • 如果 Bean 实现了 BeanFactoryAware 接口的话,Spring 将调用 setBeanFactory() 方法,将 BeanFactory 容器实例传入
  • 如果 Bean 实现了 ApplicationContextAware 接口的话,Spring 将调用 Bean 的 setApplicationContext() 方法,将 bean 所在应用上下文引用传入进来。
  • 如果 Bean 实现了 BeanPostProcessor 接口,Spring 就将调用他们的 postProcessBeforeInitialization() 方法。
  • 如果 Bean 实现了 InitializingBean 接口,Spring 将调用他们的 afterPropertiesSet() 方法。类似的,如果 bean 使用 init-method 声明了初始化方法,该方法也会被调用
  • 如果 Bean 实现了 BeanPostProcessor 接口,Spring 就将调用他们的 postProcessAfterInitialization() 方法。
  • 此时,Bean 已经准备就绪,可以被应用程序使用了。他们将一直驻留在应用上下文中,直到应用上下文被销毁。
  • 如果 bean 实现了 DisposableBean 接口,Spring 将调用它的 destory() 接口方法,同样,如果 bean 使用了 destory-method 声明销毁方法,该方法也会被调用。

接口方法的分类

Bean 的完整生命周期经历了各种方法的调用,这些方法可以分类一下三类

Bean自身的方法:

这个包括了 Bean 本身调用的方法和通过配置文件中 的 init-method 和 destroy-method 指定的方法

Bean 级生命周期的方法

这个包括了 BeanNameAware、BeanFactoryAware、InitializingBean 和 DiposableBean 这些接口的方法

容器级生命周期的方法

这个包括了 InstantiationAwareBeanPostProcessor 和 BeanPostProcessor 这两个接口实现,一般称它们的实现类为“后处理器”。

工程后处理器接口方法

这个包括了 AspectJWeavingEnabler, ConfigurationClassPostProcessor, CustomAutowireConfigurer 等等非常有用的工厂后处理器接口的方法。工厂后处理器也是容器级的。在应用上下文装配配置文件之后立即调用。

DEMO 举例

我们用一个简单的 Spring Bean 来演示一下 Spring Bean 的生命周期。

首先是一个简单的 Spring Bean,调用 Bean 自身的方法和 Bean 级生命周期接口方法,为了方便演示,它实现了 BeanNameAware、BeanFactoryAware、InitializingBean 和 DiposableBean 这4个接口,同时有2个方法,对应配置文件中 的 init-method 和 destroy-method。如下:

代码语言:javascript
复制
package springBeanTest;

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;

public class Person implements BeanFactoryAware, BeanNameAware,
        InitializingBean, DisposableBean {

    private String name;
    private String address;
    private int phone;

    private BeanFactory beanFactory;
    private String beanName;

    public Person() {
        System.out.println("【构造器】调用 Person 的构造器实例化");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        System.out.println("【注入属性】注入属性 name");
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        System.out.println("【注入属性】注入属性 address");
        this.address = address;
    }

    public int getPhone() {
        return phone;
    }

    public void setPhone(int phone) {
        System.out.println("【注入属性】注入属性 phone");
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "Person [address=" + address + ", name=" + name + ", phone="
                + phone + "]";
    }

    // 这是 BeanFactoryAware 接口方法
    @Override
    public void setBeanFactory(BeanFactory arg0) throws BeansException {
        System.out
                .println("【 BeanFactoryAware 接口】调用BeanFactoryAware.setBeanFactory()");
        this.beanFactory = arg0;
    }

    // 这是 BeanNameAware 接口方法
    @Override
    public void setBeanName(String arg0) {
        System.out.println("【 BeanNameAware 接口】调用BeanNameAware.setBeanName()");
        this.beanName = arg0;
    }

    // 这是 InitializingBean 接口方法
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out
                .println("【 InitializingBean 接口】调用InitializingBean.afterPropertiesSet()");
    }

    // 这是 DiposibleBean 接口方法
    @Override
    public void destroy() throws Exception {
        System.out.println("【 DiposibleBean 接口】调用DiposibleBean.destory()");
    }

    // 通过 <bean> 的 init-method 属性指定的初始化方法
    public void myInit() {
        System.out.println("【 init-method 】调用 <bean> 的 init-method 属性指定的初始化方法");
    }

    // 通过 <bean> 的 destroy-method 属性指定的初始化方法
    public void myDestory() {
        System.out.println("【 destroy-method 】调用 <bean> 的 destroy-method 属性指定的初始化方法");
    }
}

接下来是演示 BeanPostProcessor 接口的方法,如下:

代码语言:javascript
复制
package springBeanTest;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class MyBeanPostProcessor implements BeanPostProcessor {

    public MyBeanPostProcessor() {
        super();
        System.out.println("这是 BeanPostProcessor 实现类构造器!!");
        // TODO Auto-generated constructor stub
    }

    @Override
    public Object postProcessAfterInitialization(Object arg0, String arg1)
            throws BeansException {
        System.out
        .println("BeanPostProcessor 接口方法 postProcessAfterInitialization 对属性进行更改!");
        return arg0;
    }

    @Override
    public Object postProcessBeforeInitialization(Object arg0, String arg1)
            throws BeansException {
        System.out
        .println("BeanPostProcessor 接口方法 postProcessBeforeInitialization 对属性进行更改!");
        return arg0;
    }
}

如上,BeanPostProcessor 接口包括2个方法 postProcessAfterInitialization 和 postProcessBeforeInitialization,这两个方法的第一个参数都是要处理的 Bean 对象,第二个参数都是 Bean 的 name。返回值也都是要处理的 Bean 对象。这里要注意。

InstantiationAwareBeanPostProcessor 接口本质是 BeanPostProcessor 的子接口,一般我们继承 Spring 为其提供的适配器类 InstantiationAwareBeanPostProcessor Adapter 来使用它,如下:

代码语言:javascript
复制
package springBeanTest;

import java.beans.PropertyDescriptor;

import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;

public class MyInstantiationAwareBeanPostProcessor extends
        InstantiationAwareBeanPostProcessorAdapter {

    public MyInstantiationAwareBeanPostProcessor() {
        super();
        System.out
                .println("这是 InstantiationAwareBeanPostProcessorAdapter 实现类构造器!!");
    }

    // 接口方法、实例化 Bean 之前调用
    @Override
    public Object postProcessBeforeInstantiation(Class beanClass,
            String beanName) throws BeansException {
        System.out
                .println("InstantiationAwareBeanPostProcessor 调用 postProcessBeforeInstantiation 方法");
        return null;
    }

    // 接口方法、实例化 Bean 之后调用
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        System.out
                .println("InstantiationAwareBeanPostProcessor 调用 postProcessAfterInitialization 方法");
        return bean;
    }

    // 接口方法、设置某个属性时调用
    @Override
    public PropertyValues postProcessPropertyValues(PropertyValues pvs,
            PropertyDescriptor[] pds, Object bean, String beanName)
            throws BeansException {
        System.out
                .println("InstantiationAwareBeanPostProcessor 调用 postProcessPropertyValues 方法");
        return pvs;
    }
}

参考

https://www.cnblogs.com/zrtqsk/p/3735273.html https://www.cnblogs.com/javazhiyin/p/10905294.html

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • Bean 的生命周期
  • 接口方法的分类
    • Bean自身的方法:
      • Bean 级生命周期的方法
        • 容器级生命周期的方法
          • 工程后处理器接口方法
          • DEMO 举例
          • 参考
          相关产品与服务
          容器服务
          腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档