写在前面
Spring IOC这个部分还是很难的,我基本有了一年多的使用经验才慢慢开始看源码,但都是头大无比,一定要静下心慢慢看,就像一杯苦茶,越品越有味道!
Webx是阿里开源的web框架:
http://www.openwebx.org/docs/Webx3_Guide_Book.html
HSF是阿里的
IOC大致流程
IOC容器的两个最主要的两个接口BeanFactory
和ApplicationContext
相信大家都接触过,IOC整个初始化流程非常复杂,分为两个主要的过程:
- 注册BeanDefinition
- getBean
Spring在复杂的流程中也为开发者留有一些接口,开发人员可以利用这些接口完成自己一些项目功能,或者在其之上继续开发框架。这部分也经常会以Spring生命周期的形式出现在各类资料上,那我们来疏导一下:
BeanFactoryPostProcessor
public interface BeanFactoryPostProcessor {
/**
* Modify the application context's internal bean factory after its standard
* initialization. All bean definitions will have been loaded, but no beans
* will have been instantiated yet. This allows for overriding or adding
* properties even to eager-initializing beans.
* @param beanFactory the bean factory used by the application context
* @throws org.springframework.beans.BeansException in case of errors
*/
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
}
BeanFactoryPostProcessor容器级操作,会在整个beanFactory初始化之后调用用户定义的BeanFactoryPostProcessor,例如placeholder,就是在BeanFactory注册好了之后对其中的placeholder进行替换。
Aware
顾名思义,这是spring提供的用户可以对spring容器的一些感知,常见的有ApplicationContextAware
public interface ApplicationContextAware extends Aware {
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}
Aware的调用是被ApplicationContextAwareProcessor这个BeanPostProcessor在postProcessBeforeInitialization时调用的。有点绕,你可以先看下面的,然后再回来。
BeanPostProcessor
先看代码
public interface BeanPostProcessor {
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}
BeanPostProcessor是在执行用户定义的init-method前后执行before和after的,上例中的Aware就是在before的时候执行的。
InitializingBean
InitializingBean是在用户的init-method之前执行
public interface InitializingBean {
void afterPropertiesSet() throws Exception;
}
有点乱了是不是,简单屡一下ApplicationContext的refresh过程,也就是初始化过程,首先会注册BeanFactory,然后执行BeanFactoryPostProcessor之后注册ApplicationContextAwareProcess