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

本文详细介绍了Spring中初始化Bean的两种方式:InitializingBean接口和init-method属性。通过源码分析,揭示了它们在Bean初始化过程中的执行时机。尽管两者功能相似,但InitializingBean需要实现接口,存在侵入性,而init-method则更为灵活。文中还通过代码示例展示了这两种方法的使用,并进行了性能对比,推荐在实际开发中优先考虑使用init-method进行初始化扩展。
摘要由CSDN通过智能技术生成

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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值