Spring - InitializingBean扩展接口

Posted 小小工匠

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring - InitializingBean扩展接口相关的知识,希望对你有一定的参考价值。

文章目录


Pre

Spring Boot - 扩展接口一览

org.springframework.beans.factory.InitializingBean

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之前

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


源码解析

我们直接

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;
	

继续

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



扩展示例

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

    

以上是关于Spring - InitializingBean扩展接口的主要内容,如果未能解决你的问题,请参考以下文章

spring常用接口 InitializingBean的作用

Spring Bean InitializingBean和DisposableBean实例

spring中InitializingBean接口使用理解

spring中InitializingBean接口使用理解

spring中InitializingBean接口使用理解

Spring - InitializingBean扩展接口