spring bean初始化扩展之InitializingBean和 init-method源码解析

InitializingBean和init-method介绍

InitializingBean

InitializingBean是一个接口,它定义了一个afterPropertiesSet方法

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;

}

init-method

init-method,一般我们在bean中会定义相关的初始化方法,希望spring容器初始bean时,调用我们定义的初始化方法,而这个方法我们一般会通过在xml配置bean时通过init-method标签来指定对应的初始化方法,或者是现在流行的注解式开发,通过@Bean(initMethod=“xxx”)指定对应的初始化方法。

@Configuration
public class MainConfigOfLifeCycle {
   
	@Bean(initMethod="init")
	public Car car(){
   
		return new Car();
	}
}

InitializingBean和init-method的作用执行时机

继续通过AbstractAutowireCapableBeanFactory中初始化bean的源码中,了解一下InitializingBean和init-method的作用执行时机。

protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
   
		if (System.getSecurityManager() != null) {
   
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
   
				invokeAwareMethods(beanName, bean);
				return null;
			}, getAccessControlContext());
		}
		else {
   
			//调用调用此方法进行部分Aware接口的回调
			invokeAwareMethods(beanName, bean);
		}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值