前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring - InitializingBean扩展接口

Spring - InitializingBean扩展接口

作者头像
小小工匠
发布2022-12-06 15:28:42
2560
发布2022-12-06 15:28:42
举报
文章被收录于专栏:小工匠聊架构小工匠聊架构

文章目录

在这里插入图片描述
在这里插入图片描述

Pre

Spring Boot - 扩展接口一览

在这里插入图片描述
在这里插入图片描述

org.springframework.beans.factory.InitializingBean

代码语言:javascript
复制
public interface InitializingBean {

	/**
	 * Invoked by the containing {@code BeanFactory} after it has set all bean properties
	 * and satisfied {@link BeanFactoryAware}, {@code ApplicationContextAware} etc.
	 * <p>This method allows the bean instance to perform validation of its overall
	 * configuration and final initialization when all bean properties have been set.
	 * @throws Exception in the event of misconfiguration (such as failure to set an
	 * essential property) or if initialization fails for any other reason
	 */
	void afterPropertiesSet() throws Exception;

}
在这里插入图片描述
在这里插入图片描述

InitializingBean接口为bean提供了初始化方法的方式,只有afterPropertiesSet方法。

凡是实现该接口的类,在初始化bean的时候都会执行该方法。这个扩展点的触发时机在postProcessAfterInitialization之前

使用场景举例: 实现此接口来进行系统启动的时候一些业务指标的初始化工作。


源码解析

在这里插入图片描述
在这里插入图片描述

我们直接

代码语言:javascript
复制
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
		// ....

		try {
			invokeInitMethods(beanName, wrappedBean, mbd);
		}
		catch (Throwable ex) {
		 	// ....
		}
		if (mbd == null || !mbd.isSynthetic()) {
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

		return wrappedBean;
	}

继续

在这里插入图片描述
在这里插入图片描述
代码语言:javascript
复制
protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd)
        throws Throwable {
        // 判断 bean 是否实现了 InitializingBean 接口
    boolean isInitializingBean = (bean instanceof InitializingBean);
    if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
        if (logger.isTraceEnabled()) {
            logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
        }
        // 系统安全处理器为空则直接执行 else 流程, 调用 afterPropertiesSet 方法
        // 默认为空,所以直接 else 流程
        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();
        }
    }

    if (mbd != null && bean.getClass() != NullBean.class) {
        // 判断是否指定了 initMethod 方法, 如果指定会进行调用
        String initMethodName = mbd.getInitMethodName();
        // 如果 initMethod 方法名称为 “afterPropertiesSet”, 则不调用
        if (StringUtils.hasLength(initMethodName) &&
                !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
                !mbd.isExternallyManagedInitMethod(initMethodName)) {
            // 通过反射调用 initMethod 指定方法
            invokeCustomInitMethod(beanName, bean, mbd);
        }
    }
}
在这里插入图片描述
在这里插入图片描述

扩展示例

代码语言:javascript
复制
package com.artisan.bootspringextend.testextends;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 小工匠
 * @version 1.0
 * @description: TODO
 * @date 2022/12/5 0:21
 * @mark: show me the code , change the world
 */
@Slf4j
@Configuration
public class ExtendInitializingBean implements InitializingBean {
    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("--->ExtendInitializingBean#afterPropertiesSet called");
    }
}
在这里插入图片描述
在这里插入图片描述
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-12-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • Pre
  • org.springframework.beans.factory.InitializingBean
  • 源码解析
  • 扩展示例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档