从源码了解spring bean实例化过程

初始化示例

我们先来看下spring如何手动初始化一个对象

ClassPathResource res = new ClassPathResource("beans.xml");
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
reader.loadBeanDefinitions(res);
User user=(User) factory.getBean("user");
Paste_Image.png

spring源码解析

所以我们先从DefaultListableBeanFactory开始了解

AbstractBeanFactory

public <T> T getBean(String name, Class<T> requiredType, Object... args) throws BeansException {
        return doGetBean(name, requiredType, args, false);
}
    protected <T> T doGetBean(final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
            throws BeansException {

  • 1.去掉&开头
        final String beanName = transformedBeanName(name);
    protected String transformedBeanName(String name) {
        return canonicalName(BeanFactoryUtils.transformedBeanName(name));
    }
  • 2.如果是单例且存在,就直接取过来
        Object bean;
        //拿到缓存的单例实例
        Object sharedInstance = getSingleton(beanName);
        if (sharedInstance != null && args == null) {
            ....
            bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
        }
  • 3.不存在单例缓存里面却处于创建状态,可能是循环引用,抛出异常
        else {
            //可能是一个循环引用,因为拿不到bean但是却处于创建状态
            if (isPrototypeCurrentlyInCreation(beanName)) {
                //Requested bean is currently in creation: Is there an unresolvable circular reference?
                throw new BeanCurrentlyInCreationException(beanName);
            }
  • 4.在父BeanFactory查找
            BeanFactory parentBeanFactory = getParentBeanFactory();
//本beanfactory找不到
            if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
                // 找不到拿原始名去找
                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);
                }
            }
  • 5.创建标记,(用于清除)
            if (!typeCheckOnly) {
                markBeanAsCreated(beanName);
            }
  • 6.寻找bean定义信息,并针对bean定义进行验证
            try {
                final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                checkMergedBeanDefinition(mbd, beanName, args);
  • 7.处理依赖信息,这里会针对xml定义中的depends-on进行处理
                String[] dependsOn = mbd.getDependsOn();
                if (dependsOn != null) {
                    for (String dependsOnBean : dependsOn) {
                        if (isDependent(beanName, dependsOnBean)) {
                        ....
                    registerDependentBean(dependsOnBean, beanName);
                        getBean(dependsOnBean);
                    }
                }

具体通过这个私有方法来解决依赖的
假设A依赖于B,那么在创建A之前,必须保证B先被创建。
在创建了B之后,这里会进行依赖信息存储。后面在递归调用一下,不过依赖关系反过来。
dependentBeanMap放 A->[B,C,D] (A所依赖的B,C,D)

private boolean isDependent(String beanName, String dependentBeanName, Set<String> alreadySeen) {
        if (alreadySeen != null && alreadySeen.contains(beanName)) {
            return false;
        }
        String canonicalName = canonicalName(beanName);
        Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);
        if (dependentBeans == null) {
            return false;
        }
        if (dependentBeans.contains(dependentBeanName)) {
            return true;
        }
        for (String transitiveDependency : dependentBeans) {
            if (alreadySeen == null) {
                alreadySeen = new HashSet<String>();
            }
            alreadySeen.add(beanName);
            if (isDependent(transitiveDependency, dependentBeanName, alreadySeen)) {
                return true;
            }
        }
        return false;
    }

单例模式就调用getSingleton(String beanName, ObjectFactory<?> singletonFactory)

                // 单例
                if (mbd.isSingleton()) {
                    ....
                    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                }
    public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
              ....
//private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);
        synchronized (this.singletonObjects) {
            Object singletonObject = this.singletonObjects.get(beanName);
                ....
                beforeSingletonCreation(beanName);
                ....
                    singletonObject = singletonFactory.getObject();
                ....
                    addSingleton(beanName, singletonObject);
                
            }
            return (singletonObject != NULL_OBJECT ? singletonObject : null);
        }
    }

原型模式,来一次创一个

                else if (mbd.isPrototype()) {
                    Object prototypeInstance = null;
                    try {
                        beforePrototypeCreation(beanName);
                        prototypeInstance = createBean(beanName, mbd, args);
                    }
                    finally {
                        afterPrototypeCreation(beanName);
                    }
                    bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
                }

其他模式,比如scope=request

                else {
                    String scopeName = mbd.getScope();
//private final Map<String, Scope> scopes = new LinkedHashMap<String, Scope>(8);
                    final Scope scope = this.scopes.get(scopeName);
                    ....
                    try {
                        Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
                            @Override
                            public Object getObject() throws BeansException {
                                beforePrototypeCreation(beanName);
                                try {
                                    return createBean(beanName, mbd, args);
                                }
                                finally {
                                    afterPrototypeCreation(beanName);
                                }
                            }
                        });
                        bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                    }
                    ....
                }
            }
            ....
        }
  • 8.无论哪种模式都会进入AbstractAutowireCapableBeanFactory的createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
                ....
                RootBeanDefinition mbdToUse = mbd;
        // 解析beanDefinition,以确保bean定义中的class可以被正确解析
        Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
        if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
            mbdToUse = new RootBeanDefinition(mbd);
            mbdToUse.setBeanClass(resolvedClass);
        }

        // 准备和验证配置的方法注入,若验证失败抛出BeanDefinitionValidationException
        try {
            mbdToUse.prepareMethodOverrides();
        }
        ....

        try {
            // 如果实现了InstantiationAwareBeanPostProcessor就先postProcessBeforeInstantiation(Class<?> beanClass, String beanName)->postProcessAfterInitialization(Object bean, String beanName)
            Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
            if (bean != null) {
                return bean;
            }
        }
        ....

        Object beanInstance = doCreateBean(beanName, mbdToUse, args);
        ....
        }
        return beanInstance;
  • 9.Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
    if (instanceWrapper == null) {
        //反射出类
        instanceWrapper = createBeanInstance(beanName, mbd, args);
    }            
    final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
    Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
    mbd.resolvedTargetType = beanType;

    // Allow post-processors to modify the merged bean definition.
    synchronized (mbd.postProcessingLock) {
        if (!mbd.postProcessed) {
            try {
                //获取所有MergedBeanDefinitionPostProcessor,调用一遍postProcessMergedBeanDefinition
                //这里将会调用@PostConstruct注解的方法
                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
            }
            catch (Throwable ex) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Post-processing of merged bean definition failed", ex);
            }
            mbd.postProcessed = true;
        }
    }
    ....
    if (exposedObject != null) {
        exposedObject = initializeBean(beanName, exposedObject, mbd);
    }
    ....

10.Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd)

        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged(new PrivilegedAction<Object>() {
                @Override
                public Object run() {
                       //setBeanName#BeanNameAware
                       //->setBeanClassLoader#BeanClassLoaderAware
                       //->setBeanFactory#BeanFactoryAware
                    invokeAwareMethods(beanName, bean);
                    return null;
                }
            }, getAccessControlContext());
        }
        else {
            invokeAwareMethods(beanName, bean);
        }

        Object wrappedBean = bean;
        if (mbd == null || !mbd.isSynthetic()) {
                    //->postProcessBeforeInitialization#BeanPostProcessor
            wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
        }

        try {
                        //->afterPropertiesSet#InitializingBean
            invokeInitMethods(beanName, wrappedBean, mbd);
        }
        ....

        if (mbd == null || !mbd.isSynthetic()) {
                    //->postProcessAfterInitialization#BeanPostProcessor
            wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
        }
        return wrappedBean;
    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);
            }
        }
    }
    protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
            throws Throwable {

        boolean isInitializingBean = (bean instanceof InitializingBean);
        if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
            ....
            if (System.getSecurityManager() != null) {
                try {
                    AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                        @Override
                        public Object run() throws Exception {
                            ((InitializingBean) bean).afterPropertiesSet();
                            return null;
                        }
                    }, getAccessControlContext());
                }
                catch (PrivilegedActionException pae) {
                    throw pae.getException();
                }
            }
            else {
                ((InitializingBean) bean).afterPropertiesSet();
            }
        }

        if (mbd != null) {
            String initMethodName = mbd.getInitMethodName();
            if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
                    !mbd.isExternallyManagedInitMethod(initMethodName)) {
                invokeCustomInitMethod(beanName, bean, mbd);
            }
        }
    }
  • 10.destroyBean
@Override
public void destroyBean(Object existingBean) {
   new DisposableBeanAdapter(existingBean, getBeanPostProcessors(), getAccessControlContext()).destroy();
}

@Override
public void destroy() {
    if (!CollectionUtils.isEmpty(this.beanPostProcessors)) {
        //获取所有DestructionAwareBeanPostProcessor 调用postProcessBeforeDestruction
        //@PreDestroy
        for (DestructionAwareBeanPostProcessor processor : this.beanPostProcessors) {
            processor.postProcessBeforeDestruction(this.bean, this.beanName);
        }
    }

    //调用DisposableBean#destroy
    if (this.invokeDisposableBean) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invoking destroy() on bean with name '" + this.beanName + "'");
        }
        try {
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                    @Override
                    public Object run() throws Exception {
                        ((DisposableBean) bean).destroy();
                        return null;
                    }
                }, acc);
            }
            else {
                ((DisposableBean) bean).destroy();
            }
        }
        catch (Throwable ex) {
            String msg = "Invocation of destroy method failed on bean with name '" + this.beanName + "'";
            //...
        }
    }
         //xml的destroy-method
    if (this.destroyMethod != null) {
        invokeCustomDestroyMethod(this.destroyMethod);
    }
    else if (this.destroyMethodName != null) {
        Method methodToCall = determineDestroyMethod();
        if (methodToCall != null) {
            invokeCustomDestroyMethod(methodToCall);
        }
    }
}
public class InitAndDestroySeqBean implements InitializingBean,DisposableBean,BeanPostProcessor,InstantiationAwareBeanPostProcessor {

    public InitAndDestroySeqBean() {
        System.out.println("构造方法");
    }

    @PostConstruct
    public void postConstruct(){
        System.out.println("@PostConstruct");
    }

    @Override public void afterPropertiesSet() throws Exception {
        System.out.println("afterPropertiesSet()#InitializingBean");

    }

    public void initMethod(){
        System.out.println("init-method");

    }

    @PreDestroy
    public void preDestroy(){
        System.out.println("@PreDestroy");
    }


    @Override public void destroy() throws Exception {
        System.out.println("destroy()#DisposableBean");
    }


    public void destroyMethod(){
        System.out.println("destroy-method");
    }


    @Override public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        System.out.println("postProcessBeforeInitialization(Object bean, String beanName)#BeanPostProcessor");
        return bean;
    }


    @Override public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        System.out.println("postProcessAfterInitialization(Object bean, String beanName)#BeanPostProcessor");
        return bean;
    }


    @Override public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName)
            throws BeansException {
        System.out.println("postProcessBeforeInstantiation(Class<?> beanClass, String beanName)#InstantiationAwareBeanPostProcessor");
        return null;
    }


    @Override public boolean postProcessAfterInstantiation(Object bean, String beanName)
            throws BeansException {
        System.out.println("postProcessAfterInstantiation(Object bean, String beanName)#InstantiationAwareBeanPostProcessor");

        return false;
    }


    @Override public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds,
            Object bean, String beanName) throws BeansException {
        System.out.println("postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds,\n"
                + "            Object bean, String beanName)#InstantiationAwareBeanPostProcessor");

        return null;
    }
}

20170308:11:34:52.866 [main] INFO   Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@49c43f4e, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@290dbf45, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@12028586, org.springframework.test.context.support.DirtiesContextTestExecutionListener@17776a8, org.springframework.test.context.transaction.TransactionalTestExecutionListener@69a10787, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@2d127a61]20170308:11:34:52.972 [main] INFO   Loading XML bean definitions from URL [file:/Users/dsc/IdeaProjects/firDemo/firdemo/web/target/classes/init.xml]
20170308:11:34:53.105 [main] INFO   Refreshing org.springframework.context.support.GenericApplicationContext@2b4a2ec7: startup date [Wed Mar 08 11:34:53 CST 2017]; root of context hierarchy
构造方法
@PostConstruct
afterPropertiesSet()#InitializingBean
init-method
beanName)#InstantiationAwareBeanPostProcessor**guavaCache
postProcessAfterInstantiation(Object bean, String beanName)#InstantiationAwareBeanPostProcessor**guavaCache
postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds,
            Object bean, String beanName)#InstantiationAwareBeanPostProcessor**guavaCache
postProcessBeforeInitialization(Object bean, String beanName)#BeanPostProcessor**guavaCache
afterPropertiesSet#InitializingBean**guavaCache
postProcessAfterInitialization(Object bean, String beanName)#BeanPostProcessor**guavaCache
20170308:11:34:53.286 [Thread-0] INFO   Closing org.springframework.context.support.GenericApplicationContext@2b4a2ec7: startup date [Wed Mar 08 11:34:53 CST 2017]; root of context hierarchy
@PreDestroy
destroy()#DisposableBean
destroy-method
  
  

Spring生命周期

通过源码我们清晰的看到

  1. 拿到应用中所有实现了InstantiationAwareBeanPostProcessor接口的类,就先postProcessBeforeInstantiation(Class<?> beanClass, String beanName)->postProcessAfterInitialization(Object bean, String beanName)

如果已经能拿到相应的bean则直接返回不进行下面的操作

  1. 本bean如果
    • 实现了BeanNameAware就调用setBeanName把bean名字放入

    • 实现了BeanClassLoaderAware就调用setBeanClassLoader把ClassLoader放入

    • 实现了BeanFactoryAware调用setBeanFactory把BeanFactory放入

  2. 拿到应用中所有实现了BeanPostProcessor接口的类,调用postProcessBeforeInstantiation(Class<?> beanClass, String beanName)拿到bean
  3. 反射实例化bean
  4. @PostConstruct注解的方法
  5. 本bean如果实现了InitializingBean接口,则调用afterPropertiesSet
  6. 本bean如果在xml里面配置了init-method则调用
  7. 拿到应用中所有实现了BeanPostProcessor接口的类,调用postProcessAfterInitialization(Object bean, String beanName) 拿到bean返回,就是最终在容器里面的bean
  8. @PreDestroy注解的方法
  9. 本bean如果实现了DisposableBean则调用destroy()
  10. 本bean如果在xml里面配置了destroy-method则调用

刚才反复提到了几个接口,我们来单独看下他们的使用:

InstantiationAwareBeanPostProcessor接口

public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {

    Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException;

    boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException;

    PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException;
}

BeanNameAware接口,通过实现这个接口可以获取到bean的id名

public interface BeanNameAware extends Aware {

   void setBeanName(String name);

}

BeanClassLoaderAware接口,可以获取到bean的ClassLoader

public interface BeanClassLoaderAware extends Aware {
   
   void setBeanClassLoader(ClassLoader classLoader);

}

BeanFactoryAware接口,通过实现这个接口可以获取到beanFactory

public interface BeanFactoryAware extends Aware {

   void setBeanFactory(BeanFactory beanFactory) throws BeansException;

}

ApplicationContextAware接口,获取ApplicationContext

public interface ApplicationContextAware extends Aware {

   void setApplicationContext(ApplicationContext applicationContext) throws BeansException;

}

BeanPostProcessor接口

public interface BeanPostProcessor {

    Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;

    Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;

}

InitializingBean接口

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

DisposableBean接口

public interface DisposableBean {
    void destroy() throws Exception;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 201,784评论 5 474
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,745评论 2 378
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 148,702评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,229评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,245评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,376评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,798评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,471评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,655评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,485评论 2 318
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,535评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,235评论 3 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,793评论 3 304
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,863评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,096评论 1 258
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,654评论 2 348
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,233评论 2 341

推荐阅读更多精彩内容