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 真正去解析配置类
- processMemberClasses
- Process any @PropertySource annotations
- Process any @ComponentScan annotations
- Process any @Import annotations
- Process any @ImportResource annotations
- Process individual @Bean methods
- Process default methods on interfaces
- 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也顺利完成初始化。