Spring 是分层的 full-stack(英文意思:全栈的,一般意味着各层能够无缝的集成在一起) 轻量级(复杂度比较低)开源框架,以 IoC 和 AOP 为内核,提供了展现层 Spring MVC 和业务层事务管理等众多的企业级应用技术,还能整合开源世界众多著名的第三方框架和类库,已经成为使用最多的 Java EE 企业应用开源框架
publicclass al {publicstaticvoidmain(String[] args){al a =newal();a.fa1();a.fa2();}publicvoidfa1(){long l =System.currentTimeMillis();System.out.println("fa1");long l1 =System.currentTimeMillis();System.out.println("执行时长:"+(l1 - l));}publicvoidfa2(){long l =System.currentTimeMillis();System.out.println("fa2");long l1 =System.currentTimeMillis();System.out.println("执行时长:"+(l1 - l));}}
CREATEDATABASE springtext CHARACTERSET utf8;USE springtext;CREATETABLE spring(
id INTPRIMARYKEYAUTO_INCREMENT,
NAME VARCHAR(20),
money INT);INSERTINTO spring VALUES(1,'张三',1000);INSERTINTO spring VALUES(2,'李四',1000);
<beansdefault-lazy-init="true"><!--位置可以随便放,只要空格(回车相当于空格)隔开即可,不会影响其他属性--><!--
no beans will be eagerly pre-instantiated... :
没有bean会被急切地预实例化
--></beans>
packagecom.factory;importorg.springframework.lang.Nullable;/****/// 可以让我们⾃定义Bean的创建过程(完成复杂Bean的定义)publicinterfaceFactoryBean<T>extendsorg.springframework.beans.factory.FactoryBean{@Nullable//注解提醒你使用非空判断(方法和成员变量都可以,局部和类一般不行),但也只是提醒,除了特别的地方,并无特殊作用,你也可以通过注释来代替他// 返回FactoryBean创建的Bean实例,如果isSingleton返回true,则该实例会放到Spring容器的单例对象缓存池中(Map)TgetObject()throwsException;@Nullable// 返回FactoryBean创建的Bean类型Class<?>getObjectType();// 返回作用域是否单例defaultbooleanisSingleton(){returntrue;}}//实际上在spring就存在这个接口://// Source code recreated from a .class file by IntelliJ IDEA// (powered by FernFlower decompiler)//packageorg.springframework.beans.factory;importorg.springframework.lang.Nullable;publicinterfaceFactoryBean<T>{@NullableTgetObject()throwsException;@NullableClass<?>getObjectType();defaultbooleanisSingleton(){returntrue;}}
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsd"><!--循环依赖问题--><beanid="lagouBean"class="com.lagou.edu.LagouBean"><propertyname="itBean"ref="itBean"></property></bean><beanid="itBean"class="com.lagou.edu.ItBean"><propertyname="lagouBean"ref="lagouBean"></property></bean><!--实际上如果根据前面我们自己操作的注入方式,一般没有循环依赖,这是因为他们只是操作同一个值,只是赋值关系但是如果是创建对象,即多例的情况下,就容易出现了(单例一般没有),你认为下面的代码会出现问题吗:
public class a {public b b = new b();}public class b {public a a = new a(); //这里是创建对象,如果是赋值的话,那么就不会出现问题}
public class c {public static void main(String[] args) {a a =new a();b b = new b();System.out.println(a);System.out.println(b);}
}
答:实际上会出现问题,一直操作中途的,而多例由于也是中途(getBean中继续getBean,一直这样(Spring内部造成的循环,因为需要考虑其自身方法,导致方法的多次调用,且基本无限,最终导致容易导致栈帧的变多,所以一般情况下,方法本身可能会有变量使得在调用一定的程度时,他的值也在一定的值,最终出现报错来直接的结束方法,这就是为什么使用多例,是出现错误而没有出现栈溢出的原因),是否与这里的创建对象中继续创建对象是类似的呢),所以就会出现循环依赖,但是上面的都是单例,所以不会出现--></beans>
根据上面的调试分析,我们发现 Bean对象创建的⼏个关键时机点代码层级的调用都在AbstractApplicationContext 类 的 refresh 方法中,可⻅这个方法对于Spring IoC 容器初始化来说相当 关键,汇总如下:
Spring IoC容器初始化主流程:
由上分析可知,Spring IoC 容器初始化的关键环节就在 AbstractApplicationContext#refresh()方法中(#代表对应方法是该类里面的方法) ,我们查看 refresh 方法来俯瞰容器创建的主体流程,主体流程下的具体⼦流程我们后面再来讨论
//public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContext {//public abstract class AbstractXmlApplicationContext extends AbstractRefreshableConfigApplicationContext {//public abstract class AbstractRefreshableConfigApplicationContext extends AbstractRefreshableApplicationContext//public abstract class AbstractRefreshableApplicationContext extends AbstractApplicationContext {//所以ClassPathXmlApplicationContext可以执行这里的refresh方法// ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:application.xml");publicabstractclassAbstractApplicationContextextendsDefaultResourceLoaderimplementsConfigurableApplicationContext{//..@Overridepublicvoidrefresh()throwsBeansException,IllegalStateException{synchronized(this.startupShutdownMonitor){// Prepare this context for refreshing.// 第一步:刷新前的预处理prepareRefresh();// Tell the subclass to refresh the internal bean factory.//第二步:获取BeanFactory,默认实现是DefaultListableBeanFactory//加载BeanDefinition 并注册到 BeanDefinitionRegistryConfigurableListableBeanFactory beanFactory =obtainFreshBeanFactory();// Prepare the bean factory for use in this context.// 第三步:BeanFactory的预准备工作(BeanFactory进行一些设置,比如context的类加载器等)prepareBeanFactory(beanFactory);try{// Allows post-processing of the bean factory in context subclasses.// 第四步:BeanFactory准备工作完成后进行的后置处理工作postProcessBeanFactory(beanFactory);// Invoke factory processors registered as beans in the context.// 第五步:实例化并调用实现了BeanFactoryPostProcessor接⼝的BeaninvokeBeanFactoryPostProcessors(beanFactory);// Register bean processors that intercept bean creation.// 第六步:注册BeanPostProcessor(Bean的后置处理器),在创建bean的前后等执行registerBeanPostProcessors(beanFactory);//要额外注意,上面的两个操作也是存在循环依赖的,最终他们两个方法是有联系的,只是一般我们不会操作注入,基本上操作方式也是三级缓存,或者说是一样的(最终到一级的),由于一般不操作注入,所以通常我们对循环依赖的说明只是针对单纯的bean来说的,且由于也是三级缓存,所以我们只要分析单纯的bean即可// Initialize message source for this context.// 第七步:初始化MessageSource组件(做国际化功能;消息绑定,消息解析)initMessageSource();// Initialize event multicaster for this context.// 第⼋步:初始化事件派发器initApplicationEventMulticaster();// Initialize other special beans in specific context subclasses.// 第九步:⼦类重写这个方法,在容器刷新的时候可以⾃定义逻辑onRefresh();// Check for listener beans and register them.// 第⼗步:注册应用的监听器,就是注册实现了ApplicationListener接⼝的监听器beanregisterListeners();// Instantiate all remaining (non-lazy-init) singletons./*第⼗一步:初始化所有剩下的⾮懒加载的单例bean初始化创建⾮懒加载方式的单例Bean实例(未设置属性)填充属性初始化方法调用(比如调用afterPropertiesSet方法、init-method方法)调用BeanPostProcessor(后置处理器)对实例bean进行后置处*/finishBeanFactoryInitialization(beanFactory);// Last step: publish corresponding event./*
第⼗二步:完成context的刷新。主要是调用LifecycleProcessor的onRefresh()方法,并且发布事件 (ContextRefreshedEvent)*/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();}}}//..}
publicabstractclassAbstractXmlApplicationContextextendsAbstractRefreshableConfigApplicationContext{//..//到这里来@OverrideprotectedvoidloadBeanDefinitions(DefaultListableBeanFactory beanFactory)throwsBeansException,IOException{// Create a new XmlBeanDefinitionReader for the given BeanFactory.//给指定的beanFactory创建这个对象,用来解析xml对象的,实际上对应的方法refresh对应的类,早就给出一个指定xml配置文件的地方了,只是我们并没有说明而已XmlBeanDefinitionReader beanDefinitionReader =newXmlBeanDefinitionReader(beanFactory);// Configure the bean definition reader with this context's// resource loading environment.//给这个对象设置一些context的上下文环境属性beanDefinitionReader.setEnvironment(this.getEnvironment());beanDefinitionReader.setResourceLoader(this);beanDefinitionReader.setEntityResolver(newResourceEntityResolver(this));// Allow a subclass to provide custom initialization of the reader,// then proceed with actually loading the bean definitions.//提供给子类实现一些自定义的初始化策略initBeanDefinitionReader(beanDefinitionReader);//真正的进行加载BeanDefinition(或者说BeanDefinitions)loadBeanDefinitions(beanDefinitionReader);}//..//到这里protectedvoidloadBeanDefinitions(XmlBeanDefinitionReader reader)throwsBeansException,IOException{//从对应的资源对象中加载BeanDefinitionResource[] configResources =getConfigResources();if(configResources !=null){reader.loadBeanDefinitions(configResources);}//从xml配置文件中加载BeanDefinitionString[] configLocations =getConfigLocations();if(configLocations !=null){//XmlBeanDefinitionReader readerreader.loadBeanDefinitions(configLocations);//到这里}}//..}//XmlBeanDefinitionReader reader//public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader {publicabstractclassAbstractBeanDefinitionReaderimplementsBeanDefinitionReader,EnvironmentCapable{//..//第四到@OverridepublicintloadBeanDefinitions(Resource... resources)throwsBeanDefinitionStoreException{Assert.notNull(resources,"Resource array must not be null");int count =0;for(Resource resource : resources){count +=loadBeanDefinitions(resource);//这里进入,直接操作资源对象了,而不是xml(String,String可以保存非常多信息哦,甚至是html网页信息也行的,所以xml被String读取保存也是可行的)}return count;}//第二到@OverridepublicintloadBeanDefinitions(String location)throwsBeanDefinitionStoreException{returnloadBeanDefinitions(location,null);}//第三到publicintloadBeanDefinitions(String location,@NullableSet<Resource> actualResources)throwsBeanDefinitionStoreException{//获取上下文的资源加载器ResourceLoader resourceLoader =getResourceLoader();if(resourceLoader ==null){thrownewBeanDefinitionStoreException("Cannot load bean definitions from location ["+ location +"]: no ResourceLoader available");}//判断资源加载器是否是对应的ResourcePatternResolver类型(是否是其或者其的子类),一般读取文件路径操作基本都是操作这个接口if(resourceLoader instanceofResourcePatternResolver){// Resource pattern matching available.try{//统一加载转换为Resource资源对象Resource[] resources =((ResourcePatternResolver) resourceLoader).getResources(location);//加载资源中的BeanDefinition的对象,并返回其数量,这里是主要的,我们进入,发现回到第二到int count =loadBeanDefinitions(resources);if(actualResources !=null){Collections.addAll(actualResources, resources);}if(logger.isTraceEnabled()){logger.trace("Loaded "+ count +" bean definitions from location pattern ["+ location +"]");}return count;}catch(IOException ex){thrownewBeanDefinitionStoreException("Could not resolve bean definition resource pattern ["+ location +"]", ex);}}else{// Can only load single resources by absolute URL.Resource resource = resourceLoader.getResource(location);int count =loadBeanDefinitions(resource);if(actualResources !=null){actualResources.add(resource);}if(logger.isTraceEnabled()){logger.trace("Loaded "+ count +" bean definitions from location ["+ location +"]");}return count;}}//先到这里@OverridepublicintloadBeanDefinitions(String... locations)throwsBeanDefinitionStoreException{Assert.notNull(locations,"Location array must not be null");int count =0;//如果有多个配置文件,循环读取加载,并统计总共加载了多少个BeanDefinition(一般标签就是一个BeanDefinition,Spring 解析 bean 标签成为一个 JavaBean, 这个JavaBean 就是 BeanDefinition(显示问题,一般是复制粘贴的),在后面会说明的他的加载过程)for(String location : locations){count +=loadBeanDefinitions(location);}return count;}}publicclassXmlBeanDefinitionReaderextendsAbstractBeanDefinitionReader{//..@OverridepublicintloadBeanDefinitions(Resource resource)throwsBeanDefinitionStoreException{returnloadBeanDefinitions(newEncodedResource(resource));}publicintloadBeanDefinitions(EncodedResource encodedResource)throwsBeanDefinitionStoreException{Assert.notNull(encodedResource,"EncodedResource must not be null");if(logger.isTraceEnabled()){logger.trace("Loading XML bean definitions from "+ encodedResource);}Set<EncodedResource> currentResources =this.resourcesCurrentlyBeingLoaded.get();if(currentResources ==null){currentResources =newHashSet<>(4);this.resourcesCurrentlyBeingLoaded.set(currentResources);}if(!currentResources.add(encodedResource)){thrownewBeanDefinitionStoreException("Detected cyclic loading of "+ encodedResource +" - check your import definitions!");}try{InputStream inputStream = encodedResource.getResource().getInputStream();try{//把xml文件流封装为InputSource对象InputSource inputSource =newInputSource(inputStream);if(encodedResource.getEncoding()!=null){inputSource.setEncoding(encodedResource.getEncoding());}//执行加载逻辑(大多数do开头的才会真正的进行数据的处理),而不是将数据移动或者较少的处理returndoLoadBeanDefinitions(inputSource, encodedResource.getResource());}finally{inputStream.close();}}catch(IOException ex){thrownewBeanDefinitionStoreException("IOException parsing XML document from "+ encodedResource.getResource(), ex);}finally{currentResources.remove(encodedResource);if(currentResources.isEmpty()){this.resourcesCurrentlyBeingLoaded.remove();}}}//..//到这里protectedintdoLoadBeanDefinitions(InputSource inputSource,Resource resource)throwsBeanDefinitionStoreException{try{//读取xml信息,将xml中信息保存到Document对象中//我们大多数可能知道import org.dom4j.Document;,但是这里是package org.w3c.dom.Document;,最终的作用其实还是一样的,只是实现不同而已Document doc =doLoadDocument(inputSource, resource);//解析Document对象,真正的封装BeanDefinitions对象并进行注册int count =registerBeanDefinitions(doc, resource);if(logger.isDebugEnabled()){logger.debug("Loaded "+ count +" bean definitions from "+ resource);}return count;}catch(BeanDefinitionStoreException ex){throw ex;}catch(SAXParseException ex){thrownewXmlBeanDefinitionStoreException(resource.getDescription(),"Line "+ ex.getLineNumber()+" in XML document from "+ resource +" is invalid", ex);}catch(SAXException ex){thrownewXmlBeanDefinitionStoreException(resource.getDescription(),"XML document from "+ resource +" is invalid", ex);}catch(ParserConfigurationException ex){thrownewBeanDefinitionStoreException(resource.getDescription(),"Parser configuration exception parsing XML from "+ resource, ex);}catch(IOException ex){thrownewBeanDefinitionStoreException(resource.getDescription(),"IOException parsing XML document from "+ resource, ex);}catch(Throwable ex){thrownewBeanDefinitionStoreException(resource.getDescription(),"Unexpected exception parsing XML document from "+ resource, ex);}}//..//到这里publicintregisterBeanDefinitions(Document doc,Resource resource)throwsBeanDefinitionStoreException{BeanDefinitionDocumentReader documentReader =createBeanDefinitionDocumentReader();//获取已有BeanDefinition的数量int countBefore =getRegistry().getBeanDefinitionCount();//注册BeanDefinition,这里我们进入registerBeanDefinitions以及createReaderContext(某些初始化,比如命令空间的判断)documentReader.registerBeanDefinitions(doc,createReaderContext(resource));//返回新注册的BeanDefinition的数量returngetRegistry().getBeanDefinitionCount()- countBefore;}//..publicXmlReaderContextcreateReaderContext(Resource resource){returnnewXmlReaderContext(resource,this.problemReporter,this.eventListener,this.sourceExtractor,this,getNamespaceHandlerResolver());}//..}//BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();publicclassDefaultBeanDefinitionDocumentReaderimplementsBeanDefinitionDocumentReader{//..//到这里@OverridepublicvoidregisterBeanDefinitions(Document doc,XmlReaderContext readerContext){this.readerContext = readerContext;//最终注册的地方doRegisterBeanDefinitions(doc.getDocumentElement());}//..protectedvoiddoRegisterBeanDefinitions(Element root){// Any nested <beans> elements will cause recursion in this method. In// order to propagate and preserve <beans> default-* attributes correctly,// keep track of the current (parent) delegate, which may be null. Create// the new (child) delegate with a reference to the parent for fallback purposes,// then ultimately reset this.delegate back to its original (parent) reference.// this behavior emulates a stack of delegates without actually necessitating one.BeanDefinitionParserDelegate parent =this.delegate;this.delegate =createDelegate(getReaderContext(), root, parent);if(this.delegate.isDefaultNamespace(root)){String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);if(StringUtils.hasText(profileSpec)){String[] specifiedProfiles =StringUtils.tokenizeToStringArray(profileSpec,BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);// We cannot use Profiles.of(...) since profile expressions are not supported// in XML config. See SPR-12458 for details.if(!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)){if(logger.isDebugEnabled()){logger.debug("Skipped XML bean definition file due to specified profiles ["+ profileSpec +"] not matching: "+getReaderContext().getResource());}return;}}}preProcessXml(root);//到这里parseBeanDefinitions(root,this.delegate);postProcessXml(root);this.delegate = parent;}//..protectedvoidparseBeanDefinitions(Element root,BeanDefinitionParserDelegate delegate){if(delegate.isDefaultNamespace(root)){NodeList nl = root.getChildNodes();for(int i =0; i < nl.getLength(); i++){Node node = nl.item(i);if(node instanceofElement){Element ele =(Element) node;if(delegate.isDefaultNamespace(ele)){//解析默认的标签元素,我们进入这里parseDefaultElement(ele, delegate);}else{//解析自定义的标签元素delegate.parseCustomElement(ele);}}}}else{delegate.parseCustomElement(root);}}//到这里privatevoidparseDefaultElement(Element ele,BeanDefinitionParserDelegate delegate){//import元素处理if(delegate.nodeNameEquals(ele, IMPORT_ELEMENT)){importBeanDefinitionResource(ele);}//alias元素处理elseif(delegate.nodeNameEquals(ele, ALIAS_ELEMENT)){processAliasRegistration(ele);}//bean元素处理elseif(delegate.nodeNameEquals(ele, BEAN_ELEMENT)){//我们进入这个processBeanDefinition(ele, delegate);}//嵌套beans的处理elseif(delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)){// recursedoRegisterBeanDefinitions(ele);}}//..//到这里protectedvoidprocessBeanDefinition(Element ele,BeanDefinitionParserDelegate delegate){//解析对应bean的BeanDefinition(bean信息封装给他的),BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);if(bdHolder !=null){//如果有自定义标签,则处理自定义标签bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);try{// Register the final decorated instance.//这里会完成BeanDefinition的注册,我们进入BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder,getReaderContext().getRegistry());}catch(BeanDefinitionStoreException ex){getReaderContext().error("Failed to register bean definition with name '"+bdHolder.getBeanName()+"'", ele, ex);}// Send registration event.getReaderContext().fireComponentRegistered(newBeanComponentDefinition(bdHolder));}}//..}//实际上大多数的框架的类在调用使用时,都是从上到下的调用,当然,有些类并非如此,所以只是说明大多数而已//最终到这里publicabstractclassBeanDefinitionReaderUtils{//..publicstaticvoidregisterBeanDefinition(BeanDefinitionHolder definitionHolder,BeanDefinitionRegistry registry)throwsBeanDefinitionStoreException{// Register bean definition under primary name.String beanName = definitionHolder.getBeanName();//这个一般就是对应的id名称了,当然,也会与name相关的,前提是id不存在//最终的注册,我们进入registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());// Register aliases for bean name, if any.String[] aliases = definitionHolder.getAliases();if(aliases !=null){for(String alias : aliases){//别名的保存registry.registerAlias(beanName, alias);}}}//..}@SuppressWarnings("serial")publicclassDefaultListableBeanFactoryextendsAbstractAutowireCapableBeanFactoryimplementsConfigurableListableBeanFactory,BeanDefinitionRegistry,Serializable{//..//到这里@OverridepublicvoidregisterBeanDefinition(String beanName,BeanDefinition beanDefinition)throwsBeanDefinitionStoreException{Assert.hasText(beanName,"Bean name must not be empty");Assert.notNull(beanDefinition,"BeanDefinition must not be null");if(beanDefinition instanceofAbstractBeanDefinition){try{((AbstractBeanDefinition) beanDefinition).validate();}catch(BeanDefinitionValidationException ex){thrownewBeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,"Validation of bean definition failed", ex);}}BeanDefinition existingDefinition =this.beanDefinitionMap.get(beanName);if(existingDefinition !=null){if(!isAllowBeanDefinitionOverriding()){thrownewBeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);}elseif(existingDefinition.getRole()< beanDefinition.getRole()){// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTUREif(logger.isInfoEnabled()){logger.info("Overriding user-defined bean definition for bean '"+ beanName +"' with a framework-generated bean definition: replacing ["+existingDefinition +"] with ["+ beanDefinition +"]");}}elseif(!beanDefinition.equals(existingDefinition)){if(logger.isDebugEnabled()){logger.debug("Overriding bean definition for bean '"+ beanName +"' with a different definition: replacing ["+ existingDefinition +"] with ["+ beanDefinition +"]");}}else{if(logger.isTraceEnabled()){logger.trace("Overriding bean definition for bean '"+ beanName +"' with an equivalent definition: replacing ["+ existingDefinition +"] with ["+ beanDefinition +"]");}}this.beanDefinitionMap.put(beanName, beanDefinition);}else{if(hasBeanCreationStarted()){// Cannot modify startup-time collection elements anymore (for stable iteration)synchronized(this.beanDefinitionMap){this.beanDefinitionMap.put(beanName, beanDefinition);List<String> updatedDefinitions =newArrayList<>(this.beanDefinitionNames.size()+1);updatedDefinitions.addAll(this.beanDefinitionNames);updatedDefinitions.add(beanName);this.beanDefinitionNames = updatedDefinitions;removeManualSingletonName(beanName);}}else{// Still in startup registration phase//真正的注册,可以看到是put方法,即放入map中了,一个名称,一个beanDefinitionthis.beanDefinitionMap.put(beanName, beanDefinition);this.beanDefinitionNames.add(beanName);removeManualSingletonName(beanName);}this.frozenBeanDefinitionNames =null;}if(existingDefinition !=null||containsSingleton(beanName)){resetBeanDefinition(beanName);}elseif(isConfigurationFrozen()){clearByTypeCache();}}//..}//至此,我们最终到达this.beanDefinitionMap.put(beanName, beanDefinition);,即对应的bean注册或者添加完毕,最终返回存放bean的工厂,即ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();的确是获取工厂的
测试String是否可以写上很多信息:
packagecom.test;importorg.junit.Test;/****/publicclassTest1{@Testpublicvoidtext1(){String a ="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";System.out.println(a);}}
/*finishBeanFactoryInitialization(beanFactory); 我们进入*/publicabstractclassAbstractApplicationContextextendsDefaultResourceLoaderimplementsConfigurableApplicationContext{//..protectedvoidfinishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory){// Initialize conversion service for this context.if(beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME)&&beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME,ConversionService.class)){beanFactory.setConversionService(beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME,ConversionService.class));}// Register a default embedded value resolver if no bean post-processor// (such as a PropertyPlaceholderConfigurer bean) registered any before:// at this point, primarily for resolution in annotation attribute values.if(!beanFactory.hasEmbeddedValueResolver()){beanFactory.addEmbeddedValueResolver(strVal ->getEnvironment().resolvePlaceholders(strVal));}// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class,false,false);for(String weaverAwareName : weaverAwareNames){getBean(weaverAwareName);}// Stop using the temporary ClassLoader for type matching.beanFactory.setTempClassLoader(null);// Allow for caching all bean definition metadata, not expecting further changes.beanFactory.freezeConfiguration();// Instantiate all remaining (non-lazy-init) singletons.//实例化所有立即加载的单例bean,我们进入这里beanFactory.preInstantiateSingletons();}//.. }//到这里@SuppressWarnings("serial")publicclassDefaultListableBeanFactoryextendsAbstractAutowireCapableBeanFactoryimplementsConfigurableListableBeanFactory,BeanDefinitionRegistry,Serializable{//..@OverridepublicvoidpreInstantiateSingletons()throwsBeansException{if(logger.isTraceEnabled()){logger.trace("Pre-instantiating singletons in "+this);}// Iterate over a copy to allow for init methods which in turn register new bean definitions.// While this may not be part of the regular factory bootstrap, it does otherwise work fine.//所有bean的名字,后面就操作循环,来为每个bean进行创建List<String> beanNames =newArrayList<>(this.beanDefinitionNames);// Trigger initialization of all non-lazy singleton beans...//触发所有非延迟加载单例bean的初始化,主要步骤为getBeanfor(String beanName : beanNames){//合并父BeanDefinition信息,通常需要父的某些信息RootBeanDefinition bd =getMergedLocalBeanDefinition(beanName);if(!bd.isAbstract()&& bd.isSingleton()&&!bd.isLazyInit()){if(isFactoryBean(beanName)){//主要步骤,String FACTORY_BEAN_PREFIX = "&";这里就知道了吧(前面的工厂,或者说自定义创建过程)Object bean =getBean(FACTORY_BEAN_PREFIX + beanName);if(bean instanceofFactoryBean){FactoryBean<?> factory =(FactoryBean<?>) bean;boolean isEagerInit;if(System.getSecurityManager()!=null&& factory instanceofSmartFactoryBean){isEagerInit =AccessController.doPrivileged((PrivilegedAction<Boolean>)((SmartFactoryBean<?>) factory)::isEagerInit,getAccessControlContext());}else{isEagerInit =(factory instanceofSmartFactoryBean&&((SmartFactoryBean<?>) factory).isEagerInit());}if(isEagerInit){getBean(beanName);}}}else{//直接到这里,因为不是工厂bean,自然也没有对应的&存放,我们进入这里getBean(beanName);//他内部进行了保存,所以并不需要进行得到返回值//这里需要额外注意,如果不是立即加载可能并不操作保存}}}// Trigger post-initialization callback for all applicable beans...for(String beanName : beanNames){Object singletonInstance =getSingleton(beanName);if(singletonInstance instanceofSmartInitializingSingleton){SmartInitializingSingleton smartSingleton =(SmartInitializingSingleton) singletonInstance;if(System.getSecurityManager()!=null){AccessController.doPrivileged((PrivilegedAction<Object>)()->{smartSingleton.afterSingletonsInstantiated();returnnull;},getAccessControlContext());}else{smartSingleton.afterSingletonsInstantiated();}}}}//.. }publicabstractclassAbstractBeanFactoryextendsFactoryBeanRegistrySupportimplementsConfigurableBeanFactory{//.. @OverridepublicObjectgetBean(String name)throwsBeansException{//继续进入returndoGetBean(name,null,null,false);}//..protected<T>TdoGetBean(String name,@NullableClass<T> requiredType,@NullableObject[] args,boolean typeCheckOnly)throwsBeansException{//解析beanName(也就是id或者name),得到对应的名称来表示class的,也会考虑工厂的&来得到对应表示的beanName,在后面通常会使用该名称来进一步处理或者说得到&,一般与单纯的得到是不同的String beanName =transformedBeanName(name);Object bean;// Eagerly check singleton cache for manually registered singletons.//单纯尝试从缓存中获取bean(一般spring也有缓存,代表bean不用去容器操作步骤找了,而是直接的返回)Object sharedInstance =getSingleton(beanName);//如果已经存在就返回if(sharedInstance !=null&& args ==null){if(logger.isTraceEnabled()){if(isSingletonCurrentlyInCreation(beanName)){logger.trace("Returning eagerly cached instance of singleton bean '"+ beanName +"' that is not fully initialized yet - a consequence of a circular reference");}else{logger.trace("Returning cached instance of singleton bean '"+ beanName +"'");}}bean =getObjectForBeanInstance(sharedInstance, name, beanName,null);}else{// Fail if we're already creating this bean instance:// We're assumably within a circular reference.//如果是Prototype(即多例模式),且开启允许循环依赖,那么报错,因为多例模式是容易出现循环依赖的,所以就不能直接的允许循环依赖if(isPrototypeCurrentlyInCreation(beanName)){thrownewBeanCurrentlyInCreationException(beanName);}// Check if bean definition exists in this factory.//检查父工厂中是否存在该对象(一般代表配置文件中的配置文件,那么里面的配置文件就是子工厂,而外面的就是父工厂),若存在的话一般拿出来进行处理,并考虑覆盖关系(读取时,是只能操作一个id的)BeanFactory parentBeanFactory =getParentBeanFactory();//没有父工厂,自然不会考虑这里if(parentBeanFactory !=null&&!containsBeanDefinition(beanName)){// Not found -> check parent.String nameToLookup =originalBeanName(name);if(parentBeanFactory instanceofAbstractBeanFactory){return((AbstractBeanFactory) parentBeanFactory).doGetBean(nameToLookup, requiredType, args, typeCheckOnly);}elseif(args !=null){// Delegation to parent with explicit args.return(T) parentBeanFactory.getBean(nameToLookup, args);}elseif(requiredType !=null){// No args -> delegate to standard getBean method.return parentBeanFactory.getBean(nameToLookup, requiredType);}else{return(T) parentBeanFactory.getBean(nameToLookup);}}//然后到这里if(!typeCheckOnly){markBeanAsCreated(beanName);}try{//合并父子bean的属性RootBeanDefinition mbd =getMergedLocalBeanDefinition(beanName);checkMergedBeanDefinition(mbd, beanName, args);// Guarantee initialization of beans that the current bean depends on.//处理dependsOn配置(这个我们并不熟悉,虽然他也是一个校验)String[] dependsOn = mbd.getDependsOn();if(dependsOn !=null){for(String dep : dependsOn){if(isDependent(beanName, dep)){thrownewBeanCreationException(mbd.getResourceDescription(), beanName,"Circular depends-on relationship between '"+ beanName +"' and '"+ dep +"'");}registerDependentBean(dep, beanName);try{getBean(dep);}catch(NoSuchBeanDefinitionException ex){thrownewBeanCreationException(mbd.getResourceDescription(), beanName,"'"+ beanName +"' depends on missing bean '"+ dep +"'", ex);}}}// Create bean instance.//开始创建单例beanif(mbd.isSingleton()){//我们进入这里sharedInstance =getSingleton(beanName,()->{try{//创建bean,这个表达式作为参数传递returncreateBean(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);}elseif(mbd.isPrototype()){// It's a prototype -> create a new instance.Object prototypeInstance =null;try{beforePrototypeCreation(beanName);prototypeInstance =createBean(beanName, mbd, args);}finally{afterPrototypeCreation(beanName);}bean =getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);}else{String scopeName = mbd.getScope();if(!StringUtils.hasLength(scopeName)){thrownewIllegalStateException("No scope name defined for bean ´"+ beanName +"'");}Scope scope =this.scopes.get(scopeName);if(scope ==null){thrownewIllegalStateException("No Scope registered for scope name '"+ scopeName +"'");}try{Object scopedInstance = scope.get(beanName,()->{beforePrototypeCreation(beanName);try{returncreateBean(beanName, mbd, args);}finally{afterPrototypeCreation(beanName);}});bean =getObjectForBeanInstance(scopedInstance, name, beanName, mbd);}catch(IllegalStateException ex){thrownewBeanCreationException(beanName,"Scope '"+ scopeName +"' is not active for the current thread; consider "+"defining a scoped proxy for this bean if you intend to refer to it from a singleton",ex);}}}catch(BeansException ex){cleanupAfterBeanCreationFailure(beanName);throw ex;}}// Check if required type matches the type of the actual bean instance.if(requiredType !=null&&!requiredType.isInstance(bean)){try{T convertedBean =getTypeConverter().convertIfNecessary(bean, requiredType);if(convertedBean ==null){thrownewBeanNotOfRequiredTypeException(name, requiredType, bean.getClass());}return convertedBean;}catch(TypeMismatchException ex){if(logger.isTraceEnabled()){logger.trace("Failed to convert bean '"+ name +"' to required type '"+ClassUtils.getQualifiedName(requiredType)+"'", ex);}thrownewBeanNotOfRequiredTypeException(name, requiredType, bean.getClass());}}return(T) bean;}//..}publicclassDefaultSingletonBeanRegistryextendsSimpleAliasRegistryimplementsSingletonBeanRegistry{//..publicObjectgetSingleton(String beanName,ObjectFactory<?> singletonFactory){Assert.notNull(beanName,"Bean name must not be null");synchronized(this.singletonObjects){Object singletonObject =this.singletonObjects.get(beanName);if(singletonObject ==null){//是否正在销毁,是的话,就会抛出异常的if(this.singletonsCurrentlyInDestruction){thrownewBeanCreationNotAllowedException(beanName,"Singleton bean creation not allowed while singletons of this factory are in destruction "+"(Do not request a bean from a BeanFactory in a destroy method implementation!)");}if(logger.isDebugEnabled()){logger.debug("Creating shared instance of singleton bean '"+ beanName +"'");}//验证完要真正开始创建的对象,先标识该bean正在被创建,因为springbean创建的过程复杂,步骤很多,需要标识防止万一(比如一个bean还会存在很多子标签,以及属性的操作,并且是否需要其他的bean来创建他,然后考虑是否保留最终注入,还是帮助创建,然后注入的说法,这里有很多种方式,具体的spring通常是先注入,后放map)beforeSingletonCreation(beanName);boolean newSingleton =false;boolean recordSuppressedExceptions =(this.suppressedExceptions ==null);if(recordSuppressedExceptions){this.suppressedExceptions =newLinkedHashSet<>();}try{//ObjectFactory<?> singletonFactory//创建bean,这个表达式作为参数传递/*所以我们进入之前的://创建bean,这个表达式作为参数传递return createBean(beanName, mbd, args); 进入这里*/singletonObject = singletonFactory.getObject();newSingleton =true;}catch(IllegalStateException ex){// Has the singleton object implicitly appeared in the meantime ->// if yes, proceed with it since the exception indicates that state.singletonObject =this.singletonObjects.get(beanName);if(singletonObject ==null){throw ex;}}catch(BeanCreationException ex){if(recordSuppressedExceptions){for(Exception suppressedException :this.suppressedExceptions){ex.addRelatedCause(suppressedException);}}throw ex;}finally{if(recordSuppressedExceptions){this.suppressedExceptions =null;}afterSingletonCreation(beanName);}if(newSingleton){addSingleton(beanName, singletonObject);}}return singletonObject;}}//.. }publicabstractclassAbstractAutowireCapableBeanFactoryextendsAbstractBeanFactoryimplementsAutowireCapableBeanFactory{//..//后置最终到这里(按照顺序来的,所以记得仔细观察,这个顺序一般是类里面的方法顺序,以后就不提醒了)@OverridepublicObjectapplyBeanPostProcessorsAfterInitialization(Object existingBean,String beanName)throwsBeansException{Object result = existingBean;//操作对应的所有的后置 for(BeanPostProcessor processor :getBeanPostProcessors()){Object current = processor.postProcessAfterInitialization(result, beanName);//对应的后置方法,所以这里就操作了,最后返回beanif(current ==null){return result;}result = current;}return result;}//..@OverrideprotectedObjectcreateBean(String beanName,RootBeanDefinition mbd,@NullableObject[] args)throwsBeanCreationException{if(logger.isTraceEnabled()){logger.trace("Creating instance of bean '"+ beanName +"'");}RootBeanDefinition mbdToUse = mbd;// Make sure bean class is actually resolved at this point, and// clone the bean definition in case of a dynamically resolved Class// which cannot be stored in the shared merged bean definition.//获取类信息/*//合并父子bean的属性RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); 得到的信息中也包括mbd的*/Class<?> resolvedClass =resolveBeanClass(mbd, beanName);if(resolvedClass !=null&&!mbd.hasBeanClass()&& mbd.getBeanClassName()!=null){mbdToUse =newRootBeanDefinition(mbd);mbdToUse.setBeanClass(resolvedClass);}// Prepare method overrides.try{mbdToUse.prepareMethodOverrides();}catch(BeanDefinitionValidationException ex){thrownewBeanDefinitionStoreException(mbdToUse.getResourceDescription(),beanName,"Validation of method overrides failed", ex);}try{// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.Object bean =resolveBeforeInstantiation(beanName, mbdToUse);if(bean !=null){return bean;}}catch(Throwable ex){thrownewBeanCreationException(mbdToUse.getResourceDescription(), beanName,"BeanPostProcessor before instantiation of bean failed", ex);}try{//这里我们进入,真正的创建bean(do来做事情)Object beanInstance =doCreateBean(beanName, mbdToUse, args);if(logger.isTraceEnabled()){logger.trace("Finished creating instance of bean '"+ beanName +"'");}return beanInstance;}catch(BeanCreationException|ImplicitlyAppearedSingletonException ex){// A previously detected exception with proper bean creation context already,// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.throw ex;}catch(Throwable ex){thrownewBeanCreationException(mbdToUse.getResourceDescription(), beanName,"Unexpected exception during bean creation", ex);}}//到这里protectedObjectdoCreateBean(String beanName,RootBeanDefinition mbd,@NullableObject[] args)throwsBeanCreationException{// Instantiate the bean.BeanWrapper instanceWrapper =null;if(mbd.isSingleton()){instanceWrapper =this.factoryBeanInstanceCache.remove(beanName);}if(instanceWrapper ==null){//创建bean实例,仅仅调用构造方法,但是并没有设置属性instanceWrapper =createBeanInstance(beanName, mbd, args);}Object bean = instanceWrapper.getWrappedInstance();Class<?> beanType = instanceWrapper.getWrappedClass();if(beanType !=NullBean.class){mbd.resolvedTargetType = beanType;}// Allow post-processors to modify the merged bean definition.synchronized(mbd.postProcessingLock){if(!mbd.postProcessed){try{applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);}catch(Throwable ex){thrownewBeanCreationException(mbd.getResourceDescription(), beanName,"Post-processing of merged bean definition failed", ex);}mbd.postProcessed =true;}}// Eagerly cache singletons to be able to resolve circular references// even when triggered by lifecycle interfaces like BeanFactoryAware.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");}//这个是扩展的,其中一般我们会将后面的表达式放入对应的value中,在得到三级缓存时,他会进行对二级缓存的扩展,最终放入二级缓存中addSingletonFactory(beanName,()->getEarlyBeanReference(beanName, mbd, bean));}// Initialize the bean instance.//初始化bean实例Object exposedObject = bean;try{//前面是创建bean,这里是填充属性populateBean(beanName, mbd, instanceWrapper);//调用初始化方法,应用BeanPostProcessor后置处理器,我们进入这里exposedObject =initializeBean(beanName, exposedObject, mbd);}catch(Throwable ex){if(ex instanceofBeanCreationException&& beanName.equals(((BeanCreationException) ex).getBeanName())){throw(BeanCreationException) ex;}else{thrownewBeanCreationException(mbd.getResourceDescription(), beanName,"Initialization of bean failed", ex);}}if(earlySingletonExposure){Object earlySingletonReference =getSingleton(beanName,false);if(earlySingletonReference !=null){if(exposedObject == bean){exposedObject = earlySingletonReference;}elseif(!this.allowRawInjectionDespiteWrapping &&hasDependentBean(beanName)){String[] dependentBeans =getDependentBeans(beanName);Set<String> actualDependentBeans =newLinkedHashSet<>(dependentBeans.length);for(String dependentBean : dependentBeans){if(!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)){actualDependentBeans.add(dependentBean);}}if(!actualDependentBeans.isEmpty()){thrownewBeanCurrentlyInCreationException(beanName,"Bean with name '"+ beanName +"' has been injected into other beans ["+StringUtils.collectionToCommaDelimitedString(actualDependentBeans)+"] in its raw version as part of a circular reference, but has eventually been "+"wrapped. This means that said other beans do not use the final version of the "+"bean. This is often the result of over-eager type matching - consider using "+"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");}}}}// Register bean as disposable.try{registerDisposableBeanIfNecessary(beanName, bean, mbd);}catch(BeanDefinitionValidationException ex){thrownewBeanCreationException(mbd.getResourceDescription(), beanName,"Invalid destruction signature", ex);}return exposedObject;//最后返回}//..//到这里protectedObjectinitializeBean(String beanName,Object bean,@NullableRootBeanDefinition mbd){if(System.getSecurityManager()!=null){AccessController.doPrivileged((PrivilegedAction<Object>)()->{invokeAwareMethods(beanName, bean);returnnull;},getAccessControlContext());}else{invokeAwareMethods(beanName, bean);}Object wrappedBean = bean;if(mbd ==null||!mbd.isSynthetic()){wrappedBean =applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);}try{invokeInitMethods(beanName, wrappedBean, mbd);}catch(Throwable ex){thrownewBeanCreationException((mbd !=null? mbd.getResourceDescription():null),beanName,"Invocation of init method failed", ex);}if(mbd ==null||!mbd.isSynthetic()){//进入这里wrappedBean =applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);}return wrappedBean;}//..}
//到这里@SuppressWarnings("serial")publicclassDefaultListableBeanFactoryextendsAbstractAutowireCapableBeanFactoryimplementsConfigurableListableBeanFactory,BeanDefinitionRegistry,Serializable{//..@OverridepublicvoidpreInstantiateSingletons()throwsBeansException{if(logger.isTraceEnabled()){logger.trace("Pre-instantiating singletons in "+this);}// Iterate over a copy to allow for init methods which in turn register new bean definitions.// While this may not be part of the regular factory bootstrap, it does otherwise work fine.//所有bean的名字List<String> beanNames =newArrayList<>(this.beanDefinitionNames);// Trigger initialization of all non-lazy singleton beans...//触发所有非延迟加载单例bean的初始化,主要步骤为getBeanfor(String beanName : beanNames){//合并父BeanDefinition信息,通常需要父的某些信息RootBeanDefinition bd =getMergedLocalBeanDefinition(beanName);//这里判断的if(!bd.isAbstract()&& bd.isSingleton()&&!bd.isLazyInit()){//这里判断的if(isFactoryBean(beanName)){//主要步骤,String FACTORY_BEAN_PREFIX = "&";这里就知道了吧(前面的工厂,或者说自定义创建过程)Object bean =getBean(FACTORY_BEAN_PREFIX + beanName);if(bean instanceofFactoryBean){FactoryBean<?> factory =(FactoryBean<?>) bean;boolean isEagerInit;if(System.getSecurityManager()!=null&& factory instanceofSmartFactoryBean){isEagerInit =AccessController.doPrivileged((PrivilegedAction<Boolean>)((SmartFactoryBean<?>) factory)::isEagerInit,getAccessControlContext());}else{isEagerInit =(factory instanceofSmartFactoryBean&&((SmartFactoryBean<?>) factory).isEagerInit());}if(isEagerInit){getBean(beanName);}}}else{//直接到这里,因为不是工厂bean,自然也没有对应的&存放,我们进入这里getBean(beanName);}}}// Trigger post-initialization callback for all applicable beans...for(String beanName : beanNames){Object singletonInstance =getSingleton(beanName);if(singletonInstance instanceofSmartInitializingSingleton){SmartInitializingSingleton smartSingleton =(SmartInitializingSingleton) singletonInstance;if(System.getSecurityManager()!=null){AccessController.doPrivileged((PrivilegedAction<Object>)()->{smartSingleton.afterSingletonsInstantiated();returnnull;},getAccessControlContext());}else{smartSingleton.afterSingletonsInstantiated();}}}}//.. }
//到这里@SuppressWarnings("serial")publicclassDefaultListableBeanFactoryextendsAbstractAutowireCapableBeanFactoryimplementsConfigurableListableBeanFactory,BeanDefinitionRegistry,Serializable{//..@OverridepublicvoidpreInstantiateSingletons()throwsBeansException{if(logger.isTraceEnabled()){logger.trace("Pre-instantiating singletons in "+this);}// Iterate over a copy to allow for init methods which in turn register new bean definitions.// While this may not be part of the regular factory bootstrap, it does otherwise work fine.//所有bean的名字List<String> beanNames =newArrayList<>(this.beanDefinitionNames);// Trigger initialization of all non-lazy singleton beans...//触发所有非延迟加载单例bean的初始化,主要步骤为getBeanfor(String beanName : beanNames){//合并父BeanDefinition信息,通常需要父的某些信息RootBeanDefinition bd =getMergedLocalBeanDefinition(beanName);if(!bd.isAbstract()&& bd.isSingleton()&&!bd.isLazyInit()){//只能是立即的进入,否则不会操作到getBean方法,这就是延迟加载的唯一判断的地方,即延迟操作不创建bean的原因(或者初始化不创建)if(isFactoryBean(beanName)){//主要步骤,String FACTORY_BEAN_PREFIX = "&";这里就知道了吧(前面的工厂,或者说自定义创建过程)Object bean =getBean(FACTORY_BEAN_PREFIX + beanName);if(bean instanceofFactoryBean){FactoryBean<?> factory =(FactoryBean<?>) bean;boolean isEagerInit;if(System.getSecurityManager()!=null&& factory instanceofSmartFactoryBean){isEagerInit =AccessController.doPrivileged((PrivilegedAction<Boolean>)((SmartFactoryBean<?>) factory)::isEagerInit,getAccessControlContext());}else{isEagerInit =(factory instanceofSmartFactoryBean&&((SmartFactoryBean<?>) factory).isEagerInit());}if(isEagerInit){getBean(beanName);}}}else{//直接到这里,因为不是工厂bean,自然也没有对应的&存放,我们进入这里getBean(beanName);//他内部进行了保存,所以并不需要进行得到返回值//这里需要额外注意,如果不是立即加载可能并不操作保存}}}// Trigger post-initialization callback for all applicable beans...for(String beanName : beanNames){Object singletonInstance =getSingleton(beanName);if(singletonInstance instanceofSmartInitializingSingleton){SmartInitializingSingleton smartSingleton =(SmartInitializingSingleton) singletonInstance;if(System.getSecurityManager()!=null){AccessController.doPrivileged((PrivilegedAction<Object>)()->{smartSingleton.afterSingletonsInstantiated();returnnull;},getAccessControlContext());}else{smartSingleton.afterSingletonsInstantiated();}}}}//.. }
//从这里可以看出,属性的设置和初始化(这里的前面的代码)是一起的,只是可能由于在设置时,帮助其进行操作使得对应的循环跳过,而这个帮助可能在让他初始化时,继续到这里形成循环依赖,而spring采用提前暴露,也就是直接的赋值(你已经初始化了的,所以可以赋值(能获得,自然也是提前暴露出去的,所以称为提前暴露对象的方法),然后我得到了,自然你也可以来得到我了)//前面是创建bean,这里是填充属性populateBean(beanName, mbd, instanceWrapper);//一般的,我们将这样的操作称为三级缓存的解决操作(可以说是专门操作循环依赖的,或者说是类),一般其他暴露并初始化的放在三级缓存,而进行了处理即成型的放入一级缓存操作,中间的二级缓存也存放成型的bean,只是他只进行某些扩展处理,而不会像一级缓存暴露使用,和三级缓存暴露使用,所以在一定程度上,只有二个缓存,虽然实际存在三个(一级和三级一般是map,而二级一般是三级对应的value)//上面的:然后我得到了,自然你也可以来得到我了,在一定程度上可以使用代码来表示:/*
package com.lagou.edu;
public class a {class b {public b() {}d d;void setb(d d) {this.d = d;}}class d {b b;public d() {}void setd(b b) {this.b = b;}}public void main(String[] args) {d d = new d(); //首先初始化的b b = new b();b.setb(d); //然后我得到了d.setd(b); //自然你也可以来得到我了,虽然上面的也是暴露的b b = new b();,但要明白的是,b认为是先操作的,所以你必然得到完整,而不是一开始的残缺,但是b先操作并不代表在spring中是b先完毕,这是由于spring的创建和set是一起的,所以在spring中一般是b先完毕,我们看后面的源码就知道了}
}*/
//我们直接到之前的如下:publicabstractclassAbstractBeanFactoryextendsFactoryBeanRegistrySupportimplementsConfigurableBeanFactory{//..@SuppressWarnings("unchecked")protected<T>TdoGetBean(String name,@NullableClass<T> requiredType,@NullableObject[] args,boolean typeCheckOnly)throwsBeansException{String beanName =transformedBeanName(name);Object bean;// Eagerly check singleton cache for manually registered singletons.Object sharedInstance =getSingleton(beanName);if(sharedInstance !=null&& args ==null){if(logger.isTraceEnabled()){if(isSingletonCurrentlyInCreation(beanName)){logger.trace("Returning eagerly cached instance of singleton bean '"+ beanName +"' that is not fully initialized yet - a consequence of a circular reference");}else{logger.trace("Returning cached instance of singleton bean '"+ beanName +"'");}}bean =getObjectForBeanInstance(sharedInstance, name, beanName,null);}else{// Fail if we're already creating this bean instance:// We're assumably within a circular reference.//如果是Prototype(即多例模式),且开启允许循环依赖(一般是只是否存在,主要看源码就知道了),那么报错,因为多例模式是容易出现循环依赖的,所以就不能直接的允许循环依赖//这里就是对应的一个错误(BeanCurrentlyInCreationException)的地方,我们进入if(isPrototypeCurrentlyInCreation(beanName)){thrownewBeanCurrentlyInCreationException(beanName);}// Check if bean definition exists in this factory.BeanFactory parentBeanFactory =getParentBeanFactory();if(parentBeanFactory !=null&&!containsBeanDefinition(beanName)){// Not found -> check parent.String nameToLookup =originalBeanName(name);if(parentBeanFactory instanceofAbstractBeanFactory){return((AbstractBeanFactory) parentBeanFactory).doGetBean(nameToLookup, requiredType, args, typeCheckOnly);}elseif(args !=null){// Delegation to parent with explicit args.return(T) parentBeanFactory.getBean(nameToLookup, args);}elseif(requiredType !=null){// No args -> delegate to standard getBean method.return parentBeanFactory.getBean(nameToLookup, requiredType);}else{return(T) parentBeanFactory.getBean(nameToLookup);}}if(!typeCheckOnly){markBeanAsCreated(beanName);}try{RootBeanDefinition mbd =getMergedLocalBeanDefinition(beanName);checkMergedBeanDefinition(mbd, beanName, args);// Guarantee initialization of beans that the current bean depends on.String[] dependsOn = mbd.getDependsOn();if(dependsOn !=null){for(String dep : dependsOn){if(isDependent(beanName, dep)){thrownewBeanCreationException(mbd.getResourceDescription(), beanName,"Circular depends-on relationship between '"+ beanName +"' and '"+ dep +"'");}registerDependentBean(dep, beanName);try{getBean(dep);}catch(NoSuchBeanDefinitionException ex){thrownewBeanCreationException(mbd.getResourceDescription(), beanName,"'"+ beanName +"' depends on missing bean '"+ dep +"'", ex);}}}// Create bean instance.if(mbd.isSingleton()){//单例进入sharedInstance =getSingleton(beanName,()->{try{returncreateBean(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);}elseif(mbd.isPrototype()){// It's a prototype -> create a new instance.Object prototypeInstance =null;try{//到这里代表没有开启允许循环依赖,那么到这里//创建原型bean之前添加标记beforePrototypeCreation(beanName);//创建原型bean,由于在初始化填充时,可能会继续操作(多例是实时创建的,所以存在继续操作的说法,而单例由于三级缓存的缘故,所以基本解决的),最终导致由于上面标记设置了值,使得isPrototypeCurrentlyInCreation方法为true,那么对应的错误就出现了prototypeInstance =createBean(beanName, mbd, args);}finally{//都创建好了,他自然也不用考虑什么循环了,所以删除标记,而避免其他因为他的存在导致的循环依赖,因为是一步一步过去的,即有顺序的//创建原型bean之后删除标记afterPrototypeCreation(beanName);}bean =getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);}else{String scopeName = mbd.getScope();if(!StringUtils.hasLength(scopeName)){thrownewIllegalStateException("No scope name defined for bean ´"+ beanName +"'");}Scope scope =this.scopes.get(scopeName);if(scope ==null){thrownewIllegalStateException("No Scope registered for scope name '"+ scopeName +"'");}try{Object scopedInstance = scope.get(beanName,()->{beforePrototypeCreation(beanName);try{returncreateBean(beanName, mbd, args);}finally{afterPrototypeCreation(beanName);}});bean =getObjectForBeanInstance(scopedInstance, name, beanName, mbd);}catch(IllegalStateException ex){thrownewBeanCreationException(beanName,"Scope '"+ scopeName +"' is not active for the current thread; consider "+"defining a scoped proxy for this bean if you intend to refer to it from a singleton",ex);}}}catch(BeansException ex){cleanupAfterBeanCreationFailure(beanName);throw ex;}}// Check if required type matches the type of the actual bean instance.if(requiredType !=null&&!requiredType.isInstance(bean)){try{T convertedBean =getTypeConverter().convertIfNecessary(bean, requiredType);if(convertedBean ==null){thrownewBeanNotOfRequiredTypeException(name, requiredType, bean.getClass());}return convertedBean;}catch(TypeMismatchException ex){if(logger.isTraceEnabled()){logger.trace("Failed to convert bean '"+ name +"' to required type '"+ClassUtils.getQualifiedName(requiredType)+"'", ex);}thrownewBeanNotOfRequiredTypeException(name, requiredType, bean.getClass());}}return(T) bean;}//..protectedbooleanisPrototypeCurrentlyInCreation(String beanName){Object curVal =this.prototypesCurrentlyInCreation.get();return(curVal !=null&&(curVal.equals(beanName)||(curVal instanceofSet&&((Set<?>) curVal).contains(beanName))));}//..}
//我们回到之前的prototypeInstance = createBean(beanName, mbd, args);,实际上单例也存在这个方法//我们进入://最终可以找到这个(AbstractAutowireCapableBeanFactory类里面的):Object beanInstance =doCreateBean(beanName, mbdToUse, args);//前面说明了//我们进入://到这里protectedObjectdoCreateBean(String beanName,RootBeanDefinition mbd,@NullableObject[] args)throwsBeanCreationException{// Instantiate the bean.BeanWrapper instanceWrapper =null;if(mbd.isSingleton()){instanceWrapper =this.factoryBeanInstanceCache.remove(beanName);}if(instanceWrapper ==null){//创建bean实例,仅仅调用构造方法,但是并没有设置属性instanceWrapper =createBeanInstance(beanName, mbd, args);}//开始考虑三级缓存Object bean = instanceWrapper.getWrappedInstance();Class<?> beanType = instanceWrapper.getWrappedClass();if(beanType !=NullBean.class){mbd.resolvedTargetType = beanType;}// Allow post-processors to modify the merged bean definition.synchronized(mbd.postProcessingLock){if(!mbd.postProcessed){try{applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);}catch(Throwable ex){thrownewBeanCreationException(mbd.getResourceDescription(), beanName,"Post-processing of merged bean definition failed", ex);}mbd.postProcessed =true;}}// Eagerly cache singletons to be able to resolve circular references// even when triggered by lifecycle interfaces like BeanFactoryAware.//到这里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));}// Initialize the bean instance.//初始化bean实例Object exposedObject = bean;try{//前面是创建bean,这里是填充属性(bean),现在我们进入了(之前没有进入)populateBean(beanName, mbd, instanceWrapper);//调用初始化方法,应用BeanPostProcessor后置处理器,我们进入这里exposedObject =initializeBean(beanName, exposedObject, mbd);}catch(Throwable ex){//后面的省略了
/*
我们进入上面的addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));里面:
*/publicclassDefaultSingletonBeanRegistryextendsSimpleAliasRegistryimplementsSingletonBeanRegistry{//..protectedvoidaddSingletonFactory(String beanName,ObjectFactory<?> singletonFactory){Assert.notNull(singletonFactory,"Singleton factory must not be null");synchronized(this.singletonObjects){if(!this.singletonObjects.containsKey(beanName)){//加入三级缓存(beanName是当前的bean名称),并且给出singletonFactory来给二级缓存进行扩展操作this.singletonFactories.put(beanName, singletonFactory);//二级缓存,对应加上三级缓存,自然不能存在低级缓存this.earlySingletonObjects.remove(beanName);this.registeredSingletons.add(beanName);}}}//..}
publicabstractclassAbstractAutowireCapableBeanFactoryextendsAbstractBeanFactoryimplementsAutowireCapableBeanFactory{//..@SuppressWarnings("deprecation")// for postProcessPropertyValuesprotectedvoidpopulateBean(String beanName,RootBeanDefinition mbd,@NullableBeanWrapper bw){if(bw ==null){if(mbd.hasPropertyValues()){thrownewBeanCreationException(mbd.getResourceDescription(), beanName,"Cannot apply property values to null instance");}else{// Skip property population phase for null instance.return;}}// 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 instanceofInstantiationAwareBeanPostProcessor){InstantiationAwareBeanPostProcessor ibp =(InstantiationAwareBeanPostProcessor) bp;if(!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)){return;}}}}PropertyValues pvs =(mbd.hasPropertyValues()? mbd.getPropertyValues():null);int resolvedAutowireMode = mbd.getResolvedAutowireMode();if(resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE){MutablePropertyValues newPvs =newMutablePropertyValues(pvs);// Add property values based on autowire by name if applicable.if(resolvedAutowireMode == AUTOWIRE_BY_NAME){autowireByName(beanName, mbd, bw, newPvs);}// Add property values based on autowire by type if applicable.if(resolvedAutowireMode == AUTOWIRE_BY_TYPE){autowireByType(beanName, mbd, bw, newPvs);}pvs = newPvs;}boolean hasInstAwareBpps =hasInstantiationAwareBeanPostProcessors();boolean needsDepCheck =(mbd.getDependencyCheck()!=AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);PropertyDescriptor[] filteredPds =null;if(hasInstAwareBpps){if(pvs ==null){pvs = mbd.getPropertyValues();}for(BeanPostProcessor bp :getBeanPostProcessors()){if(bp instanceofInstantiationAwareBeanPostProcessor){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;}}}if(needsDepCheck){if(filteredPds ==null){filteredPds =filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);}checkDependencies(beanName, mbd, filteredPds, pvs);}if(pvs !=null){//直接到这里applyPropertyValues(beanName, mbd, bw, pvs);}}//..protectedvoidapplyPropertyValues(String beanName,BeanDefinition mbd,BeanWrapper bw,PropertyValues pvs){if(pvs.isEmpty()){return;}if(System.getSecurityManager()!=null&& bw instanceofBeanWrapperImpl){((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());}MutablePropertyValues mpvs =null;List<PropertyValue> original;if(pvs instanceofMutablePropertyValues){mpvs =(MutablePropertyValues) pvs;if(mpvs.isConverted()){// Shortcut: use the pre-converted values as-is.try{bw.setPropertyValues(mpvs);return;}catch(BeansException ex){thrownewBeanCreationException(mbd.getResourceDescription(), beanName,"Error setting property values", ex);}}original = mpvs.getPropertyValueList();}else{original =Arrays.asList(pvs.getPropertyValues());}TypeConverter converter =getCustomTypeConverter();if(converter ==null){converter = bw;}BeanDefinitionValueResolver valueResolver =newBeanDefinitionValueResolver(this, beanName, mbd, converter);// Create a deep copy, resolving any references for values.List<PropertyValue> deepCopy =newArrayList<>(original.size());boolean resolveNecessary =false;for(PropertyValue pv : original){if(pv.isConverted()){deepCopy.add(pv);}else{//到这里,这里是对应操作set的依赖名称,也就是解决循环依赖的地方,你进行调试可以发现对应的beanName是我们的bean名称,而propertyName则是property标签对应的名称String propertyName = pv.getName();Object originalValue = pv.getValue();//拿取对应的bean,准备进行设置操作的(里面最终操作了三级缓存的),我们进入Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);//后面就是进行了设置操作,如set,了解即可Object convertedValue = resolvedValue;boolean convertible = bw.isWritableProperty(propertyName)&&!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);if(convertible){convertedValue =convertForProperty(resolvedValue, propertyName, bw, converter);}// Possibly store converted value in merged bean definition,// in order to avoid re-conversion for every created bean instance.if(resolvedValue == originalValue){if(convertible){pv.setConvertedValue(convertedValue);}deepCopy.add(pv);}elseif(convertible && originalValue instanceofTypedStringValue&&!((TypedStringValue) originalValue).isDynamic()&&!(convertedValue instanceofCollection||ObjectUtils.isArray(convertedValue))){pv.setConvertedValue(convertedValue);deepCopy.add(pv);}else{resolveNecessary =true;deepCopy.add(newPropertyValue(pv, convertedValue));}}}if(mpvs !=null&&!resolveNecessary){mpvs.setConverted();}// Set our (possibly massaged) deep copy.try{bw.setPropertyValues(newMutablePropertyValues(deepCopy));}catch(BeansException ex){thrownewBeanCreationException(mbd.getResourceDescription(), beanName,"Error setting property values", ex);}}//..}classBeanDefinitionValueResolver{//..@NullablepublicObjectresolveValueIfNecessary(Object argName,@NullableObject value){// We must check each value to see whether it requires a runtime reference// to another bean to be resolved.if(value instanceofRuntimeBeanReference){RuntimeBeanReference ref =(RuntimeBeanReference) value;//我们进入returnresolveReference(argName, ref);}elseif(value instanceofRuntimeBeanNameReference){String refName =((RuntimeBeanNameReference) value).getBeanName();refName =String.valueOf(doEvaluate(refName));if(!this.beanFactory.containsBean(refName)){thrownewBeanDefinitionStoreException("Invalid bean name '"+ refName +"' in bean reference for "+ argName);}return refName;}elseif(value instanceofBeanDefinitionHolder){// Resolve BeanDefinitionHolder: contains BeanDefinition with name and aliases.BeanDefinitionHolder bdHolder =(BeanDefinitionHolder) value;returnresolveInnerBean(argName, bdHolder.getBeanName(), bdHolder.getBeanDefinition());}elseif(value instanceofBeanDefinition){// Resolve plain BeanDefinition, without contained name: use dummy name.BeanDefinition bd =(BeanDefinition) value;String innerBeanName ="(inner bean)"+BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR +ObjectUtils.getIdentityHexString(bd);returnresolveInnerBean(argName, innerBeanName, bd);}elseif(value instanceofManagedArray){// May need to resolve contained runtime references.ManagedArray array =(ManagedArray) value;Class<?> elementType = array.resolvedElementType;if(elementType ==null){String elementTypeName = array.getElementTypeName();if(StringUtils.hasText(elementTypeName)){try{elementType =ClassUtils.forName(elementTypeName,this.beanFactory.getBeanClassLoader());array.resolvedElementType = elementType;}catch(Throwable ex){// Improve the message by showing the context.thrownewBeanCreationException(this.beanDefinition.getResourceDescription(),this.beanName,"Error resolving array type for "+ argName, ex);}}else{elementType =Object.class;}}returnresolveManagedArray(argName,(List<?>) value, elementType);}elseif(value instanceofManagedList){// May need to resolve contained runtime references.returnresolveManagedList(argName,(List<?>) value);}elseif(value instanceofManagedSet){// May need to resolve contained runtime references.returnresolveManagedSet(argName,(Set<?>) value);}elseif(value instanceofManagedMap){// May need to resolve contained runtime references.returnresolveManagedMap(argName,(Map<?,?>) value);}elseif(value instanceofManagedProperties){Properties original =(Properties) value;Properties copy =newProperties();original.forEach((propKey, propValue)->{if(propKey instanceofTypedStringValue){propKey =evaluate((TypedStringValue) propKey);}if(propValue instanceofTypedStringValue){propValue =evaluate((TypedStringValue) propValue);}if(propKey ==null|| propValue ==null){thrownewBeanCreationException(this.beanDefinition.getResourceDescription(),this.beanName,"Error converting Properties key/value pair for "+ argName +": resolved to null");}copy.put(propKey, propValue);});return copy;}elseif(value instanceofTypedStringValue){// Convert value to target type here.TypedStringValue typedStringValue =(TypedStringValue) value;Object valueObject =evaluate(typedStringValue);try{Class<?> resolvedTargetType =resolveTargetType(typedStringValue);if(resolvedTargetType !=null){returnthis.typeConverter.convertIfNecessary(valueObject, resolvedTargetType);}else{return valueObject;}}catch(Throwable ex){// Improve the message by showing the context.thrownewBeanCreationException(this.beanDefinition.getResourceDescription(),this.beanName,"Error converting typed String value for "+ argName, ex);}}elseif(value instanceofNullBean){returnnull;}else{returnevaluate(value);}}//..//到这里@NullableprivateObjectresolveReference(Object argName,RuntimeBeanReference ref){try{Object bean;String refName = ref.getBeanName();refName =String.valueOf(doEvaluate(refName));if(ref.isToParent()){if(this.beanFactory.getParentBeanFactory()==null){thrownewBeanCreationException(this.beanDefinition.getResourceDescription(),this.beanName,"Can't resolve reference to bean '"+ refName +"' in parent factory: no parent factory available");}bean =this.beanFactory.getParentBeanFactory().getBean(refName);}else{//到这里,我们进入可以发现,是操作了对应的:/*@Overridepublic Object getBean(String name) throws BeansException {return doGetBean(name, null, null, false);}是否发现非常眼熟呢,也就是说,你没有那么我帮你进行创建,然后根据流程,你在操作时,由于三级缓存的存在,必然可以拿取引用,从而解决循环问题,这里可以发现,是第一次对方的来先完毕的(在spring中一般是b先完毕,我们看后面的源码就知道了)*/bean =this.beanFactory.getBean(refName);//refName就是对应依赖的bean的名称this.beanFactory.registerDependentBean(refName,this.beanName);}if(bean instanceofNullBean){bean =null;}return bean;}catch(BeansException ex){thrownewBeanCreationException(this.beanDefinition.getResourceDescription(),this.beanName,"Cannot resolve reference to bean '"+ ref.getBeanName()+"' while setting "+ argName, ex);}}//..}
参考了一些代码,实现了局域网的实时语音对讲功能,只要同网段局域网即可通话,文字聊天,传输文件等,包含了飞鸽传输的功能。 主要是录音发送和接收播放录音比较重要。录音线程: Java代码 public class Audi…
this 是自身的一个对象,代表对象本身,是指向对象本身的一个指针。
用法分为3种: 1.普通的直接引用,this 相当于是指向当前对象本身 2.形参与成员名字重名,用this 来区分 public Student(String name, int age) {this.…