如何记忆Spring Bean的生命周期

转载地址:https://chaycao.github.io/2020/02/15/%E5%A6%82%E4%BD%95%E8%AE%B0%E5%BF%86Spring-Bean%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F/

1. 引言

“请你描述下 Spring Bean 的生命周期?”,这是面试官考察 Spring 的常用问题,可见是 Spring 中很重要的知识点。

我之前在准备面试时,去网上搜过答案,大多以下图给出的流程作为答案。

Spring的生命周期

但是当我第一次看到该图时,就产生了很多困扰,“Aware,BeanPostProcessor……这些都是什么啊?而且这么多步骤,太多了,该怎么记啊?”。

其实要记忆该过程,还是需要我们先去理解,本文将从以下两方面去帮助理解 Bean 的生命周期:

  1. 生命周期的概要流程:对 Bean 的生命周期进行概括,并且结合代码来理解;

  2. 扩展点的作用:详细介绍 Bean 生命周期中所涉及到的扩展点的作用。

2. 生命周期的概要流程

Bean 的生命周期概括起来就是 4 个阶段:

  1. 实例化(Instantiation)
  2. 属性赋值(Populate)
  3. 初始化(Initialization)
  4. 销毁(Destruction)

Spring生命周期(概要)

  1. 实例化:第 1 步,实例化一个 bean 对象;

  2. 属性赋值:第 2 步,为 bean 设置相关属性和依赖;
  3. 初始化:第 3~7 步,步骤较多,其中第 5、6 步为初始化操作,第 3、4 步为在初始化前执行,第 7 步在初始化后执行,该阶段结束,才能被用户使用;
  4. 销毁:第 8~10步,第8步不是真正意义上的销毁(还没使用呢),而是先在使用前注册了销毁的相关调用接口,为了后面第9、10步真正销毁 bean 时再执行相应的方法。

下面我们结合代码来直观的看下,在 doCreateBean() 方法中能看到依次执行了这 4 个阶段:

// AbstractAutowireCapableBeanFactory.java
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
    throws BeanCreationException {

    // 1. 实例化
    BeanWrapper instanceWrapper = null;
    if (instanceWrapper == null) {
        instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    
    Object exposedObject = bean;
    try {
        // 2. 属性赋值
        populateBean(beanName, mbd, instanceWrapper);
        // 3. 初始化
        exposedObject = initializeBean(beanName, exposedObject, mbd);
    }

    // 4. 销毁-注册回调接口
    try {
        registerDisposableBeanIfNecessary(beanName, bean, mbd);
    }

    return exposedObject;
}

由于初始化包含了第 3~7步,较复杂,所以我们进到 initializeBean() 方法里具体看下其过程(注释的序号对应图中序号):

// AbstractAutowireCapableBeanFactory.java
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
    // 3. 检查 Aware 相关接口并设置相关依赖
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
            invokeAwareMethods(beanName, bean);
            return null;
        }, getAccessControlContext());
    }
    else {
        invokeAwareMethods(beanName, bean);
    }

    // 4. BeanPostProcessor 前置处理
    Object wrappedBean = bean;
    if (mbd == null || !mbd.isSynthetic()) {
        wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
    }

    // 5. 若实现 InitializingBean 接口,调用 afterPropertiesSet() 方法
    // 6. 若配置自定义的 init-method方法,则执行
    try {
        invokeInitMethods(beanName, wrappedBean, mbd);
    }
    catch (Throwable ex) {
        throw new BeanCreationException(
            (mbd != null ? mbd.getResourceDescription() : null),
            beanName, "Invocation of init method failed", ex);
    }
    // 7. BeanPostProceesor 后置处理
    if (mbd == null || !mbd.isSynthetic()) {
        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }

    return wrappedBean;
}

在 invokInitMethods() 方法中会检查 InitializingBean 接口和 init-method 方法,销毁的过程也与其类似:

// DisposableBeanAdapter.java
public void destroy() {
    // 9. 若实现 DisposableBean 接口,则执行 destory()方法
    if (this.invokeDisposableBean) {
        try {
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
                    ((DisposableBean) this.bean).destroy();
                    return null;
                }, this.acc);
            }
            else {
                ((DisposableBean) this.bean).destroy();
            }
        }
    }
    
	// 10. 若配置自定义的 detory-method 方法,则执行
    if (this.destroyMethod != null) {
        invokeCustomDestroyMethod(this.destroyMethod);
    }
    else if (this.destroyMethodName != null) {
        Method methodToInvoke = determineDestroyMethod(this.destroyMethodName);
        if (methodToInvoke != null) {
            invokeCustomDestroyMethod(ClassUtils.getInterfaceMethodIfPossible(methodToInvoke));
        }
    }
}

从 Spring 的源码我们可以直观的看到其执行过程,而我们记忆其过程便可以从这 4 个阶段出发,实例化、属性赋值、初始化、销毁。其中细节较多的便是初始化,涉及了 Aware、BeanPostProcessor、InitializingBean、init-method 的概念。这些都是 Spring 提供的扩展点,其具体作用将在下一节讲述。

3. 扩展点的作用

3.1 Aware 接口

若 Spring 检测到 bean 实现了 Aware 接口,则会为其注入相应的依赖。所以通过让bean 实现 Aware 接口,则能在 bean 中获得相应的 Spring 容器资源。

Spring 中提供的 Aware 接口有:

  1. BeanNameAware:注入当前 bean 对应 beanName;
  2. BeanClassLoaderAware:注入加载当前 bean 的 ClassLoader;
  3. BeanFactoryAware:注入 当前BeanFactory容器 的引用。

其代码实现如下:

// AbstractAutowireCapableBeanFactory.java
private void invokeAwareMethods(final String beanName, final Object bean) {
    if (bean instanceof Aware) {
        if (bean instanceof BeanNameAware) {
            ((BeanNameAware) bean).setBeanName(beanName);
        }
        if (bean instanceof BeanClassLoaderAware) {
            ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
            
        }
        if (bean instanceof BeanFactoryAware) {
            ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
        }
    }
}

以上是针对 BeanFactory 类型的容器,而对于 ApplicationContext 类型的容器,也提供了 Aware 接口,只不过这些 Aware 接口的注入实现,是通过 BeanPostProcessor 的方式注入的,但其作用仍是注入依赖。

  1. EnvironmentAware:注入 Enviroment,一般用于获取配置属性;
  2. EmbeddedValueResolverAware:注入 EmbeddedValueResolver(Spring EL解析器),一般用于参数解析;
  3. ApplicationContextAware(ResourceLoader、ApplicationEventPublisherAware、MessageSourceAware):注入 ApplicationContext 容器本身。

其代码实现如下:

// ApplicationContextAwareProcessor.java
private void invokeAwareInterfaces(Object bean) {
    if (bean instanceof EnvironmentAware) {
        ((EnvironmentAware)bean).setEnvironment(this.applicationContext.getEnvironment());
    }

    if (bean instanceof EmbeddedValueResolverAware) {
        ((EmbeddedValueResolverAware)bean).setEmbeddedValueResolver(this.embeddedValueResolver);
    }

    if (bean instanceof ResourceLoaderAware) {
        ((ResourceLoaderAware)bean).setResourceLoader(this.applicationContext);
    }

    if (bean instanceof ApplicationEventPublisherAware) {
        ((ApplicationEventPublisherAware)bean).setApplicationEventPublisher(this.applicationContext);
    }

    if (bean instanceof MessageSourceAware) {
        ((MessageSourceAware)bean).setMessageSource(this.applicationContext);
    }

    if (bean instanceof ApplicationContextAware) {
        ((ApplicationContextAware)bean).setApplicationContext(this.applicationContext);
    }

}

3.2 BeanPostProcessor

BeanPostProcessor 是 Spring 为修改 bean提供的强大扩展点,其可作用于容器中所有 bean,其定义如下:

public interface BeanPostProcessor {

	// 初始化前置处理
	default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	// 初始化后置处理
	default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

}

常用场景有:

  1. 对于标记接口的实现类,进行自定义处理。例如3.1节中所说的ApplicationContextAwareProcessor,为其注入相应依赖;再举个例子,自定义对实现解密接口的类,将对其属性进行解密处理;
  2. 为当前对象提供代理实现。例如 Spring AOP 功能,生成对象的代理类,然后返回。
// AbstractAutoProxyCreator.java
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
    TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
    if (targetSource != null) {
        if (StringUtils.hasLength(beanName)) {
            this.targetSourcedBeans.add(beanName);
        }
        Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
        Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
        this.proxyTypes.put(cacheKey, proxy.getClass());
        // 返回代理类
        return proxy;
    }

    return null;
}

3.3 InitializingBean 和 init-method

InitializingBean 和 init-method 是 Spring 为 bean 初始化提供的扩展点。

InitializingBean接口 的定义如下:

public interface InitializingBean {
	void afterPropertiesSet() throws Exception;
}

在 afterPropertiesSet() 方法写初始化逻辑。

指定 init-method 方法,指定初始化方法:

<?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="demo" class="com.chaycao.Demo" init-method="init()"/>
    
</beans>

DisposableBean 和 destory-method 与上述类似,就不描述了。

4. 总结

最后总结下如何记忆 Spring Bean 的生命周期:

  • 首先是实例化、属性赋值、初始化、销毁这 4 个大阶段;

  • 再是初始化的具体操作,有 Aware 接口的依赖注入、BeanPostProcessor 在初始化前后的处理以及 InitializingBean 和 init-method 的初始化操作;

  • 销毁的具体操作,有注册相关销毁回调接口,最后通过DisposableBean 和 destory-method 进行销毁。

5. 参考

  1. 请别再问Spring Bean的生命周期了!
  2. 聊聊spring的那些扩展机制

 

Spring Bean 生命周期 (实例结合源码彻底讲透)

转载地址:https://segmentfault.com/a/1190000020747302

 

Spring 复盘(三) | Bean 的生命周期

转载地址:https://juejin.cn/post/6844903929491226632

bean-lifecycle

 

继续 Spring 复盘,今天看了下 Spring 的 Bean 生命周期。

1、典型的 Spring 生命周期

在传统的 Java 应用中,bean 的生命周期很简单,使用 Java 关键字 new 进行Bean 的实例化,然后该 Bean 就能够使用了。一旦 bean 不再被使用,则由 Java 自动进行垃圾回收,简直不要太简单。

相比之下,Spring 管理 Bean 的生命周期就复杂多了,正确理解 Bean 的生命周期非常重要,因为 Spring 对 Bean 的管理可扩展性非常强,下面展示了一个 Bea 的构造过程。

Spring Bean 生命周期

 

以上图片出自 《Spring 实战(第四版)》一书,图片描述了一个经典的 Spring Bean 的生命周期,书中随他的解释如下:

1.Spring对bean进行实例化; 2.Spring将值和bean的引用注入到bean对应的属性中; 3.如果bean实现了BeanNameAware接口,Spring将bean的ID传递给 setBean-Name()方法; 4.如果bean实现了BeanFactoryAware接口,Spring将调 用setBeanFactory()方法,将BeanFactory容器实例传入; 5.如果bean实现了ApplicationContextAware接口,Spring将调 用setApplicationContext()方法,将bean所在的应用上下文的 引用传入进来; 6.如果bean实现了BeanPostProcessor接口,Spring将调用它们 的post-ProcessBeforeInitialization()方法; 7.如果bean实现了InitializingBean接口,Spring将调用它们的 after-PropertiesSet()方法。类似地,如果bean使用init- method声明了初始化方法,该方法也会被调用; 8.如果bean实现了BeanPostProcessor接口,Spring将调用它们 的post-ProcessAfterInitialization()方法; 9.此时,bean已经准备就绪,可以被应用程序使用了,它们将一直 驻留在应用上下文中,直到该应用上下文被销毁; 10.如果bean实现了DisposableBean接口,Spring将调用它的 destroy()接口方法。同样,如果bean使用destroy-method声明 了销毁方法,该方法也会被调用。

2、验证 Spring Bean 周期

写了下代码验证以上说法,首先创建一个 Person 类,它就是我们要验证的 Bean ,为方便测试,他实现了 BeanNameAware, BeanFactoryAware, ApplicationContextAware, InitializingBean, DisposableBean。代码如下:

package com.nasus.bean;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Scope;

/**
 * Project Name:review_spring <br/>
 * Package Name:PACKAGE_NAME <br/>
 * Date:2019/9/1 16:29 <br/>
 *
 * @author <a href="turodog@foxmail.com">chenzy</a><br/>
 */
@Scope("ProtoType")
public class Person implements BeanNameAware, BeanFactoryAware,
        ApplicationContextAware, InitializingBean, DisposableBean {

    private static final Logger LOGGER = LoggerFactory.getLogger(Person.class);

    private String name;

    public Person(){
        System.out.println("1、开始实例化 person ");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
        System.out.println("2、设置 name 属性");
    }

    @Override
    public void setBeanName(String beanId) {
        System.out.println("3、Person 实现了 BeanNameAware 接口,Spring 将 Person 的 "
                + "ID=" + beanId + "传递给 setBeanName 方法");
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("4、Person 实现了 BeanFactoryAware 接口,Spring 调"
                + "用 setBeanFactory()方法,将 BeanFactory 容器实例传入");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("5、Person 实现了 ApplicationContextAware 接口,Spring 调"
                + "用 setApplicationContext()方法,将 person 所在的应用上下文的"
                + "引用传入进来");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("8、Person 实现了 InitializingBean 接口,Spring 调用它的"
                + "afterPropertiesSet()方法。类似地,如果 person 使用 init-"
                + "method 声明了初始化方法,该方法也会被调用");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("13、Person 实现了 DisposableBean 接口,Spring 调用它的"
                + "destroy() 接口方法。同样,如果 person 使用 destroy-method 声明"
                + "了销毁方法,该方法也会被调用");
    }

    /**
     * xml 中声明的 init-method 方法
     */
    public void initMethod(){
        System.out.println("9、xml 中声明的 init-method 方法");
    }

    /**
     * xml 中声明的 destroy-method 方法
     */
    public void destroyMethod(){
        System.out.println("14、xml 中声明的 destroy-method 方法");
        System.out.println("end---------------destroy-----------------");
    }

    // 自定义初始化方法
    @PostConstruct
    public void springPostConstruct(){
        System.out.println("7、@PostConstruct 调用自定义的初始化方法");
    }

    // 自定义销毁方法
    @PreDestroy
    public void springPreDestory(){
        System.out.println("12、@PreDestory 调用自定义销毁方法");
    }

    @Override
    protected void finalize() throws Throwable {
        System.out.println("finalize 方法");
    }
}
复制代码

除此之外,创建了一个 MyBeanPostProcessor 类继承自 BeanPostProcessor 这个类只关心 Person 初始化前后要做的事情。比如,初始化之前,加载其他 Bean。代码如下:

package com.nasus.lifecycle;

import com.nasus.bean.Person;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

/**
 * Project Name:review_spring <br/>
 * Package Name:PACKAGE_NAME <br/>
 * Date:2019/9/1 16:25 <br/>
 *
 * @author <a href="turodog@foxmail.com">chenzy</a><br/>
 */
public class MyBeanPostProcessor implements BeanPostProcessor {

    // 容器加载的时候会加载一些其他的 bean,会调用初始化前和初始化后方法
    // 这次只关注 Person 的生命周期
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if(bean instanceof Person){
            System.out.println("6、初始化 Person 之前执行的方法");
        }
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if(bean instanceof Person){
            System.out.println("10、初始化 Person 完成之后执行的方法");
        }
        return bean;
    }

}
复制代码

resource 文件夹下新建一个 bean_lifecycle.xml 文件注入相关 bean ,代码如下:

<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-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 扫描bean -->
    <context:component-scan base-package="com.nasus"/>

    <!-- 实现了用户自定义初始化和销毁方法 -->
    <bean id="person" class="com.nasus.bean.Person" init-method="initMethod" destroy-method="destroyMethod">
        <!-- 注入bean 属性名称 -->
        <property name="name" value="nasus" />
    </bean>

    <!--引入自定义的BeanPostProcessor-->
    <bean class="com.nasus.lifecycle.MyBeanPostProcessor"/>

</beans>
复制代码

测试类,获取 person 这个 Bean 并使用它,代码如下:

import com.nasus.bean.Person;
import java.awt.print.Book;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Project Name:review_spring <br/>
 * Package Name:PACKAGE_NAME <br/>
 * Date:2019/9/1 16:38 <br/>
 *
 * @author <a href="turodog@foxmail.com">chenzy</a><br/>
 */
public class lifeCycleTest {

    @Test
    public void testLifeCycle(){
        // 为面试而准备的Bean生命周期加载过程
        ApplicationContext context = new ClassPathXmlApplicationContext("bean_lifecycle.xml");
        Person person = (Person)context.getBean("person");
        // 使用属性
        System.out.println("11、实例化完成使用属性:Person name = " + person.getName());
        // 关闭容器
        ((ClassPathXmlApplicationContext) context).close();
    }

}
复制代码

lifeCycleTest 方法最后关闭了容器,关闭的同时控制台日志输出如下:

1、开始实例化 person 
2、设置 name 属性
3、Person 实现了 BeanNameAware 接口,Spring 将 Person 的 ID=person传递给 setBeanName 方法
4、Person 实现了 BeanFactoryAware 接口,Spring 调用 setBeanFactory()方法,将 BeanFactory 容器实例传入
5、Person 实现了 ApplicationContextAware 接口,Spring 调用 setApplicationContext()方法,将 person 所在的应用上下文的引用传入进来
6、初始化 Person 之前执行的方法
7、@PostConstruct 调用自定义的初始化方法
8、Person 实现了 InitializingBean 接口,Spring 调用它的afterPropertiesSet()方法。类似地,如果 person 使用 init-method 声明了初始化方法,该方法也会被调用
9、xml 中声明的 init-method 方法
10、初始化 Person 完成之后执行的方法
11、实例化完成使用属性:Person name = nasus
12、@PreDestory 调用自定义销毁方法
13、Person 实现了 DisposableBean 接口,Spring 调用它的destroy() 接口方法。同样,如果 person 使用 destroy-method 声明了销毁方法,该方法也会被调用
14、xml 中声明的 destroy-method 方法
end---------------destroy-----------------
复制代码

由以上日志可知,当 person 默认是单例模式时,bean 的生命周期与容器的生命周期一样,容器初始化,bean 也初始化。容器销毁,bean 也被销毁。那如果,bean 是非单例呢?

3、在 Bean 实例化完成后,销毁前搞事情 有时我们需要在 Bean 属性值 set 好之后和 Bean 销毁之前做一些事情,比如检查 Bean 中某个属性是否被正常的设置好值了。Spring 框架提供了多种方法让我们可以在 Spring Bean 的生命周期中执行 initialization 和 pre-destroy 方法。这些方法我在上面已经测试过了,以上代码实现了多种方法,它是重复,开发中选以下其一即可,比如:

  • 在配置文件中指定的 init-method 和 destroy-method 方法
  • 实现 InitializingBean 和 DisposableBean 接口
  • 使用 @PostConstruct 和 @PreDestroy 注解(墙裂推荐使用)

4、多实例模式下的 Bean 生命周期 上面测试中的 person 默认是 singleton 的,现在我们将 person 改为 protoType 模式,bean_lifecycle.xml 做如下代码修改,其余类保持不变:

<!-- 实现了用户自定义初始化和销毁方法 -->
<bean id="person" scope="prototype" class="com.nasus.bean.Person" init-method="initMethod" destroy-method="destroyMethod">
     <!-- 注入bean 属性名称 -->
     <property name="name" value="nasus" />
</bean>
复制代码

此时的日志输出如下:

1、开始实例化 person 
2、设置 name 属性
3、Person 实现了 BeanNameAware 接口,Spring 将 Person 的 ID=person传递给 setBeanName 方法
4、Person 实现了 BeanFactoryAware 接口,Spring 调用 setBeanFactory()方法,将 BeanFactory 容器实例传入
5、Person 实现了 ApplicationContextAware 接口,Spring 调用 setApplicationContext()方法,将 person 所在的应用上下文的引用传入进来
6、初始化 Person 之前执行的方法
7、@PostConstruct 调用自定义的初始化方法
8、Person 实现了 InitializingBean 接口,Spring 调用它的afterPropertiesSet()方法。类似地,如果 person 使用 init-method 声明了初始化方法,该方法也会被调用
9、xml 中声明的 init-method 方法
10、初始化 Person 完成之后执行的方法
11、实例化完成使用属性:Person name = nasus
复制代码

此时,容器关闭,person 对象并没有销毁。原因在于,单实例模式下,bean 的生命周期由容器管理,容器生,bean 生;容器死,bean 死。而在多实例模式下,Spring 就管不了那么多了,bean 的生命周期,交由客户端也就是程序员或者 JVM 来进行管理。

5、多实例模式下 Bean 的加载时机

首先说说单实例,单实例模式下,bean 在容器加载那一刻起,就已经完成实例化了,证明如下,我启用 debug 模式,在 20 行打了一个断点,而日志却如下所示,说明了 bean 在 19 行,初始化容器的时候,已经完成实例化了。

 

单实例 bean 的加载时机

 

再说多实例模式下,这个模式下,bean 在需要用到 bean 的时候才进行初始化,证明如下,同样执行完 19 行,多实例模式下,控制台一片空白,说明此时的 bean 是未被加载的。

 

多实例模式下 bean 加载时机

 

debug 走到 23 行时,需要用到 bean 时,bean 才被加载了,验证如下。在开发中,我们把这种加载叫做懒加载,它的用处就是减轻程序开销,等到要用时才加载,而不是一上来就加载全部。

 

多实例模式下 bean 加载时机

 

6、单实例 bean 如何实现延迟加载

只需在 xml 中加上 lazy-init 属性为 true 即可。如下,它的加载方式就变成了懒加载。

<!-- 实现了用户自定义初始化和销毁方法 -->
<bean id="person" lazy-init="true" class="com.nasus.bean.Person" init-method="initMethod" destroy-method="destroyMethod">
     <!-- 注入bean 属性名称 -->
     <property name="name" value="nasus" />
</bean>
复制代码

如果想对所有的默认单例 bean 都应用延迟初始化,可以在根节点 beans 设置 default-lazy-init 属性为 true,如下所示:

<beans default-lazy-init="true" …>
复制代码

推荐阅读: *1、*java | 什么是动态代理

*2、*Spring 复盘(1) | IOC

*3、*Spring 复盘(2) | AOP

*4、*SpringBoot | 启动原理

5、SpringBoot | 自动配置原理

*6、*Spring MVC 复盘 | 工作原理及配置详解


作者:一个优秀的废人
链接:https://juejin.cn/post/6844903929491226632
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
posted @ 2020-12-19 21:38  清风名曰  阅读(432)  评论(0)    收藏  举报