首页 > 其他分享 >Bean的生命周期

Bean的生命周期

时间:2023-06-06 12:32:17浏览次数:25  
标签:生命周期 bean System Bean println public out

1.  什么是Bean的生命周期  49

Spring其实就是一个管理Bean对象的工厂。它负责对象的创建,对象的销毁等。

所谓的生命周期就是:对象从创建开始到最终销毁的整个过程。

什么时候创建Bean对象?

创建Bean对象的前后会调用什么方法?

Bean对象什么时候销毁?

Bean对象的销毁前后调用什么方法?

2. 为什么要知道Bean的生命周期  49

其实生命周期的本质是:在哪个时间节点上调用了哪个类的哪个方法。

我们需要充分的了解在这个生命线上,都有哪些特殊的时间节点。

只有我们知道了特殊的时间节点都在哪,到时我们才可以确定代码写到哪。

我们可能需要在某个特殊的时间点上执行一段特定的代码,这段代码就可以放到这个节点上。当生命线走到这里的时候,自然会被调用。

3. Bean的生命周期之5步   49

Bean生命周期的管理,可以参考Spring的源码:AbstractAutowireCapableBeanFactory类的doCreateBean()方法。

Bean生命周期可以粗略的划分为五大步:

● 第一步:实例化Bean

● 第二步:Bean属性赋值

● 第三步:初始化Bean

● 第四步:使用Bean

● 第五步:销毁Bean

Bean的生命周期_spring

3.1 编写测试程序: 49

定义一个Bean

package com.powernode.spring6.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;

/**
 *
 * Bean的生命周期按照粗略的五步的话:  49
 * 第一步:实例化Bean(调用无参数构造方法。)
 * 第二步:给Bean属性赋值(调用set方法。)
 * 第三步:初始化Bean(会调用Bean的init方法。注意:这个init方法需要自己写,自己配。)
 * 第四步:使用Bean
 * 第五步:销毁Bean(会调用Bean的destroy方法。注意:这个destroy方法需要自己写,自己配。)
 **/
public class User{

    private String name;

    public void setName(String name) {
        System.out.println("第二步:给对象的属性赋值。");
        this.name = name;
    }

    public User() {
        System.out.println("第一步:无参数构造方法执行。");
    }

    // 这个方法需要自己写,自己配。方法名随意。
    public void initBean(){
        System.out.println("第三步:初始化Bean。");
    }

    // 这个方法需要自己写,自己配。方法名随意。
    public void destroyBean(){
        System.out.println("第五步:销毁Bean。");
    }

//    @Override
//    public void setBeanClassLoader(ClassLoader classLoader) {
//        System.out.println("Bean这个类的加载器:" + classLoader);
//    }
//
//    @Override
//    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
//        System.out.println("生产这个Bean的工厂对象是:" + beanFactory);
//    }
//
//    @Override
//    public void setBeanName(String name) {
//        System.out.println("这个Bean的名字是:" + name);
//    }
//
//    @Override
//    public void afterPropertiesSet() throws Exception {
//        System.out.println("InitializingBean's afterPropertiesSet执行。");
//    }
//
//    @Override
//    public void destroy() throws Exception {
//        System.out.println("DisposableBean's destroy方法执行");
//    }
}
<!--    研究bean的生命周期  49-->
    <!--需要手动指定初始化方法,和销毁方法。-->
    <bean id="user" class="com.powernode.spring6.bean.User"
          init-method="initBean" destroy-method="destroyBean">
        <property name="name" value="zhangsan"/>
    </bean>

//测试bean的生命周期  49
    @Test
    public void testBeanLifecycleTest(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        User user = applicationContext.getBean("user", User.class);
        System.out.println("第四步:使用bean:"+user);
        // 注意:必须手动关闭Spring容器,这样Spring容器才会销毁Bean.
        ClassPathXmlApplicationContext context = (ClassPathXmlApplicationContext) applicationContext;
        context.close();
    }

Bean的生命周期_生命周期_02

3.2 需要注意的: 49

● 第一:只有正常关闭spring容器,bean的销毁方法才会被调用。

● 第二:ClassPathXmlApplicationContext类才有close()方法。

● 第三:配置文件中的init-method指定初始化方法。destroy-method指定销毁方法。

3.2.1 再次强调

Bean的生命周期五步:

    第一步:实例化Bean

    第二步:Bean属性赋值

    第三步:初始化Bean

    第四步:使用Bean

    第五步:销毁Bean

4. Bean生命周期之7步  50

4.1 Bean生命周期七步:比五步添加的那两步在哪里?

在初始化Bean的前和后。

    第一步:实例化Bean

    第二步:Bean属性赋值

    第三步:执行“Bean后处理器”的before方法。

    第四步:初始化Bean

    第五步:执行“Bean后处理器”的after方法。

    第六步:使用Bean

    第七步:销毁Bean

在以上的5步中,第3步是初始化Bean,如果你还想在初始化前和初始化后添加代码,可以加入“Bean后处理器”。

编写一个类实现BeanPostProcessor类,并且重写before和after方法:

package com.powernode.spring6.bean;

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

/**
 * 日志Bean后处理器。  50
 **/
public class LogBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("执行Bean后处理器的before方法。");
        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }

    // 方法有两个参数:
    // 第一个参数:刚创建的bean对象。
    // 第二个参数:bean的名字。
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("执行Bean后处理器的after方法。");
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}

在spring.xml文件中配置“Bean后处理器”:

 <!--配置Bean后处理器。  50-->
    <!--注意:这个Bean后处理器将作用于整个配置文件中所有的bean。-->
    <bean class="com.powernode.spring6.bean.LogBeanPostProcessor"/>

Bean的生命周期_System_03

4.2 注意  50

一定要注意:在spring.xml文件中配置的Bean后处理器将作用于当前配置文件中所有的Bean。

如果加上Bean后处理器的话,Bean的生命周期就是7步了:

Bean的生命周期_System_04

5. Bean生命周期之10步  51

5.1 Bean生命周期十步:比七步添加的那三步在哪里?  51

   5.1.1  点位1:

在“Bean后处理器”before方法之前

        干了什么事儿?

            检查Bean是否实现了Aware相关的接口,如果实现了接口则调用这些接口中的方法。

            然后调用这些方法的目的是为了给你传递一些数据,让你更加方便使用。

5.1.2 点位2:

在“Bean后处理器”before方法之后

        干了什么事儿?

            检查Bean是否实现了InitializingBean接口,如果实现了,则调用接口中的方法。

5.1.3 点位3:

使用Bean之后,或者说销毁Bean之前

        干了什么事儿?

            检查Bean是否实现了DisposableBean接口,如果实现了,则调用接口中的方法。

5.1.4 添加的这三个点位的特点:

都是在检查你这个Bean是否实现了某些特定的接口,如果实现了这些接口,则Spring容器会调用这个接口中的方法。

如果根据源码跟踪,可以划分更细粒度的步骤,10步:

Bean的生命周期_spring_05

5.2 上图中检查Bean是否实现了Aware的相关接口是什么意思? 51

Aware相关的接口包括:BeanNameAware、BeanClassLoaderAware、BeanFactoryAware

● 当Bean实现了BeanNameAware,Spring会将Bean的名字传递给Bean。

● 当Bean实现了BeanClassLoaderAware,Spring会将加载该Bean的类加载器传递给Bean。

● 当Bean实现了BeanFactoryAware,Spring会将Bean工厂对象传递给Bean。

5.3 测试以上10步,可以让User类实现5个接口,并实现所有方法:51

● BeanNameAware

● BeanClassLoaderAware

● BeanFactoryAware

● InitializingBean

● DisposableBean

package com.powernode.spring6.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;

/**
 *
 * Bean的生命周期按照粗略的五步的话:  49
 * 第一步:实例化Bean(调用无参数构造方法。)
 * 第二步:给Bean属性赋值(调用set方法。)
 * 第三步:初始化Bean(会调用Bean的init方法。注意:这个init方法需要自己写,自己配。)
 * 第四步:使用Bean
 * 第五步:销毁Bean(会调用Bean的destroy方法。注意:这个destroy方法需要自己写,自己配。)
 **/
public class User implements
        BeanNameAware, BeanClassLoaderAware,BeanFactoryAware,InitializingBean,DisposableBean{

    private String name;

    public void setName(String name) {
        System.out.println("第二步:给对象的属性赋值。");
        this.name = name;
    }

    public User() {
        System.out.println("第一步:无参数构造方法执行。");
    }

    // 这个方法需要自己写,自己配。方法名随意。
    public void initBean(){
        System.out.println("第四步:初始化Bean。");
    }

    // 这个方法需要自己写,自己配。方法名随意。
    public void destroyBean(){
        System.out.println("第七步:销毁Bean。");
    }


    @Override
    public void setBeanClassLoader(ClassLoader classLoader) {
        System.out.println("Bean这个类的加载器:" + classLoader);
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("生产这个Bean的工厂对象是:" + beanFactory);
    }

    @Override
    public void setBeanName(String name) {
        System.out.println("这个Bean的名字是:" + name);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("InitializingBean's afterPropertiesSet执行。");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("DisposableBean's destroy方法执行");
    }
}
package com.powernode.spring6.bean;

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

/**
 * 日志Bean后处理器。  50
 **/
public class LogBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("第三步:执行Bean后处理器的before方法。");
        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }

    // 方法有两个参数:
    // 第一个参数:刚创建的bean对象。
    // 第二个参数:bean的名字。
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("第五步:执行Bean后处理器的after方法。");
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}
<?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后处理器。  50-->
    <!--注意:这个Bean后处理器将作用于整个配置文件中所有的bean。-->
    <bean class="com.powernode.spring6.bean.LogBeanPostProcessor"/>

<!--    研究bean的生命周期  49-->
    <!--需要手动指定初始化方法,和销毁方法。-->
    <bean id="user" class="com.powernode.spring6.bean.User"
          init-method="initBean" destroy-method="destroyBean">
        <property name="name" value="zhangsan"/>
    </bean>

<!--    <bean id="vip" class="com.powernode.spring6.bean.Vip"/>-->


</beans>
package com.powernode.spring6.test;

import com.powernode.spring6.bean.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanLifecycleTest {

    //测试bean的生命周期  49-50
    @Test
    public void testBeanLifecycleTest(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        User user = applicationContext.getBean("user", User.class);
        System.out.println("第六步:使用bean:"+user);
        // 注意:必须手动关闭Spring容器,这样Spring容器才会销毁Bean.
        ClassPathXmlApplicationContext context = (ClassPathXmlApplicationContext) applicationContext;
        context.close();
    }
}

Bean的生命周期_Bean_06

通过测试可以看出来:

● InitializingBean的方法早于init-method的执行。

● DisposableBean的方法早于destroy-method的执行。

对于SpringBean的生命周期,掌握之前的7步即可。够用。

6. Bean的作用域不同,管理方式不同  52

Spring 根据Bean的作用域来选择管理方式。

● 对于singleton作用域的Bean,Spring 能够精确地知道该Bean何时被创建,何时初始化完成,以及何时被销毁;

● 而对于 prototype 作用域的 Bean,Spring 只负责创建,当容器创建了 Bean 的实例后,Bean 的实例就交给客户端代码管理,Spring 容器将不再跟踪其生命周期。

我们把之前User类的spring.xml文件中的配置scope设置为prototype:

    <!--配置Bean后处理器。  50-->
    <!--注意:这个Bean后处理器将作用于整个配置文件中所有的bean。-->
    <bean class="com.powernode.spring6.bean.LogBeanPostProcessor"/>

<!--    研究bean的生命周期  49-->
    <!--需要手动指定初始化方法,和销毁方法。-->
    <bean id="user" class="com.powernode.spring6.bean.User"
          init-method="initBean" destroy-method="destroyBean" scope="prototype">
        <property name="name" value="zhangsan"/>
    </bean>

/**
     * Spring容器只对singleton的Bean进行完整的生命周期管理。
     * 如果是prototype作用域的Bean,Spring容器只负责将该Bean初始化完毕。
     * 等客户端程序一旦获取到该Bean之后,Spring容器就不再管理该对象的生命周期了。
     */
    //测试bean的生命周期  49-50
    @Test
    public void testBeanLifecycleTest(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        User user = applicationContext.getBean("user", User.class);
        System.out.println("第六步:使用bean:"+user);
        // 注意:必须手动关闭Spring容器,这样Spring容器才会销毁Bean.
        ClassPathXmlApplicationContext context = (ClassPathXmlApplicationContext) applicationContext;
        context.close();
    }

Bean的生命周期_spring_07

通过测试一目了然。只执行了前8步,第9和10都没有执行。

7. 自己new的对象如何让Spring管理  53

有些时候可能会遇到这样的需求,某个java对象是我们自己new的,然后我们希望这个对象被Spring容器管理,怎么实现?

package com.powernode.spring6.bean;

/**
 * 自己new的对象如何让Spring管理  53
 **/
public class Student {
}
//自己new的对象如何让Spring管理  53
    @Test
    public void testRegisterBean(){
        // 自己new的对象
        Student student = new Student();
        System.out.println(student);

        // 将以上自己new的这个对象纳入Spring容器来管理。半路上交给Spring来管理。
        DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
        factory.registerSingleton("studentBean",student);

        // 从spring容器中获取
        Object studentBean = factory.getBean("studentBean");
        System.out.println(studentBean);
    }

Bean的生命周期_生命周期_08

标签:生命周期,bean,System,Bean,println,public,out
From: https://blog.51cto.com/u_15784725/6423922

相关文章

  • Bean的循环依赖问题
    1. 什么是Bean的循环依赖  54A对象中有B属性。B对象中有A属性。这就是循环依赖。我依赖你,你也依赖我。比如:丈夫类Husband,妻子类Wife。Husband中有Wife的引用。Wife中有Husband的引用。packagecom.powernode.spring6.bean;/***什么是Bean的循环依赖54*丈夫类54**......
  • Spring Bean生命周期详解
    本文结合Spring源码5.1.7.RELEASE,详细分析SpringBean生命周期,包括主要流程以及Spring一系列的扩展方法,最后通过测试实例演示主要步骤。Spring提供的Bean扩展方法大致分为三类,一类是BeanPostProcessor接口,一类是BeanFactoryProcessor接口,还有一类是Aware接口。Sprin......
  • 【Exception】The dependencies of some of the beans in the application context fo
    案发现场***************************APPLICATIONFAILEDTOSTART***************************Description:Thedependenciesofsomeofthebeansintheapplicationcontextformacycle:┌─────┐|asyncConfigdefinedinfile[E:\code\spring-boot-demo\t......
  • 深度解析iOS应用程序的生命周期
     摘要:iOS应用程序一般都是由自己编写的代码和系统框架组成,系统框架提供一些基本infrastructure给App来运行,而开发者则自己编写代码定制App的外观和行为,了解iOSInfrastructure及其如何工作对编写App很有帮助。iOS应用程序一般都是由自己编写的代码和系统框架(systemframeworks)组成......
  • Spring Bean生命周期之三级缓存循环依赖
    目录1三级缓存1.1引言1.2三级缓存各个存放对象1.3解决循环依赖条件1.3.1解决循环依赖条件1.3.2Sprin中Bean的顺序1.3.3更改加载顺序1.3.3.1构造方法依赖(推荐)1.3.3.2参数注入1.3.3.3@DependsOn(“xxx”)1.3.3.4BeanDefinitionRegistryPostProcessor接口1.3.4执行顺......
  • 【Python】如何在FastAPI中使用UUID标记日志,以跟踪一个请求的完整生命周期
    为什么要使用uuid标记日志?在分布式系统中,一个请求可能会经过多个服务,每个服务都会生成自己的日志。如果我们只使用普通的日志记录,那么很难将这些日志串联在一起,以至难以跟踪一个请求的完整生命周期。如果能够使用uuid标记日志,为每个请求生成一个唯一的uuid,且这个日志可以在不同......
  • 二、JMX自定义MBean
    一、自定义MBeanpublicinterfaceHelloMBean{StringgetName();voidsetName(Stringname);Stringprint();}HelloMBean必须以MBean结尾。@Slf4jpublicclassHelloimplementsHelloMBean{privateStringname;@OverridepublicSt......
  • 《面试1v1》SpringBean生命周期
    我是javapub,一名Markdown程序员从......
  • Bean的作用域
    1. singleton  371.1 默认情况下,Spring的IoC容器创建的Bean对象是单例的嘛37来测试一下:packagecom.powernode.spring6.bean;//Bean的作用域37publicclassSpringBean{}Bean的作用域37--><beanid="sb"class="com.powernode.spring6.bean.SpringBean">b......
  • 如何在Spring初始化Bean或销毁Bean前执行某些操作
    阅读文本大概需要3分钟。0x01:通过在Bean中定义init-method和destory-method方法1.publicclassCar{2.3.4.publicCar(){5.System.out.println("Car'sConstructor..");6.}7.8.9.publicvoidinit(){10.System.out.println("Car'sInit...&......