上一篇博客针对spring关于bean的注册梳理到了BeanPostProcessor,同时梳理到了bean的注册,整体看下来厚些凌乱,这篇博客会顺带回顾上篇博客的内容,然后梳理在BeanFactory中refresh操作的一些细节。
开始的实例代码
public class TestConfig {
public static void main(String[] args) {
AnnotationConfigApplicationContext annotationConfigApplicationContext =
new AnnotationConfigApplicationContext();
annotationConfigApplicationContext.register(AppConfigTest.class);
annotationConfigApplicationContext.refresh();
TestBean bean = annotationConfigApplicationContext.getBean(TestBean.class);
TestBean testBean = annotationConfigApplicationContext.getBean(TestBean.class);
}
}
上篇博客说道,在构造函数中,会实例化一个scanner和一个reader
/**
* Create a new AnnotationConfigApplicationContext that needs to be populated
* through {@link #register} calls and then manually {@linkplain #refresh refreshed}.
*/
public AnnotationConfigApplicationContext() {
//创建一个beanDefinition的读取器——BeanDefinitionReader
//TODO:就是在这里头,完成了6个关键的类的实例化
this.reader = new AnnotatedBeanDefinitionReader(this);
//实例化了一个扫描器,但是spring真正的自动扫描并不是靠这个完成的
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
之后开始注册bean并刷新BeanFactory容器
/**
* 主要就是register和refresh方法,上一篇博客已经梳理了一下register
*/
public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
this();//这里构建了一个类的扫描器和一个BeanDefinitionReader的读取器
register(componentClasses);
refresh();
}
register方法就是上篇博客中的主要内容。上篇博客中还提到,在构造方法中完成主要的6个内部类的注册。这六个类分别如下
//new AnnotatedBeanDefinitionReader(this);这行代码的底层就会完成下面6个类的实例化
//唯一的一个BeanFactoryPostProcessor,实际对应的是ConfigurationClassPostProcessor
internalConfigurationAnnotationProcessor//这个非常重要,这篇博客大部分的内容与这个有关
//其余四个是BeanPostProcessor
internalEventListenerFactory
internalEventListenerProcessor
internalPersistenceAnnotationProcessor
internalAutowiredAnnotationProcessor
internalCommonAnnotationProcessor
源码中如下
直接进入refresh方法,这个方法中如下所示
//AbstractApplicationContext 中的第515行
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
//TODO :refresh容器的前记录一些时间戳的信息,并不重要
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
//TODO : 获取当前容器对应的工厂ConfigurableListableBeanFactory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
//TODO:为beanFactory的refresh构建一些类
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
//TODO:注入一些BeanFactory的属性
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
//TODO: 调用BeanFactory的后置处理器 BeanFactoryPostProcessor
invokeBeanFactoryPostProcessors(beanFactory);
//后面的暂时省略
}
catch (BeansException ex) {
//后面的暂时省略
}
finally {
//后面的暂时省略
}
}
}
前面两个方法不重要,可以直接看prepareBeanFactory()方法
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
//TODO:前三行不太重要
beanFactory.setBeanClassLoader(getClassLoader());
//TODO:增加bean表达式解释器,后面再总结
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
//TODO:对象与String类型的转换,比如 需要根据test转换成指定的bean对象
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
//TODO:为每一个bean加入一个后置处理器
//TODO:为什么有些bean实现了ApplicationContextAware就能自动注入ApplicationContext,原因就在这里
// Configure the bean factory with context callbacks.
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
//TODO: 忽略掉以下六个类型的依赖注入
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.
//TODO:替换当前BeanFactory的一些依赖
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.
//TODO:不重要
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
//TODO:注入spring的环境和属性对象(environment和properties)
// Register default environment beans.
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
}
之后refresh方法中的postProcessBeanFactory这个方法没有任何实现,这个可以直接忽略,下面进入refresh方法中的invokeBeanFactoryPostProcessors方法。
// AbstractApplicationContext中的第713行,主要作用是执行自定义的BeanFactoryPostProcessor和spring自定义的BeanFactoryPostProcessor
/**
* Instantiate and invoke all registered BeanFactoryPostProcessor beans,
* respecting explicit order if given.
* Must be called before singleton instantiation.
*/
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
//TODO:通过委托对象调用指定的BeanFactoryPostProcessor(这里是调用自定义的BeanFactoryPostProcessor)
//TODO:注意一下,这里非常重要,如果我们自定义的BeanFactoryPostProcessor没有显示的通过代码add加入到容器中,则这里也无法获取到。
//TODO:同时,这里只是获取自定义的BeanFactoryPostProcessor,ConfigurationClassPostProcessor并不会得到。
//TODO:这个集合也是定义在AbstractApplicationContext中,属性为: BeanFactoryPostProcessors to apply on refresh.
private final List<BeanFactoryPostProcessor> beanFactoryPostProcessors = new ArrayList<>();
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)
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
这个方法有几个需要注意的,getBeanFactoryPostProcessors()方法中是获取自定义的BeanFactoryPostProcessor,无法获取spring内部自定义的BeanFactoryPostProcessor接口。进入到PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors()方法中,这个方法贼长也贼复杂。其中有几个List集合需要说明一下
List<BeanFactoryPostProcessor> regularPostProcessors; //存放自定义的BeanFactoryPostProcessor
List<BeanDefinitionRegistryPostProcessor> registryProcessors;//存放自定义的BeanDefinitionRegistryPostProcessor
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors;//存放spring内部自定义的BeanDefinitionRegistryPostProcessor
spring中该方法的源码
//PostProcessorRegistrationDelegate 中的第56行
//TODO : 真正的调用BeanFactoryPostProcessor的后置处理器
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
Set<String> processedBeans = new HashSet<>();
//TODO:如果BeanFactory是一个注册器(这个好像必会进入)
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
//TODO:这里定义了两个集合,一个是BeanFactoryPostProcessor,一个是BeanDefinitionRegistryPostProcessor
//TODO:放自定义的BeanFactoryPostProcessor
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
//TODO:BeanDefinitionRegistryPostProcessor只是继承了BeanFactoryPostProcessor接口而已
//TODO:放自定义的BeanDefinitionRegistryPostProcessor
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
//TODO : 遍历传入过来的集合beanFactoryPostProcessors
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
//TODO:如果自定义的BeanFactoryPostProcessor实现了BeanDefinitionRegistryPostProcessor接口
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {//TODO:如果是BeanDefinitionRegistryPostProcessor
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
registryProcessor.postProcessBeanDefinitionRegistry(registry);//TODO:调用postProcessor其中的方法
registryProcessors.add(registryProcessor);
}
else {//TODO:如果自定义的BeanFactoryPostProcessor没有实现现BeanDefinitionRegistryPostProcessor接口
regularPostProcessors.add(postProcessor); //TODO:将自定义的BeanFactoryProcessor放到上面定义的集合中
}
}
// 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.
//TODO:又定义一个集合存放BeanDefinitionRegistryPostProcessor,这个集合存放的是spring内部实现了这个接口的类
//TODO:放spring内部定义的BeanDefinitionRegistryPostProcessor
//TODO:每次真正调用的,才是这个集合中的BeanDefinitionRegistryPostProcessor
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
//TODO:根据bean的类型获取bean的名称,这里获取的是BeanDefinitionRegistryPostProcessor类型的
//TODO:首先调用实现了PriorityOrdered接口的BeanDefinitionRegistryPostProcessor
//TODO:根据Type获取对应类型的beanName,这里才会获取出内部定义的ConfigurationClassPostProcessor
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
//TODO:遍历上面获得的postProcessorNames,并根据每个beanName获取对应的beanDefinition,然后放到currentRegistryProcessors中
//TODO:如果没有自定义的,则这个时候这里就一个
//TODO:同时将遍历的每一个beanName放到processedBeans中
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
//TODO:将 ConfigurationClassPostProcessor 标记为已经处理
processedBeans.add(ppName);
}
}
//TODO:设置排序,不重要
sortPostProcessors(currentRegistryProcessors, beanFactory);
//TODO:合并两个集合,将spring自定义的Processors加入到registryProcessors中,可以看到所谓的currentRegistryProcessors就是一个过渡的
registryProcessors.addAll(currentRegistryProcessors);
//TODO:真正的开始调用BeanDefinitionRegistryPostProcessor中的方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
//TODO:清空currentRegistryProcessors,这里就清除了 ConfigurationClassPostProcessor
currentRegistryProcessors.clear();
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
//TODO:开始调用实现了Ordered接口的BeanDefinitionRegistryPostProcessor类
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);
}
}
//TODO:和上面的操作一样,但是这个时候 currentRegistryProcessors 中只会有实现了Ordered接口的BeanDefinitionRegistryPostProcessor
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
//TODO:最后,调用其他的BeanDefinitionRegistryPostProcessors,直到没有更多的BeanDefinitionRegistryPostProcessors实现类
//TODO:简单点说这里就是在扫除剩余的没被调用的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.
//TODO:到这里,调用postProcessBeanFactory(即BeanDefinitionRegistryPostProcessors的父类)的回调方法,这里面就有针对@Configuration类的增强操作
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
//TODO:如果一个beanFactory不是注册器,这个应该是一个兼容操作,老版本的spring的BeanFactory是没有实现Registry接口的
else {
// Invoke factory processors registered with the context instance.
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
//TODO:开始处理 BeanFactoryProcessor 类型的类,并回调指定的方法(就是只实现了BeanFactoryPorcessor接口的类)
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
//TODO:如果已经在processedBeans集合中,这里不再做处理
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();//TODO:存放实现了 PriorityOrdered 接口的 BeanFactoryProcessor
List<String> orderedPostProcessorNames = new ArrayList<>(); //TODO:存放实现了 Ordered 接口的 BeanFactoryProcessor
List<String> nonOrderedPostProcessorNames = new ArrayList<>();//TODO:存放没有实现 Ordered 接口也没有实现 PriorityOrdered 的 BeanFactoryProcessor
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);
}
}
//TODO:调用实现了PriorityOrdered接口的BeanFactoryPostProcessor回调方法
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
//TODO:调用实现了Ordered接口的 BeanFactoryPostProcessors 回调方法
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Finally, invoke all other BeanFactoryPostProcessors.
//TODO:最后,处理两个接口为没有实现的正常的 BeanFactoryPostProcessors 回调方法
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
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...
beanFactory.clearMetadataCache();
}
这里说明一下,其中的BeanDefinitionRegistryPostProcessor继承至BeanFactoryPostProcessor,如下所示
public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {
/**
* Modify the application context's internal bean definition registry after its
* standard initialization. All regular bean definitions will have been loaded,
* but no beans will have been instantiated yet. This allows for adding further
* bean definitions before the next post-processing phase kicks in.
* @param registry the bean definition registry used by the application context
* @throws org.springframework.beans.BeansException in case of errors
*/
void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;
}
扩展了BeanFactoryPostProcessor中的方法。上述代码中理清各个list是干嘛的,但是还有一个重点,就是这个方法invokeBeanDefinitionRegistryPostProcessors;这个方法里头的主要操作如下
//PostProcessorRegistrationDelegate 中的第295行
//TODO:调用目标对象的postProcessorBeanDefinitionRegistry方法
private static void invokeBeanDefinitionRegistryPostProcessors(
Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry) {
for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
//一个接口的方法,最终会跳到ConfigurationClassPostProcessor的第221行
postProcessor.postProcessBeanDefinitionRegistry(registry);
}
}
//TODO:ConfigurationClassPostProcessor的第221行
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
int registryId = System.identityHashCode(registry);
if (this.registriesPostProcessed.contains(registryId)) {
throw new IllegalStateException(
"postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
}
if (this.factoriesPostProcessed.contains(registryId)) {
throw new IllegalStateException(
"postProcessBeanFactory already called on this post-processor against " + registry);
}
this.registriesPostProcessed.add(registryId);
//TODO:真正的调用方式, 这里会跳到ConfigurationClassPostProcessor的第264行
processConfigBeanDefinitions(registry);
}
真正的BeanFactoryPostProcessor的调用方法
//TODO:BeanFactoryPostProcessor中真正的调用方法,ConfigurationClassPostProcessor中的第264行
//TODO:这个方法就是取出我们自定义的TestConfig,并完成对TestConfig的解析
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
//TODO:到这里了,candidateNames里头就有7个类,分别是6个核心类,一个我们自己定义的TestConfig类
String[] candidateNames = registry.getBeanDefinitionNames();
for (String beanName : candidateNames) {
BeanDefinition beanDef = registry.getBeanDefinition(beanName);
//TODO:判断bean是否是核心配置类,bd中configurationClass是否等于full,或者configurationClass是否等于lite
//TODO:判断bean是否被处理过,如果bd中的configruationClass属性等于full或者lite,则表示被处理过
if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) ||
ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {
if (logger.isDebugEnabled()) {
logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
}
}
//TODO:检查beanDef是否满足Configuration类的条件,如果满足,则放入configCandidates集合中
//TODO:针对checkConfigurationClassCandidate方法,这个方法比较简单,这里就不展开说了。如果想看详情,跳转到下面关于这个方法的解析
else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
}
}
// Return immediately if no @Configuration classes were found
if (configCandidates.isEmpty()) {
return;
}
// Sort by previously determined @Order value, if applicable
configCandidates.sort((bd1, bd2) -> {
int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
return Integer.compare(i1, i2);
});
// Detect any custom bean name generation strategy supplied through the enclosing application context
//TODO:不太重要,命名解析器
SingletonBeanRegistry sbr = null;
if (registry instanceof SingletonBeanRegistry) {
sbr = (SingletonBeanRegistry) registry;
if (!this.localBeanNameGeneratorSet) {
BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR);
if (generator != null) {
this.componentScanBeanNameGenerator = generator;
this.importBeanNameGenerator = generator;
}
}
}
if (this.environment == null) {
this.environment = new StandardEnvironment();
}
// Parse each @Configuration class
ConfigurationClassParser parser = new ConfigurationClassParser(
this.metadataReaderFactory, this.problemReporter, this.environment,
this.resourceLoader, this.componentScanBeanNameGenerator, registry);
Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
do {
//TODO:解析candidates中的配置类,真正完成扫描
parser.parse(candidates);
parser.validate();
Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
configClasses.removeAll(alreadyParsed);
// Read the model and create bean definitions based on its content
if (this.reader == null) {
this.reader = new ConfigurationClassBeanDefinitionReader(
registry, this.sourceExtractor, this.resourceLoader, this.environment,
this.importBeanNameGenerator, parser.getImportRegistry());
}
this.reader.loadBeanDefinitions(configClasses);
alreadyParsed.addAll(configClasses);
candidates.clear();
if (registry.getBeanDefinitionCount() > candidateNames.length) {
String[] newCandidateNames = registry.getBeanDefinitionNames();
Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
Set<String> alreadyParsedClasses = new HashSet<>();
for (ConfigurationClass configurationClass : alreadyParsed) {
alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
}
for (String candidateName : newCandidateNames) {
if (!oldCandidateNames.contains(candidateName)) {
BeanDefinition bd = registry.getBeanDefinition(candidateName);
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
!alreadyParsedClasses.contains(bd.getBeanClassName())) {
candidates.add(new BeanDefinitionHolder(bd, candidateName));
}
}
}
candidateNames = newCandidateNames;
}
}
while (!candidates.isEmpty());
// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
}
if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
// Clear cache in externally provided MetadataReaderFactory; this is a no-op
// for a shared cache since it'll be cleared by the ApplicationContext.
((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
}
}
关于checkConfigurationClassCandidate方法的补充说明
//TODO:ConfigurationClassUtils 中的82行
//TODO:判断给定的beanDef是否是一个configuration,判断这个beanDef是否包含了@Configuration,@Service
public static boolean checkConfigurationClassCandidate(
BeanDefinition beanDef, MetadataReaderFactory metadataReaderFactory) {
String className = beanDef.getBeanClassName();
if (className == null || beanDef.getFactoryMethodName() != null) {
return false;
}
//TODO:获取beanDefinition的注解元数据信息
AnnotationMetadata metadata;
//TODO:判断是否是注解的bean annotatedBeanDefinition是自定义的bean,如果是spring内部定义的是rootBeanDefinition
if (beanDef instanceof AnnotatedBeanDefinition &&
className.equals(((AnnotatedBeanDefinition) beanDef).getMetadata().getClassName())) {
// Can reuse the pre-parsed metadata from the given BeanDefinition...
metadata = ((AnnotatedBeanDefinition) beanDef).getMetadata();//TODO:获取bean上的注解
}
//TODO:如果这个类并不是注解的BeanDefinition
else if (beanDef instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) beanDef).hasBeanClass()) {
// Check already loaded Class if present...
// since we possibly can't even load the class file for this Class.
Class<?> beanClass = ((AbstractBeanDefinition) beanDef).getBeanClass();
metadata = new StandardAnnotationMetadata(beanClass, true);//TODO:获取bean上的注解信息
}
else {
try {
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(className);
metadata = metadataReader.getAnnotationMetadata();
}
catch (IOException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Could not find class file for introspecting configuration annotations: " +
className, ex);
}
return false;
}
}
/**
* 下述的两个是if-else if,判断只会走一个分支,也就是如果只判断了@Configuration就不会判断其他的注解,
* 之后的Component,ComponentScan,Import,ImportResource之后再进行判断
*/
/**
* TODO:如果加了@Configuration注解是一个配置类,
* 可以看到isFullConfigurationCandidate方法底层就一行代码——metadata.isAnnotated(Configuration.class.getName());
* 这个就是判断是否有@Configuration注解
*/
if (isFullConfigurationCandidate(metadata)) {
//TODO:则将beanDefinition中的configurationClass属性设置为full
beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL);
}
//TODO:如果是一个lite 的Configuration类(lite是精英的意思),设置beadDefinition中的属性configurationClass为lite
//TODO:判断是否加了如下的注解,Compnent,ComponentScan,Import,ImportResource
// candidateIndicators.add(Component.class.getName());
// candidateIndicators.add(ComponentScan.class.getName());
// candidateIndicators.add(Import.class.getName());
// candidateIndicators.add(ImportResource.class.getName());
else if (isLiteConfigurationCandidate(metadata)) {
beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE);
}
else {//TODO:如果两者都不满足,则直接返回false
return false;
}
// It's a full or lite configuration candidate... Let's determine the order value, if any.
//TODO:设置排序 不太重要
Integer order = getOrder(metadata);
if (order != null) {
beanDef.setAttribute(ORDER_ATTRIBUTE, order);
}
return true;
}
这里可以看到,上述方法中的逻辑,如果这个类加上了@Configuration注解,则这个类被标记为full,如果这个类没有标记@Configuration,而只是标记了@Component,@ComponentScan,@Import,@ImportResource则这个类被标记为lite
目前,根据代码的梳理,我们已经梳理到了parse方法,这个方法底部就是真正的解析各个@Configuration的类了
/**
* ConfigurationClassParser中的第163行,这里并不是很重要
*/
//TODO:解析BeanDefintion
public void parse(Set<BeanDefinitionHolder> configCandidates) {
for (BeanDefinitionHolder holder : configCandidates) {
BeanDefinition bd = holder.getBeanDefinition();
try {
if (bd instanceof AnnotatedBeanDefinition) {
//由于我们是以注解的方式来阅读源码,因此会调用这个
parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
}
else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {
//如果不是注解
parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());
}
else {
parse(bd.getBeanClassName(), holder.getBeanName());
}
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(
"Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex);
}
}
this.deferredImportSelectorHandler.process();
}
继续往下走
/**
* ConfigurationClassParser 中的第200行
*/
protected final void parse(AnnotationMetadata metadata, String beanName) throws IOException {
processConfigurationClass(new ConfigurationClass(metadata, beanName));
}
/**
* ConfigurationClassParser 中的第219行
*/
protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
//判断当前的configClass是否可以跳过,不重要
if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
return;
}
ConfigurationClass existingClass = this.configurationClasses.get(configClass);
if (existingClass != null) {
if (configClass.isImported()) {
if (existingClass.isImported()) {
existingClass.mergeImportedBy(configClass);
}
// Otherwise ignore new imported config class; existing non-imported class overrides it.
return;
}
else {
// Explicit bean definition found, probably replacing an import.
// Let's remove the old one and go with the new one.
this.configurationClasses.remove(configClass);
this.knownSuperclasses.values().removeIf(configClass::equals);
}
}
// Recursively process the configuration class and its superclass hierarchy.
//TODO:将Configuration类封装成一个SourceClass
SourceClass sourceClass = asSourceClass(configClass);
//do-while操作循环处理configClass
do {
//TODO:真正的处理configuration类
sourceClass = doProcessConfigurationClass(configClass, sourceClass);
}
while (sourceClass != null);
this.configurationClasses.put(configClass, configClass);
}
继续往下操作
//TODO:处理Configuration的配置类
//.ConfigurationClassParser中的第263行,这里既是处理@Configuration类的核心逻辑所在。
@Nullable
protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
throws IOException {
//TODO:如果有@Component标签
if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
// Recursively process any member (nested) classes first
processMemberClasses(configClass, sourceClass);
}
// Process any @PropertySource annotations
for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), PropertySources.class,
org.springframework.context.annotation.PropertySource.class)) {
if (this.environment instanceof ConfigurableEnvironment) {
processPropertySource(propertySource);
}
else {
logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
"]. Reason: Environment must implement ConfigurableEnvironment");
}
}
//TODO:处理componentScan注解
// Process any @ComponentScan annotations
Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
if (!componentScans.isEmpty() &&
!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
for (AnnotationAttributes componentScan : componentScans) {
// The config class is annotated with @ComponentScan -> perform the scan immediately
Set<BeanDefinitionHolder> scannedBeanDefinitions =
this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
// Check the set of scanned definitions for any further config classes and parse recursively if needed
for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
if (bdCand == null) {
bdCand = holder.getBeanDefinition();
}
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
parse(bdCand.getBeanClassName(), holder.getBeanName());
}
}
}
}
//TODO:处理@Import注解
// Process any @Import annotations
processImports(configClass, sourceClass, getImports(sourceClass), true);
//TODO:处理@ImportResource
// Process any @ImportResource annotations
AnnotationAttributes importResource =
AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
if (importResource != null) {
String[] resources = importResource.getStringArray("locations");
Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
for (String resource : resources) {
String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
configClass.addImportedResource(resolvedResource, readerClass);
}
}
// Process individual @Bean methods
Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
for (MethodMetadata methodMetadata : beanMethods) {
configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
}
//TODO:处理接口中默认的方法
// Process default methods on interfaces
processInterfaces(configClass, sourceClass);
// Process superclass, if any
if (sourceClass.getMetadata().hasSuperClass()) {
String superclass = sourceClass.getMetadata().getSuperClassName();
if (superclass != null && !superclass.startsWith("java") &&
!this.knownSuperclasses.containsKey(superclass)) {
this.knownSuperclasses.put(superclass, configClass);
// Superclass found, return its annotation metadata and recurse
return sourceClass.getSuperClass();
}
}
// No superclass -> processing is complete
return null;
}
从代理中的注释可以看到,其实这个方法就是处理了各个注解标签,并完成相关的逻辑处理,具体的逻辑处理我们后面再谈
总体来看,依旧按照流水线的操作从refresh方法一直梳理下来,如果整体看完这篇博客还是需要毅力的,其实大部分的内容,倒是小弟在阅读源码的一个粗略总结,并不详细,只是梳理了IOC的大致流程,关于ImportSelector和ImportSelector和ImportBeanDefinitionRegistrar的一个区别,可以看下面这篇文章。
关于ImportSelector和ImportBeanDefinitionRegistrar的区别