Spring - InitializingBean扩展接口

2022-12-06 15:28:42 浏览数 (1)

文章目录

  • Pre
  • org.springframework.beans.factory.InitializingBean
  • 源码解析
  • 扩展示例

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");
    }
}

0 人点赞