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

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

被折叠的 条评论
为什么被折叠?



