本文主要是介绍Spring Boot 系统学习第三天:Spring依赖注入原理分析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.概述
Spring中关于依赖注入的代码实现非常丰富,涉及大量类和组件之间的协作与交互。从原理上讲,任何一个框架都存在一条核心执行流程,只要抓住这条主流程,就能把握框架的整体代码结构,Spring也不例外。无论采用何种依赖注入机制,前提都是Spring IoC容器正常启动。因此,IoC容器初始化就是我们理解和把握依赖注入实现机制的前提。
本篇结合Bean的生命周期,把IoC容器初始化过程梳理成两大步骤,即Bean的注册和Bean的实例化。这两个步骤就构成了一条代码主流程。
2 Bean的注册
在使用Spring时,可以通过获取一个应用上下文(ApplicationContext)对象来操作各种Bean,示例代码如下:
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(ModulesWebApplication.class);
这里的ApplicationContext接口代表的就是一个Spring IoC容器,而在Spring中存在一大批ApplicationContext接口的实现类。如果使用注解的配置方式,就可以使用上述代码中的AnnotationConfigApplicationContext来初始化容器上下文对象。刚开始阅读Spring源码时,建议直接从AnnotationConfigApplicationContext的启动流程切入,这一流程位于它的构造函数中,代码如下:
public AnnotationConfigApplicationContext(Class<?>... componentClasses) {this();//根据注解配置类注册Beanthis.register(componentClasses);//刷新容器this.refresh();}public AnnotationConfigApplicationContext(String... basePackages) {this();//根据包路径配置扫描Beanthis.scan(basePackages);//刷新容器this.refresh();}
这两个构造函数的作用很明确,一个是根据注解配置类注册Bean,另一个则是根据包路径配置扫描Bean。这里以register()方法为例,来讨论Bean的注册过程。该方法源码如下:
public void register(Class<?>... componentClasses) {Assert.notEmpty(componentClasses, "At least one component class must be specified");StartupStep registerComponentClass = this.getApplicationStartup().start("spring.context.component-classes.register").tag("classes", () -> {return Arrays.toString(componentClasses);});this.reader.register(componentClasses);registerComponentClass.end();}
这里依赖AnnotationBeanDefinitionReader工具类来完成Bean的注册。AnnotationBeanDefinitionReader会遍历所有传入的annotatedClasses注解类,然后通过doRegisterBean()方法完成注册。
private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name, @Nullable Class<? extends Annotation>[] qualifiers, @Nullable Supplier<T> supplier, @Nullable BeanDefinitionCustomizer[] customizers) {//将注解配置类信息转换成一种BeanDefinitionAnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);if (!this.conditionEvaluator.shouldSkip(abd.getMetadata())) {abd.setInstanceSupplier(supplier);//获取Bean的作用域元数据,解析Bean作用域ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);abd.setScope(scopeMetadata.getScopeName());//生成beanNameString beanName = name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry);//解析AnnotationBeanDefinitionReader中的@Lazy,@Primary等注解AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);int var10;int var11;//处理@Qualifier注解if (qualifiers != null) {Class[] var9 = qualifiers;var10 = qualifiers.length;for(var11 = 0; var11 < var10; ++var11) {Class<? extends Annotation> qualifier = var9[var11];if (Primary.class == qualifier) {//如果设置了@Primary注解,则设置当前Bean为首选Beanabd.setPrimary(true);} else if (Lazy.class == qualifier) {//如果设置@Lazy注解,则设置当前Bean为延迟加载模式abd.setLazyInit(true);} else {//其他注解添加到BeanDefinition中abd.addQualifier(new AutowireCandidateQualifier(qualifier));}}}if (customizers != null) {BeanDefinitionCustomizer[] var13 = customizers;var10 = customizers.length;for(var11 = 0; var11 < var10; ++var11) {BeanDefinitionCustomizer customizer = var13[var11];customizer.customize(abd);}}BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);//注册Bean对象BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);}}
这段代码包含Bean注册过程中的三个核心步骤,如下图:
首选,构建用来描述Bean实例信息的BeanDefinition对象,需要将注解配置类信息转成AnnotatedGenericBeanDefinition数据结构,而AnnotatedGenericBeanDefinition就是一种BeanDefinition,包含了Bean的构造器参数、各种属性值以及所添加的注解信息。
然后,设置BeanDefinition属性,这一步骤完成对@Scope、@Primary、@Lazy等注解的处理。
最后, 通过registerBeanDefinition()方法完成Bean的注册,该方法内部通过ListableBeanFactory的实现类DefaultListableBeanFactory将Bean定义信息注册到Spring IoC容器中。ListableBeanFactory是Spring中常用的一个BeanFactory,通过这个接口,可以一次获取多个Bean。
3 Bean的实例化
请注意,到现在为止,Spring IoC容易对Bean的创建过程并没有完成,我们只是将Bean的定义加载到容器中而已。但是容器本身可能已经存在这些Bean的定义,所以我们还需要调用ApplicationContext接口的抽象实现类AbstractApplicationContext中的refresh()方法刷新容器,正如我们在前面看到的AnnotationConfigApplicationContext构造函数所执行的那样。可以说,refresh()方法是整个Spring容器中最为核心的一个方法,值得详细讨论。但因为这里关注的依赖注入,所以只列出refresh()方法中与该主题相关的代码,源码如下:
public void refresh() throws BeansException, IllegalStateException {synchronized(this.startupShutdownMonitor) {//提取配置信息转化为BeanDefinition并注册到BeanFactory中StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");this.prepareRefresh();ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();this.prepareBeanFactory(beanFactory);try {//初始化所有的单利Beanthis.postProcessBeanFactory(beanFactory);StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");this.invokeBeanFactoryPostProcessors(beanFactory);this.registerBeanPostProcessors(beanFactory);beanPostProcess.end();this.initMessageSource();this.initApplicationEventMulticaster();this.onRefresh();this.registerListeners();this.finishBeanFactoryInitialization(beanFactory);this.finishRefresh();} catch (BeansException var10) {if (this.logger.isWarnEnabled()) {this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var10);}this.destroyBeans();this.cancelRefresh(var10);throw var10;} finally {this.resetCommonCaches();contextRefresh.end();}}}
可以看到,obtainFreshBeanFactory方法完成BeanDefinition的注册并返回一个BeanFactory。对于AnnotationConfigApplicationContext而言,这一步实际上就是将BeanDefinition注册到DefaultListableBeanFactory。而finishBeanFactoryInitialization()方法才是真的完成Bean实例化的入口。在这个方法中,完成Bean的实例化代码实际上位于它的子类DefaultListableBeanFactory中,代码如下:
public void preInstantiateSingletons() throws BeansException {if (this.logger.isTraceEnabled()) {this.logger.trace("Pre-instantiating singletons in " + this);}List<String> beanNames = new ArrayList(this.beanDefinitionNames);Iterator var2 = beanNames.iterator();//触发所有非懒加载的单例Bean的初始化操作while(true) {String beanName;Object bean;do {while(true) {RootBeanDefinition bd;do {do {do {if (!var2.hasNext()) {var2 = beanNames.iterator();while(var2.hasNext()) {beanName = (String)var2.next();Object singletonInstance = this.getSingleton(beanName);if (singletonInstance instanceof SmartInitializingSingleton) {StartupStep smartInitialize = this.getApplicationStartup().start("spring.beans.smart-initialize").tag("beanName", beanName);SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton)singletonInstance;if (System.getSecurityManager() != null) {AccessController.doPrivileged(() -> {smartSingleton.afterSingletonsInstantiated();return null;}, this.getAccessControlContext());} else {smartSingleton.afterSingletonsInstantiated();}smartInitialize.end();}}return;}beanName = (String)var2.next();bd = this.getMergedLocalBeanDefinition(beanName);} while(bd.isAbstract());} while(!bd.isSingleton());} while(bd.isLazyInit());if (this.isFactoryBean(beanName)) {bean = this.getBean("&" + beanName);break;}//获取Beanthis.getBean(beanName);}} while(!(bean instanceof FactoryBean));FactoryBean<?> factory = (FactoryBean)bean;boolean isEagerInit;if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {SmartFactoryBean var10000 = (SmartFactoryBean)factory;((SmartFactoryBean)factory).getClass();isEagerInit = (Boolean)AccessController.doPrivileged(var10000::isEagerInit, this.getAccessControlContext());} else {isEagerInit = factory instanceof SmartFactoryBean && ((SmartFactoryBean)factory).isEagerInit();}if (isEagerInit) {this.getBean(beanName);}}}
接下里,进入到getBean()方法中,这个方法可以从BeanFactory中获取一个Bean,而Bean的初始化过程也被封装在这方法中。在getBean()方法中,一路跟踪代码会发现需要深入分析的实际上是一个createBean抽象方法。代码如下:BeanFactory中的createBean()方法
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)throws BeanCreationException {}
请注意,在Spring中,实现这个抽象方法的唯一BeanFactory是AbstractAutowireCapableBeanFactory。从命名上看,就可以联想到@Autowire注解。在AbstractAutowireCapableBeanFactory中,真正完成Bean的创建实在doCreateBean()方法中。这个方法较长,请重点看注释部分即可。AbstractAutowireCapableBeanFactory中的doCreateBean()方法源码如下:
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)throws BeanCreationException {BeanWrapper instanceWrapper = null;if (mbd.isSingleton()) {instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);}if (instanceWrapper == null) {//1.初始化BeaninstanceWrapper = createBeanInstance(beanName, mbd, args);}Object bean = instanceWrapper.getWrappedInstance();Class<?> beanType = instanceWrapper.getWrappedClass();if (beanType != NullBean.class) {mbd.resolvedTargetType = beanType;}synchronized (mbd.postProcessingLock) {if (!mbd.postProcessed) {try {applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);}catch (Throwable ex) {throw new BeanCreationException(mbd.getResourceDescription(), beanName,"Post-processing of merged bean definition failed", ex);}mbd.postProcessed = true;}}boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&isSingletonCurrentlyInCreation(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));}Object exposedObject = bean;try {//2.初始化Bean实例populateBean(beanName, mbd, instanceWrapper);//3.初始化Bean实例的回调exposedObject = initializeBean(beanName, exposedObject, mbd);}catch (Throwable ex) {if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {throw (BeanCreationException) ex;}}if (earlySingletonExposure) {Object earlySingletonReference = getSingleton(beanName, false);if (earlySingletonReference != null) {if (exposedObject == bean) {exposedObject = earlySingletonReference;}else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {String[] dependentBeans = getDependentBeans(beanName);Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);for (String dependentBean : dependentBeans) {if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {actualDependentBeans.add(dependentBean);}}}}}// Register bean as disposable.try {registerDisposableBeanIfNecessary(beanName, bean, mbd);}catch (BeanDefinitionValidationException ex) {throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);}return exposedObject;}
可以看到这里包含了三个核心子方法,它们的名称和作用如下图
以上三个步骤中,createBeanInstance()方法用于根据配置生成具体的Bean,最终通过基于构造器的反射方法实现这一目标。请注意,执行完这一步之后,Bean已经被创建了,但还不完成,因为属性还没有被注入。
接下来的populateBean()方法就是用于实现属性的自动注入,包含byName、byType类型的自动装配,以及基于@Autowire、@Value注解的属性设值。执行完这一步之后,可以说Bean已经是完整的了。
最后的initializeBean()方法则更多是一种扩展性的实现机制,用于在Bean初始化完成之后执行一些定制化操作。
到此,针对整个Bean的注入过程(即Bean的注册和实例化),围绕核心流程做了剖析和总结,在这个过程中比较容易碰到一个问题就陷入代码细节而忽略主体步骤。因此,如果想要跳出源码阅读的困境,快速掌握框架的实现原理,就必须从核心流程来看待框架。
这篇关于Spring Boot 系统学习第三天:Spring依赖注入原理分析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!