Spring Framework,也就是我们常说的Spring框架,我觉得其中最核心的部分应该就是IOC容器了,Spring的IOC容器的实现也叫做DI,也就是依赖注入。这篇博客要说的就是这其中的大概的实现过程。
AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(SpringConfig.class);
Spring的启动只需要这样一行代码就可以了
public AnnotationConfigApplicationContext(Class>... componentClasses) {
this();
register(componentClasses);
refresh();
}
先看一看类图
在这个类图中,最核心的一个就是AbstractApplicationContext。
接着看代码,首先初始化注解以及XML的读取或者扫描的两个类,接着将实例化AnnotationConfigApplicationContext时传入的类,也就是register方法中传入的类,生成BeanDefinition(这里必须先要弄明白BeanDefinition和Bean的区别),存入beanDefinitionMap,而此时并没有执行扫描,接着执行refresh方法。
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
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.
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方法,这里主要是web环境下加载一些配置属性,不过这需要GenericWebApplicationContext去实现,如果是当前AnnotationConfigApplicationContext ,默认无动作
// Initialize any placeholder property sources in the context environment.
initPropertySources();
接着获取一个BeanFactory,这个BeanFactory当前已经创建,不过只是获取过程中做了一些和序列化相关的操作,这个BeanFactory也是相当重要,看一看类图
接着prepareBeanFactory方法,设置了一些公共的处理器什么的
接着postProcessBeanFactory方法,这个是BeanFactory的后置处理,交给子类实现,当前类没有操作
接着invokeBeanFactoryPostProcessors方法
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
首先循环执行当前的beanFactoryPostProcessors,不过目前beanFactoryPostProcessors肯定是空,在之前的代码,并没有将继承了BeanDefinitionRegistryPostProcessor接口的类添加到beanFactoryPostProcessors集合中的代码,因此如果想在这里执行到,那就只能自己写代码,在refresh()方法之前,直接调用addBeanFactoryPostProcessor手动添加。
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
}
接着会从当前的BeanDefinition集合中找出实现了PriorityOrdered和BeanDefinitionRegistryPostProcessor的BeanDefinition,然后根据BeanDefinition获取Bean然后执行postProcessBeanDefinitionRegistry方法,这个getBean的过程待会再看,当前这里只会有一个之前实例化AnnotatedBeanDefinitionReader时添加的ConfigurationClassPostProcessor,名称是org.springframework.context.annotation.internalConfigurationAnnotationProcessor。
这个ConfigurationClassPostProcessor正是用来执行扫描注解的处理器,看他的postProcessBeanDefinitionRegistry方法。
首先会将刚开始写的那行代码我们自己的配置类SpringConfig,查看是否有@import @component @componentScan或者@importResource这几个注解
for (String beanName : candidateNames) {
BeanDefinition beanDef = registry.getBeanDefinition(beanName);
if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {
if (logger.isDebugEnabled()) {
logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
}
}
else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
}
}
这上面candidateNames包括了之前spring框架中自动注册的几个BeanDefinition,不过系统注册的这几个显然都不可能满足条件,完成之后接下来就会进行解析,扫描出所有的类路径之后,通过reader读取生成BeanDefinition。自此所有的添加注解的BeanDefinition都已经在BeanFactory中了。
回到PostProcessorRegistrationDelegate中,接下来会从所有的BeanDefinition中获取实现了Ordered接口的BeanDefinitionRegistryPostProcessor得到Bean然后执行postProcessBeanDefinitionRegistry方法,再接下来获取其他所有的BeanDefinitionRegistryPostProcessor得到Bean然后执行postProcessBeanDefinitionRegistry方法。再接下来就会统一调用所有
BeanDefinitionRegistryPostProcessor的postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
ConfigurationClassPostProcessor的postProcessBeanFactory方法中首先对所有注解了@configuration的类做了一个增强,也就是代理,cglib的代理
ConfigurationClassEnhancer enhancer = new ConfigurationClassEnhancer();
for (Map.Entry entry : configBeanDefs.entrySet()) {
AbstractBeanDefinition beanDef = entry.getValue();
// If a @Configuration class gets proxied, always proxy the target class
beanDef.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE);
// Set enhanced subclass of the user-specified bean class
Class> configClass = beanDef.getBeanClass();
Class> enhancedClass = enhancer.enhance(configClass, this.beanClassLoader);
if (configClass != enhancedClass) {
if (logger.isTraceEnabled()) {
logger.trace(String.format("Replacing bean definition '%s' existing class '%s' with " +
"enhanced class '%s'", entry.getKey(), configClass.getName(), enhancedClass.getName()));
}
beanDef.setBeanClass(enhancedClass);
}
}
最后添加了一个ImportAwareBeanPostProcessor的后置处理器,返回。
再接下来,找出所有实现了BeanFactoryPostProcessor接口的BeanDefinition同样获取出Bean,之前获取的是实现了BeanDefinitionRegistryPostProcessor接口的Bean,BeanDefinitionRegistryPostProcessor接口继承了BeanFactoryPostProcessor,所以这里获取的bean集合包括了之前获取到的,不过已经执行过的,这里会跳过
if (processedBeans.contains(ppName)) {
// skip - already processed in first phase above
}
和之前一样,先依序调用实现了PriorityOrdered的,再调用实现了Ordered,最后调用两个都没实现的,除开自定义的,当前默认有一个EventListenerMethodProcessor已经注册,因此会被调用。
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
this.beanFactory = beanFactory;
Map beans = beanFactory.getBeansOfType(EventListenerFactory.class, false, false);
List factories = new ArrayList<>(beans.values());
AnnotationAwareOrderComparator.sort(factories);
this.eventListenerFactories = factories;
}
这里获取了所有实现了EventListenerFactory的BeanDefinition并生成Bean,存入列表中。而这个类还实现了SmartInitializingSingleton接口,实现了这个接口会在Bean初始化结束后被调用,所以先看一看其中的方法,其中最重要的是processBean方法,其中会获取具有@EventListener方法注解的类,并获取类中注解了@EventListener的方法,创建一个ApplicationListener,添加进context中,也就是当前的AbstractApplicationContext中。
// Non-empty set of methods
ConfigurableApplicationContext context = this.applicationContext;
Assert.state(context != null, "No ApplicationContext set");
List factories = this.eventListenerFactories;
Assert.state(factories != null, "EventListenerFactory List not initialized");
for (Method method : annotatedMethods.keySet()) {
for (EventListenerFactory factory : factories) {
if (factory.supportsMethod(method)) {
Method methodToUse = AopUtils.selectInvocableMethod(method, context.getType(beanName));
ApplicationListener> applicationListener =
factory.createApplicationListener(beanName, targetType, methodToUse);
if (applicationListener instanceof ApplicationListenerMethodAdapter) {
((ApplicationListenerMethodAdapter) applicationListener).init(context, this.evaluator);
}
context.addApplicationListener(applicationListener);
break;
}
}
}
最后返回,回到invokeBeanFactoryPostProcessors方法中,接下来注册了一个LoadTimeWeaverAwareProcessor,这个用于编译期间织入代码。再返回
接下来是registerBeanPostProcessors(beanFactory)方法,上个方法顾名思义就是执行bean工厂的后置处理器,而这个方法顾名思义就是注册bean的后置处理器。
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
其中的方法很简单,最开始添加了一个BeanPostProcessorChecker,接着顺序同样是先继承了PriorityOrdered,然后Ordered,最后其他依次添加,最后又添加了一个ApplicationListenerDetector
再接着执行initMessageSource方法,当前spring内部没有注册messageSource,自定义的也没有,所以注册了一个默认的DelegatingMessageSource,这个主要用来处理国际化的
再接着是initApplicationEventMulticaster方法,同样当前spring内部没有注册ApplicationEventMulticaster,自定义的也没有,所以设置了一个默认的SimpleApplicationEventMulticaster,
再接着是onRefresh方法,交由子类实现,默认无实现。
再往下看registerListeners方法,首先,获取当前的ApplicationEventMulticaster,将当前已经注册的ApplicationListener添加进来,这里贼需要注意,上面看的注册的ApplicationListener发生的时候都是在所有bean初始化完成之后,所以这里获取的ApplicationListener只能开始的时候通过手动注册,当前是空。
for (ApplicationListener> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
再接着看finishBeanFactoryInitialization方法。
首先,注册了一个ConversionService,然后添加了一个EmbeddedValueResolver,然后通过getBean去生成LoadTimeWeaverAware的Bean,不过当前没有LoadTimeWeaverAware。然后调用了freezeConfiguration方法。
public void freezeConfiguration() {
this.configurationFrozen = true;
this.frozenBeanDefinitionNames = StringUtils.toStringArray(this.beanDefinitionNames);
}
以上准备完成之后,调用preInstantiateSingletons方法。首先会判断,如果是Abstract,或者不是单例的,或者注解设置了Lazy懒加载的,都直接跳过
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit())
如果符合条件的,如果是FactoryBean,还会判断是否需要立即实例化FactoryBean中生产的对象。其他不是FactoryBean的,都会直接执行getBean方法,其中调用doGetBean,这里面非常的复杂。
在doGetBean方法中,首先会调用getSingleton方法,默认传入参数allowEarlyReference是true,这个参数往下看就会明白了。
/**
* Return the (raw) singleton object registered under the given name.
* Checks already instantiated singletons and also allows for an early
* reference to a currently created singleton (resolving a circular reference).
* @param beanName the name of the bean to look for
* @param allowEarlyReference whether early references should be created or not
* @return the registered singleton object, or {@code null} if none found
*/
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
ObjectFactory> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}
首先会从singletonObjects这个map中查看是否已经创建,如果已经创建直接返回,否则再判断isSingletonCurrentlyInCreation,从字面上看就是,这个对象当前是否正在创建中,第一次执行到这,之前并没有向singletonsCurrentlyInCreation这个Set集合中添加过,所以肯定是空,返回
/**
* Return whether the specified singleton bean is currently in creation
* (within the entire factory).
* @param beanName the name of the bean
*/
public boolean isSingletonCurrentlyInCreation(String beanName) {
return this.singletonsCurrentlyInCreation.contains(beanName);
}
接着判断是否空,当前肯定是空
if (sharedInstance != null && args == null)
所以跳过,往下,获取parentBeanFactory,当前在之前肯定没设置过这东西,所以空,继续往下,调用了markBeanAsCreated方法,就是标记bean是正在创建中了
/**
* Mark the specified bean as already created (or about to be created).
* This allows the bean factory to optimize its caching for repeated
* creation of the specified bean.
* @param beanName the name of the bean
*/
protected void markBeanAsCreated(String beanName) {
if (!this.alreadyCreated.contains(beanName)) {
synchronized (this.mergedBeanDefinitions) {
if (!this.alreadyCreated.contains(beanName)) {
// Let the bean definition get re-merged now that we're actually creating
// the bean... just in case some of its metadata changed in the meantime.
clearMergedBeanDefinition(beanName);
this.alreadyCreated.add(beanName);
}
}
}
}
再往下,获取depenceOn,看是否设置了依赖注解
// Guarantee initialization of beans that the current bean depends on.
String[] dependsOn = mbd.getDependsOn();
如果有依赖,调用registerDependentBean方法,当前bean的name存入dependenciesForBeanMap,name是key,值是依赖的bean的name的list,而依赖的bean的name存入dependentBeanMap,值是当前bean的name的list
/**
* Register a dependent bean for the given bean,
* to be destroyed before the given bean is destroyed.
* @param beanName the name of the bean
* @param dependentBeanName the name of the dependent bean
*/
public void registerDependentBean(String beanName, String dependentBeanName) {
String canonicalName = canonicalName(beanName);
synchronized (this.dependentBeanMap) {
Set dependentBeans =
this.dependentBeanMap.computeIfAbsent(canonicalName, k -> new LinkedHashSet<>(8));
if (!dependentBeans.add(dependentBeanName)) {
return;
}
}
synchronized (this.dependenciesForBeanMap) {
Set dependenciesForBean =
this.dependenciesForBeanMap.computeIfAbsent(dependentBeanName, k -> new LinkedHashSet<>(8));
dependenciesForBean.add(canonicalName);
}
}
再接着会继续调用getBean方法,传入的是依赖的bean的name,递归调用。
try {
getBean(dep);
}
而如果没有依赖,那就继续往下,会调用getSingleton方法,传入一个内部类,内部类中就是一个createBean方法,先看getSingleton方法
// Create bean instance.
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
首先会从singletonObjects这个map中获取实例,当前实例并没有创建,所以会走接下来的方法,接下来调用beforeSingletonCreation方法,这里会将当前Bean的name添加进singletonsCurrentlyInCreation这个Map中
/**
* Callback before singleton creation.
* The default implementation register the singleton as currently in creation.
* @param beanName the name of the singleton about to be created
* @see #isSingletonCurrentlyInCreation
*/
protected void beforeSingletonCreation(String beanName) {
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
}
再接着就会执行singletonFactory.getObject(),这个singletonFactory就是之前传过来的匿名内部类,所以这个方法就是createBean方法
// Create bean instance.
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
首先会调用resolveBeforeInstantiation方法,这里面会看当前的BeanFactory中是否存在继承了InstantiationAwareBeanPostProcessor的BeanPostProcessor,如果存在就调用postProcessBeforeInstantiation方法,返回实例,如果有实例返回,就在下面调用当前所有BeanPostProcessor的postProcessAfterInitialization方法,然后根据当前是不是产生了实例将BeanDefinition的beforeInstantiationResolved设为true或false,这里主要是为了创建代理对象
/**
* Apply before-instantiation post-processors, resolving whether there is a
* before-instantiation shortcut for the specified bean.
* @param beanName the name of the bean
* @param mbd the bean definition for the bean
* @return the shortcut-determined bean instance, or {@code null} if none
*/
@Nullable
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// Make sure bean class is actually resolved at this point.
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
Class> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
返回之后,如果有实例产生,就直接返回,接下来会调用doCreateBean方法
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
首先会从factoryBeanInstanceCache这个map中删除并获取一个对象,如果第一次进来,这里肯定不存在,往下,如果不存在,那么会调用createBeanInstance方法,createBeanInstance方法就是创建了一个当前类的实例,并通过BeanWrapper包装了一下,所以对象是在这里被创建的。createBeanInstance方法中有个地方很重要,如果当前Bean需要构造方法注入Bean的话,会调用到autowireConstructor方法
Constructor>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}
方法中最后会调用到beanFactory.resolveDependency来创建注入的对象,到这里先跳过,后面会提到
接着调用applyMergedBeanDefinitionPostProcessors方法,执行BeanFactory中所有实现了MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition方法。
再往下有这么一个判断,这里判断三个,一个是否单例,一个是否支持循环依赖,这个参数默认是true,只能手动在最开始更改,最后就是判断singletonsCurrentlyInCreation这个map中是否存在。
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
/**
* Return whether the specified singleton bean is currently in creation
* (within the entire factory).
* @param beanName the name of the bean
*/
public boolean isSingletonCurrentlyInCreation(String beanName) {
return this.singletonsCurrentlyInCreation.contains(beanName);
}
这个singletonsCurrentlyInCreation之前已经添加过了,所以判断通过,往下会执行addSingletonFactory方法,同样传入匿名内部类,这里需要重点注意的是,这个匿名内部类中getEarlyBeanReference方法的参数是这里传入的,尤其重要的是这个bean就是这里刚刚创建的bean,这里非常关键
再看addSingletonFactory方法,方法中会将之前传入的匿名内部类放入singletonFactories这个map中,接着从earlySingletonObjects中删除,目前该map中没有当前beanName,最后往registeredSingletons中添加当前beanName
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
/**
* Add the given singleton factory for building the specified singleton
* if necessary.
* To be called for eager registration of singletons, e.g. to be able to
* resolve circular references.
* @param beanName the name of the bean
* @param singletonFactory the factory for the singleton object
*/
protected void addSingletonFactory(String beanName, ObjectFactory> singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
synchronized (this.singletonObjects) {
if (!this.singletonObjects.containsKey(beanName)) {
this.singletonFactories.put(beanName, singletonFactory);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
}
再往下,执行populateBean方法,听字面意思,就是填充Bean实例的属性。
首先调用所有的InstantiationAwareBeanPostProcessor执行postProcessAfterInstantiation方法,如果方法返回False就会停止,当前populateBean方法就会返回
// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
// state of the bean before properties are set. This can be used, for example,
// to support styles of field injection.
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}
}
接着获取resolvedAutowireMode,非xml都是0,所以继续往下
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse;
}
}
接下来,会找出当前容器中所有实现了InstantiationAwareBeanPostProcessor的BeanPostProcessor,调postProcessProperties方法。首先,在博客最初说到的ConfigurationClassPostProcessor执行的postProcessBeanFactory中注册了一个ImportAwareBeanPostProcessor,该后置处理器的postProcessProperties方法中对在ImportAwareBeanPostProcessor中创建的代理方法设置了BeanFactory属性。
@Override
public PropertyValues postProcessProperties(@Nullable PropertyValues pvs, Object bean, String beanName) {
// Inject the BeanFactory before AutowiredAnnotationBeanPostProcessor's
// postProcessProperties method attempts to autowire other configuration beans.
if (bean instanceof EnhancedConfiguration) {
((EnhancedConfiguration) bean).setBeanFactory(this.beanFactory);
}
return pvs;
}
接着是最开始this()中定义的AnnotatedBeanDefinitionReader中注册的CommonAnnotationBeanPostProcessor,这个后置处理器的postProcessProperties方法主要对当前Bean中注释了@Resource注解的属性进行了注入
@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
InjectionMetadata metadata = findResourceMetadata(beanName, bean.getClass(), pvs);
try {
metadata.inject(bean, beanName, pvs);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Injection of resource dependencies failed", ex);
}
return pvs;
}
首先获取需要注入的元数据信息,然后执行metadata.inject方法。
public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
Collection checkedElements = this.checkedElements;
Collection elementsToIterate =
(checkedElements != null ? checkedElements : this.injectedElements);
if (!elementsToIterate.isEmpty()) {
for (InjectedElement element : elementsToIterate) {
if (logger.isTraceEnabled()) {
logger.trace("Processing injected element of bean '" + beanName + "': " + element);
}
element.inject(target, beanName, pvs);
}
}
}
方法中循环需要依赖注入的对象,执行inject方法,这些需要依赖注入的对象InjectedElement是一个抽象类,这里的实现是定义在CommonAnnotationBeanPostProcessor中的ResourceElement
看刚才element.inject方法,首先调用的是抽象类中的方法,方法中判断了是字段类型或是方法类型,字段和方法的注入执行不同的方法,不过流程都差不多,这里看字段的注入。
/**
* Either this or {@link #getResourceToInject} needs to be overridden.
*/
protected void inject(Object target, @Nullable String requestingBeanName, @Nullable PropertyValues pvs)
throws Throwable {
if (this.isField) {
Field field = (Field) this.member;
ReflectionUtils.makeAccessible(field);
field.set(target, getResourceToInject(target, requestingBeanName));
}
else {
if (checkPropertySkipping(pvs)) {
return;
}
try {
Method method = (Method) this.member;
ReflectionUtils.makeAccessible(method);
method.invoke(target, getResourceToInject(target, requestingBeanName));
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
}
getResourceToInject方法调用的就是实现类中也就是ResourceElement中的getResourceToInject方法。
@Override
protected Object getResourceToInject(Object target, @Nullable String requestingBeanName) {
return (this.lazyLookup ? buildLazyResourceProxy(this, requestingBeanName) :
getResource(this, requestingBeanName));
}
懒加载的是返回一个代理,否则执行getResource方法,该方法中调用了autowireResource方法,这里会判断这个需要注入的对象在工厂中是否有实例或者是BeanDefinition,,如果没有,会调用beanFactory.resolveDependency方法,需要注意的是传入的requestingBeanName参数不是这个需要注入的Bean,而是需要注入的Bean这个字段所在的Bean,假设容器中有,会往下调用beanFactory.resolveBeanByName方法
//-------------------------------------------------------------------------
// Delegate methods for resolving injection points
//-------------------------------------------------------------------------
@Override
public Object resolveBeanByName(String name, DependencyDescriptor descriptor) {
InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
try {
return getBean(name, descriptor.getDependencyType());
}
finally {
ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
}
}
方法中再次执行到了getBean方法,而到了这里,又再次执行getSingleton方法,结合之前的,可以确定当前同样会在第二个判断返回,同样接下来的方法会和之前一模一样,而如果这个bean中如果还需要依赖注入,同样还会再这样来一遍,不过还有一种情况,那就是很经典的依赖注入是怎么解决的。
之前看的是CommonAnnotationBeanPostProcessor,是解决@resource注入的,而在CommonAnnotationBeanPostProcessor调用之后,会调用AutowiredAnnotationBeanPostProcessor,这个同样是AnnotatedBeanDefinitionReader中注册的,是解决@Autowired注入的,这里逻辑比之前更精简,首先InjectedElement,根据方法或者字段会生产两种实现类,字段AutowiredFieldElement和方法AutowiredMethodElement方法,字段的话接下来就会调用到beanFactory.resolveDependency方法,这个也是CommonAnnotationBeanPostProcessor中提到的。而且这个在之前构造方法注入的时候也同样到了这个方法。往下,懒加载的属性会生成一个TargetSource对象。该对象中getTarget方法调用了doResolveDependency方法
Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
descriptor, requestingBeanName);
而如果不是懒加载属性,那接下来就会立即调用doResolveDependency方法,方法中最后会调用resolveCandidate方法,方法中又是getBean方法
instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
/**
* Resolve the specified bean name, as a candidate result of the matching
* algorithm for this dependency, to a bean instance from the given factory.
* The default implementation calls {@link BeanFactory#getBean(String)}.
* Subclasses may provide additional arguments or other customizations.
* @param beanName the bean name, as a candidate result for this dependency
* @param requiredType the expected type of the bean (as an assertion)
* @param beanFactory the associated factory
* @return the bean instance (never {@code null})
* @throws BeansException if the bean could not be obtained
* @since 4.3.2
* @see BeanFactory#getBean(String)
*/
public Object resolveCandidate(String beanName, Class> requiredType, BeanFactory beanFactory)
throws BeansException {
return beanFactory.getBean(beanName);
}
而接着一路又会调用到了getSingleton方法,而此时此刻,方法中isSingletonCurrentlyInCreation判断通过,进入下一步
/**
* Return the (raw) singleton object registered under the given name.
* Checks already instantiated singletons and also allows for an early
* reference to a currently created singleton (resolving a circular reference).
* @param beanName the name of the bean to look for
* @param allowEarlyReference whether early references should be created or not
* @return the registered singleton object, or {@code null} if none found
*/
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
ObjectFactory> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}
先判断earlySingletonObjects中是否有,否则从singletonFactories中获取,而这个singletonFactory 是当初在doCreateBean方法中添加的一个匿名内部类,所以这里singletonFactory.getObject()就会执行匿名内部类的方法,调用getEarlyBeanReference,而之前说了,这个传入的bean就是那时候创建的bean对象。
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
/**
* Obtain a reference for early access to the specified bean,
* typically for the purpose of resolving a circular reference.
* @param beanName the name of the bean (for error handling purposes)
* @param mbd the merged bean definition for the bean
* @param bean the raw bean instance
* @return the object to expose as bean reference
*/
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
}
}
}
return exposedObject;
}
这里一次执行当前所有实现了SmartInstantiationAwareBeanPostProcessor的后置处理器,执行getEarlyBeanReference方法,目前默认的后置处理器都未做操作。如果自定义了BeanPostProcessor,同样此时也会调用执行。返回最终的Bean。
返回对象之后,向this.earlySingletonObjects这个map中添加,而将singletonFactories这个map中的实例删除,返回,再往下,处理FactoryBean对象
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
最后一直一直返回,回到AutowiredAnnotationBeanPostProcessor的inject方法中,最后调用完field.set方法继续返回,回到populateBean方法中,最后执行applyPropertyValues方法,这个也是设置属性值,没去详细看,应该是xml会用到,原理和上面基本类似。此时此刻,当前Bean已经组建完成了。
再返回,接下来调用initializeBean方法。
首先调用invokeAwareMethods方法,方法中调用了三个Aware的方法,BeanNameAware,BeanClassLoaderAware和BeanFactoryAware
private void invokeAwareMethods(final String beanName, final Object bean) {
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
接着调用applyBeanPostProcessorsBeforeInitialization,方法里获取了所有BeanPostProcessor调用postProcessBeforeInitialization方法。
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
首先是ApplicationContextAwareProcessor,如果当前bean实现了几个Aware接口,会调用invokeAwareInterfaces方法
private void invokeAwareInterfaces(Object bean) {
if (bean instanceof EnvironmentAware) {
((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
}
if (bean instanceof EmbeddedValueResolverAware) {
((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
}
if (bean instanceof ResourceLoaderAware) {
((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
}
if (bean instanceof ApplicationEventPublisherAware) {
((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
}
if (bean instanceof MessageSourceAware) {
((MessageSourceAware) bean).setMessageSource(this.applicationContext);
}
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
}
}
接着是ImportAwareBeanPostProcessor,如果bean实现了ImportAware,那就调用setImportMetadata方法
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
if (bean instanceof ImportAware) {
ImportRegistry ir = this.beanFactory.getBean(IMPORT_REGISTRY_BEAN_NAME, ImportRegistry.class);
AnnotationMetadata importingClass = ir.getImportingClassFor(ClassUtils.getUserClass(bean).getName());
if (importingClass != null) {
((ImportAware) bean).setImportMetadata(importingClass);
}
}
return bean;
}
接着是CommonAnnotationBeanPostProcessor,方法在父类InitDestroyAnnotationBeanPostProcessor中,方法中就是执行注解了@PostConstruct的初始化方法
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
try {
metadata.invokeInitMethods(bean, beanName);
}
catch (InvocationTargetException ex) {
throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Failed to invoke init method", ex);
}
return bean;
}
所有的BeanPostProcessor执行完之后,返回,再往下调用invokeInitMethods方法,如果当前bean实现了InitializingBean,会调用afterPropertiesSet的初始化方法。
((InitializingBean) bean).afterPropertiesSet()
再往下调用自定义的初始化方法,就是xml中配置的那个
if (mbd != null && bean.getClass() != NullBean.class) {
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd);
}
}
再往下调用applyBeanPostProcessorsAfterInitialization方法,方法中同样是取出所有的BeanPostProcesser,不同的是这里调用postProcessAfterInitialization方法
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
这里当前只需要注意ApplicationListenerDetector,这个后置处理器中判断了当前Bean有没有实现ApplicationListener,有的话添加进applicationListeners中
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (bean instanceof ApplicationListener) {
// potentially not detected as a listener by getBeanNamesForType retrieval
Boolean flag = this.singletonNames.get(beanName);
if (Boolean.TRUE.equals(flag)) {
// singleton bean (top-level or inner): register on the fly
this.applicationContext.addApplicationListener((ApplicationListener>) bean);
}
else if (Boolean.FALSE.equals(flag)) {
if (logger.isWarnEnabled() && !this.applicationContext.containsBean(beanName)) {
// inner bean with other scope - can't reliably process events
logger.warn("Inner bean '" + beanName + "' implements ApplicationListener interface " +
"but is not reachable for event multicasting by its containing ApplicationContext " +
"because it does not have singleton scope. Only top-level listener beans are allowed " +
"to be of non-singleton scope.");
}
this.singletonNames.remove(beanName);
}
}
return bean;
}
返回,createBean方法结束,回到getSingleton(String beanName, ObjectFactory> singletonFactory)这个方法,接下来执行afterSingletonCreation方法,清理singletonsCurrentlyInCreation
/**
* Callback after singleton creation.
* The default implementation marks the singleton as not in creation anymore.
* @param beanName the name of the singleton that has been created
* @see #isSingletonCurrentlyInCreation
*/
protected void afterSingletonCreation(String beanName) {
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) {
throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");
}
}
最后将实例添加进 singletonObjects中,也就是容器中,然后清理一下之前用到的几个map。
if (newSingleton) {
addSingleton(beanName, singletonObject);
}
/**
* Add the given singleton object to the singleton cache of this factory.
* To be called for eager registration of singletons.
* @param beanName the name of the bean
* @param singletonObject the singleton object
*/
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
this.singletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
自此,Bean正式创建完成,继续返回,如果现在是在递归调用,那么同样的返回,一直回到preInstantiateSingletons方法中。
当所有的beanDefinitionNames循环创建完成之后,接下来再次循环
// Trigger post-initialization callback for all applicable beans...
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction
如果bean继承了SmartInitializingSingleton,那么这里就会被调用,联想最开始的EventListenerMethodProcessor,afterSingletonsInstantiated就是在这里被调用的,一个个ApplicationListener在这里被生成。
执行完之后,finishBeanFactoryInitialization方法也就执行完成了
再接着是finishRefresh方法
/**
* Finish the refresh of this context, invoking the LifecycleProcessor's
* onRefresh() method and publishing the
* {@link org.springframework.context.event.ContextRefreshedEvent}.
*/
protected void finishRefresh() {
// Clear context-level resource caches (such as ASM metadata from scanning).
clearResourceCaches();
// Initialize lifecycle processor for this context.
initLifecycleProcessor();
// Propagate refresh to lifecycle processor first.
getLifecycleProcessor().onRefresh();
// Publish the final event.
publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active.
LiveBeansView.registerApplicationContext(this);
}
首先是initLifecycleProcessor方法,注册了一个LifecycleProcessor
/**
* Initialize the LifecycleProcessor.
* Uses DefaultLifecycleProcessor if none defined in the context.
* @see org.springframework.context.support.DefaultLifecycleProcessor
*/
protected void initLifecycleProcessor() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
this.lifecycleProcessor =
beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
if (logger.isTraceEnabled()) {
logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
}
}
else {
DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
defaultProcessor.setBeanFactory(beanFactory);
this.lifecycleProcessor = defaultProcessor;
beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
if (logger.isTraceEnabled()) {
logger.trace("No '" + LIFECYCLE_PROCESSOR_BEAN_NAME + "' bean, using " +
"[" + this.lifecycleProcessor.getClass().getSimpleName() + "]");
}
}
}
注册好之后调用onRefresh方法,方法中调用startBeans
@Override
public void onRefresh() {
startBeans(true);
this.running = true;
}
方法中首先获取容器中所有实现了Lifecycle的bean,接着做了个判断,如果实现了SmartLifecycle,那么isAutoStartup返回true的进入,或者autoStartupOnly是false,不过当前传入的是true,进入后,获取所有Lifecycle的phase,根据phase的大小排序,小的先执行start方法,大的后执行
// Internal helpers
private void startBeans(boolean autoStartupOnly) {
Map lifecycleBeans = getLifecycleBeans();
Map phases = new HashMap<>();
lifecycleBeans.forEach((beanName, bean) -> {
if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
int phase = getPhase(bean);
LifecycleGroup group = phases.get(phase);
if (group == null) {
group = new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly);
phases.put(phase, group);
}
group.add(beanName, bean);
}
});
if (!phases.isEmpty()) {
List keys = new ArrayList<>(phases.keySet());
Collections.sort(keys);
for (Integer key : keys) {
phases.get(key).start();
}
}
}
返回,接着调用publishEvent方法。创建并发布ContextRefreshedEvent事件
getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
Executor executor = getTaskExecutor();
for (ApplicationListener> listener : getApplicationListeners(event, type)) {
if (executor != null) {
executor.execute(() -> invokeListener(listener, event));
}
else {
invokeListener(listener, event);
}
}
}
获取到当前ContextRefreshedEvent事件类型的所有监听器,循环调用onApplicationEvent方法
@SuppressWarnings({"rawtypes", "unchecked"})
private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
try {
listener.onApplicationEvent(event);
}
catch (ClassCastException ex) {
String msg = ex.getMessage();
if (msg == null || matchesClassCastMessage(msg, event.getClass())) {
// Possibly a lambda-defined listener which we could not resolve the generic event type for
// -> let's suppress the exception and just log a debug message.
Log logger = LogFactory.getLog(getClass());
if (logger.isTraceEnabled()) {
logger.trace("Non-matching event type for listener: " + listener, ex);
}
}
else {
throw ex;
}
}
}
最后调用resetCommonCaches清除各种缓存,spring框架启动就到此结束了。
当然spring框架中肯定还有许多的细节,而且这篇博客我也不敢保证完全正确,因为spring框架是真的非常难,非常庞大。