SpringBean的生命周期

简介: SpringBean的生命周期

正文


一、SpringBean的生命周期


实例化一个Bean-通过无参构造函数;


按照Spring上下文对实例化的Bean进行配置--也就是IOC注入,属性注入。


如果这个Bean已经实现了BeanNameAware接口,会调用它实现的setBeanName(String)方法,此处传递的就是Spring配置文件中Bean的id值。


如果这个Bean已经实现了BeanFactoryAware接口,会调用它实现的setBeanFactory。


如果这个Bean已经实现了ApplicationContextAware接口,会调用

setApplicationContext(ApplicationContext)方法,传入Spring上下文ApplicationContext。

如果这个Bean关联了BeanPostProcessor接口,将会调用postProcessBeforeInitialization(Object obj, String s)方法,BeanPostProcessor经常被用作是Bean内容的更改,并且由于这个是在Bean初始化结束时调用那个的方法,也可以被应用于内存或缓存技术。

如果Bean在Spring配置文件中配置了init-method属性会自动调用其配置的初始化方法。

如果这个Bean关联了BeanPostProcessor接口,将会调用postProcessAfterInitialization(Object obj, String s)方法。此时Bean已经创建完成可以使用了。

如果Bean实现了DisposableBean这个接口,会调用那个其实现的destroy()方法。


二、源码分析


源码入口


AnnotationConfigApplicationContext.class
    //通过构造函数
  AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig.class);
  //构造函数
  public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
        this();
        this.register(componentClasses);
        this.refresh();
    }


1、this():这个方法就是一些构造器。

2、 this.register(componentClasses), 这个方法将我们的配置类MyConfig.class注册到IOC容器。


555.jpg


private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name, @Nullable Class<? extends Annotation>[] qualifiers, @Nullable Supplier<T> supplier, @Nullable BeanDefinitionCustomizer[] customizers) {
    AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
    if (!this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
        abd.setInstanceSupplier(supplier);
        ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
//设置为单例模式singleton
        abd.setScope(scopeMetadata.getScopeName());
//获取beanname,首字母小写的myConfig
        String beanName = name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry);
//判断是否懒加载、以及@DependsOn、@Role(1)等信息
        AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
        int var10;
        int var11;
        if (qualifiers != null) {
            Class[] var9 = qualifiers;
            var10 = qualifiers.length;
            for(var11 = 0; var11 < var10; ++var11) {
                Class<? extends Annotation> qualifier = var9[var11];
                if (Primary.class == qualifier) {
                    abd.setPrimary(true);
                } else if (Lazy.class == qualifier) {
                    abd.setLazyInit(true);
                } else {
                    abd.addQualifier(new AutowireCandidateQualifier(qualifier));
                }
            }
        }
        if (customizers != null) {
            BeanDefinitionCustomizer[] var13 = customizers;
            var10 = customizers.length;
            for(var11 = 0; var11 < var10; ++var11) {
                BeanDefinitionCustomizer customizer = var13[var11];
                customizer.customize(abd);
            }
        }
//将 BeanDefinition类包装成BeanDefinitionHolder类
        BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
        definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
//注册bean
        BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
    }
}


真正注册的方法是这个方法


public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException {
    Assert.hasText(beanName, "Bean name must not be empty");
    Assert.notNull(beanDefinition, "BeanDefinition must not be null");
    if (beanDefinition instanceof AbstractBeanDefinition) {
        try {
            ((AbstractBeanDefinition)beanDefinition).validate();
        } catch (BeanDefinitionValidationException var8) {
            throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName, "Validation of bean definition failed", var8);
        }
    }
//根据beanId获取bean对象,因为MyConfig还没注册到ioc所以existingDefinition=null;
    BeanDefinition existingDefinition = (BeanDefinition)this.beanDefinitionMap.get(beanName);
    if (existingDefinition != null) {
        if (!this.isAllowBeanDefinitionOverriding()) {
            throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
        }
        if (existingDefinition.getRole() < beanDefinition.getRole()) {
            if (this.logger.isInfoEnabled()) {
                this.logger.info("Overriding user-defined bean definition for bean '" + beanName + "' with a framework-generated bean definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]");
            }
        } else if (!beanDefinition.equals(existingDefinition)) {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Overriding bean definition for bean '" + beanName + "' with a different definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]");
            }
        } else if (this.logger.isTraceEnabled()) {
            this.logger.trace("Overriding bean definition for bean '" + beanName + "' with an equivalent definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]");
        }
        this.beanDefinitionMap.put(beanName, beanDefinition);
    } else {
        //判断是否创建,很显然第一次并没有
        if (this.hasBeanCreationStarted()) {
            synchronized(this.beanDefinitionMap) {
                this.beanDefinitionMap.put(beanName, beanDefinition);
                List<String> updatedDefinitions = new ArrayList(this.beanDefinitionNames.size() + 1);
                updatedDefinitions.addAll(this.beanDefinitionNames);
                updatedDefinitions.add(beanName);
                this.beanDefinitionNames = updatedDefinitions;
                this.removeManualSingletonName(beanName);
            }
        } else {
          //将bean对象存入ioc容器,
            //this.beanDefinitionMap = new ConcurrentHashMap(256);介尼玛不就是ConcurrentHashMap吗,可以看到springioc就是用Map存放的bean
  this.beanDefinitionMap.put(beanName, beanDefinition);
            //将beanname放入集合中
            this.beanDefinitionNames.add(beanName);
            this.removeManualSingletonName(beanName);
        }
        this.frozenBeanDefinitionNames = null;
    }
    if (existingDefinition == null && !this.containsSingleton(beanName)) {
        if (this.isConfigurationFrozen()) {
            this.clearByTypeCache();
        }
    } else {
        this.resetBeanDefinition(beanName);
    }
}


3、this.refresh();重点了解下面这个方法


1. //加载一切单例模式的bean(非懒加载的)
2. this.finishBeanFactoryInitialization(beanFactory);


555.jpg


DefaultListableBeanFactory类


public void preInstantiateSingletons() throws BeansException {
    if (this.logger.isTraceEnabled()) {
        this.logger.trace("Pre-instantiating singletons in " + this);
    }
    List<String> beanNames = new ArrayList(this.beanDefinitionNames);
    Iterator var2 = beanNames.iterator();
   //当不是BeanFactory,不是单例对象,不是懒加载,是抽象类的时候,退出循环
 while(true) {
        String beanName;
        Object bean;
        do {
            while(true) {
                RootBeanDefinition bd;
                do {
                    do {
                        do {
                            if (!var2.hasNext()) {
                                var2 = beanNames.iterator();
                                while(var2.hasNext()) {
                                    beanName = (String)var2.next();
                                    //解决循环依赖的问题,以后再说
                                    Object singletonInstance = this.getSingleton(beanName);
                                    if (singletonInstance instanceof SmartInitializingSingleton) {
                                        StartupStep smartInitialize = this.getApplicationStartup().start("spring.beans.smart-initialize").tag("beanName", beanName);
                                        SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton)singletonInstance;
                                        if (System.getSecurityManager() != null) {
                                            AccessController.doPrivileged(() -> {
                                                smartSingleton.afterSingletonsInstantiated();
                                                return null;
                                            }, this.getAccessControlContext());
                                        } else {
                                            smartSingleton.afterSingletonsInstantiated();
                                        }
                                        smartInitialize.end();
                                    }
                                }
                                return;
                            }
                            beanName = (String)var2.next();
                            bd = this.getMergedLocalBeanDefinition(beanName);
                        } while(bd.isAbstract());
                    } while(!bd.isSingleton());
                } while(bd.isLazyInit());
                if (this.isFactoryBean(beanName)) {
                    bean = this.getBean("&" + beanName);
                    break;
                }
                //获取bean,如果存在直接取出,不存在则创建
                this.getBean(beanName);
            }
        } while(!(bean instanceof FactoryBean));
        FactoryBean<?> factory = (FactoryBean)bean;
        boolean isEagerInit;
        if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
            SmartFactoryBean var10000 = (SmartFactoryBean)factory;
            ((SmartFactoryBean)factory).getClass();
            isEagerInit = (Boolean)AccessController.doPrivileged(var10000::isEagerInit, this.getAccessControlContext());
        } else {
            isEagerInit = factory instanceof SmartFactoryBean && ((SmartFactoryBean)factory).isEagerInit();
        }
        if (isEagerInit) {
            this.getBean(beanName);
        }
    }
}


AbstractAutowireCapableBeanFactory类


protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
        instanceWrapper = (BeanWrapper)this.factoryBeanInstanceCache.remove(beanName);
    }
    if (instanceWrapper == null) {
        //通过反射创建对象,此时对象还没有注入属性 第1步
        instanceWrapper = this.createBeanInstance(beanName, mbd, args);
    }
    Object bean = instanceWrapper.getWrappedInstance();
    Class<?> beanType = instanceWrapper.getWrappedClass();
    if (beanType != NullBean.class) {
        mbd.resolvedTargetType = beanType;
    }
    synchronized(mbd.postProcessingLock) {
        if (!mbd.postProcessed) {
            try {
                this.applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
            } catch (Throwable var17) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", var17);
            }
            mbd.postProcessed = true;
        }
    }
    boolean earlySingletonExposure = mbd.isSingleton() && this.allowCircularReferences && this.isSingletonCurrentlyInCreation(beanName);
    if (earlySingletonExposure) {
        if (this.logger.isTraceEnabled()) {
            this.logger.trace("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references");
        }
        this.addSingletonFactory(beanName, () -> {
            return this.getEarlyBeanReference(beanName, mbd, bean);
        });
    }
    Object exposedObject = bean;
    try {
        //为属性赋值 对应第2步
        this.populateBean(beanName, mbd, instanceWrapper);
        //初始化方法 
        exposedObject = this.initializeBean(beanName, exposedObject, mbd);
    } catch (Throwable var18) {
        if (var18 instanceof BeanCreationException && beanName.equals(((BeanCreationException)var18).getBeanName())) {
            throw (BeanCreationException)var18;
        }
        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", var18);
    }
    if (earlySingletonExposure) {
        Object earlySingletonReference = this.getSingleton(beanName, false);
        if (earlySingletonReference != null) {
            if (exposedObject == bean) {
                exposedObject = earlySingletonReference;
            } else if (!this.allowRawInjectionDespiteWrapping && this.hasDependentBean(beanName)) {
                String[] dependentBeans = this.getDependentBeans(beanName);
                Set<String> actualDependentBeans = new LinkedHashSet(dependentBeans.length);
                String[] var12 = dependentBeans;
                int var13 = dependentBeans.length;
                for(int var14 = 0; var14 < var13; ++var14) {
                    String dependentBean = var12[var14];
                    if (!this.removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                        actualDependentBeans.add(dependentBean);
                    }
                }
                if (!actualDependentBeans.isEmpty()) {
                    throw new BeanCurrentlyInCreationException(beanName, "Bean with name '" + beanName + "' has been injected into other beans [" + StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + "] in its raw version as part of a circular reference, but has eventually been wrapped. This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching - consider using 'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
                }
            }
        }
    }
    try {
        this.registerDisposableBeanIfNecessary(beanName, bean, mbd);
        return exposedObject;
    } catch (BeanDefinitionValidationException var16) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", var16);
    }
}


AbstractAutowireCapableBeanFactory类


protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged(() -> {
        //如果实现了BeanNameAware、BeanClassLoaderAware、BeanFactoryAware
            //执行响应的set..方法 对应第3-5步
            this.invokeAwareMethods(beanName, bean);
            return null;
        }, this.getAccessControlContext());
    } else {
        this.invokeAwareMethods(beanName, bean);
    }
    Object wrappedBean = bean;
    if (mbd == null || !mbd.isSynthetic()) {
        //前置增强器 第6步
        wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName);
    }
    try {
        //实现该InitializingBean的方法,初始化方法 第7步
        this.invokeInitMethods(beanName, wrappedBean, mbd);
    } catch (Throwable var6) {
        throw new BeanCreationException(mbd != null ? mbd.getResourceDescription() : null, beanName, "Invocation of init method failed", var6);
    }
    if (mbd == null || !mbd.isSynthetic()) {
        //后置增强 第8步
        wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }
    return wrappedBean;
}


三、代码验证


package com.xiaojie.ioc;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Role;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
 * @Description:
 * @author: xiaojie
 * @date: 2021.08.19
 */
@Component
public class User  implements InitializingBean, BeanNameAware, BeanFactoryAware, ApplicationContextAware, DisposableBean , BeanPostProcessor {
    @Value("xiaojie")
    private String name;
    @Value("18")
    private Integer age;
    public User() {
        System.out.println("1、无参构造函数。。。。。。");
    }
    @Override
    public void destroy() throws Exception {
        System.out.println("7、destroy。。。。。。");
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
    @Override
    public void setBeanName(String s) {
        System.out.println("2、setBeanName........");
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("4、ApplicationContextAware.........");
    }
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("6、postProcessAfterInitialization..........");
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("5、postProcessBeforeInitialization..........");
        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("3、BeanFactoryAware.........");
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("afterPropertiesSet.........");
    }
}


本Spring版本为5.3.9

相关文章
|
7月前
|
XML Java 数据格式
SpringBean的生命周期
SpringBean的生命周期
69 0
|
7月前
|
前端开发 Java 开发者
Bean的生命周期和作用域
Bean的生命周期和作用域
|
3月前
|
Java 开发者 Spring
Bean生命周期介绍
Spring Boot 的 Bean 生命周期管理是其核心功能之一,负责应用程序中 Java 对象(称为 Beans)的创建、配置、初始化和销毁。此功能提供了灵活的依赖注入方式,便于组件化开发。Bean 生命周期包括实例化、属性注入、初始化方法调用、使用及销毁方法调用等阶段。应用场景涵盖依赖注入、配置管理、组件扩展及切面编程。通过实现特定接口或注解,开发者可轻松管理对象生命周期,优化应用性能。示例代码展示了如何通过日志观察 Bean 生命周期的不同阶段。
112 3
|
7月前
|
存储 设计模式 Java
Bean 作用域和生命周期
Bean 作用域和生命周期
|
Java 容器 Spring
Bean生命周期
Bean生命周期
|
7月前
|
Java 开发者 Spring
Bean 的生命周期了解么
Bean 的生命周期了解么
|
前端开发 Java Spring
一文带你深入理解SpringBean生命周期之InitializingBean详解
一文带你深入理解SpringBean生命周期之InitializingBean详解
589 0
一文带你深入理解SpringBean生命周期之InitializingBean详解
|
Java Spring 容器
bean的生命周期
bean的生命周期
55 0
|
存储 安全 Java
Bean 的作用域和生命周期
Bean 的作用域和生命周期
73 1
|
XML Java 数据格式
Bean 的生命周期
Bean 的生命周期介绍