看这篇文章首先应该对spring有一些基本的理解:不建议初学者看,然后本文的源码分析走的xml配置的方式,ClassPathXmlApplicationContext是继承AbstractXmlApplicationContext->AbstractRefreshableConfigApplicationContext->AbstractRefreshableApplicationContext->AbstractApplicationContext的,spring加载跟注解方式有一丢丢区别…
文章目录
- refresh方法
- prepareRefresh 方法,准备工作
- obtainFreshBeanFactory方法
- prepareBeanFactory
- postProcessBeanFactory方法
- invokeBeanFactoryPostProcessors 执行BeanFacotyPostProcessor实现类的postProcessBeanFactory(factory)方法
refresh方法
AbstractApplicationContext的refresh方法,源码:
@Override
public void refresh() throws BeansException, IllegalStateException {
//加个锁,容器不能进行多次refresh
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
//准备工作,记录启动时间,标记"已启动"状态,处理配置文件的占位符
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
// 告诉子类刷新bean工厂,解析配置文件,注册到bean工厂,此时的bean并没有初始化
//注册也只是将信息保存到了注册中心(beanName->beanDefinition 的map)
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
//准备bean工厂,添加beanpostprocessor,手动注册一些bean
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
//执行一些特殊的BeanFactoryPostProcessor的实现类
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
//执行BeanFacotyPostProcessor实现类的postProcessBeanFactory(factory)方法
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
//注册BeanPostProcessor实现类
//BeanPostProcessor 接口两个方法: postProcessBeforeInitialization 和 postProcessAfterInitialization
//两个方法分别在类初始化之前和初始化之后执行
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
//初始化当前 ApplicationContext 的 MessageSource,国际化等等
initMessageSource();
// Initialize event multicaster for this context.
//初始化容器的事件广播
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// 初始化子类的一些特殊的bean(在初始化单例bean之前)
onRefresh();
// Check for listener beans and register them.
// 注册事件监听器,需要实现ApplicationListener
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
// 初始化所有单例的bean(懒加载除外)
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
// 最后,广播初始化完成事件
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
// 销毁已经创建的单例bean,避免占用资源
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
prepareRefresh 方法,准备工作
源码:
protected void prepareRefresh() {
// Switch to active.
//记录启动时间
this.startupDate = System.currentTimeMillis();
//将closed属性设置为false,active属性设置为true
this.closed.set(false);
this.active.set(true);
if (logger.isInfoEnabled()) {
logger.info("Refreshing " + this);
}
// Initialize any placeholder property sources in the context environment.
//初始化一些占位符属性
initPropertySources();
// Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties
//配置文件检测
getEnvironment().validateRequiredProperties();
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
this.earlyApplicationEvents = new LinkedHashSet<ApplicationEvent>();
}
obtainFreshBeanFactory方法
创建bean容器,加载注册一些beanDefinitions
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
//刷新bean工厂
refreshBeanFactory();
//获取bean工厂
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}
到这一步跟注解配置方式有区别,xml方式的话在创建容器的时候有加载一些默认的bean定义,而注解方式是在初始化AnnotationConfigApplicationContext类的时候就加载了bean容器,往bean容器中加了一些解析注解的beanfactory后置处理器,特别极其复杂…
AbstractRefreshableApplicationContext类的refreshBeanFactory的方法:
@Override
protected final void refreshBeanFactory() throws BeansException {
//判断是否已经加装过beanFactory,如果加装过,销毁所有bean,g关闭beanfactory
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
//创建DefaultListableBeanFactory
DefaultListableBeanFactory beanFactory = createBeanFactory();
//设置序列化id,不知道哪里使用
beanFactory.setSerializationId(getId());
//设置是否允许bean覆盖,是否可以循环依赖
customizeBeanFactory(beanFactory);
//加载bean定义,,重要
loadBeanDefinitions(beanFactory);
this.beanFactory = beanFactory;
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
AbstractXmlApplicationContext的loadBeanDefinitions方法:
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
//创建xml解析的类,XmlBeanDefinitionReader
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's
// resource loading environment.
//设置XmlBeanDefinitionReader的一些环境,资源加载器,然后初始化..
beanDefinitionReader.setEnvironment(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
initBeanDefinitionReader(beanDefinitionReader);
//加载bean定义,重要
loadBeanDefinitions(beanDefinitionReader);
}
两个加载配置文件最后都会走加载resource:
@Override
public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
Assert.notNull(resources, "Resource array must not be null");
int counter = 0;
for (Resource resource : resources) {
//直接看这个方法
counter += loadBeanDefinitions(resource);
}
return counter;
}
@Override
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
return loadBeanDefinitions(new EncodedResource(resource));
}
/**
* Load bean definitions from the specified XML file.
* @param encodedResource the resource descriptor for the XML file,
* allowing to specify an encoding to use for parsing the file
* @return the number of bean definitions found
* @throws BeanDefinitionStoreException in case of loading or parsing errors
*/
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
Assert.notNull(encodedResource, "EncodedResource must not be null");
if (logger.isInfoEnabled()) {
logger.info("Loading XML bean definitions from " + encodedResource);
}
//当前正在加载的EncodedResource
Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
if (currentResources == null) {
currentResources = new HashSet<EncodedResource>(4);
this.resourcesCurrentlyBeingLoaded.set(currentResources);
}
//将当前encodedResource添加到currentResources
if (!currentResources.add(encodedResource)) {
throw new BeanDefinitionStoreException(
"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
}
try {
//获取InputStream
InputStream inputStream = encodedResource.getResource().getInputStream();
try {
//将inputStream封装成org.xml.sax.InputSource
InputSource inputSource = new InputSource(inputStream);
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
//加载 bean 定义,就是各种解析了
return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
}
finally {
inputStream.close();
}
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(
"IOException parsing XML document from " + encodedResource.getResource(), ex);
}
finally {
currentResources.remove(encodedResource);
if (currentResources.isEmpty()) {
this.resourcesCurrentlyBeingLoaded.remove();
}
}
}
doLoadBeanDefinitions后面就是解析了加到beanDefinitionsMap里面,特别复杂,可以看一下…
prepareBeanFactory
比较简单,就是注册一些后置处理器,注册一些bean:
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
//设置classloader
beanFactory.setBeanClassLoader(getClassLoader());
//设置bean表达式解析器,
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
//将ResourceEditorRegistrar实例添加到工厂的propertyEditorRegistrars属性中,
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
//在工厂的beanPostProcessor属性中添加处理器,beanPostProcessor是一个ArrayList
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
//在工厂的ignoredDependencyInterfaces属性中添加Aware系列接口,忽略依赖的接口,
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
//再将上下文的一些接口与上下文本身做映射,一一放入到resolvableDependencies中
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// Register early post-processor for detecting inner beans as ApplicationListeners.
// 添加ApplicationListenerDetector后置处理器
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
//检测是否有LoadTimeWeaver,如果有就添加后置处理
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
//为匹配类型设置一个临时的classloader
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// Register default environment beans.
//判断目前这个bean工厂中是否包含指定name的bean,
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
//注册environment单例
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
//注册systemProperties单例
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
//注册systemEnvironment单例
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
}
postProcessBeanFactory方法
这个方法一般在使用web容器的时候会执行他的子类AbstractRefreshableWebApplicationContext,如果直接使用spring容器测试的话是一个空方法:
我们大概分析一下web容器这个方法,就添加了一些特殊的beanPostProcessors:
invokeBeanFactoryPostProcessors 执行BeanFacotyPostProcessor实现类的postProcessBeanFactory(factory)方法
源码:
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
// 获取beanFactoryPostProcessors并实例化,,然后调用所有beanFactoryPostProcessors
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
// 有没有LoadTimeWeaver,如果有就添加LoadTimeWeaverAwareProcessor,是一个beanPostProcessor
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
getBeanFactoryPostProcessors方法返回的是spring容器的属性beanFactoryPostProcessors,一般是空的,当然可以自定义添加,
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
public class MyApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
FirstBeanDefinitionRegistryPostProcessor firstBeanDefinitionRegistryPostProcessor = new FirstBeanDefinitionRegistryPostProcessor();
// 将自定义的firstBeanDefinitionRegistryPostProcessor添加到应用上下文中
applicationContext.addBeanFactoryPostProcessor(firstBeanDefinitionRegistryPostProcessor);
// ...自定义操作
System.out.println("SpringApplicationContextInitializer#initialize");
}
}
然后在springboot配置文件中配置:
context.initializer.classes=org.springframework.boot.demo.common.MyApplicationContextInitializer
主要方法:invokeBeanFactoryPostProcessors,先大概记录一下invokeBeanFactoryPostProcessors的调用,invokeBeanFactoryPostProcessors方法主要就是调用beanFactory后置处理器,但是spring对beanFactory后置处理器进行了扩展,BeanDefinitionRegistryPostProcessor,这个类,继承BeanFactoryPostProcessor,会先于BeanFactoryPostProcessor执行,用来在执行BeanFactoryPostProcessor的postProcessBeanFactory之前往spring容器中添加bean定义;
然后PriorityOrdered接口也是继承Ordered接口,也是优先执行;
画个图,多写几遍,大家多看几遍混个脸熟:
源码:
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
// 先执行BeanDefinitionRegistryPostProcessor,然后执行其他的
Set<String> processedBeans = new HashSet<String>();
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
//存放BeanFactoryPostProcessor
List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
//存放BeanDefinitionRegistryPostProcessor
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new LinkedList<BeanDefinitionRegistryPostProcessor>();
//首先处理传进来的beanFactoryPostProcessors,
// 将BeanDefinitionRegistryPostProcessor跟普通的BeanBeanFactoryPostProcessor分开执行,
//一开始就说了先执行BeanDefinitionRegistryPostProcessor,然后执行其他的
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
//如果是BeanDefinitionRegistryPostProcessor就执行.然后保存
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// Separate between BeanDefinitionRegistryPostProcessors that implement
// PriorityOrdered, Ordered, and the rest.
//保存当前要执行的BeanDefinitionRegistryPostProcessor
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
// 先找出所有BeanDefinitionRegistryPostProcessor的实现类,然后进行排序
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
//实现了PriorityOrdered接口的
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
//排序,根据Order接口,或者注解
sortPostProcessors(currentRegistryProcessors, beanFactory);
//添加到registryProcessors(用于最后执行postProcessBeanFactory方法)
registryProcessors.addAll(currentRegistryProcessors);
//遍历currentRegistryProcessors, 执行postProcessBeanDefinitionRegistry方法,就是for循环调用
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
//清空currentRegistryProcessors
currentRegistryProcessors.clear();
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
//同上,对实现了Ordered接口的类进行排序执行,上面一个是PriorityOrdered(优先的Order)
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
//最后调用所有剩下的BeanDefinitionRegistryPostProcessors,然后执行
boolean reiterate = true;
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
//跳过执行过的
if (!processedBeans.contains(ppName)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate = true;
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
// 调用所有的BeanDefinitionRegistryPostProcessor,的postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
//调用beanFactoryPostProcessors的postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// Invoke factory processors registered with the context instance.
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// 上面是执行所有的传入参数的beanFactoryPostProcessors,和BeanDefinitionRegistryPostProcessor
// 和容器中的BeanDefinitionRegistryPostProcessor
// 下面执行所有容器中的BeanFactoryPostProcessor
//跟上面处理逻辑差不多,先处理实现了PriorityOrdered接口的,再处理Ordered接口的,最后处理剩下的BeanFactoryPostProcessor
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
List<String> orderedPostProcessorNames = new ArrayList<String>();
List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName)) {
// skip - already processed in first phase above
}
else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
//处理order接口的
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Finally, invoke all other BeanFactoryPostProcessors.
// 最后处理剩下的
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
// Clear cached merged bean definitions since the post-processors might have
// modified the original metadata, e.g. replacing placeholders in values...
// 清除元数据缓存(mergedBeanDefinitions、allBeanNamesByType、singletonBeanNamesByType)
// 因为后置处理器可能已经修改了元数据,例如,替换值中的占位符
beanFactory.clearMetadataCache();
}