日常记录:InitializingBean是什么?

前言

今天在项目看到一个InitializingBean,不了解是什么作用,特意查了下

InitializingBean

其实,InitializingBean接口是为bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候都会执行该方法。

InitializingBean源码

public interface InitializingBean {
    void afterPropertiesSet() throws Exception;
}

InitializingBean的使用

@Component
public class TestInitialization implements InitializingBean {
    @Override
    public void afterPropertiesSet() throws Exception {
    }

}

以下是AbstractAutowireCapableBeanFactory源码中关于isInitializingBean 的一段代码

/**
	 * Give a bean a chance to react now all its properties are set,
	 * and a chance to know about its owning bean factory (this object).
	 * This means checking whether the bean implements InitializingBean or defines
	 * a custom init method, and invoking the necessary callback(s) if it does.
	 * @param beanName the bean name in the factory (for debugging purposes)
	 * @param bean the new bean instance we may need to initialize
	 * @param mbd the merged bean definition that the bean was created with
	 * (can also be {@code null}, if given an existing bean instance)
	 * @throws Throwable if thrown by init methods or by the invocation process
	 * @see #invokeCustomInitMethod
	 */
	protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
			throws Throwable {
			
		//判断该bean是否实现了实现了InitializingBean接口,
		//如果实现了InitializingBean接口,则只掉调用bean的afterPropertiesSet方法
		boolean isInitializingBean = (bean instanceof InitializingBean);
		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((PrivilegedExceptionAction<Object>) () -> {
						//调用afterPropertiesSet
						((InitializingBean) bean).afterPropertiesSet();
						return null;
					}, getAccessControlContext());
				}
				catch (PrivilegedActionException pae) {
					throw pae.getException();
				}
			}
			else {
				//调用afterPropertiesSet
				((InitializingBean) bean).afterPropertiesSet();
			}
		}

		if (mbd != null && bean.getClass() != NullBean.class) {
			String initMethodName = mbd.getInitMethodName();
			判断是否指定了init-method方法,如果指定了init-method方法,则再调用制定的init-method
			if (StringUtils.hasLength(initMethodName) &&
					!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
					!mbd.isExternallyManagedInitMethod(initMethodName)) {
				//查看该方法的源码,可以发现init-method方法中指定的方法是通过反射实现
				invokeCustomInitMethod(beanName, bean, mbd);
			}
		}
	}

总结

InitializingBean就是为一个类提供了一个初始化方法afterPropertiesSet(),该方法会在初始化bean时执行。还有一种方式,我们也可以使用init-method来指定初始化方法

init-method使用
使用@Bean的initMethod属性就可以指定初始化方法了

@Configuration
public class CustomLifeCycleConfig {
    
    @Bean(initMethod = "init",destroyMethod = "destroy")
    public Test2 test2(){
        return new Test2 ();
    }
    

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值