search
HomeJavajavaTutorialSpring lazy-init原理的分析(代码示例)

本篇文章给大家带来的内容是关于Spring lazy-init原理的分析(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

普通的bean的初始化是在容器启动初始化阶段执行的,而被lazy-init修饰的bean 则是在从容器里第一次进行context.getBean(“”)时进行触发。Spring 启动的时候会把所有bean信息(包括XML和注解)解析转化成Spring能够识别的BeanDefinition并存到Hashmap里供下面的初始化时用。接下来对每个BeanDefinition进行处理,如果是懒加载的则在容器初始化阶段不处理,其他的则在容器初始化阶段进行初始化并依赖注入。

本文我说了很多次 Spring 容器初始化bean初始化,容器的初始化有可能包括bean的初始化主要取决于该bean是否是懒加载的,特此说明怕误会 。。。:)

一.先睹为快

话不多说先写个例子看下这属性到底有什么作用,我们定义了一个叫做coffee的普通bean,代码如下:

1.普通非懒加载bean的演示

package com.test.spring;

public class Coffee {

    public Coffee() {
        System.out.println("正在初始化bean !!!调用无参构造函数");
    }
    
}
<bean name="coffee" class="com.test.spring.Coffee"/>
@Test
public void testLazyInit() {

    System.out.println("开始初始化Spring容器 ");
    // 非懒加载的bean会在容器初始化时进行bean的初始化,后面会拿Spring启动时的源码进行分析
    ApplicationContext context = new ClassPathXmlApplicationContext("spring-beans.xml");
   // 非懒加载的bean 的构造函数会在这个位置打印
    System.out.println("Spring容器初始化完毕");
    
   System.out.println("开始从容器中获取Bean");

   Coffee coffee = context.getBean("coffee", Coffee.class);

   System.out.println("获取完毕  bean :" + coffee);
}

运行结果如下:

 2.非懒加载bean的演示

<bean name="coffee" class="com.test.spring.Coffee" lazy-init="true" />
@Test
    public void testLazyInit() {

        System.out.println("开始初始化Spring容器 ");
     // 在初始化容器阶段不会对懒加载的bean进行初始化
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-beans.xml");
  
        System.out.println("Spring容器初始化完毕");

        System.out.println("开始从容器中获取Bean");
     // 在这一阶段会对懒加载的bean进行初始化
        Coffee coffee = context.getBean("coffee", Coffee.class);

        System.out.println("获取完毕  bean :" + coffee);


    }

运行结果如下:

二,原理分析

Spring 启动时主要干俩件事  1.初始化容器 2.对bean进行初始化并依赖注入。(懒加载的bean不做第二件)

但是对于大多数bean来说,bean的初始化以及依赖注入就是在容器初始化阶段进行的,只有懒加载的bean是当应用程序第一次进行getBean时进行初始化并依赖注入。下面贴出代码看下

Spring 容器初始化代码如下就一行:

ApplicationContext context = new ClassPathXmlApplicationContext("spring-beans.xml");
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
            throws BeansException {

        super(parent);
        setConfigLocations(configLocations);
        if (refresh) {
            // Spring ioc 启动入口 了解了refresh 就了解了ioc
            refresh();
        }
    }

Spring 初始化入口 refresh(省略了部分根本次无关的代码,望理解,太长了影响阅读体验)

public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            // Prepare this context for refreshing.
            prepareRefresh();

            // Prepare the bean factory for use in this context.
            prepareBeanFactory(beanFactory);

            try {
                // Allows post-processing of the bean factory in context subclasses.
                postProcessBeanFactory(beanFactory);

                // Invoke factory processors registered as beans in the context.
                invokeBeanFactoryPostProcessors(beanFactory);

                // Register bean processors that intercept bean creation.
                registerBeanPostProcessors(beanFactory);
                // Instantiate all remaining (non-lazy-init) singletons.
                // 初始化所有非 懒加载的bean!!!!
                finishBeanFactoryInitialization(beanFactory);

                // Last step: publish corresponding event.
                finishRefresh();
            }
 }

第20行则是跟本次主题有关的,就是说在容器启动的时候 只处理 non-lazy-init bean,懒加载的bean在Spring启动阶段根本不做任何处理下面看下源码就明白了

点进去第20行的finishBeanFactoryInitialization(beanFactory)里头有个初始化non-lazy-init bean的函数 preInstantiateSingletons()

具体逻辑如下

1.对beanNames 集合遍历获取每个BeanDefinition

2.判断是否是懒加载的,如果不是则继续处理(non-lazy-init bean 不做处理)

3.判断是否是factorybean 如果不是则进行实例化并依赖注入

public void preInstantiateSingletons() throws BeansException {
   // 所有beanDefinition集合
   List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);
   // 触发所有非懒加载单例bean的初始化
   for (String beanName : beanNames) {
       // 获取bean 定义
      RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
      // 判断是否是懒加载单例bean,如果是单例的并且不是懒加载的则在Spring 容器
      if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
          // 判断是否是FactoryBean
         if (isFactoryBean(beanName)) {
                final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
                boolean isEagerInit;
                if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                   isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
                      @Override
                      public Boolean run() {
                         return ((SmartFactoryBean<?>) factory).isEagerInit();
                      }
                   }, getAccessControlContext());
                }
         }else {
             // 如果是普通bean则进行初始化依赖注入,此 getBean(beanName)接下来触发的逻辑跟
             // context.getBean("beanName") 所触发的逻辑是一样的
            getBean(beanName);
         }
      }
   }
}

getBean() 方法是实现bean 初始化以及依赖注入的函数

 @Override
 public Object getBean(String name) throws BeansException {   
     return doGetBean(name, null, null, false);
 }

三,总结

对于被修饰为lazy-init的bean Spring初始化阶段不会进行init并且依赖注入,当第一次进行getBean时候进行初始化并依赖注入

对于非懒加载的bean getBean的时候会从缓存里头取 因为容器初始化阶段已经初始化了

// 容器启动初始化 会初始化并依赖注入非懒加载的bean
   ApplicationContext context = new ClassPathXmlApplicationContext("spring-beans.xml");
// lazy-init bean会进行第一次初始化并依赖注入  其他的会从缓存里取
   Coffee coffee = context.getBean("coffee", Coffee.class);

本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的Java教程视频栏目!

The above is the detailed content of Spring lazy-init原理的分析(代码示例). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools