sping @Bean创建对象五 init方法的执行以及其初始化

本文深入探讨了Spring中@Bean注解创建对象时的初始化过程,特别是init方法的执行。通过BeanPostProcessor的before和after初始化处理以及反射机制调用注解指定的初始化方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        //执行BeanPostProcessor.postProcessBeforeInitialization()
        wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);

        //执行init方法
        invokeInitMethods(beanName, wrappedBean, mbd);

        //执行BeanPostProcessor.postProcessAfterInitialization()
        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
 

说过applyBeanPostProcessorsBeforeInitialization之后,下面继续看invokeInitMethods(beanName, wrappedBean, mbd);

protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
        throws Throwable {

    boolean isInitializingBean = (bean instanceof InitializingBean);、
    //从这块代码中,执行init方法也可以让类实现InitializingBean接口,实现其afterPropertiesSet方
    if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
        }
        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)) {
            //通过反射机制执行其init方法
            invokeCustomInitMethod(beanName, bean, mbd);
        }
    }
}

通过以上代码,就是从类定义信息中获取注解中init的方法名,然后通过反射机制执行其方法


关于类定义信息的初始化,看这里https://blog.youkuaiyun.com/Bandeo/article/details/104222124

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值