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