【spring源码解析】

public AnnotationConfigApplicationContext(Class<?>... componentClasses) {  
   this();  
   register(componentClasses);  
   refresh();  
}

1. this()

产生两个BeandifinitionReader

this.reader = new AnnotatedBeanDefinitionReader(this);  
createAnnotatedBeanDefReader.end();  
this.scanner = new ClassPathBeanDefinitionScanner(this);

2. register(componentClasses);

把配置了注入到beanDefinitionMap中,spring内部还会注入其余五个内部Beandifinition
在这里插入图片描述

3. refresh()

首先得了解两个接口BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor,BeanDefinitionRegistryPostProcessor 继承BeanFactoryPostProcessor,同时拓展出一个方法postProcessBeanDefinitionRegistry出来。参考BeanDefinitionRegistryPostProcessor

BeanDefinitionRegistryPostProcessor实现类 ConfigurationClassPostProcessor介绍
这个类非常重要,其实现了BeanDefinitionRegistryPostProcessor接口与PriorityOrdered接口

public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPostProcessor,  
      PriorityOrdered, ResourceLoaderAware, ApplicationStartupAware, BeanClassLoaderAware, EnvironmentAware 

相关方法

@Override  
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);  
  
   processConfigBeanDefinitions(registry);  
}

这个方法完成配置上该扫描的bean的beanDefinition到BeanDefinitionMap中去

3.1 invokeBeanFactoryPostProcessors(beanFactory)

回到这个方法来
进入PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());看代码块

for (String ppName : postProcessorNames) {  
   if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {  
      currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));  
      processedBeans.add(ppName);  
   }  
}  
sortPostProcessors(currentRegistryProcessors, beanFactory);  
registryProcessors.addAll(currentRegistryProcessors);  
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());  
currentRegistryProcessors.clear();

看此段代码,currentRegistryProcessors 中只有ConfigurationClassPostProcessor,进入到该类的postProcessBeanDefinitionRegistry方法中。首先扫描到有@Configuration注解的配置类,然后解析这些配置类。

Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);  
Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());  
do {  
   StartupStep processConfig = this.applicationStartup.start("spring.context.config-classes.parse");  
   parser.parse(candidates);  
   parser.validate();  
  
   Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());  
   configClasses.removeAll(alreadyParsed);  
   this.reader.loadBeanDefinitions(configClasses);  
   alreadyParsed.addAll(configClasses);  
   processConfig.tag("classCount", () -> String.valueOf(configClasses.size())).end();  
  
   candidates.clear();
   }

看parser.parse(candidates)
进入到parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName())

SourceClass sourceClass = asSourceClass(configClass, filter);  
do {  
   sourceClass = doProcessConfigurationClass(configClass, sourceClass, filter);  
}  
while (sourceClass != null);

doProcessConfigurationClass 真正去解析配置类

  1. processMemberClasses
  2. Process any @PropertySource annotations
  3. Process any @ComponentScan annotations
  4. Process any @Import annotations
  5. Process any @ImportResource annotations
  6. Process individual @Bean methods
  7. Process default methods on interfaces
  8. Process superclass, if any

主要看3和4
Process any @ComponentScan annotations
会解析出符合ComponentScan中的beanDifinition,并在找到的beandifinition中循环找到符合的beandifinition,最后注入到bedifinitionMap中。
Process any @Import annotations
processImports(configClass, sourceClass, getImports(sourceClass), filter, true);

getImports(sourceClass)会找到自己写的Import注解以及@EnableAspectJAutoProxy和@EnableTransactionManagement引入的类
上面步骤会找到配置类能扫到的beanDefinition

回到this.reader.loadBeanDefinitions(configClasses)
会执行
registerBeanDefinitionForImportedConfigurationClass(configClass); 配置类当bean注入这种情况
loadBeanDefinitionsFromImportedResources(configClass.getImportedResources());

loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars());

3.2 finishBeanFactoryInitialization(beanFactory)

作用:Instantiate all remaining (non-lazy-init) singletons
最主要的方法:beanFactory.preInstantiateSingletons(),进入到里面看,进入到getBean(beanName),进入到doGetBean,首先调用getSingleton(beanName)首次获取获取不到,但这个方法很重要,解决循坏依赖的。
接着我们看

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;  
   }  
});

进入到createBean(beanName, mbd, args)
看方法 Object bean = resolveBeforeInstantiation(beanName, mbdToUse),这个方法很重要,AOP功能就是这里实现的。首先了解两个接口BeanPostProcessor和 InstantiationAwareBeanPostProcessor,InstantiationAwareBeanPostProcessor继承自BeanPostProcessor,拓展出四个方法。参考InstantiationAwareBeanPostProcessor。待讲解AOP时候细讲。

接着进入到
Object beanInstance = doCreateBean(beanName, mbdToUse, args)
instanceWrapper = createBeanInstance(beanName, mbd, args) 这个方法创造一个还未初始化的bean,未初始化就是还未为属性添加值。
记住 addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean))
这个方法很重要,在循环依赖中用到,为bean添加一个SingletonFactory。
进入到populateBean(beanName, mbd, instanceWrapper)
这段代码完成依赖注入

for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {  
   PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);  
   if (pvsToUse == null) {  
      if (filteredPds == null) {  
         filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);  
      }  
      pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);  
      if (pvsToUse == null) {  
         return;  
      }  
   }  
   pvs = pvsToUse;  
}

AutowiredAnnotationBeanPostProcessor 这个类很重要,完成@Autowired注入
在这里插入图片描述

我们以这两个类来讲 @Autowired注入和循环依赖

@Service  
public class UserService {  
    @Autowired  
    private UserController userController;  
  
  
    public void print(String name){  
        System.out.println("who am i?"+name);  
    }  
  
}

@Controller  
public class UserController {  
  
    @Autowired  
    private UserService userService;  
      
}

首先为UserController注入依赖userService。
进入到AutowiredAnnotationBeanPostProcessor.postProcessProperties方法
进入到AutowiredAnnotationBeanPostProcessor.inject中的value = resolveFieldValue(field, bean, beanName);
进入到Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
这个可以不用细看。
接着往下看进入到代码块。

else {  
   // We have exactly one match.  
   Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();  
   autowiredBeanName = entry.getKey();  
   instanceCandidate = entry.getValue();  
}  
  
if (autowiredBeanNames != null) {  
   autowiredBeanNames.add(autowiredBeanName);  
}  
if (instanceCandidate instanceof Class) {  
   instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);  
}

进入descriptor.resolveCandidate(autowiredBeanName, type, this);
这个方法去调用beanFactory.getBean(beanName)获得userService。
又走到依赖注入,为UserService注入userController,看代码块

protected Object getSingleton(String beanName, boolean allowEarlyReference) {  
   // Quick check for existing instance without full singleton lock  
   Object singletonObject = this.singletonObjects.get(beanName);  
   if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {  
      singletonObject = this.earlySingletonObjects.get(beanName);  
      if (singletonObject == null && allowEarlyReference) {  
         synchronized (this.singletonObjects) {  
            // Consistent creation of early reference within full singleton lock  
            singletonObject = this.singletonObjects.get(beanName);  
            if (singletonObject == null) {  
               singletonObject = this.earlySingletonObjects.get(beanName);  
               if (singletonObject == null) {  
                  ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);  
                  if (singletonFactory != null) {  
                     singletonObject = singletonFactory.getObject();  
                     this.earlySingletonObjects.put(beanName, singletonObject);  
                     this.singletonFactories.remove(beanName);  
                  }  
               }  
            }  
         }  
      }  
   }  
   return singletonObject;  
}

this.singletonObjects.get(beanName)和singletonObject = this.earlySingletonObjects.get(beanName);都获取不到对象userController,singletonObject = singletonFactory.getObject()在刚实例化userController之后,执行过addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
这个方法能获得刚实例化的userController,这个时候UserService 能够完成初始化,只是里面的依赖UserController只是一个刚实例化的对象。完成了userService的依赖注入,那么UserController就能顺利完成初始化。注意这里是初始化。已经为 UserController注入了userService。那么Userservice也顺利完成初始化。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值