美文网首页
Spring的@PostConstruct和Aware接口实现原

Spring的@PostConstruct和Aware接口实现原

作者: 7d972d5e05e8 | 来源:发表于2020-09-18 00:00 被阅读0次

    @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方法。是不是很灵活!!!

    相关文章

      网友评论

          本文标题:Spring的@PostConstruct和Aware接口实现原

          本文链接:https://www.haomeiwen.com/subject/jgmsyktx.html