一、通过soring xml模式分析Bean的初始化流程
new ClassPathXmlApplicationContext("applicationContext-xxx.xml");
->this.setConfigLocations(configLocations);
->this.refresh();
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
@Override
public void refresh() throws BeansException, IllegalStateException {
//注册BeanDefinition,并没有实例化并Bean
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); //AbstractApplicationContext
//设置 BeanFactory 的类加载器,添加几个 BeanPostProcessor,手动注册几个特殊的 bean
prepareBeanFactory(beanFactory);
//这里是提供给子类的扩展点,到这里的时候,所有的 Bean 都加载、注册完成了,但是都还没有初始化。具体的子类可以在这步的时候添加一些特殊的 BeanFactoryPostProcessor 的实现类或做点什么事
postProcessBeanFactory(beanFactory);
// 调用 BeanFactoryPostProcessor 各个实现类的 postProcessBeanFactory(factory) 方法
invokeBeanFactoryPostProcessors(beanFactory); //AbstractApplicationContext
// 注册BeanPostProcessor
registerBeanPostProcessors(beanFactory); //AbstractApplicationContext
//初始化所有的 singleton beans(lazy-init 的除外)
finishBeanFactoryInitialization(beanFactory);
}
}
二、obtainFreshBeanFactory()分析
2.1、obtainFreshBeanFactory将常规定义对象转换成BeanDefinition,并注册到beanFactory中
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
->refreshBeanFactory();
->DefaultListableBeanFactory beanFactory = createBeanFactory();
->customizeBeanFactory(beanFactory);
->loadBeanDefinitions(beanFactory);
->this.beanFactory = beanFactory;
loadBeanDefinitions(beanFactory); --AbstractRefreshableApplicationContext
->XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
//添加环境变量
->beanDefinitionReader.setEnvironment(getEnvironment());
->initBeanDefinitionReader(beanDefinitionReader);
->loadBeanDefinitions(beanDefinitionReader);
->String[] configLocations = getConfigLocations();
->for (String configLocation : configLocations)
->reader.loadBeanDefinitions(configLocation);
...
->BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
->documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
...
->Element root = doc.getDocumentElement(); //DefaultBeanDefinitionDocumentReader
->BeanDefinitionParserDelegate delegate = createHelper(readerContext, root); //DefaultBeanDefinitionDocumentReader
->BeanDefinitionParserDelegate delegate = new BeanDefinitionParserDelegate(readerContext);
->parseBeanDefinitions(root, delegate); //DefaultBeanDefinitionDocumentReader
...
->BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
...
->registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
->this.beanDefinitionMap.put(beanName, beanDefinition);
三、prepareBeanFactory(beanFactory)分析(添加几个 BeanPostProcessor,手动注册几个特殊的 bean)
public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext {
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
}
}
四、postProcessBeanFactory(beanFactory)分析
4.1、postProcessBeanFactory不一定会实现,根据不同的ApplicationContext有不同的处理
public class ServletWebServerApplicationContext extends GenericWebApplicationContext implements ConfigurableWebServerApplicationContext {
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
beanFactory.addBeanPostProcessor(new WebApplicationContextServletContextAwareProcessor(this));
beanFactory.ignoreDependencyInterface(ServletContextAware.class);
this.registerWebApplicationScopes();
}
}
五、invokeBeanFactoryPostProcessors(beanFactory)分析
5.1、调用registryProcessor.postProcessBeanDefinitionRegistry(registry);可以注册自定义的beanDefinition
invokeBeanFactoryPostProcessors(beanFactory); //AbstractApplicationContext
->PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
->if (beanFactory instanceof BeanDefinitionRegistry)
->for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors)
->BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor;
->registryProcessor.postProcessBeanDefinitionRegistry(registry);
六、registerBeanPostProcessors(beanFactory)分析(将BeanPostProcessor注册到beanFactory)
registerBeanPostProcessors(beanFactory); //AbstractApplicationContext
->PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
->String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
->for (String ppName : postProcessorNames)
->BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
->internalPostProcessors.add(pp);
->registerBeanPostProcessors(beanFactory, internalPostProcessors);
->for (BeanPostProcessor postProcessor : postProcessors)
->beanFactory.addBeanPostProcessor(postProcessor);
七、finishBeanFactoryInitialization(beanFactory)分析
7.1、初始化所有的 singleton beans(lazy-init 的除外)
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
beanFactory.preInstantiateSingletons();
}
}
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
public void preInstantiateSingletons() throws BeansException {
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
for (String beanName : beanNames) {
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
//非抽象类初始化
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
//通过工厂创建对象
if (isFactoryBean(beanName)) {
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
}
} else {
//直接创建对象
getBean(beanName);
}
}
}
}
//执行回调
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
smartSingleton.afterSingletonsInstantiated();
}
}
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
private final Map<Class, Object> resolvableDependencies = new HashMap<Class, Object>();
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<String, BeanDefinition>();
private final List<String> beanDefinitionNames = new ArrayList<String>();
public <T> T getBean(Class<T> requiredType) throws BeansException {
if (beanNames.length == 1) {
return getBean(beanNames[0], requiredType);
->return doGetBean(name, requiredType, null, false);
->Object sharedInstance = getSingleton(beanName);
->if (sharedInstance != null && args == null)
->bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
->else
->BeanFactory parentBeanFactory = getParentBeanFactory();
->if (parentBeanFactory != null && !containsBeanDefinition(beanName))
->return (T) parentBeanFactory.getBean(nameToLookup, args);
->final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
->String[] dependsOn = mbd.getDependsOn();
->for (String dependsOnBean : dependsOn)
->getBean(dependsOnBean);
->registerDependentBean(dependsOnBean, beanName);
->if (mbd.isSingleton())
->sharedInstance = getSingleton(beanName, new ObjectFactory() {
public Object getObject() throws BeansException {
->return createBean(beanName, mbd, args);
->bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
->else
->prototypeInstance = createBean(beanName, mbd, args);
->bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
->return (T) bean;
}
else if (beanNames.length == 0 && getParentBeanFactory() != null) {
return getParentBeanFactory().getBean(requiredType);
}
}
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException {
this.beanDefinitionMap.put(beanName, beanDefinition);
}
}
八、Bean的创建
8.1、根据第七点的分析我们知道,DefaultListableBeanFactory调用了createBean创建对象
protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
->Object beanInstance = doCreateBean(beanName, mbd, args);
//添加关联
->applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName)
->for (BeanPostProcessor bp : getBeanPostProcessors())
->bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName)
//注入依赖
->populateBean(beanName, mbd, instanceWrapper)
->for (BeanPostProcessor bp : getBeanPostProcessors())
->pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
->InjectionMetadata metadata = findResourceMetadata(bean.getClass());
->metadata.inject(bean, beanName, pvs);
->for (InjectedElement element : this.injectedElements)
->element.inject(target, beanName, pvs);
->value = beanFactory.resolveDependency(descriptor, beanName, autowiredBeanNames, typeConverter);
->field.set(bean, value);
->exposedObject = initializeBean(beanName, exposedObject, mbd);
->...
return beanInstance;
8.2、依赖的添加
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
private final Set<Class<? extends Annotation>> autowiredAnnotationTypes = new LinkedHashSet<Class<? extends Annotation>>();
private ConfigurableListableBeanFactory beanFactory;
private final Map<Class<?>, InjectionMetadata> injectionMetadataCache = new ConcurrentHashMap<Class<?>, InjectionMetadata>();
public AutowiredAnnotationBeanPostProcessor() {
this.autowiredAnnotationTypes.add(Autowired.class);
this.autowiredAnnotationTypes.add(Value.class);
this.autowiredAnnotationTypes.add((Class<? extends Annotation>)
...
}
//绑定依赖关系
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class beanType, String beanName) {
InjectionMetadata metadata = findAutowiringMetadata(beanType);
->metadata = buildAutowiringMetadata(clazz);
->LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>();
->for (Field field : targetClass.getDeclaredFields())
->currElements.add(new AutowiredFieldElement(field, required));
->for (Method method : targetClass.getDeclaredMethods())
->currElements.add(new AutowiredMethodElement(method, required, pd));
->elements.addAll(0, currElements);
->return new InjectionMetadata(clazz, elements);
->this.injectionMetadataCache.put(clazz, metadata);
}
//注入依赖对象
public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
InjectionMetadata metadata = findAutowiringMetadata(bean.getClass());
->InjectionMetadata metadata = this.injectionMetadataCache.get(clazz);
->return metadata;
metadata.inject(bean, beanName, pvs);
->value = beanFactory.resolveDependency(descriptor, beanName, autowiredBeanNames, typeConverter);
->field.set(bean, value);
return pvs;
}
}