iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Spring中bean的生命周期之getSingleton方法
  • 232
分享到

Spring中bean的生命周期之getSingleton方法

2024-04-02 19:04:59 232人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

spring中bean的生命周期 要想讲清楚spring中bean的生命周期,真的是不容易,以AnnotationConfigApplicationContext上下文为基础来讲解b

spring中bean的生命周期

要想讲清楚spring中bean的生命周期,真的是不容易,以AnnotationConfigApplicationContext上下文为基础来讲解bean的生命周期,AnnotationConfigApplicationContext是基于注解的上下文,使用XML的方式现在很少见,所以以此上下文为基础,使用XML的上下文ClassPathXmlApplicationContext的步骤和AnnotationConfigApplicationContext类似。

了解过Spring源码的都知道,在AnnotationConfigApplicationContext中调用了父类AbstractApplicationContext的refresh()方法,

refresh方法中调用了10个左右的方法,具体方法不一一细看,看今天分析的重点方法finishBeanFactoryInitialization方法,


@Override
    public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            // Prepare this context for refreshing.
            prepareRefresh();
 
            // Tell the subclass to refresh the internal bean factory.
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
 
            // 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);
 
                // Initialize message source for this context.
                initMessageSource();
 
                // Initialize event multicaster for this context.
                initApplicationEventMulticaster();
 
                // Initialize other special beans in specific context subclasses.
                onRefresh();
 
                // Check for listener beans and register them.
                registerListeners();
 
                // Instantiate all remaining (non-lazy-init) singletons.
                finishBeanFactoryInitialization(beanFactory);
 
                // Last step: publish corresponding event.
                finishRefresh();
            }
 
            catch (BeansException ex) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Exception encountered during context initialization - " +
                            "cancelling refresh attempt: " + ex);
                }
 
                // Destroy already created singletons to avoid dangling resources.
                destroyBeans();
 
                // Reset 'active' flag.
                cancelRefresh(ex);
 
                // Propagate exception to caller.
                throw ex;
            }
 
            finally {
                // Reset common introspection caches in Spring's core, since we
                // might not ever need metadata for singleton beans anymore...
                resetCommonCaches();
            }
        }
    }

在该方法中又调用了preInstantiateSingletons()方法,这个方法才是今天的主角,在该方法中会生成所有非懒加载的单例bean。方法定义如下


@Override
    public void preInstantiateSingletons() throws BeansException {
        if (logger.isTraceEnabled()) {
            logger.trace("Pre-instantiating singletons in " + this);
        }
 
        // Iterate over a copy to allow for init methods which in turn register new bean definitions.
        // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
        List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
 
        // Trigger initialization of all non-lazy singleton beans...
        for (String beanName : beanNames) {
            RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
            if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
                if (isFactoryBean(beanName)) {
                    Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
                    if (bean instanceof FactoryBean) {
                        final FactoryBean<?> factory = (FactoryBean<?>) bean;
                        boolean isEagerInit;
                        if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                            isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
                                            ((SmartFactoryBean<?>) factory)::isEagerInit,
                                    getAccessControlContext());
                        }
                        else {
                            isEagerInit = (factory instanceof SmartFactoryBean &&
                                    ((SmartFactoryBean<?>) factory).isEagerInit());
                        }
                        if (isEagerInit) {
                            getBean(beanName);
                        }
                    }
                }
                else {
                    getBean(beanName);
                }
            }
        }
 
        // Trigger post-initialization callback for all applicable beans...
        for (String beanName : beanNames) {
            Object singletonInstance = getSingleton(beanName);
            if (singletonInstance instanceof SmartInitializingSingleton) {
                final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                        smartSingleton.afterSingletonsInstantiated();
                        return null;
                    }, getAccessControlContext());
                }
                else {
                    smartSingleton.afterSingletonsInstantiated();
                }
            }
        }
    }

该方法完成的主要逻辑是遍历所有的beanName,调用getBean(beanName)方法生成单例bean,在遍历过程中对FactoryBean做了特殊的判断,大家都知道FactoryBean是一种特殊的bean,在《spring中FactoryBean是什么bean》重点分析该bean。重点看getBean(beanName)方法,getBean(beanName)方法调用了doGetBean(beanName)方法,


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

doGetBean方法定义如下,


protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
            @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
 
        final String beanName = transfORMedBeanName(name);
        Object bean;
 
        // Eagerly check singleton cache for manually registered singletons.
        Object sharedInstance = getSingleton(beanName);
        if (sharedInstance != null && args == null) {
            if (logger.isTraceEnabled()) {
                if (isSingletonCurrentlyInCreation(beanName)) {
                    logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
                            "' that is not fully initialized yet - a consequence of a circular reference");
                }
                else {
                    logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
                }
            }
            bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
        }
 
        else {
            // Fail if we're already creating this bean instance:
            // We're assumably within a circular reference.
            if (isPrototypeCurrentlyInCreation(beanName)) {
                throw new BeanCurrentlyInCreationException(beanName);
            }
 
            // Check if bean definition exists in this factory.
            BeanFactory parentBeanFactory = getParentBeanFactory();
            if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
                // Not found -> check parent.
                String nameToLookup = originalBeanName(name);
                if (parentBeanFactory instanceof AbstractBeanFactory) {
                    return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
                            nameToLookup, requiredType, args, typeCheckOnly);
                }
                else if (args != null) {
                    // Delegation to parent with explicit args.
                    return (T) parentBeanFactory.getBean(nameToLookup, args);
                }
                else if (requiredType != null) {
                    // No args -> delegate to standard getBean method.
                    return parentBeanFactory.getBean(nameToLookup, requiredType);
                }
                else {
                    return (T) parentBeanFactory.getBean(nameToLookup);
                }
            }
 
            if (!typeCheckOnly) {
                markBeanAsCreated(beanName);
            }
 
            try {
                final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                checkMergedBeanDefinition(mbd, beanName, args);
 
                // Guarantee initialization of beans that the current bean depends on.
                String[] dependsOn = mbd.getDependsOn();
                if (dependsOn != null) {
                    for (String dep : dependsOn) {
                        if (isDependent(beanName, dep)) {
                            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                    "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
                        }
                        registerDependentBean(dep, beanName);
                        try {
                            getBean(dep);
                        }
                        catch (NoSuchBeanDefinitionException ex) {
                            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                    "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
                        }
                    }
                }
 
                // Create bean instance.
                if (mbd.isSingleton()) {
                    sharedInstance = getSingleton(beanName, () -> {
                        try {
                            return createBean(beanName, mbd, args);
                        }
                        catch (BeansException ex) {
                            // Explicitly remove instance from singleton cache: It might have been put there
                            // eagerly by the creation process, to allow for circular reference resolution.
                            // Also remove any beans that received a temporary reference to the bean.
                            destroySingleton(beanName);
                            throw ex;
                        }
                    });
                    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                }
 
                else if (mbd.isPrototype()) {
                    // It's a prototype -> create a new instance.
                    Object prototypeInstance = null;
                    try {
                        beforePrototypeCreation(beanName);
                        prototypeInstance = createBean(beanName, mbd, args);
                    }
                    finally {
                        afterPrototypeCreation(beanName);
                    }
                    bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
                }
 
                else {
                    String scopeName = mbd.getScope();
                    final Scope scope = this.scopes.get(scopeName);
                    if (scope == null) {
                        throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
                    }
                    try {
                        Object scopedInstance = scope.get(beanName, () -> {
                            beforePrototypeCreation(beanName);
                            try {
                                return createBean(beanName, mbd, args);
                            }
                            finally {
                                afterPrototypeCreation(beanName);
                            }
                        });
                        bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                    }
                    catch (IllegalStateException ex) {
                        throw new BeanCreationException(beanName,
                                "Scope '" + scopeName + "' is not active for the current thread; consider " +
                                "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
                                ex);
                    }
                }
            }
            catch (BeansException ex) {
                cleanupAfterBeanCreationFailure(beanName);
                throw ex;
            }
        }
 
        // Check if required type matches the type of the actual bean instance.
        if (requiredType != null && !requiredType.isInstance(bean)) {
            try {
                T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
                if (convertedBean == null) {
                    throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
                }
                return convertedBean;
            }
            catch (TypeMismatchException ex) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Failed to convert bean '" + name + "' to required type '" +
                            ClassUtils.getQualifiedName(requiredType) + "'", ex);
                }
                throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
            }
        }
        return (T) bean;
    }

doGetBean方法中有getSingleton、getObjectForBeanInstance、createBean等方法是很重要的。在doGetBean方法中首先调用getSingleton方法检查单例缓存中是否有该bean,如果没有则判断当前bean的作用域是单例(singleton)还是原型(prototype),如果是单例的,再次调用getSingleton方法,不过这次的该方法是重载的一个;如果是原型的则调用createBean方法生成bean,上面几个步骤生成的beanInstance均要调用getObjectForBeanInstance方法获得bean对象。先看getSingleton方法


@Nullable
    protected Object getSingleton(String beanName, boolean allowEarlyReference) {
        Object singletonObject = this.singletonObjects.get(beanName);
        if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
            synchronized (this.singletonObjects) {
                singletonObject = this.earlySingletonObjects.get(beanName);
                if (singletonObject == null && allowEarlyReference) {
                    ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
                    if (singletonFactory != null) {
                        singletonObject = singletonFactory.getObject();
                        this.earlySingletonObjects.put(beanName, singletonObject);
                        this.singletonFactories.remove(beanName);
                    }
                }
            }
        }
        return singletonObject;
    }

在该方法中涉及到三个对象singletonObjects、earlySingletonObjects、singletonFactories,使用这三个对象可以很好的解决循环依赖的问题,这里暂时不讲这个,先看其中的逻辑,

执行的逻辑大概是上面的过程。对singletonObject、earlySingletonObjects、singletonFactories逐级判断,其中singletonFactories中存储的是提前暴露的实例工厂,用来生成一个实例或者实例的代理类。

本文重点对spring生成bean的入门进行了分析,重点分析了代码的调用过程及getSingleton方法,该方法还有一个重载的方法,放到后面分析。

到此这篇关于Spring中bean的生命周期之getSingleton方法的文章就介绍到这了,更多相关Spring中bean的生命周期内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Spring中bean的生命周期之getSingleton方法

本文链接: https://www.lsjlt.com/news/129532.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Spring中bean的生命周期之getSingleton方法
    Spring中bean的生命周期 要想讲清楚spring中bean的生命周期,真的是不容易,以AnnotationConfigApplicationContext上下文为基础来讲解b...
    99+
    2024-04-02
  • spring之Bean的生命周期详解
    Bean的生命周期:Bean的定义——Bean的初始化——Bean的使用——Bean的销毁Bean的定义Bean 是 spring 装配的组件模型,一切实体类都可以配置成一个 Bean ,进而就可以在任何其他的 Bean 中使用,一个 Be...
    99+
    2023-05-31
    spring bean 生命周期
  • 【Spring】Spring的Bean的生命周期
    作者简介:大家好,我是五度鱼,一个普通的Java领域博主,不停输出Java技术博客和干货。座右铭:锲而不舍,金石可镂。个人主页:五度鱼学Java的主页 文章目录 前言1. 什么是Bean的生命周期?2. 为什么要知道Bean...
    99+
    2023-08-17
    java Bean生命周期 spring
  • Spring 中 Bean 的生命周期详解
    目录前言1.Bean 生命周期2.代码演示总结前言 Java 中的公共类称之为 Bean 或 Java Bean,而 Spring 中的 Bean 指的是将对象的生命周期,交个 Sp...
    99+
    2024-04-02
  • Spring源码解析之Bean的生命周期
    一、Bean的实例化概述 前一篇分析了BeanDefinition的封装过程,最终将beanName与BeanDefinition以一对一映射关系放到beanDefinitionMa...
    99+
    2024-04-02
  • Spring中bean的生命周期有多长
    这篇文章主要介绍“Spring中bean的生命周期有多长”,在日常操作中,相信很多人在Spring中bean的生命周期有多长问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Spring中bean的生命周期有多长...
    99+
    2023-06-02
  • Spring Bean的生命周期 -- Spring入门(三)
    文章目录 前言1. 理解bean的生命周期2. Bean 生命周期的执行过程3. Bean生命周期控制入门案例4. 关闭IOC容器的两种方式5. 通过继承接口绑定生命周期方法 总结 前言 为了巩固所学的知识,作者尝试着开始...
    99+
    2023-08-17
    spring java 后端
  • spring中bean的生命周期是什么
    在Spring中,Bean的生命周期包括以下几个阶段:1. 实例化:当Spring容器接收到请求时,根据配置文件或注解等方式,在内存...
    99+
    2023-09-27
    spring bean
  • Spring bean的生命周期是什么
    Spring bean的生命周期包括以下阶段:1. 实例化(Instantiation):在容器启动时,Spring根据配置信息或注...
    99+
    2023-08-24
    Spring bean
  • Spring Bean的生命周期是什么
    这篇“Spring Bean的生命周期是什么”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Spring ...
    99+
    2023-07-05
  • 一文搞懂Spring中Bean的生命周期
    目录一、使用配置生命周期的方法二、生命周期控制——接口控制(了解)小结生命周期:从创建到消亡的完整过程 bean声明周期:bean从创建到销毁的整体过程 be...
    99+
    2024-04-02
  • 如何掌握Spring中bean的生命周期!
    这期内容当中小编将会给大家带来有关如何掌握Spring中bean的生命周期!,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。Spring 中bean 的生命周期短暂吗在spring中,从BeanFactor...
    99+
    2023-06-17
  • Spring Bean生命周期,好像人的一生。。
    大家好,我是老三,上节我们手撸了一个简单的IOC容器五分钟,手撸一个Spring容器!,这节我们来看一看Spring中Bean的生命周期,我发现,和人的一生真的很像。 简单说说IoC和Bean IoC...
    99+
    2023-09-27
    spring java 后端
  • 深入了解Spring的Bean生命周期
    目录源码下载什么是 Spring Bean 的生命周期Bean的生命周期Spring角度查看bean的定义与注册SpringBoot角度查看bean定义和注册实例化,依赖注入,初始化...
    99+
    2024-04-02
  • SpringBoot源码之Bean的生命周期
    入口方法为SpringApplication#run() 1.SpringApplication#run() public ConfigurableApplicationCont...
    99+
    2023-05-15
    SpringBoot之Bean的生命周期 bean生命周期 SpringBean生命周期
  • Spring创建Bean的生命周期详析
    目录1.Bean 的创建生命周期2.Spring AOP 大致流程3.Spring 事务4.Spring 源码阅读前戏BeanDefinitionBeanDefinitionRead...
    99+
    2024-04-02
  • 怎样理解Spring Bean生命周期
    怎样理解Spring Bean生命周期,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。在网上已经有跟多Bean的生命周期的博客,但是很多都是基于比较老的版本了,最近把整个流程...
    99+
    2023-06-16
  • Spring Bean生命周期源码分析
    这篇“Spring Bean生命周期源码分析”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Spring ...
    99+
    2023-07-05
  • 如何在spring中回调bean的生命周期
    如何在spring中回调bean的生命周期?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。生命周期回调方法对于spring bean来讲,我们默认可以指定两个生命周期回调方法...
    99+
    2023-05-31
    bean 生命周期 spring
  • Java Spring中Bean的作用域及生命周期
    目录1.Bean的作用域1.1 被修改的Bean案例1.2 为什么使用单例模式作为默认作用域1.3 作用域1.4 Bean的6种作用域1.5 设置作用域2.Spring执行流程和Be...
    99+
    2022-11-13
    Java Spring中Bean的作用域 Spring中Bean的生命周期
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作