




已阅读5页,还剩9页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
上一章当中我没有提及具体的搭建环境的步骤,一个是不得不承认有点懒,另外一个我觉得如果上章所述的那些环境都还不会搭建的话,研究spring的源码还有些过早。如果你有兴趣的话,相信已经搭建好了学习研究的环境,接下来就可以进入正题了。网上也有很多关于spring源码学习的文章以及帖子,讲的也都不错,但是有些可能高估了读者的能力,该深入的地方反倒一句带过,我现在也是在一步一步研究,和大家的进度一样,所以可能在我的角度来和各位探讨,更加容易。首先我们来说一下IOC,IOC是spring最核心的理念,包括AOP也要屈居第二,那么IOC到底是什么呢,四个字,控制反转。网上有不少是这么解释IOC的,说IOC是将对象的创建和依赖关系交给容器,这句话我相信不少人都知道,在我个人的理解,IOC就是让我们的开发变的更简单了。为什么这么说呢,光说没意思,直接上代码。publicclassPersonpublicvoidwork()System.out.println(Iamworking);上面这个是Person类,如果我们还有一个Company公司类,公司要开张需要人来工作,所以我们可能需要这样。publicclassCompanypublicPersonperson; publicCompany(Personperson)this.person=person;publicvoidopen()person.work();System.out.println(Iamopening);好了,这样可以了,虽说和现实有些区别,毕竟没有一个人的公司,但是就是这么个意思。必须要有人在公司里,公司才能开张。有了spring上述情况我们是怎么写的呢?Person类不变,Company就可以简单些了。publicclassCompanyAutowiredpublicPersonperson;publicvoidopen()person.work();System.out.println(Iamopening);OK了,使用注解后,spring里的写法是这样的,是不是简单很多?或许你可能会说,这才减少了多少代码,但是事实上是,真正的项目中,不可能有这么简单的依赖关系,或许是2层,3层甚至N层。当然,可能我们有时候用的XML,XML和注解的区别就在于这里,注解可以快速的完成依赖的注入,但是缺点也很明显,那就是比如我公司里不需要人了,我需要的是机器,那么我还要手动改代码,将Person换成机器(这里应该是英文,英语不好,懒得查了 dadiao 缪买网,只记得念“磨洗”),而如果是XML配置,那么我们只需要改下配置文件就可以。维护起来会方便很多,当然XML的缺点也很明显,那就是依赖关系复杂的时候,XML文件会比较臃肿,所以我们一般的做法是将XML分离开来。说到这里,有些扯远了,但是我觉得以上可以足够说明IOC的好处,知道了IOC的好处,我们自然就要知道怎么来实现IOC了。或许看了spring的源码,第一感觉是很蒙,包太多,我也很蒙,但是研究东西就是得沉下心来,先来关注一下这个接口,BeanFactory,附上代码。/*Copyright2002-2010theoriginalauthororauthors.*LicensedundertheApacheLicense,Version2.0(theLicense);*youmaynotusethisfileexceptincompliancewiththeLicense.*YoumayobtainacopyoftheLicenseat*/licenses/LICENSE-2.0*Unlessrequiredbyapplicablelaworagreedtoinwriting,software*distributedundertheLicenseisdistributedonanASISBASIS,*WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.*SeetheLicenseforthespecificlanguagegoverningpermissionsand*limitationsundertheLicense.*/packageorg.springframework.beans.factory;importorg.springframework.beans.BeansException;/*TherootinterfaceforaccessingaSpringbeancontainer.*Thisisthebasicclientviewofabeancontainer;*furtherinterfacessuchaslinkListableBeanFactoryand*linkorg.springframework.beans.factory.config.ConfigurableBeanFactory*areavailableforspecificpurposes.*Thisinterfaceisimplementedbyobjectsthatholdanumberofbeandefinitions,*eachuniquelyidentifiedbyaStringname.Dependingonthebeandefinition,*thefactorywillreturneitheranindependentinstanceofacontainedobject*(thePrototypedesignpattern),orasinglesharedinstance(asuperior*alternativetotheSingletondesignpattern,inwhichtheinstanceisa*singletoninthescopeofthefactory).Whichtypeofinstancewillbereturned*dependsonthebeanfactoryconfiguration:theAPIisthesame.SinceSpring*2.0,furtherscopesareavailabledependingontheconcreteapplication*context(e.g.requestandsessionscopesinawebenvironment).*ThepointofthisapproachisthattheBeanFactoryisacentralregistry*ofapplicationcomponents,andcentralizesconfigurationofapplication*components(nomoredoindividualobjectsneedtoreadpropertiesfiles,*forexample).Seechapters4and11ofExpertOne-on-OneJ2EEDesignand*Developmentforadiscussionofthebenefitsofthisapproach.*NotethatitisgenerallybettertorelyonDependencyInjection*(pushconfiguration)toconfigureapplicationobjectsthroughsetters*orconstructors,ratherthanuseanyformofpullconfigurationlikea*BeanFactorylookup.SpringsDependencyInjectionfunctionalityis*implementedusingthisBeanFactoryinterfaceanditssubinterfaces.*NormallyaBeanFactorywillloadbeandefinitionsstoredinaconfiguration*source(suchasanXMLdocument),andusetheorg.springframework.beans*packagetoconfigurethebeans.However,animplementationcouldsimplyreturn*JavaobjectsitcreatesasnecessarydirectlyinJavacode.Thereareno*constraintsonhowthedefinitionscouldbestored:LDAP,RDBMS,XML,*propertiesfile,etc.Implementationsareencouragedtosupportreferences*amongstbeans(DependencyInjection).*IncontrasttothemethodsinlinkListableBeanFactory,allofthe*operationsinthisinterfacewillalsocheckparentfactoriesifthisisa*linkHierarchicalBeanFactory.Ifabeanisnotfoundinthisfactoryinstance,*theimmediateparentfactorywillbeasked.Beansinthisfactoryinstance*aresupposedtooverridebeansofthesamenameinanyparentfactory.*Beanfactoryimplementationsshouldsupportthestandardbeanlifecycleinterfaces*asfaraspossible.Thefullsetofinitializationmethodsandtheirstandardorderis:*1.BeanNameAwaressetBeanName*2.BeanClassLoaderAwaressetBeanClassLoader*3.BeanFactoryAwaressetBeanFactory*4.ResourceLoaderAwaressetResourceLoader*(onlyapplicablewhenrunninginanapplicationcontext)*5.ApplicationEventPublisherAwaressetApplicationEventPublisher*(onlyapplicablewhenrunninginanapplicationcontext)*6.MessageSourceAwaressetMessageSource*(onlyapplicablewhenrunninginanapplicationcontext)*7.ApplicationContextAwaressetApplicationContext*(onlyapplicablewhenrunninginanapplicationcontext)*8.ServletContextAwaressetServletContext*(onlyapplicablewhenrunninginawebapplicationcontext)*9.postProcessBeforeInitializationmethodsofBeanPostProcessors*10.InitializingBeansafterPropertiesSet*11.acustominit-methoddefinition*12.postProcessAfterInitializationmethodsofBeanPostProcessors*Onshutdownofabeanfactory,thefollowinglifecyclemethodsapply:*1.DisposableBeansdestroy*2.acustomdestroy-methoddefinition*authorRodJohnson*authorJuergenHoeller*since13April2001*seeBeanNameAware#setBeanName*seeBeanClassLoaderAware#setBeanClassLoader*seeBeanFactoryAware#setBeanFactory*seeorg.springframework.context.ResourceLoaderAware#setResourceLoader*seeorg.springframework.context.ApplicationEventPublisherAware#setApplicationEventPublisher*seeorg.springframework.context.MessageSourceAware#setMessageSource*seeorg.springframework.context.ApplicationContextAware#setApplicationContext*seeorg.springframework.web.context.ServletContextAware#setServletContext*seeorg.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization*seeInitializingBean#afterPropertiesSet*seeorg.springframework.beans.factory.support.RootBeanDefinition#getInitMethodName*seeorg.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization*seeDisposableBean#destroy*seeorg.springframework.beans.factory.support.RootBeanDefinition#getDestroyMethodName*/publicinterfaceBeanFactory/*UsedtodereferencealinkFactoryBeaninstanceanddistinguishitfrom*beanscreatedbytheFactoryBean.Forexample,ifthebeannamed*myJndiObjectisaFactoryBean,getting&myJndiObject*willreturnthefactory,nottheinstancereturnedbythefactory.*/StringFACTORY_BEAN_PREFIX=&;/*Returnaninstance,whichmaybesharedorindependent,ofthespecifiedbean.*ThismethodallowsaSpringBeanFactorytobeusedasareplacementforthe*SingletonorPrototypedesignpattern.Callersmayretainreferencesto*returnedobjectsinthecaseofSingletonbeans.*Translatesaliasesbacktothecorrespondingcanonicalbeanname.*Willasktheparentfactoryifthebeancannotbefoundinthisfactoryinstance.*paramnamethenameofthebeantoretrieve*returnaninstanceofthebean*throwsNoSuchBeanDefinitionExceptionifthereisnobeandefinition*withthespecifiedname*throwsBeansExceptionifthebeancouldnotbeobtained*/ObjectgetBean(Stringname)throwsBeansException;/*Returnaninstance,whichmaybesharedorindependent,ofthespecifiedbean.*Behavesthesameaslink#getBean(String),butprovidesameasureoftype*safetybythrowingaBeanNotOfRequiredTypeExceptionifthebeanisnotofthe*requiredtype.ThismeansthatClassCastExceptioncantbethrownoncasting*theresultcorrectly,ascanhappenwithlink#getBean(String).*Translatesaliasesbacktothecorrespondingcanonicalbeanname.*Willasktheparentfactoryifthebeancannotbefoundinthisfactoryinstance.*paramnamethenameofthebeantoretrieve*paramrequiredTypetypethebeanmustmatch.Canbeaninterfaceorsuperclass*oftheactualclass,ornullforanymatch.Forexample,ifthevalue*isObject.class,thismethodwillsucceedwhatevertheclassofthe*returnedinstance.*returnaninstanceofthebean*throwsNoSuchBeanDefinitionExceptioniftheresnosuchbeandefinition*throwsBeanNotOfRequiredTypeExceptionifthebeanisnotoftherequiredtype*throwsBeansExceptionifthebeancouldnotbecreated*/TgetBean(Stringname,ClassrequiredType)throwsBeansException;/*Returnthebeaninstancethatuniquelymatchesthegivenobjecttype,ifany.*paramrequiredTypetypethebeanmustmatch;canbeaninterfaceorsuperclass.*literalnullisdisallowed.*ThismethodgoesintolinkListableBeanFactoryby-typelookupterritory*butmayalsobetranslatedintoaconventionalby-namelookupbasedonthename*ofthegiventype.Formoreextensiveretrievaloperationsacrosssetsofbeans,*uselinkListableBeanFactoryand/orlinkBeanFactoryUtils.*returnaninstanceofthesinglebeanmatchingtherequiredtype*throwsNoSuchBeanDefinitionExceptionifthereisnotexactlyonematchingbeanfound*since3.0*seeListableBeanFactory*/TgetBean(ClassrequiredType)throwsBeansException;/*Returnaninstance,whichmaybesharedorindependent,ofthespecifiedbean.*Allowsforspecifyingexplicitconstructorarguments/factorymethodarguments,*overridingthespecifieddefaultarguments(ifany)inthebeandefinition.*paramnamethenameofthebeantoretrieve*paramargsargumentstouseifcreatingaprototypeusingexplicitargumentstoa*staticfactorymethod.Itisinvalidtouseanon-nullargsvalueinanyothercase.*returnaninstanceofthebean*throwsNoSuchBeanDefinitionExceptioniftheresnosuchbeandefinition*throwsBeanDefinitionStoreExceptionifargumentshavebeengivenbut*theaffectedbeanisntaprototype*throwsBeansExceptionifthebeancouldnotbecreated*since2.5*/ObjectgetBean(Stringname,Object.args)throwsBeansException;/*Doesthisbeanfactorycontainabeanwiththegivenname?Morespecifically,*islink#getBeanabletoobtainabeaninstanceforthegivenname?*Translatesaliasesbacktothecorrespondingcanonicalbeanname.*Willasktheparentfactoryifthebeancannotbefoundinthisfactoryinstance.*paramnamethenameofthebeantoquery*returnwhetherabeanwiththegivennameisdefined*/booleancontainsBean(Stringname);/*Isthisbeanasharedsingleton?Thatis,willlink#getBeanalways*returnthesameinstance?*Note:Thismethodreturningfalsedoesnotclearlyindicate*independentinstances.Itindicatesnon-singletoninstances,whichmaycorrespond*toascopedbeanaswell.Usethelink#isPrototypeoperationtoexplicitly*checkforindependentinstances.*Translatesaliasesbacktothecorrespondingcanonicalbeanname.*Willasktheparentfactoryifthebeancannotbefoundinthisfactoryinstance.*paramnamethenameofthebeantoquery*returnwhetherthisbeancorrespondstoasingletoninstance*throwsNoSuchBeanDefinitionExceptionifthereisnobeanwiththegivenname*see#getBean*see#isPrototype*/booleanisSingleton(Stringname)throwsNoSuchBeanDefinitionException;/*Isthisbeanaprototype?Thatis,willlink#getBeanalwaysreturn*independentinstances?*Note:Thismethodreturningfalsedoesnotclearlyindicate*asingletonobject.Itindicatesnon-independentinstances,whichmaycorrespond*toascopedbeanaswell.Usethelink#isSingletonoperationtoexplicitly*checkforasharedsingletoninstance.*Translatesaliasesbacktothecorrespondingcanonicalbeanname.*Willasktheparentfactoryifthebeancannotbefoundinthisfactoryinstance.*paramnamethenameofthebeantoquery*returnwhetherthisbeanwillalwaysdeliverindependentinstances*throwsNoSuchBeanDefinitionExceptionifthereisnobeanwiththegivenname*since2.0.3*see#getBean*see#isSingleton*/booleanisPrototype(Stringname)throwsNoSuchBeanDefinitionException;/*Checkwhetherthebeanwiththegivennamematchesthespecifiedtype.*Morespecifically,checkwhetheralink#getBeancallforthegivenname*wouldreturnanobjectthatisassignabletothespecifiedtargettype.*Translatesaliasesbacktothecorrespondingcanonicalbeanname.*Willasktheparentfactoryifthebeancannotbefoundinthisfactoryinstance.*paramnamethenameofthebeantoquery*paramtargetTypethetypetomatchagainst*returntrueifthebeantypematches,*falseifitdoesntmatchorcannotbedeterminedyet*throwsNoSuchBeanDefinitionExceptionifthereisnobeanwiththegivenname*since2.0.1*see#getBean*see#getType*/booleanisTypeMatch(Stringname,ClasstargetType)throwsNoSuchBeanDefinitionException;/*Determinethetypeofthebeanwiththegivenname.Morespecifically,*determinethetypeofobjectthatlink#getBeanwouldreturnforthegivenname.*ForalinkFactoryBean,returnthetypeofobjectthattheFactoryBeancreates,*asexposedbylinkFactoryBean#getObjectType().*Translatesaliasesbacktothecorrespondingcanonicalbeanname.*Willasktheparentfactoryifthebeancannotbefoundinthisfactoryinstance.*paramnamethenameofthebeantoquery*returnthetypeofthebean,ornullifnotdeterminable*throwsNoSuchBeanDefinitionExceptionifthereisnobeanwiththegivenname*since1.1.2*see#getBean*see#isTypeMatch*/ClassgetType(Stringname)throwsNoSuchBeanDefinitionException;/*Returnthealiasesforthegivenbeanname,ifany.*Allofthosealiasespointtothesamebeanwhenusedinalink#getBeancall.*Ifthegivennameisanalias,thecorrespondingoriginalbeanname*andotheraliases(ifany)willbereturned,withtheoriginalbeanname*beingthefirstelementinthearray.*Willasktheparentfactoryifthebeancannotbefoundinthisfactoryinstance.*paramnamethebeannametocheckforaliases*returnthealiases,oranemptyarrayifnone*see#getBean*/StringgetAliases(Stringname);这个便是spring核心的Bean工厂定义,上面的author说是2001年写的,已经历史久远了,这个类是spring中所有bean工厂,也就是俗称的IOC容器的祖宗,各种IOC容器都只是它的实现或者为了满足特别需求的扩展实现,包括我们平时用的最多的ApplicationContext。从上面的方法就可以看出,这些工厂的实现最大的作用就是根据bean的名称亦或类型等等,来返回一个bean的实例。一个工厂如果想拥有这样的功能,那么它一定需要以下几个因素:1.需要持有各种bean的定义,否则无法正确的完成bean的实例化。2.需要持有bean之间的依赖关系,否则在bean实例化的过程中也会出现问题。例如上例,如果我们只是各自持有Person和Company,却不知道他们的依赖关系,那么在Company初始化以后,调用open方法时,就会报空指针。这是因为Company其实并没有真正的被正确初始化。3.以上两种都要依赖于我们所写的依赖关系的定义,暂且认为是XML文件(其实可以是各种各样的),那么我们需要一个工具来完成XML文件的读取。我目前想到的,只需要满足以上三种条件,便可以创建一个bean工厂,来生产各种bean。当然,spring有更高级的做法,以上只是我们直观的去想如何实现IOC。其实在上述过程中仍旧有一些问题,比如第一步,我们需要持有bean的定义,如何持有?这是一个问题。我们知道spring的XML配置文件中,有一个属性是lazy-init,这就说明,bean在何时实例化我们是可以控制的。这个属性默认是false,但是我们可以将这个属性设置为true,也就是说spring容器初始化以后,配置了延迟加载的各种bean都还未产生,它们只在需要的时候出现。所以我们无法直接的创建一个Map来持有这些bean的实例,在这里要注意,我们要储存的是bean的定义,而非实例。那么接下来,又是一个祖宗级别的接口要出现了,来看BeanDefinition。/*Copyright2002-2009theoriginalauthororauthors.*LicensedundertheApacheLicense,Version2.0(theLicense);*youmaynotusethisfileexceptincompliancewiththeLicense.*YoumayobtainacopyoftheLicenseat*/licenses/LICENSE-2.0*Unlessrequiredbyapplicablelaworagreedtoinwriting,software*distributedundertheLicenseisdistributedonanASISBASIS,*WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.*SeetheLicenseforthespecificlanguagegoverningpermissionsand*limitationsundertheLicense.*/packageorg.springframework.beans.factory.config;importorg.springframework.beans.BeanMetadataElement;importorg.springframework.beans.MutablePropertyValues;importorg.springframework.core.AttributeAccessor;/*ABeanDefinitiondescribesabeaninstance,whichhaspropertyvalues,*constructorargumentvalues,andfurtherinformationsuppliedby*concreteimplementations.*Thisisjustaminimalinterface:Themainintentionistoallowa*linkBeanFactoryPostProcessorsuchaslinkPropertyPlaceholderConfigurer*tointrospectandmodifypropertyvaluesandotherbeanmetadata.*authorJuergenHoeller*authorRobHarrop*since19.03.2004*seeConfigurableListableBeanFactory#getBeanDefinition*seeorg.springframework.beans.factory.support.RootBeanDefinition*seeorg.springframework.beans.factory.support.ChildBeanDefinition*/publicinterfaceBeanDefinitionextendsAttributeAccessor,BeanMetadataElement/*Scopeidentifierforthestandardsingletonscope:singleton.*Notethatextendedbeanfactoriesmightsupportfurtherscopes.*see#setScope*/StringSCOPE_SINGLETON=ConfigurableBeanFactory.SCOPE_SINGLETON;/*Scopeidentifierforthestandardprototypescope:prototype.*Notethatextendedbeanfactoriesmightsupportfurtherscopes.*see#setScope*/StringSCOPE_PROTOTYPE=ConfigurableBeanFactory.SCOPE_PROTOTYPE;/*RolehintindicatingthataBeanDefinitionisamajorpart*oftheapplication.Typicallycorrespondstoauser-definedbean.*/intROLE_APPLICATION=0;/*RolehintindicatingthataBeanDefinitionisasupporting*partofsomelargerconfiguration,typicallyanouter*linkorg.springframework.beans.factory.parsing.ComponentDefinition.*SUPPORTbeansareconsideredimportantenoughtobeaware*ofwhenlookingmorecloselyataparticular*linkorg.springframework.beans.factory.parsing.ComponentDefinition,*butnotwhenlookingattheoverallconfigurationofanapplication.*/intROLE_SUPPORT=1;/*RolehintindicatingthataBeanDefinitionisprovidingan*entirelybackgroundroleandhasnorelevancetotheend-user.Thishintis*usedwhenregisteringbeansthatarecompletelypartoftheinternalworkings*ofalinkorg.springframework.beans.factory.parsing.ComponentDefinition.*/intROLE_INFRASTRUCTURE=2;/*Returnthenameoftheparentdefinitionofthisbeandefinition,ifany.*/StringgetParentName();/*Setthenameoftheparentdefinitionofthisbeandefinition,ifany.*/voidsetParentName(StringparentName);/*Returnthecurrentbeanclassnameofthisbeandefinition.*Notethatthisdoesnothavetobetheactualclassnameusedatruntime,in*caseofachilddefinitionoverri
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 学校教育与职业技能培训协议
- 企业运营成本控制方案库
- 艺术流派及发展历程概述:美术课堂教学设计
- 直接引语与间接引语的转换规则:六年级英语语法课教案
- 小猪学样550字(11篇)
- 纪念塔课件教学
- 银滩之旅250字(12篇)
- 关于七夕节的英语作文11篇
- 2025年事业单位招聘统计类试卷:统计学在美学中的
- 2025年商务英语(BEC)中级考试真题模拟卷:模拟实战演练
- 九上英语单词表人教版
- 2025年北京车牌租赁合同范本
- 2024年高考新课标Ⅱ卷语文试题讲评课件
- 4S店企业职业卫生培训
- 静脉配液治疗操作核对流程
- 检验科糖尿病
- 产科医疗安全与质量控制制度
- 石油化工设备维护与检修手册
- 拆迁工程成本控制方案
- DB31-T 1502-2024 工贸行业有限空间作业安全管理规范
- 合肥新华书店招聘笔试题库2024
评论
0/150
提交评论