spring bean的生命周期

spring的核心包(core包)实现了spring的一个核心功能IOC(反转控制)模式,提供了spring框架的核心功能。

什么是IOC:IOC就是反转控制,即:对象的控制管理权从我们手中交给了spring的专门容器(IOC容器)来负责。例如:传统的设计,我们使用某个对象直接new,是程序主动创建依赖对象,而使用IOC容器后,对象的创建工作全部由IOC控制,这就是控制,控制了外部资源的获取(不知是对象,也包括文件等)。反转:传统变成,都是程序主动控制去获取直接依赖的对象,IOC容器却是由容器帮我们查找和注入依赖对象,我们自己的对象只需要被动的接受IOC注入的依赖对象即可,不需要进行控制,这就是反转。

对象的控制管理权交给了IOC容器,那么IOC容器中的spring Bean对象的声明周期又是怎样的?

spring bean的生命周期

在spring中,通过BeanFactory或者Application中取得的对象实例,都是单例(Singleton),即每次获取到的都是同一个对象,这对于多线程来说是一个好处,不用考虑多线程获取对象时,有可能的对象数据不一致。当然也可以通过singleton=false,取消单例。
spring bean的声明周期,是从Bean的实例到销毁的全过程。
1 实例化:BeanFactoryPostProcessor接口的实现类,调用postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)方法。

2 实例化:InstantiationAwareBeanPostProcessor接口的实现类,调用 postProcessBeforeInstantiation(Class

各种接口方法分类

Bean的生命周期中会经过各种方法调用,具体方法可以分为以下几类:
1 bean的自身方法:主要是Bean本身的方法(对象自有的方法:static代码块,构造函数等)和通过xml文件配置init-method(初始化方法)和destroy-method(bean的销毁方法)。
2 Bean级生命周期接口方法:各种Aware接口,例如:BeanNmaeAware(获取bean配置文件的id),BeanFactoryAware(获取bean所在的容器),InitliazingBean(bean进行property赋值后)和DisposableBean(销毁bean接口)。通过这些接口,bean可以在初始化和析构后做一些特定的动作。
3 容器级声明周期接口防范:BeanPostProcessor接口的各种实现类和InstantiationAwareBeanPostProcessor(BeanPostProcessor的特殊实现类),当然了还有一些其他的后处理器,都是实现了BeanPostProcessor,只需要在xml文件中声明该接口的实现类即可。
4 工厂后处理器:BeanFactoryProstProcessor的实现类包括AspectJWeavingEnabler、ConfigurationClassPostProcessor、CustomAutowireConfigurer等等有用的工厂后处理器接口方法。工厂后处理器也是容器级的,在应用上下文配置文件即可调用。

从源代码中分析Bean的整个创建过程:

1 getBean(String beanName)
以ClassPathXmlApplicationContext中的getBean进行回追,发现是调用AbstractApplicationContext中的DefaultListableBeanFactory的getBean方法,而DefaullListableBeanFactory中并没有getBean(String beanName)方法,那只能从父级着手,最后再AbstractBeanFactory中找到了getBean(String beanName)方法,该方法又调用doGetBean(final String name, final Class requiredType, final Object[] args, boolean typeCheckOnly)方法

dogetBean()源码

**
     * Return an instance, which may be shared or independent, of the specified bean.
     * @param name the name of the bean to retrieve
     * @param requiredType the required type of the bean to retrieve
     * @param args arguments to use if creating a prototype using explicit arguments to a
     * static factory method. It is invalid to use a non-null args value in any other case.
     * @param typeCheckOnly whether the instance is obtained for a type check,
     * not for actual use
     * @return an instance of the bean
     * @throws BeansException if the bean could not be created
     */
//从注释中就能发现doGetBean就是返回bean实例对象。
    @SuppressWarnings("unchecked")
    protected <T> T doGetBean(
            final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
            throws BeansException {
        //通过翻译把name转化为BeanFactory能识别的唯一标识
        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.isDebugEnabled()) {
                if (isSingletonCurrentlyInCreation(beanName)) {
                    logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
                            "' that is not fully initialized yet - a consequence of a circular reference");
                }
                else {
                    logger.debug("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.
            //因为因ClassPathXmlApplicationContext创建,没有设置parentFactory,这个可以忽略
            BeanFactory parentBeanFactory = getParentBeanFactory();
            if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
                // Not found -> check parent.
                String nameToLookup = originalBeanName(name);
                if (args != null) {
                    // Delegation to parent with explicit args.
                    return (T) parentBeanFactory.getBean(nameToLookup, args);
                }
                else {
                    // No args -> delegate to standard getBean method.
                    return parentBeanFactory.getBean(nameToLookup, requiredType);
                }
            }
            //设置为正在create bean
            if (!typeCheckOnly) {
                markBeanAsCreated(beanName);
            }

            try {
                //获取beanName是否设置了parent,如果设置了就需要合并
                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 dependsOnBean : dependsOn) {
                        getBean(dependsOnBean);
                        registerDependentBean(dependsOnBean, beanName);
                    }
                }

                // Create bean instance.
                if (mbd.isSingleton()) {
                    //bean配置为单例模式,本文默认设置了单利模式,直接进入,后面的判断不做解说
                    sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
                        public Object getObject() throws BeansException {
                            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()) {
                    //忽略代码
                }

                else {
                    //忽略代码

        }

        // Check if required type matches the type of the actual bean instance.
        if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
            try {
                return getTypeConverter().convertIfNecessary(bean, requiredType);
            }
            catch (TypeMismatchException ex) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Failed to convert bean '" + name + "' to required type [" +
                            ClassUtils.getQualifiedName(requiredType) + "]", ex);
                }
                throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
            }
        }
        return (T) bean;
    }

DefaultSingletonBeanRegistry的getSingleton(String beanName, ObjectFactory

/**
     * Return the (raw) singleton object registered under the given name,
     * creating and registering a new one if none registered yet.
     * @param beanName the name of the bean
     * @param singletonFactory the ObjectFactory to lazily create the singleton
     * with, if necessary
     * @return the registered singleton object
     */
     //返回一个singleton对象,如果没有就创建和注册,有就直接返回。
    public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
        Assert.notNull(beanName, "'beanName' must not be null");
        synchronized (this.singletonObjects) {
            Object singletonObject = this.singletonObjects.get(beanName);
            if (singletonObject == null) {
                if (this.singletonsCurrentlyInDestruction) {
                    throw new BeanCreationNotAllowedException(beanName,
                            "Singleton bean creation not allowed while the singletons of this factory are in destruction " +
                            "(Do not request a bean from a BeanFactory in a destroy method implementation!)");
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
                }
                beforeSingletonCreation(beanName);
                boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
                if (recordSuppressedExceptions) {
                    this.suppressedExceptions = new LinkedHashSet<Exception>();
                }
                //从这儿可以看出来,getSingleton方法的主要作用就是对创建singleton前进行校验,并且对生成后的singleton进行相关的注册,因此我们返回AbstractBeanFactory中的doGetBean中
                try {
                    //调用了getObject方法
                    singletonObject = singletonFactory.getObject();
                }
                catch (BeanCreationException ex) {
                    if (recordSuppressedExceptions) {
                        for (Exception suppressedException : this.suppressedExceptions) {
                            ex.addRelatedCause(suppressedException);
                        }
                    }
                    throw ex;
                }
                finally {
                    if (recordSuppressedExceptions) {
                        this.suppressedExceptions = null;
                    }
                    //获取bean对象后,继续相关的操作
                    afterSingletonCreation(beanName);
                }
                addSingleton(beanName, singletonObject);
            }
            return (singletonObject != NULL_OBJECT ? singletonObject : null);
        }
    }
通过DefaultSingletonBeanRegistry可以发现,该类并不负责bean对象的创建,只是负责singleton的注册和相关除创建的其他工作,例如:校验,注册等。因此创建工作还是得去AbstractBeanFactory中doGetBean的getSingleton()方法处,通过查看,发现创建bean的操作还是在AbstractBeanFactory中的createBean(String beanName, RootBeanDefinition mbd, Object[] args)内。而createBean被子类AbstractAutowireCapableBeanFactory重写了。

AbstractAutowireCapableBeanFactory的createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)源码

/**
     * Central method of this class: creates a bean instance,
     * populates the bean instance, applies post-processors, etc.
     * @see #doCreateBean
     */
     //从注释上就可以看到createBean方法的左右:创建bean实例,并且进行填充(赋值)、调用PostProcessor接口的实现类
    @Override
    protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
            throws BeanCreationException {

        if (logger.isDebugEnabled()) {
            logger.debug("Creating instance of bean '" + beanName + "'");
        }
        // Make sure bean class is actually resolved at this point. 
        //看看class文件有没有转化为Class对象,即解析
        resolveBeanClass(mbd, beanName);

        // Prepare method overrides.
        try {
            mbd.prepareMethodOverrides();
        }
        catch (BeanDefinitionValidationException ex) {
            throw new BeanDefinitionStoreException(mbd.getResourceDescription(),
                    beanName, "Validation of method overrides failed", ex);
        }

        try {
            // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
            //提供了一个BeanPostProcessor接口,返回一个对象替代由spring提供的bean对象。
            Object bean = resolveBeforeInstantiation(beanName, mbd);
            if (bean != null) {
                return bean;
            }
        }
        catch (Throwable ex) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                    "BeanPostProcessor before instantiation of bean failed", ex);
        }

        Object beanInstance = doCreateBean(beanName, mbd, args);
        if (logger.isDebugEnabled()) {
            logger.debug("Finished creating instance of bean '" + beanName + "'");
        }
        return beanInstance;
    }

通过AbstractAutowireCapableBeanFactory的createBean方法,发现在 resolveBeforeInstantiation()处提供了一个BeanPostProcessor接口,允许实现类提供一个bean对象,替代spring使用doCreateBean方法生成的对象。

resolveBeforeInstantiation源码 ##

/**
     * Apply before-instantiation post-processors, resolving whether there is a
     * before-instantiation shortcut for the specified bean.
     * @param beanName the name of the bean
     * @param mbd the bean definition for the bean
     * @return the shortcut-determined bean instance, or {@code null} if none
     */
    protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
        Object bean = null;
        //判断mdb是否设置了beforeInstantiationResolved属性,只要配置了InstantiationAwareBeanPostProcessor接口的实现类,那么beforeInstantiationResolved就是true。
        if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
            // Make sure bean class is actually resolved at this point.
            if (mbd.hasBeanClass() && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
                //这是InstantiationAwareBeanPostProcessor实现类的方法,获取自定义bean的实例。
                bean = applyBeanPostProcessorsBeforeInstantiation(mbd.getBeanClass(), beanName);
                if (bean != null) {
                    //如果提供了自定义的bean对象的实例,调用BeanPostProcessor接口的其他实现类
                    bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
                }
            }
            mbd.beforeInstantiationResolved = (bean != null);
        }
        return bean;
    }

进入:applyBeanPostProcessorsBeforeInstantiation方法中

/**
     * Apply InstantiationAwareBeanPostProcessors to the specified bean definition
     * (by class and name), invoking their {@code postProcessBeforeInstantiation} methods.
     * <p>Any returned object will be used as the bean instead of actually instantiating
     * the target bean. A {@code null} return value from the post-processor will
     * result in the target bean being instantiated.
     * @param beanClass the class of the bean to be instantiated
     * @param beanName the name of the bean
     * @return the bean object to use instead of a default instance of the target bean, or {@code null}
     * @throws BeansException if any post-processing failed
     * @see InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation
     */
    protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName)
            throws BeansException {

        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                //调用InstantiationAwareBeanPostProcessor接口的实现类的postProcessBeforInstantiation方法,这就是bean声明周期中,第一个接口,也是特殊的BeanPostProcessro接口,注意只有配置了InstantiationAwareBeanPostProcessor接口的实现类才行。
                Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
                if (result != null) {
                    return result;
                }
            }
        }
        return null;
    }
通过applyBeanPostProcessorsBeforeInstantiation 我们发现了spring bean声明周期中暴漏的第一个接口,然后接着resolveBeforeInstantiation方法解析,如果我们提供了一个自定义的bean对象,那么就会进入 

public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
        throws BeansException {

    Object result = existingBean;
        //调用配置的其他BeanPostProcessor的实现类
        result = beanProcessor.postProcessAfterInitialization(result, beanName);
        if (result == null) {
            return result;
        }
    }
    return result;
}

至此,spring bean声明周期中暴漏的第一个接口InstantiationAwareBeanPostProcessor就已经明确了。只有实现了该接口的实现类,可以通过postProcessBeforInstantiation方法,提供一个自定义的bean的实例,当然了,如果返回一个null,那么bean对象的实例仍然交给spring提供。

返回AbstractAutowireCapableBeanFactory中,我们接着createBean看,通过上述代码发现,如果配置了InstantiationAwareBeanPostProcessor的实例,并且返回的对象非空,那么就会直接把该对象作为bean的实例对象,结束整个spring的bean实例的生成,如果返回的是空,那么就继续spring的bean实例创建,我们接着这块继续看:

//上接:AbstractAutowireCapableBeanFactory的createBean方法,直接调用doCreateBean直接创建
Object beanInstance = doCreateBean(beanName, mbd, args);
        if (logger.isDebugEnabled()) {
            logger.debug("Finished creating instance of bean '" + beanName + "'");
        }
        return beanInstance;

AbstractAutowireCapableBeanFactory的doCreateBean方法源码

/**
     * Actually create the specified bean. Pre-creation processing has already happened
     * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
     * <p>Differentiates between default bean instantiation, use of a
     * factory method, and autowiring a constructor.
     * @param beanName the name of the bean
     * @param mbd the merged bean definition for the bean
     * @param args arguments to use if creating a prototype using explicit arguments to a
     * static factory method. This parameter must be {@code null} except in this case.
     * @return a new instance of the bean
     * @throws BeanCreationException if the bean could not be created
     * @see #instantiateBean
     * @see #instantiateUsingFactoryMethod
     * @see #autowireConstructor
     */
    protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
        // Instantiate the bean.
        BeanWrapper instanceWrapper = null;
        //通过BeanWrapper创建了bean的实例对象。
        if (mbd.isSingleton()) {
            instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
        }
        //创建bean实例
        if (instanceWrapper == null) {
            instanceWrapper = createBeanInstance(beanName, mbd, args);
        }
        final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
        Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);

        // Allow post-processors to modify the merged bean definition.
        synchronized (mbd.postProcessingLock) {
            if (!mbd.postProcessed) {
                //此处暴漏了第二个出入口:即实现了MergedBeanDefinitionPostProcessor接口的实现类,就在此处执行,至于MergedBeanDefinitionPostProcessor的作用,暂时不太清楚,等以后再探索。
                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
                mbd.postProcessed = true;
            }
        }

        //忽略部分代码 

        // Initialize the bean instance.
        Object exposedObject = bean;
        try {
            //填充数据,即根据property配置,填充相关的数据
            populateBean(beanName, mbd, instanceWrapper);
            if (exposedObject != null) {
                //开始进入bean的初始化,即赋值,针对bean对象的属性进行赋值操作。
                exposedObject = initializeBean(beanName, exposedObject, mbd);
            }
        }
        catch (Throwable ex) {
            if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
                throw (BeanCreationException) ex;
            }
            else {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
            }
        }

        //忽略部分代码

        // Register bean as disposable.
        try {
            //提供注册disposableBean的机会,要么bean实现DispoableBean接口,要么实现DestructionAwareBeanPostProcessor接口。
            registerDisposableBeanIfNecessary(beanName, bean, mbd);
        }
        catch (BeanDefinitionValidationException ex) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
        }
        //完成bean的创建,返回对象,此时该bean对象就可以供使用了。
        return exposedObject;
    }

进入AbstractAutowireBeanFactory的populateBean()看看,会发现

/**
     * Populate the bean instance in the given BeanWrapper with the property values
     * from the bean definition.
     * @param beanName the name of the bean
     * @param mbd the bean definition for the bean
     * @param bw BeanWrapper with bean instance
     */
    protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
        PropertyValues pvs = mbd.getPropertyValues();

        if (bw == null) {
            if (!pvs.isEmpty()) {
                throw new BeanCreationException(
                        mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
            }
            else {
                // Skip property population phase for null instance.
                return;
            }
        }

        // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
        // state of the bean before properties are set. This can be used, for example,
        // to support styles of field injection.
        //仍是给InstantiationAwareBeanPostProcessor提供机会修改,既可以全部否定property配置,也可以修改property属性。
        boolean continueWithPropertyPopulation = true;

        if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof InstantiationAwareBeanPostProcessor) {
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                    //如果InstantiationAwareBeanPostProcessor的postProcessAfterInstantiation返回值为false,那么就是屏蔽后续的property属性的填充
                    if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                        continueWithPropertyPopulation = false;
                        break;
                    }
                }
            }
        }

        if (!continueWithPropertyPopulation) {
            return;
        }

        //忽略部分代码

        boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
        boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);

        if (hasInstAwareBpps || needsDepCheck) {
            PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
            if (hasInstAwareBpps) {
                for (BeanPostProcessor bp : getBeanPostProcessors()) {
                    if (bp instanceof InstantiationAwareBeanPostProcessor) {
                        InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                        //提供修改property的机会
                        pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                        if (pvs == null) {
                            return;
                        }
                    }
                }
            }
            if (needsDepCheck) {
                checkDependencies(beanName, mbd, filteredPds, pvs);
            }
        }
        //填充数据
        applyPropertyValues(beanName, mbd, bw, pvs);
    }
    //结束property属性的填充
总结populateBean方法中,提供了postProcessAfterInstantiation:实例化之后是否要填充的入口

在AbstractAutowireCapableBeanFactory的doCreateBean方法中,完成populateBean方法后,紧接着就是initializeBean(),初始化bean

AbstractAutowireCapabelBeanFactory的initializeBean()方法源码

/**
     * Initialize the given bean instance, applying factory callbacks
     * as well as init methods and bean post processors.
     * <p>Called from {@link #createBean} for traditionally defined beans,
     * and from {@link #initializeBean} for existing bean instances.
     * @param beanName the bean name in the factory (for debugging purposes)
     * @param bean the new bean instance we may need to initialize
     * @param mbd the bean definition that the bean was created with
     * (can also be {@code null}, if given an existing bean instance)
     * @return the initialized bean instance (potentially wrapped)
     * @see BeanNameAware
     * @see BeanClassLoaderAware
     * @see BeanFactoryAware
     * @see #applyBeanPostProcessorsBeforeInitialization
     * @see #invokeInitMethods
     * @see #applyBeanPostProcessorsAfterInitialization
     */
     //注释:初始化bean实例,调用init methods和post processors
    protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
        //设置权限,调用各种Aware方法,例如:BeanNameAware、BeanFactoryAware
        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged(new PrivilegedAction<Object>() {
                public Object run() {
                    invokeAwareMethods(beanName, bean);
                    return null;
                }
            }, getAccessControlContext());
        }
        else {
            invokeAwareMethods(beanName, bean);
        }

        Object wrappedBean = bean;
        if (mbd == null || !mbd.isSynthetic()) {
            //调用各种自定义的BeanPostProcessor接口的实现类
            wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
        }

        try {
            //初始化init-method,先调用InitializingBean接口的afterPropertySet方法,然后调用配置的init-method,
            invokeInitMethods(beanName, wrappedBean, mbd);
        }
        catch (Throwable ex) {
            throw new BeanCreationException(
                    (mbd != null ? mbd.getResourceDescription() : null),
                    beanName, "Invocation of init method failed", ex);
        }

        if (mbd == null || !mbd.isSynthetic()) {
            wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
        }
        return wrappedBean;
    }

进入invokeAwareMethods方法中可以看到,其中有三种Aware接口。用来设置:beanName,beanFactory,beanClassLoader

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(getBeanClassLoader());
            }
            if (bean instanceof BeanFactoryAware) {
                ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
            }
        }
    }

至此spring bean实例的创建就算完成了,可以提供使用了。

总结:spring bean的创建:1 创建bean之前,提供机会,让用户提供自定义bean的实例,即设置InstantiationAwareBeanPostProecessor的postProcessBeforeInstantiation(),返回一个非空对象,这样就结束了spring bean的创建;
2 如果不采用自定义的bean实例,那么就使用spring提供的bean创建,当然此时仍然提供了InstantiationAwareBeanPostProecessor的postProcessAfterInstantiation()方法,决定是否进行property填充,如果不填充就跳过,如果填充又提供了InstantiationAwareBeanPostProcessor的postProcessProperty()进行property属性的修改。
3 当bean 实例化后,还提供了一些接口:各种Aware接口,各种自定义BeanPostProcessor接口的实现类的postProcessBeforeInitialization,InitializingBean,init-method方法用于初始化,初始化完成后,又
调用BeanPostProcessor接口的实现类的postProcessAfterInitialization,通过上述顺序的初始化,就可以提供bean对象供使用了。

销毁

只需要调用registerShutdownHook()方法即可。会调用在AbstractAutowireCapableBeanFactory中doCreateBean方法内registerDisposableBeanIfNecessary注册的相关disposableBean,可以有DisposableBean和实现DestructionAwareBeanPostProcessor接口的实现类,以及配置的destory-method。
调用顺序:
DestructionAwareBeanPostProcessor->DisposableBean->destroy-method

参考:
1 http://www.cnblogs.com/zrtqsk/p/3735273.html 提供了不少的表现方案
2 http://www.iteye.com/topic/1122859 源码展示

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值