Spring中Bean的生命周期(三种版本循序渐进,简单易懂)

版本一:五步骤

  1. 实例化
  2. 依赖注入
  3. 用户自定义的初始化方法
  4. 使用Bean
  5. 销毁Bean

实验代码

  • 定义一个Product
public class Product {

    private String name ;

    public Product(){
        System.out.println("实例化: product 无参构造去被调用....");
    }

    public Product(String name) {
        this.name = name;
    }
    public void setName(String name) {
        System.out.println("依赖注入:设置name的值...");
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Product{name=" + name + "}";
    }

    public void init(){
        System.out.println("初始化:product 初始化");
    }

    public void destory(){
        System.out.println("销毁:product 的销毁");
    }
}
  • spring.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="product" class="com.hhyy.vo.Product" init-method="init" destroy-method="destory">
        <property name="name" value="手机"></property>
    </bean>
</beans>
  • 测试
package com.hhyy;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppTest {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("spring.xml");
        Object product = ioc.getBean("product");
        System.out.println("使用Bean:使用Bean.....");
        ioc.close();
    }
}

结果:

实例化: product 无参构造去被调用....
依赖注入:设置name的值...
初始化:product 初始化
使用Bean:使用Bean.....
销毁:product 的销毁

版本二:七步骤

  1. 实例化
  2. 依赖注入
  3. BeanPostProcessor before 方法
  4. 用户自定义的初始化方法
  5. BeanPostProcessor after 方法
  6. 使用Bean
  7. 销毁Bean

实验代码

  • 创建一个自定义的 BeanPostProcessor
package com.hhyy.process;

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

public class MyProcessor implements BeanPostProcessor {

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

        if(beanName.equals("product")){
            System.out.println("postProcessBefore:\t product--BeanPostProcessor before 方法");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if(beanName.equals("product")){
            System.out.println("postProcessAfter:\tproduct--BeanPostProcessor After 方法");
        }
        return bean;
    }
}
  • spring.xml 中添加
<bean id="myProcessor" class="com.hhyy.process.MyProcessor"></bean>

结果

实例化: 				 product 无参构造去被调用....
依赖注入:				设置name的值...
postProcessBefore:	   product--BeanPostProcessor before 方法
初始化:				 product 初始化
postProcessAfter:	   product--BeanPostProcessor After 方法
使用Bean:	 			  使用Bean.....
销毁:					  product 的销毁

版本三:十步骤

  1. 实例化
  2. 依赖注入
  3. 调用 BeanNameAwareBeanFactoryAwareXXXAware 功能接口中的方法
  4. BeanPostProcessor before 方法
  5. InitializngBean 接口的 afterPropertiesSet 方法
  6. 用户自定义的初始化方法
  7. BeanPostProcessor after 方法
  8. 使用Bean
  9. DisposableBean 接口的方法。
  10. 销毁Bean

实验代码

  • 在 product 中加入
public class Product implements BeanNameAware, BeanFactoryAware, InitializingBean, DisposableBean {
    /*.......*/
    
    @Override
    public void setBeanName(String s) {
        System.out.println("aware: bean name "+s);
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("aware: bean factory "+beanFactory);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("InitializingBean: afterPropertiesSet(), 属性填充后会进行afterPropertiesSet方法");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("DisposableBean: destroy() IOC 销毁前,调用该方法");
    }
}
  • 结果
实例化: 	 product 无参构造去被调用....
依赖注入:	设置name的值...
aware: 		bean name product
aware: 		bean factory org.springframework.beans.factory.support.DefaultListableBeanFactory@79b4d0f: defining beans [product,myProcessor]; root of factory hierarchy
    
postProcessBefore:	 product--BeanPostProcessor before 方法
InitializingBean: afterPropertiesSet(), 属性填充后会进行afterPropertiesSet方法
初始化:	product 初始化
postProcessAfter:	product--BeanPostProcessor After 方法
使用Bean:	 使用Bean.....
DisposableBean: destroy() IOC 销毁前,调用该方法
销毁:	product 的销毁

在添加一个Bean查看输出结果

  • 创建Order
public class Order implements BeanNameAware, BeanFactoryAware, InitializingBean, DisposableBean {
    private String name ;

    public Order(){
        System.out.println("[Order] 实例化: \tOrder 无参构造去被调用....");
    }

    public Order(String name) {
        this.name = name;
    }
    public void setName(String name) {
        System.out.println("[Order] 依赖注入:\t设置name的值...");
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Order{name=" + name + "}";
    }

    public void init(){
        System.out.println("[Order] 初始化:\tproduct 初始化");
    }

    public void destory(){
        System.out.println("[Order] 销毁:\tproduct 的销毁");
    }


    @Override
    public void setBeanName(String s) {
        System.out.println("[Order] aware: bean name "+s);
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("[Order] aware: bean factory "+beanFactory);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("[Order] InitializingBean: afterPropertiesSet(), 属性填充后会进行afterPropertiesSet方法");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("[Order] DisposableBean: destroy() IOC 销毁前,调用该方法");
    }
}
  • 配置 spring.xml
<bean id="order" class="com.hhyy.vo.Order" init-method="init" destroy-method="destory">
    <property name="name" value="订单1"></property>
</bean>
  • 结果
[Product] 实例化: 	product 无参构造去被调用....
[Product] 依赖注入:	设置name的值...
[Product] aware: bean name product
[Product] aware: bean factory org.springframework.beans.factory.support.DefaultListableBeanFactory@79b4d0f: defining beans [product,order,myProcessor]; root of factory hierarchy
[product] postProcessBefore:	 product--BeanPostProcessor before 方法
[Product] InitializingBean: afterPropertiesSet(), 属性填充后会进行afterPropertiesSet方法
[Product] 初始化:	product 初始化
[product] postProcessAfter:	product--BeanPostProcessor After 方法

[Order] 实例化: 	Order 无参构造去被调用....
[Order] 依赖注入:	设置name的值...
[Order] aware: bean name order
[Order] aware: bean factory org.springframework.beans.factory.support.DefaultListableBeanFactory@79b4d0f: defining beans [product,order,myProcessor]; root of factory hierarchy
[order] postProcessBefore:	 order--BeanPostProcessor before 方法
[Order] InitializingBean: afterPropertiesSet(), 属性填充后会进行afterPropertiesSet方法
[Order] 初始化:	order 初始化
[order] postProcessAfter:	 order--BeanPostProcessor After 方法

[product] 使用Bean:	 使用Bean.....
[order] 使用Bean:	 使用Bean.....

[Order] DisposableBean: destroy() Bean 销毁前,调用该方法
[Order] 销毁:	product 的销毁
[Product] DisposableBean: destroy() Bean 销毁前,调用该方法
[Product] 销毁:	product 的销毁

XXXAware 的作用

通常使用 Spring Aware 的目的是为了让 Bean 获得 Spring 容器的服务。

  • 想获取Bean的Name。让Bean实现BeanNameAware接口,beanName会通过 setBeanName 方法传到Bean中。
  • 想获取Bean的Factory。让Bean实现BeanFactoryAware接口。

InitializingBean 的 afterPropertiesSet 的作用

可以在IOC容器对Bean设置了属性值之后,利用已经赋值的属性做一些事情。比如某个属性的值是依赖某个属性的。

参考

https://www.bilibili.com/video/BV1L14y1S7cf
https://www.cnblogs.com/FraserYu/p/11211235.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值