Spring中的bean的生命周期

Spring中的bean的生命周期主要包含以下四个阶段:

  1. 实例化Bean:在Spring容器启动时,根据配置文件或注解创建Bean的实例。这个阶段是通过调用构造函数来完成的。

  2. Bean属性填充:在实例化Bean之后,Spring会通过依赖注入的方式将Bean所需的属性值注入到Bean中。这个阶段是通过调用setter方法来完成的。

  3. 初始化Bean:在Bean属性填充完成后,Spring会调用Bean的初始化方法对Bean进行一些额外的初始化操作。这个阶段可以通过实现InitializingBean接口的afterPropertiesSet()方法或在配置文件中使用init-method属性来指定初始化方法。

  4. 销毁Bean:在Spring容器关闭时,会调用Bean的销毁方法对Bean进行一些清理工作。这个阶段可以通过实现DisposableBean接口的destroy()方法或在配置文件中使用destroy-method属性来指定销毁方法。

更加具体的步骤通过下面的实际案例来讲解

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

package com.ape.test;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import sun.util.resources.cldr.my.CurrencyNames_my;

/**
 * @author Jey
 * @version 1.0
 * @since 2024/1/7
 */
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{" +
                "name='" + name + '\'' +
                ", address='" + address + '\'' +
                ", phone=" + phone +
                '}';
    }

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

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

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

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

    }

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

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

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

BeanPostProcessor接口包括2个方法postProcessAfterInitialization和postProcessBeforeInitialization,这两个方法的第一个参数都是要处理的Bean对象,第二个参数都是Bean的name。返回值也都是要处理的Bean对象。
执行BeanPostProcessor前置处理: 如果想对Bean 进行一些自定义的前置处理,那么可以让Bean实现了BeanPostProcessor 接口,将会在该阶段调用postProcessBeforeInitialization(0bject obj, String s)方法。

执行BeanPostProcessor后置处理:如果这个Bean 实现了BeanPostProcessor接口,将会调用postProcessAfterInitialization(0bject obj, String s)方法,由于这个方法是在Bean初始化结束后调用;

package com.ape.test;

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

/**
 * @author Jey
 * @version 1.0
 * @since 2024/1/8
 */
public class MyBeanPostProcessor implements BeanPostProcessor {
    public MyBeanPostProcessor() {
        super();
        System.out.println("这是BeanPostProcessor实现类构造器~");
    }



    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

        System.out.println("BeanPostProcessor的before方法对属性进行更改!");
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("BeanPostProcessor的after方法方法对属性进行更改!");
        return bean;
    }
}

演示工厂后处理器接口方法,如下:

package com.ape.test;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

/**
 * @author Jey
 * @version 1.0
 * @since 2024/1/8
 */
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    public MyBeanFactoryPostProcessor() {
        super();
        System.out.println("这是BeanFactoryPostProcessor实现类构造器!!");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0) throws BeansException {
        System.out.println("BeanFactoryPostProcessor调用postProcessBeanFactory方法");
        BeanDefinition bd = arg0.getBeanDefinition("person");
        bd.getPropertyValues().addPropertyValue("phone", "110");
    }
}

配置文件如下application.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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="person" class="com.ape.test.Person" init-method="doInit"
          destroy-method="doDestory" scope="singleton" p:name="张三" p:address="广州"
          p:phone="159" />

    <bean id="beanPostProcessor" class="com.ape.test.MyBeanPostProcessor">
    </bean>


    <bean id="beanFactoryPostProcessor" class="com.ape.test.MyBeanFactoryPostProcessor">
    </bean>
</beans>

测试一下:

package com.ape.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author Jey
 * @version 1.0
 * @since 2024/1/8
 */
public class Test01 {
    public static void main(String[] args) throws Exception {
        System.out.println("现在开始初始化容器");

        ApplicationContext factory = new ClassPathXmlApplicationContext("application.xml");
        System.out.println("容器初始化成功");
        //得到Preson,并使用
        Person person = factory.getBean("person",Person.class);
        System.out.println(person);

        System.out.println("现在开始关闭容器!");
        person.destroy();
        person.doDestory();
    }
}

结果是

现在开始初始化容器
这是BeanFactoryPostProcessor实现类构造器!!
BeanFactoryPostProcessor调用postProcessBeanFactory方法
这是BeanPostProcessor实现类构造器~
【构造器】调用Person的构造器实例化
【注入属性】注入属性address
【注入属性】注入属性name
【注入属性】注入属性phone
【BeanNameAware接口】调用BeanNameAware.setBeanName()
【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()
BeanPostProcessor的before方法对属性进行更改!
【InitializingBean接口】调用InitializingBean.afterPropertiesSet()
【init-method】调用配置文件application中<bean>的init-method属性指定的初始化方法
BeanPostProcessor的after方法方法对属性进行更改!
容器初始化成功
Person{name='张三', address='广州', phone=110}
现在开始关闭容器!
【DiposibleBean接口】调用DiposibleBean.destory()
【destroy-method】调用配置文件application中<bean>的destroy-method属性指定的初始化方法

Process finished with exit code 0

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值