Spring的@PostConstruct和Aware接口实现原理

@PostConstruct是由CommonAnnotationBeanPostProcessor类实现的。

一、CommonAnnotationBeanPostProcessor是什么时候加载进去的呢?

我们首先看到CommonAnnotationBeanPostProcessor是spring context下的包,说明是spring自带的类。我们就大胆猜想,它是spring的创世纪类,即internal类。我们怎么验证呢?我们知道spring自带的创世纪类是在下面的构造方法里面:

public AnnotationConfigApplicationContext() {
        this.reader = new AnnotatedBeanDefinitionReader(this);
        this.scanner = new ClassPathBeanDefinitionScanner(this);
    }

new AnnotatedBeanDefinitionReader的时候会调用:

AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);

里面有段代码会添加CommonAnnotationBeanPostProcessor类:

// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
        if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
            RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
            def.setSource(source);
            beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
        }

二、CommonAnnotationBeanPostProcessor怎么和@PostConstruct关联上的?

首先看下该类的无参构造方法:

public CommonAnnotationBeanPostProcessor() {
        setOrder(Ordered.LOWEST_PRECEDENCE - 3);
        setInitAnnotationType(PostConstruct.class);
        setDestroyAnnotationType(PreDestroy.class);
        ignoreResourceType("javax.xml.ws.WebServiceContext");
    }

这个无参构造方法肯定会在实例化该类的时候被调用。
看到里面有PostConstruct注解了吧。在详细看下setInitAnnotationType方法:

public void setInitAnnotationType(Class<? extends Annotation> initAnnotationType) {
        this.initAnnotationType = initAnnotationType;
    }

会把PostConstruct.class赋值给initAnnotationType属性。这个属性所属的类为InitDestroyAnnotationBeanPostProcessor,可以看到它实现了BeanPostProcessor接口。

我们就很容易猜想了,PostConstruct肯定在BeanPostProcessor的两个拓展方法其中一个被执行了。

三、验证BeanPostProcessor中哪个拓展方法调用了@PostConstruct注解

大不了我们看下InitDestroyAnnotationBeanPostProcessor类的这两个方法的实现:

@Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
        try {
            metadata.invokeInitMethods(bean, beanName);
        }
        catch (InvocationTargetException ex) {
            throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());
        }
        catch (Throwable ex) {
            throw new BeanCreationException(beanName, "Failed to invoke init method", ex);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

很明显postProcessAfterInitialization这个方法的实现直接返回bean,没做任何处理,排除。我们看下postProcessBeforeInitialization方法。里面有个findLifecycleMetadata方法得到metadata,然后调用invokeInitMethods。我们可以猜想出来,metadata肯定是一个method反射对象,然后通过反射调用该方法。是不是有可能findLifecycleMetadata方法,返回的就是@PostConstruct注解的方法呢?

private LifecycleMetadata findLifecycleMetadata(Class<?> clazz) {
        if (this.lifecycleMetadataCache == null) {
            // Happens after deserialization, during destruction...
            return buildLifecycleMetadata(clazz);
        }
        // Quick check on the concurrent map first, with minimal locking.
        LifecycleMetadata metadata = this.lifecycleMetadataCache.get(clazz);
        if (metadata == null) {
            synchronized (this.lifecycleMetadataCache) {
                metadata = this.lifecycleMetadataCache.get(clazz);
                if (metadata == null) {
                    metadata = buildLifecycleMetadata(clazz);
                    this.lifecycleMetadataCache.put(clazz, metadata);
                }
                return metadata;
            }
        }
        return metadata;
    }

核心方法在buildLifecycleMetadata:

private LifecycleMetadata buildLifecycleMetadata(final Class<?> clazz) {
        final boolean debug = logger.isDebugEnabled();
        LinkedList<LifecycleElement> initMethods = new LinkedList<LifecycleElement>();
        LinkedList<LifecycleElement> destroyMethods = new LinkedList<LifecycleElement>();
        Class<?> targetClass = clazz;

        do {
            final LinkedList<LifecycleElement> currInitMethods = new LinkedList<LifecycleElement>();
            final LinkedList<LifecycleElement> currDestroyMethods = new LinkedList<LifecycleElement>();

            ReflectionUtils.doWithLocalMethods(targetClass, new ReflectionUtils.MethodCallback() {
                @Override
                public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                    if (initAnnotationType != null) {
                        if (method.getAnnotation(initAnnotationType) != null) {
                             // PostConstruct 赋值给了initAnnotationType,只要用@PostConstruct修饰的方法,必然会进来。
                            LifecycleElement element = new LifecycleElement(method);
                            currInitMethods.add(element);
                            if (debug) {
                                logger.debug("Found init method on class [" + clazz.getName() + "]: " + method);
                            }
                        }
                    }
                    if (destroyAnnotationType != null) {
                        if (method.getAnnotation(destroyAnnotationType) != null) {
                            currDestroyMethods.add(new LifecycleElement(method));
                            if (debug) {
                                logger.debug("Found destroy method on class [" + clazz.getName() + "]: " + method);
                            }
                        }
                    }
                }
            });

            initMethods.addAll(0, currInitMethods);
            destroyMethods.addAll(currDestroyMethods);
            targetClass = targetClass.getSuperclass();
        }
        while (targetClass != null && targetClass != Object.class);

        return new LifecycleMetadata(clazz, initMethods, destroyMethods);
    }

看到关键字ReflectionUtils.doWithLocalMethods(class,() -> doWith)了吗?遍历class所有的method,执行doWith方法。而doWith方法里面出现了最关键的initAnnotationType。是不是关联上了第二节说的那个方法了:

public void setInitAnnotationType(Class<? extends Annotation> initAnnotationType) {
        // PostConstruct 赋值给了initAnnotationType
        this.initAnnotationType = initAnnotationType;
    }

最终,bean class所有用@PostConstruct注解修饰的方法,都会被返回给第三节中的findLifecycleMetadata方法。如下:

@Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
        try {
            metadata.invokeInitMethods(bean, beanName);
        }
        catch (InvocationTargetException ex) {
            throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());
        }
        catch (Throwable ex) {
            throw new BeanCreationException(beanName, "Failed to invoke init method", ex);
        }
        return bean;
    }

我们看下metadata.invokeInitMethods方法。

public void invokeInitMethods(Object target, String beanName) throws Throwable {
            Collection<LifecycleElement> initMethodsToIterate =
                    (this.checkedInitMethods != null ? this.checkedInitMethods : this.initMethods);
            if (!initMethodsToIterate.isEmpty()) {
                boolean debug = logger.isDebugEnabled();
                for (LifecycleElement element : initMethodsToIterate) {
                    if (debug) {
                        logger.debug("Invoking init method on bean '" + beanName + "': " + element.getMethod());
                    }
                    element.invoke(target);
                }
            }
        }

element.invoke(target)不就是method.invoke(object)嘛~

四、知道@PostConstruct怎么被调用了,那它什么时候被调用呢?

上节我们已经知道了@PostConstruct被类CommonAnnotationBeanPostProcessor的构造函数添加进去的,该类继承了InitDestroyAnnotationBeanPostProcessor。而它又实现了BeanPostProcessor接口,并且实现在postProcessBeforeInitialization方法里面。

我们都知道postProcessBeforeInitialization方法是在doCreatedBean的initializeBean的applyBeanPostProcessorsBeforeInitialization方法里面。如下:

@Override
    public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
            throws BeansException {

        Object result = existingBean;
        for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
            result = beanProcessor.postProcessBeforeInitialization(result, beanName);
            if (result == null) {
                return result;
            }
        }
        return result;
    }

beanProcessor.postProcessBeforeInitialization方法,可不就有CommonAnnotationBeanPostProcessor嘛~因为它是spring的创世纪类,由第一节中的spring自动加载进去。

所以我们这里可以知道初始化bean的时候(参考initializeBean方法的实现),那几个初始化方法的执行顺序了。

invokeAwareMethods -> postProcessBeforeInitialization(ApplicationContextAwareProcessor会执行剩下的aware方法) -> afterPropertiesSet -> initMethod -> postProcessAfterInitialization(AOP)

Spring的Aware接口实现原理

aware其实就是spring的回调方法,用来在某一个生命周期阶段,调用用户的回调方法。

比如:我们创建一个bean实现ApplicationContextAware接口,该接口只有一个方法:setApplicationContext。那么我们的bean既然实现了该接口,必须重写该方法,这个时候我们就可以在这个bean里面定义一个容器,来接收spring回调给我们的ApplicationContext容器。这样,咱们就可以拿到整个spring容器了。

再比如:我们创建一个bean实现BeanNameAware接口,那么spring会在特殊生命周期阶段回调咱们的bean的setBeanName。我们同样也可以定义一个String成员属性来接收这个beanName。

所以,aware接口给了程序员可以让spring回调我们业务的口子。比如:我们自己实现一个demoAware。由于demoAware并没有被spring预先硬编码进去,所以想要spring回调demoAware的实现类,我们可以看考ApplicationContextAwareProcessor。咱们可以实现BeanPostProcessor,在postProcessBeforeInitialization或者postProcessAfterInitialization的方法里面,调用invokeAwareInterfaces方法。是不是很灵活!!!

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