美文网首页springbootSpring Cloud
spring中使用@PostConstruct注解与实现Init

spring中使用@PostConstruct注解与实现Init

作者: 黑铁大魔王 | 来源:发表于2020-07-27 20:56 被阅读0次

    使用spring时,在某个Class被初始化之后再执行一些代码,可以

    1. @PostConstruct注解方法,如:
    package org.dhframework;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import javax.annotation.PostConstruct;
    
    @Component
    public class Test4 {
    
        @PostConstruct
        public void pc1() {
            System.out.println("Test4.postConstruct()");
        }
    }
    
    

    @PostConstruct应用场景:
    在生成对象时候做一些初始化操作,而这些初始化操作又依赖于依赖注入(populateBean),那么就无法在构造函数中实现。这时,可以使用@PostConstruct注解一个方法来完成初始化,@PostConstruct注解的方法将会在依赖注入完成后被自动调用。

    题外话:为何构造函数中无法使用依赖注入的属性呢?
    因为在做doCreateBean时,大致的步骤是这样的

    1. 实例化bean,这里会调用构造方法
    2. 填充属性,就是依赖注入
    3. 初始化bean,
      • 调用后置处理器,其中会执行@PostConstruct注解方法
      • 执行bean的生命周期中的初始化回调方法,也就是InitializingBean接口的afterPropertiesSet()方法

    那么,显然在构造方法执行的时候,属性填充还没有开始,所以 构造函数中无法使用依赖注入的属性

    1. 也可以让该Class实现InitializingBean接口,重写public void afterPropertiesSet() throws Exception{ ... } 方法,如:
    package org.dhframework;
    
    import org.springframework.beans.factory.InitializingBean;
    import org.springframework.stereotype.Component;
    
    @Component
    public class Test4 implements InitializingBean {
        @Override
        public void afterPropertiesSet() throws Exception {
            System.out.println("Test4 InitializingBean.afterPropertiesSet()");
    
        }
    }
    
    

    这两种方式,在源码上,都是在doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)方法中,populateBean(beanName, mbd, instanceWrapper)填充属性(依赖注入)完成后的initializeBean(beanName, exposedObject, mbd)方法里完成的。
    看下方法的代码:

        protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                    invokeAwareMethods(beanName, bean);
                    return null;
                }, getAccessControlContext());
            }
            else {
                invokeAwareMethods(beanName, bean);
            }
    
            Object wrappedBean = bean;
            if (mbd == null || !mbd.isSynthetic()) {
                // 1. 第七次调用后置处理器,执行bean初始化之前需要被执行的方法,如@PostConstruct注解的方法
                wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
            }
    
            try {
                // 2. 执行InitializingBean接口的afterPropertiesSet()方法
                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;
        }
    

    @PostConstruct注解方法的执行

    上面代码,第一处注释,第七次调用后置处理器,


    第七次调用后置处理器

    在后置处理器CommonAnnotationBeanPostProcessor的父类InitDestroyAnnotationBeanPostProcessorpostProcessBeforeInitialization(Object bean, String beanName)方法里进行@PostConstruct注解方法的处理

    postProcessBeforeInitialization
    注意metadata里面,initMethods与checkedInitMethods的值。(这两个属性是何时赋值的,请看spring(碎片001), @PostConstruct相关,metadata里的initMethods何时被赋值
    )
    接下来执行metadata.invokeInitMethods(bean, beanName);
            public void invokeInitMethods(Object target, String beanName) throws Throwable {
                // 通过checkedInitMethods得到initMethodsToIterate
                Collection<LifecycleElement> checkedInitMethods = this.checkedInitMethods;
                Collection<LifecycleElement> initMethodsToIterate =
                        (checkedInitMethods != null ? checkedInitMethods : this.initMethods);
                if (!initMethodsToIterate.isEmpty()) {
                    for (LifecycleElement element : initMethodsToIterate) {
                        if (logger.isTraceEnabled()) {
                            logger.trace("Invoking init method on bean '" + beanName + "': " + element.getMethod());
                        }
                        // 接下来调用下面的invoke方法反射执行@PostConstruct注解的方法
                        element.invoke(target);
                    }
                }
            }
    
            public void invoke(Object target) throws Throwable {
                ReflectionUtils.makeAccessible(this.method);
                this.method.invoke(target, (Object[]) null);
            }
    
    反射执行方法

    至此,@PostConstruct注解方法执行完毕

    下面来看InitializingBean接口的afterPropertiesSet()方法,

    由下图可以看到,invokeInitMethods()方法的执行是紧接着后置处理器的执行

    image.png
    protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
                throws Throwable {
    
        //  第一处注释:如果实现了InitializingBean,就会执行afterPropertiesSet()方法
        boolean isInitializingBean = (bean instanceof InitializingBean);
            if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
                }
                if (System.getSecurityManager() != null) {
                    try {
                        AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
                            ((InitializingBean) bean).afterPropertiesSet();
                            return null;
                        }, getAccessControlContext());
                    }
                    catch (PrivilegedActionException pae) {
                        throw pae.getException();
                    }
                }
                else {
                    // 第二处注释:执行afterPropertiesSet()
                    ((InitializingBean) bean).afterPropertiesSet();
                }
            }
    
            // 第三处注释:执行init-method
            if (mbd != null && bean.getClass() != NullBean.class) {
                String initMethodName = mbd.getInitMethodName();
                if (StringUtils.hasLength(initMethodName) &&
                        !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
                        !mbd.isExternallyManagedInitMethod(initMethodName)) {
                    invokeCustomInitMethod(beanName, bean, mbd);
                }
            }
        }
    

    上面的第一处,第二处两处注释已经很好的说明了afterPropertiesSet()的执行步骤了。首先判断当前bean是否实现了InitializingBean接口,然后去执行afterPropertiesSet()方法

    再来看看第三住注释:这里是调用init-method指定的方法

    protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd)
                throws Throwable {
            // 先来一顿操作猛如虎
            String initMethodName = mbd.getInitMethodName();
            Assert.state(initMethodName != null, "No init method set");
            Method initMethod = (mbd.isNonPublicAccessAllowed() ?
                    BeanUtils.findMethod(bean.getClass(), initMethodName) :
                    ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));
    
            if (initMethod == null) {
                if (mbd.isEnforceInitMethod()) {
                    throw new BeanDefinitionValidationException("Could not find an init method named '" +
                            initMethodName + "' on bean with name '" + beanName + "'");
                }
                else {
                    if (logger.isTraceEnabled()) {
                        logger.trace("No default init method named '" + initMethodName +
                                "' found on bean with name '" + beanName + "'");
                    }
                    // Ignore non-existent default lifecycle methods.
                    return;
                }
            }
    
            if (logger.isTraceEnabled()) {
                logger.trace("Invoking init method  '" + initMethodName + "' on bean with name '" + beanName + "'");
            }
            Method methodToInvoke = ClassUtils.getInterfaceMethodIfPossible(initMethod);
    
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                    ReflectionUtils.makeAccessible(methodToInvoke);
                    return null;
                });
                try {
                    AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () ->
                            methodToInvoke.invoke(bean), getAccessControlContext());
                }
                catch (PrivilegedActionException pae) {
                    InvocationTargetException ex = (InvocationTargetException) pae.getException();
                    throw ex.getTargetException();
                }
            }
            else {
                try {
                    ReflectionUtils.makeAccessible(methodToInvoke);
                    // 这里就调用init-method了
                    methodToInvoke.invoke(bean);
                }
                catch (InvocationTargetException ex) {
                    throw ex.getTargetException();
                }
            }
        }
    

    相关文章

      网友评论

        本文标题:spring中使用@PostConstruct注解与实现Init

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